blob: 8457bc35f5024fbd889f50f7c8960a67e1b268ba [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"
48#include "llvm/Target/TargetMachine.h"
49#include "llvm/Target/TargetOptions.h"
50#include "llvm/Support/Compiler.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000051#include "llvm/Support/CommandLine.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000052#include "llvm/Support/Debug.h"
53#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000054#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000055#include <algorithm>
56using namespace llvm;
57
Dale Johannesen601d3c02008-09-05 01:48:15 +000058/// LimitFloatPrecision - Generate low-precision inline sequences for
59/// some float libcalls (6, 8 or 12 bits).
60static unsigned LimitFloatPrecision;
61
62static cl::opt<unsigned, true>
63LimitFPPrecision("limit-float-precision",
64 cl::desc("Generate low-precision inline sequences "
65 "for some float libcalls"),
66 cl::location(LimitFloatPrecision),
67 cl::init(0));
68
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000069/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
Dan Gohman2c91d102009-01-06 22:53:52 +000070/// of insertvalue or extractvalue indices that identify a member, return
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000071/// the linearized index of the start of the member.
72///
73static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
74 const unsigned *Indices,
75 const unsigned *IndicesEnd,
76 unsigned CurIndex = 0) {
77 // Base case: We're done.
78 if (Indices && Indices == IndicesEnd)
79 return CurIndex;
80
81 // Given a struct type, recursively traverse the elements.
82 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
83 for (StructType::element_iterator EB = STy->element_begin(),
84 EI = EB,
85 EE = STy->element_end();
86 EI != EE; ++EI) {
87 if (Indices && *Indices == unsigned(EI - EB))
88 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
89 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
90 }
Dan Gohman2c91d102009-01-06 22:53:52 +000091 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000092 }
93 // Given an array type, recursively traverse the elements.
94 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
95 const Type *EltTy = ATy->getElementType();
96 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
97 if (Indices && *Indices == i)
98 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
99 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
100 }
Dan Gohman2c91d102009-01-06 22:53:52 +0000101 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000102 }
103 // We haven't found the type we're looking for, so keep searching.
104 return CurIndex + 1;
105}
106
107/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
108/// MVTs that represent all the individual underlying
109/// non-aggregate types that comprise it.
110///
111/// If Offsets is non-null, it points to a vector to be filled in
112/// with the in-memory offsets of each of the individual values.
113///
114static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
115 SmallVectorImpl<MVT> &ValueVTs,
116 SmallVectorImpl<uint64_t> *Offsets = 0,
117 uint64_t StartingOffset = 0) {
118 // Given a struct type, recursively traverse the elements.
119 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
120 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
121 for (StructType::element_iterator EB = STy->element_begin(),
122 EI = EB,
123 EE = STy->element_end();
124 EI != EE; ++EI)
125 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
126 StartingOffset + SL->getElementOffset(EI - EB));
127 return;
128 }
129 // Given an array type, recursively traverse the elements.
130 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
131 const Type *EltTy = ATy->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000132 uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000133 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
134 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
135 StartingOffset + i * EltSize);
136 return;
137 }
138 // Base case: we can get an MVT for this LLVM IR type.
139 ValueVTs.push_back(TLI.getValueType(Ty));
140 if (Offsets)
141 Offsets->push_back(StartingOffset);
142}
143
Dan Gohman2a7c6712008-09-03 23:18:39 +0000144namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000145 /// RegsForValue - This struct represents the registers (physical or virtual)
146 /// that a particular set of values is assigned, and the type information about
147 /// the value. The most common situation is to represent one value at a time,
148 /// but struct or array values are handled element-wise as multiple values.
149 /// The splitting of aggregates is performed recursively, so that we never
150 /// have aggregate-typed registers. The values at this point do not necessarily
151 /// have legal types, so each value may require one or more registers of some
152 /// legal type.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000153 ///
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000154 struct VISIBILITY_HIDDEN RegsForValue {
155 /// TLI - The TargetLowering object.
156 ///
157 const TargetLowering *TLI;
158
159 /// ValueVTs - The value types of the values, which may not be legal, and
160 /// may need be promoted or synthesized from one or more registers.
161 ///
162 SmallVector<MVT, 4> ValueVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000163
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000164 /// RegVTs - The value types of the registers. This is the same size as
165 /// ValueVTs and it records, for each value, what the type of the assigned
166 /// register or registers are. (Individual values are never synthesized
167 /// from more than one type of register.)
168 ///
169 /// With virtual registers, the contents of RegVTs is redundant with TLI's
170 /// getRegisterType member function, however when with physical registers
171 /// it is necessary to have a separate record of the types.
172 ///
173 SmallVector<MVT, 4> RegVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000174
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000175 /// Regs - This list holds the registers assigned to the values.
176 /// Each legal or promoted value requires one register, and each
177 /// expanded value requires multiple registers.
178 ///
179 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000180
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000181 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000182
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000183 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000184 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000185 MVT regvt, MVT valuevt)
186 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
187 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000188 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000189 const SmallVector<MVT, 4> &regvts,
190 const SmallVector<MVT, 4> &valuevts)
191 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
192 RegsForValue(const TargetLowering &tli,
193 unsigned Reg, const Type *Ty) : TLI(&tli) {
194 ComputeValueVTs(tli, Ty, ValueVTs);
195
196 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
197 MVT ValueVT = ValueVTs[Value];
198 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
199 MVT RegisterVT = TLI->getRegisterType(ValueVT);
200 for (unsigned i = 0; i != NumRegs; ++i)
201 Regs.push_back(Reg + i);
202 RegVTs.push_back(RegisterVT);
203 Reg += NumRegs;
204 }
205 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000206
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000207 /// append - Add the specified values to this one.
208 void append(const RegsForValue &RHS) {
209 TLI = RHS.TLI;
210 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
211 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
212 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
213 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000214
215
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000216 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000217 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000218 /// Chain/Flag as the input and updates them for the output Chain/Flag.
219 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000220 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000221 SDValue &Chain, SDValue *Flag) const;
222
223 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000224 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000225 /// Chain/Flag as the input and updates them for the output Chain/Flag.
226 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000227 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000228 SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000229
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000230 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Evan Cheng697cbbf2009-03-20 18:03:34 +0000231 /// operand list. This adds the code marker, matching input operand index
232 /// (if applicable), and includes the number of values added into it.
233 void AddInlineAsmOperands(unsigned Code,
234 bool HasMatching, unsigned MatchingIdx,
235 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000236 };
237}
238
239/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000240/// PHI nodes or outside of the basic block that defines it, or used by a
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000241/// switch or atomic instruction, which may expand to multiple basic blocks.
242static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
243 if (isa<PHINode>(I)) return true;
244 BasicBlock *BB = I->getParent();
245 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
246 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
247 // FIXME: Remove switchinst special case.
248 isa<SwitchInst>(*UI))
249 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 Sandsceb4d1a2009-01-12 20:38:59 +0000297 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(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: {
334 DwarfWriter *DW = DAG.getDwarfWriter();
335 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
336
337 if (DW && DW->ValidDebugInfo(SPI->getContext())) {
338 DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
Bill Wendling0582ae92009-03-13 04:39:26 +0000339 std::string Dir, FN;
340 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
341 CU.getFilename(FN));
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000342 unsigned idx = MF->getOrCreateDebugLocID(SrcFile,
Scott Michelfdc40a02009-02-17 22:15:04 +0000343 SPI->getLine(),
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000344 SPI->getColumn());
345 DL = DebugLoc::get(idx);
346 }
347
348 break;
349 }
350 case Intrinsic::dbg_func_start: {
351 DwarfWriter *DW = DAG.getDwarfWriter();
352 if (DW) {
353 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
354 Value *SP = FSI->getSubprogram();
355
356 if (DW->ValidDebugInfo(SP)) {
357 DISubprogram Subprogram(cast<GlobalVariable>(SP));
358 DICompileUnit CU(Subprogram.getCompileUnit());
Bill Wendling0582ae92009-03-13 04:39:26 +0000359 std::string Dir, FN;
360 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
361 CU.getFilename(FN));
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000362 unsigned Line = Subprogram.getLineNumber();
363 DL = DebugLoc::get(MF->getOrCreateDebugLocID(SrcFile, Line, 0));
364 }
365 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000366
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000367 break;
368 }
369 }
370 }
371 }
372
373 PN = dyn_cast<PHINode>(I);
374 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000375
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000376 unsigned PHIReg = ValueMap[PN];
377 assert(PHIReg && "PHI node does not have an assigned virtual register!");
378
379 SmallVector<MVT, 4> ValueVTs;
380 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
381 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
382 MVT VT = ValueVTs[vti];
383 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000384 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000385 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000386 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000387 PHIReg += NumRegisters;
388 }
389 }
390 }
391}
392
393unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
394 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
395}
396
397/// CreateRegForValue - Allocate the appropriate number of virtual registers of
398/// the correctly promoted or expanded types. Assign these registers
399/// consecutive vreg numbers and return the first assigned number.
400///
401/// In the case that the given value has struct or array type, this function
402/// will assign registers for each member or element.
403///
404unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
405 SmallVector<MVT, 4> ValueVTs;
406 ComputeValueVTs(TLI, V->getType(), ValueVTs);
407
408 unsigned FirstReg = 0;
409 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
410 MVT ValueVT = ValueVTs[Value];
411 MVT RegisterVT = TLI.getRegisterType(ValueVT);
412
413 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
414 for (unsigned i = 0; i != NumRegs; ++i) {
415 unsigned R = MakeReg(RegisterVT);
416 if (!FirstReg) FirstReg = R;
417 }
418 }
419 return FirstReg;
420}
421
422/// getCopyFromParts - Create a value that contains the specified legal parts
423/// combined into the value they represent. If the parts combine to a type
424/// larger then ValueVT then AssertOp can be used to specify whether the extra
425/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
426/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000427static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
428 const SDValue *Parts,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000429 unsigned NumParts, MVT PartVT, MVT ValueVT,
430 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000431 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000433 SDValue Val = Parts[0];
434
435 if (NumParts > 1) {
436 // Assemble the value from multiple parts.
437 if (!ValueVT.isVector()) {
438 unsigned PartBits = PartVT.getSizeInBits();
439 unsigned ValueBits = ValueVT.getSizeInBits();
440
441 // Assemble the power of 2 part.
442 unsigned RoundParts = NumParts & (NumParts - 1) ?
443 1 << Log2_32(NumParts) : NumParts;
444 unsigned RoundBits = PartBits * RoundParts;
445 MVT RoundVT = RoundBits == ValueBits ?
446 ValueVT : MVT::getIntegerVT(RoundBits);
447 SDValue Lo, Hi;
448
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000449 MVT HalfVT = ValueVT.isInteger() ?
450 MVT::getIntegerVT(RoundBits/2) :
451 MVT::getFloatingPointVT(RoundBits/2);
452
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000453 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000454 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
455 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000456 PartVT, HalfVT);
457 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000458 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
459 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000460 }
461 if (TLI.isBigEndian())
462 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000463 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000464
465 if (RoundParts < NumParts) {
466 // Assemble the trailing non-power-of-2 part.
467 unsigned OddParts = NumParts - RoundParts;
468 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Scott Michelfdc40a02009-02-17 22:15:04 +0000469 Hi = getCopyFromParts(DAG, dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000470 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000471
472 // Combine the round and odd parts.
473 Lo = Val;
474 if (TLI.isBigEndian())
475 std::swap(Lo, Hi);
476 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000477 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
478 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000479 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000480 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000481 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
482 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000483 }
484 } else {
485 // Handle a multi-element vector.
486 MVT IntermediateVT, RegisterVT;
487 unsigned NumIntermediates;
488 unsigned NumRegs =
489 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
490 RegisterVT);
491 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
492 NumParts = NumRegs; // Silence a compiler warning.
493 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
494 assert(RegisterVT == Parts[0].getValueType() &&
495 "Part type doesn't match part!");
496
497 // Assemble the parts into intermediate operands.
498 SmallVector<SDValue, 8> Ops(NumIntermediates);
499 if (NumIntermediates == NumParts) {
500 // If the register was not expanded, truncate or copy the value,
501 // as appropriate.
502 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000503 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000504 PartVT, IntermediateVT);
505 } else if (NumParts > 0) {
506 // If the intermediate type was expanded, build the intermediate operands
507 // from the parts.
508 assert(NumParts % NumIntermediates == 0 &&
509 "Must expand into a divisible number of parts!");
510 unsigned Factor = NumParts / NumIntermediates;
511 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000512 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000513 PartVT, IntermediateVT);
514 }
515
516 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
517 // operands.
518 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000519 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000520 ValueVT, &Ops[0], NumIntermediates);
521 }
522 }
523
524 // There is now one part, held in Val. Correct it to match ValueVT.
525 PartVT = Val.getValueType();
526
527 if (PartVT == ValueVT)
528 return Val;
529
530 if (PartVT.isVector()) {
531 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000532 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000533 }
534
535 if (ValueVT.isVector()) {
536 assert(ValueVT.getVectorElementType() == PartVT &&
537 ValueVT.getVectorNumElements() == 1 &&
538 "Only trivial scalar-to-vector conversions should get here!");
Evan Chenga87008d2009-02-25 22:49:59 +0000539 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000540 }
541
542 if (PartVT.isInteger() &&
543 ValueVT.isInteger()) {
544 if (ValueVT.bitsLT(PartVT)) {
545 // For a truncate, see if we have any information to
546 // indicate whether the truncated bits will always be
547 // zero or sign-extension.
548 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000549 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000550 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000551 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000552 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000553 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000554 }
555 }
556
557 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
558 if (ValueVT.bitsLT(Val.getValueType()))
559 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000560 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000561 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000562 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000563 }
564
565 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000566 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000567
568 assert(0 && "Unknown mismatch!");
569 return SDValue();
570}
571
572/// getCopyToParts - Create a series of nodes that contain the specified value
573/// split into legal parts. If the parts contain more bits than Val, then, for
574/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000575static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Chris Lattner01426e12008-10-21 00:45:36 +0000576 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000577 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000579 MVT PtrVT = TLI.getPointerTy();
580 MVT ValueVT = Val.getValueType();
581 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000582 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000583 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
584
585 if (!NumParts)
586 return;
587
588 if (!ValueVT.isVector()) {
589 if (PartVT == ValueVT) {
590 assert(NumParts == 1 && "No-op copy with multiple parts!");
591 Parts[0] = Val;
592 return;
593 }
594
595 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
596 // If the parts cover more bits than the value has, promote the value.
597 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
598 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000599 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000600 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
601 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000602 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000603 } else {
604 assert(0 && "Unknown mismatch!");
605 }
606 } else if (PartBits == ValueVT.getSizeInBits()) {
607 // Different types of the same size.
608 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000609 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000610 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
611 // If the parts cover less bits than value has, truncate the value.
612 if (PartVT.isInteger() && ValueVT.isInteger()) {
613 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000614 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000615 } else {
616 assert(0 && "Unknown mismatch!");
617 }
618 }
619
620 // The value may have changed - recompute ValueVT.
621 ValueVT = Val.getValueType();
622 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
623 "Failed to tile the value with PartVT!");
624
625 if (NumParts == 1) {
626 assert(PartVT == ValueVT && "Type conversion failed!");
627 Parts[0] = Val;
628 return;
629 }
630
631 // Expand the value into multiple parts.
632 if (NumParts & (NumParts - 1)) {
633 // The number of parts is not a power of 2. Split off and copy the tail.
634 assert(PartVT.isInteger() && ValueVT.isInteger() &&
635 "Do not know what to expand to!");
636 unsigned RoundParts = 1 << Log2_32(NumParts);
637 unsigned RoundBits = RoundParts * PartBits;
638 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000639 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000640 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000641 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000642 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000643 if (TLI.isBigEndian())
644 // The odd parts were reversed by getCopyToParts - unreverse them.
645 std::reverse(Parts + RoundParts, Parts + NumParts);
646 NumParts = RoundParts;
647 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000648 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000649 }
650
651 // The number of parts is a power of 2. Repeatedly bisect the value using
652 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000653 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000654 MVT::getIntegerVT(ValueVT.getSizeInBits()),
655 Val);
656 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
657 for (unsigned i = 0; i < NumParts; i += StepSize) {
658 unsigned ThisBits = StepSize * PartBits / 2;
659 MVT ThisVT = MVT::getIntegerVT (ThisBits);
660 SDValue &Part0 = Parts[i];
661 SDValue &Part1 = Parts[i+StepSize/2];
662
Scott Michelfdc40a02009-02-17 22:15:04 +0000663 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000664 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000665 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000666 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000667 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000668 DAG.getConstant(0, PtrVT));
669
670 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000671 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000672 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000673 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000674 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000675 }
676 }
677 }
678
679 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000680 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000681
682 return;
683 }
684
685 // Vector ValueVT.
686 if (NumParts == 1) {
687 if (PartVT != ValueVT) {
688 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000689 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000690 } else {
691 assert(ValueVT.getVectorElementType() == PartVT &&
692 ValueVT.getVectorNumElements() == 1 &&
693 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000694 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000695 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000696 DAG.getConstant(0, PtrVT));
697 }
698 }
699
700 Parts[0] = Val;
701 return;
702 }
703
704 // Handle a multi-element vector.
705 MVT IntermediateVT, RegisterVT;
706 unsigned NumIntermediates;
Dan Gohmane9530ec2009-01-15 16:58:17 +0000707 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000708 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
709 RegisterVT);
710 unsigned NumElements = ValueVT.getVectorNumElements();
711
712 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
713 NumParts = NumRegs; // Silence a compiler warning.
714 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
715
716 // Split the vector into intermediate operands.
717 SmallVector<SDValue, 8> Ops(NumIntermediates);
718 for (unsigned i = 0; i != NumIntermediates; ++i)
719 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000720 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000721 IntermediateVT, Val,
722 DAG.getConstant(i * (NumElements / NumIntermediates),
723 PtrVT));
724 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000725 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000726 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000727 DAG.getConstant(i, PtrVT));
728
729 // Split the intermediate operands into legal parts.
730 if (NumParts == NumIntermediates) {
731 // If the register was not expanded, promote or copy the value,
732 // as appropriate.
733 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000734 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000735 } else if (NumParts > 0) {
736 // If the intermediate type was expanded, split each the value into
737 // legal parts.
738 assert(NumParts % NumIntermediates == 0 &&
739 "Must expand into a divisible number of parts!");
740 unsigned Factor = NumParts / NumIntermediates;
741 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000742 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000743 }
744}
745
746
747void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
748 AA = &aa;
749 GFI = gfi;
750 TD = DAG.getTarget().getTargetData();
751}
752
753/// clear - Clear out the curret SelectionDAG and the associated
754/// state and prepare this SelectionDAGLowering object to be used
755/// for a new block. This doesn't clear out information about
756/// additional blocks that are needed to complete switch lowering
757/// or PHI node updating; that information is cleared out as it is
758/// consumed.
759void SelectionDAGLowering::clear() {
760 NodeMap.clear();
761 PendingLoads.clear();
762 PendingExports.clear();
763 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000764 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000765}
766
767/// getRoot - Return the current virtual root of the Selection DAG,
768/// flushing any PendingLoad items. This must be done before emitting
769/// a store or any other node that may need to be ordered after any
770/// prior load instructions.
771///
772SDValue SelectionDAGLowering::getRoot() {
773 if (PendingLoads.empty())
774 return DAG.getRoot();
775
776 if (PendingLoads.size() == 1) {
777 SDValue Root = PendingLoads[0];
778 DAG.setRoot(Root);
779 PendingLoads.clear();
780 return Root;
781 }
782
783 // Otherwise, we have to make a token factor node.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000784 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000785 &PendingLoads[0], PendingLoads.size());
786 PendingLoads.clear();
787 DAG.setRoot(Root);
788 return Root;
789}
790
791/// getControlRoot - Similar to getRoot, but instead of flushing all the
792/// PendingLoad items, flush all the PendingExports items. It is necessary
793/// to do this before emitting a terminator instruction.
794///
795SDValue SelectionDAGLowering::getControlRoot() {
796 SDValue Root = DAG.getRoot();
797
798 if (PendingExports.empty())
799 return Root;
800
801 // Turn all of the CopyToReg chains into one factored node.
802 if (Root.getOpcode() != ISD::EntryToken) {
803 unsigned i = 0, e = PendingExports.size();
804 for (; i != e; ++i) {
805 assert(PendingExports[i].getNode()->getNumOperands() > 1);
806 if (PendingExports[i].getNode()->getOperand(0) == Root)
807 break; // Don't add the root if we already indirectly depend on it.
808 }
809
810 if (i == e)
811 PendingExports.push_back(Root);
812 }
813
Dale Johannesen66978ee2009-01-31 02:22:37 +0000814 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000815 &PendingExports[0],
816 PendingExports.size());
817 PendingExports.clear();
818 DAG.setRoot(Root);
819 return Root;
820}
821
822void SelectionDAGLowering::visit(Instruction &I) {
823 visit(I.getOpcode(), I);
824}
825
826void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
827 // Note: this doesn't use InstVisitor, because it has to work with
828 // ConstantExpr's in addition to instructions.
829 switch (Opcode) {
830 default: assert(0 && "Unknown instruction type encountered!");
831 abort();
832 // Build the switch statement using the Instruction.def file.
833#define HANDLE_INST(NUM, OPCODE, CLASS) \
834 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
835#include "llvm/Instruction.def"
836 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000837}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000838
839void SelectionDAGLowering::visitAdd(User &I) {
840 if (I.getType()->isFPOrFPVector())
841 visitBinary(I, ISD::FADD);
842 else
843 visitBinary(I, ISD::ADD);
844}
845
846void SelectionDAGLowering::visitMul(User &I) {
847 if (I.getType()->isFPOrFPVector())
848 visitBinary(I, ISD::FMUL);
849 else
850 visitBinary(I, ISD::MUL);
851}
852
853SDValue SelectionDAGLowering::getValue(const Value *V) {
854 SDValue &N = NodeMap[V];
855 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000856
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000857 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
858 MVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000859
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000860 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000861 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000862
863 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
864 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000865
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000866 if (isa<ConstantPointerNull>(C))
867 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000868
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000869 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000870 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000871
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000872 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
873 !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000874 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000875
876 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
877 visit(CE->getOpcode(), *CE);
878 SDValue N1 = NodeMap[V];
879 assert(N1.getNode() && "visit didn't populate the ValueMap!");
880 return N1;
881 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000882
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000883 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
884 SmallVector<SDValue, 4> Constants;
885 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
886 OI != OE; ++OI) {
887 SDNode *Val = getValue(*OI).getNode();
888 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
889 Constants.push_back(SDValue(Val, i));
890 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000891 return DAG.getMergeValues(&Constants[0], Constants.size(),
892 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000893 }
894
895 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
896 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
897 "Unknown struct or array constant!");
898
899 SmallVector<MVT, 4> ValueVTs;
900 ComputeValueVTs(TLI, C->getType(), ValueVTs);
901 unsigned NumElts = ValueVTs.size();
902 if (NumElts == 0)
903 return SDValue(); // empty struct
904 SmallVector<SDValue, 4> Constants(NumElts);
905 for (unsigned i = 0; i != NumElts; ++i) {
906 MVT EltVT = ValueVTs[i];
907 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000908 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000909 else if (EltVT.isFloatingPoint())
910 Constants[i] = DAG.getConstantFP(0, EltVT);
911 else
912 Constants[i] = DAG.getConstant(0, EltVT);
913 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000914 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000915 }
916
917 const VectorType *VecTy = cast<VectorType>(V->getType());
918 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000919
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000920 // Now that we know the number and type of the elements, get that number of
921 // elements into the Ops array based on what kind of constant it is.
922 SmallVector<SDValue, 16> Ops;
923 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
924 for (unsigned i = 0; i != NumElements; ++i)
925 Ops.push_back(getValue(CP->getOperand(i)));
926 } else {
927 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
928 "Unknown vector constant!");
929 MVT EltVT = TLI.getValueType(VecTy->getElementType());
930
931 SDValue Op;
932 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000933 Op = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000934 else if (EltVT.isFloatingPoint())
935 Op = DAG.getConstantFP(0, EltVT);
936 else
937 Op = DAG.getConstant(0, EltVT);
938 Ops.assign(NumElements, Op);
939 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000940
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000941 // Create a BUILD_VECTOR node.
Evan Chenga87008d2009-02-25 22:49:59 +0000942 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
943 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000944 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000945
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000946 // If this is a static alloca, generate it as the frameindex instead of
947 // computation.
948 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
949 DenseMap<const AllocaInst*, int>::iterator SI =
950 FuncInfo.StaticAllocaMap.find(AI);
951 if (SI != FuncInfo.StaticAllocaMap.end())
952 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
953 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000954
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000955 unsigned InReg = FuncInfo.ValueMap[V];
956 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000957
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000958 RegsForValue RFV(TLI, InReg, V->getType());
959 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000960 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000961}
962
963
964void SelectionDAGLowering::visitRet(ReturnInst &I) {
965 if (I.getNumOperands() == 0) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000966 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000967 MVT::Other, getControlRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000968 return;
969 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000970
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000971 SmallVector<SDValue, 8> NewValues;
972 NewValues.push_back(getControlRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000973 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000974 SmallVector<MVT, 4> ValueVTs;
975 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000976 unsigned NumValues = ValueVTs.size();
977 if (NumValues == 0) continue;
978
979 SDValue RetOp = getValue(I.getOperand(i));
980 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000981 MVT VT = ValueVTs[j];
982
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000983 unsigned NumParts = TLI.getNumRegisters(VT);
984 MVT PartVT = TLI.getRegisterType(VT);
985 SmallVector<SDValue, 4> Parts(NumParts);
986 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000987
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000988 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000989 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000990 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000991 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000992 ExtendKind = ISD::ZERO_EXTEND;
993
Dale Johannesen66978ee2009-01-31 02:22:37 +0000994 getCopyToParts(DAG, getCurDebugLoc(),
995 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000996 &Parts[0], NumParts, PartVT, ExtendKind);
997
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000998 // 'inreg' on function refers to return value
999 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +00001000 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001001 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001002 for (unsigned i = 0; i < NumParts; ++i) {
1003 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001004 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001005 }
1006 }
1007 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00001008 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001009 &NewValues[0], NewValues.size()));
1010}
1011
1012/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1013/// the current basic block, add it to ValueMap now so that we'll get a
1014/// CopyTo/FromReg.
1015void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1016 // No need to export constants.
1017 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001018
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001019 // Already exported?
1020 if (FuncInfo.isExportedInst(V)) return;
1021
1022 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1023 CopyValueToVirtualRegister(V, Reg);
1024}
1025
1026bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1027 const BasicBlock *FromBB) {
1028 // The operands of the setcc have to be in this block. We don't know
1029 // how to export them from some other block.
1030 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1031 // Can export from current BB.
1032 if (VI->getParent() == FromBB)
1033 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001034
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001035 // Is already exported, noop.
1036 return FuncInfo.isExportedInst(V);
1037 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001038
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001039 // If this is an argument, we can export it if the BB is the entry block or
1040 // if it is already exported.
1041 if (isa<Argument>(V)) {
1042 if (FromBB == &FromBB->getParent()->getEntryBlock())
1043 return true;
1044
1045 // Otherwise, can only export this if it is already exported.
1046 return FuncInfo.isExportedInst(V);
1047 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001048
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001049 // Otherwise, constants can always be exported.
1050 return true;
1051}
1052
1053static bool InBlock(const Value *V, const BasicBlock *BB) {
1054 if (const Instruction *I = dyn_cast<Instruction>(V))
1055 return I->getParent() == BB;
1056 return true;
1057}
1058
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001059/// getFCmpCondCode - Return the ISD condition code corresponding to
1060/// the given LLVM IR floating-point condition code. This includes
1061/// consideration of global floating-point math flags.
1062///
1063static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1064 ISD::CondCode FPC, FOC;
1065 switch (Pred) {
1066 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1067 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1068 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1069 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1070 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1071 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1072 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1073 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1074 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1075 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1076 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1077 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1078 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1079 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1080 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1081 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1082 default:
1083 assert(0 && "Invalid FCmp predicate opcode!");
1084 FOC = FPC = ISD::SETFALSE;
1085 break;
1086 }
1087 if (FiniteOnlyFPMath())
1088 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001089 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001090 return FPC;
1091}
1092
1093/// getICmpCondCode - Return the ISD condition code corresponding to
1094/// the given LLVM IR integer condition code.
1095///
1096static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1097 switch (Pred) {
1098 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1099 case ICmpInst::ICMP_NE: return ISD::SETNE;
1100 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1101 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1102 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1103 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1104 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1105 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1106 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1107 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1108 default:
1109 assert(0 && "Invalid ICmp predicate opcode!");
1110 return ISD::SETNE;
1111 }
1112}
1113
Dan Gohmanc2277342008-10-17 21:16:08 +00001114/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1115/// This function emits a branch and is used at the leaves of an OR or an
1116/// AND operator tree.
1117///
1118void
1119SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1120 MachineBasicBlock *TBB,
1121 MachineBasicBlock *FBB,
1122 MachineBasicBlock *CurBB) {
1123 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001124
Dan Gohmanc2277342008-10-17 21:16:08 +00001125 // If the leaf of the tree is a comparison, merge the condition into
1126 // the caseblock.
1127 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1128 // The operands of the cmp have to be in this block. We don't know
1129 // how to export them from some other block. If this is the first block
1130 // of the sequence, no exporting is needed.
1131 if (CurBB == CurMBB ||
1132 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1133 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001134 ISD::CondCode Condition;
1135 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001136 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001137 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001138 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001139 } else {
1140 Condition = ISD::SETEQ; // silence warning.
1141 assert(0 && "Unknown compare instruction");
1142 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001143
1144 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001145 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1146 SwitchCases.push_back(CB);
1147 return;
1148 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001149 }
1150
1151 // Create a CaseBlock record representing this branch.
1152 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1153 NULL, TBB, FBB, CurBB);
1154 SwitchCases.push_back(CB);
1155}
1156
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001157/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001158void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1159 MachineBasicBlock *TBB,
1160 MachineBasicBlock *FBB,
1161 MachineBasicBlock *CurBB,
1162 unsigned Opc) {
1163 // If this node is not part of the or/and tree, emit it as a branch.
1164 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001165 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001166 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1167 BOp->getParent() != CurBB->getBasicBlock() ||
1168 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1169 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1170 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001171 return;
1172 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001173
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001174 // Create TmpBB after CurBB.
1175 MachineFunction::iterator BBI = CurBB;
1176 MachineFunction &MF = DAG.getMachineFunction();
1177 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1178 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001179
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001180 if (Opc == Instruction::Or) {
1181 // Codegen X | Y as:
1182 // jmp_if_X TBB
1183 // jmp TmpBB
1184 // TmpBB:
1185 // jmp_if_Y TBB
1186 // jmp FBB
1187 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001188
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001189 // Emit the LHS condition.
1190 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001191
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001192 // Emit the RHS condition into TmpBB.
1193 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1194 } else {
1195 assert(Opc == Instruction::And && "Unknown merge op!");
1196 // Codegen X & Y as:
1197 // jmp_if_X TmpBB
1198 // jmp FBB
1199 // TmpBB:
1200 // jmp_if_Y TBB
1201 // jmp FBB
1202 //
1203 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001204
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001205 // Emit the LHS condition.
1206 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001207
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001208 // Emit the RHS condition into TmpBB.
1209 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1210 }
1211}
1212
1213/// If the set of cases should be emitted as a series of branches, return true.
1214/// If we should emit this as a bunch of and/or'd together conditions, return
1215/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001216bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001217SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1218 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001219
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001220 // If this is two comparisons of the same values or'd or and'd together, they
1221 // will get folded into a single comparison, so don't emit two blocks.
1222 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1223 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1224 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1225 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1226 return false;
1227 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001228
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001229 return true;
1230}
1231
1232void SelectionDAGLowering::visitBr(BranchInst &I) {
1233 // Update machine-CFG edges.
1234 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1235
1236 // Figure out which block is immediately after the current one.
1237 MachineBasicBlock *NextBlock = 0;
1238 MachineFunction::iterator BBI = CurMBB;
1239 if (++BBI != CurMBB->getParent()->end())
1240 NextBlock = BBI;
1241
1242 if (I.isUnconditional()) {
1243 // Update machine-CFG edges.
1244 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001245
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001246 // If this is not a fall-through branch, emit the branch.
1247 if (Succ0MBB != NextBlock)
Scott Michelfdc40a02009-02-17 22:15:04 +00001248 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001249 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001250 DAG.getBasicBlock(Succ0MBB)));
1251 return;
1252 }
1253
1254 // If this condition is one of the special cases we handle, do special stuff
1255 // now.
1256 Value *CondVal = I.getCondition();
1257 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1258
1259 // If this is a series of conditions that are or'd or and'd together, emit
1260 // this as a sequence of branches instead of setcc's with and/or operations.
1261 // For example, instead of something like:
1262 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001263 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001264 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001265 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001266 // or C, F
1267 // jnz foo
1268 // Emit:
1269 // cmp A, B
1270 // je foo
1271 // cmp D, E
1272 // jle foo
1273 //
1274 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001275 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001276 (BOp->getOpcode() == Instruction::And ||
1277 BOp->getOpcode() == Instruction::Or)) {
1278 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1279 // If the compares in later blocks need to use values not currently
1280 // exported from this block, export them now. This block should always
1281 // be the first entry.
1282 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001283
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001284 // Allow some cases to be rejected.
1285 if (ShouldEmitAsBranches(SwitchCases)) {
1286 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1287 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1288 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1289 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001290
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001291 // Emit the branch for this block.
1292 visitSwitchCase(SwitchCases[0]);
1293 SwitchCases.erase(SwitchCases.begin());
1294 return;
1295 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001296
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001297 // Okay, we decided not to do this, remove any inserted MBB's and clear
1298 // SwitchCases.
1299 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1300 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001301
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001302 SwitchCases.clear();
1303 }
1304 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001305
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001306 // Create a CaseBlock record representing this branch.
1307 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1308 NULL, Succ0MBB, Succ1MBB, CurMBB);
1309 // Use visitSwitchCase to actually insert the fast branch sequence for this
1310 // cond branch.
1311 visitSwitchCase(CB);
1312}
1313
1314/// visitSwitchCase - Emits the necessary code to represent a single node in
1315/// the binary search tree resulting from lowering a switch instruction.
1316void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1317 SDValue Cond;
1318 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001319 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001320
1321 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001322 if (CB.CmpMHS == NULL) {
1323 // Fold "(X == true)" to X and "(X == false)" to !X to
1324 // handle common cases produced by branch lowering.
1325 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1326 Cond = CondLHS;
1327 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1328 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001329 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001330 } else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001331 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001332 } else {
1333 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1334
Anton Korobeynikov23218582008-12-23 22:25:27 +00001335 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1336 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001337
1338 SDValue CmpOp = getValue(CB.CmpMHS);
1339 MVT VT = CmpOp.getValueType();
1340
1341 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00001342 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001343 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001344 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001345 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001346 VT, CmpOp, DAG.getConstant(Low, VT));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001347 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001348 DAG.getConstant(High-Low, VT), ISD::SETULE);
1349 }
1350 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001351
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001352 // Update successor info
1353 CurMBB->addSuccessor(CB.TrueBB);
1354 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001355
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001356 // Set NextBlock to be the MBB immediately after the current one, if any.
1357 // This is used to avoid emitting unnecessary branches to the next block.
1358 MachineBasicBlock *NextBlock = 0;
1359 MachineFunction::iterator BBI = CurMBB;
1360 if (++BBI != CurMBB->getParent()->end())
1361 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001362
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001363 // If the lhs block is the next block, invert the condition so that we can
1364 // fall through to the lhs instead of the rhs block.
1365 if (CB.TrueBB == NextBlock) {
1366 std::swap(CB.TrueBB, CB.FalseBB);
1367 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001368 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001369 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001370 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001371 MVT::Other, getControlRoot(), Cond,
1372 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001373
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001374 // If the branch was constant folded, fix up the CFG.
1375 if (BrCond.getOpcode() == ISD::BR) {
1376 CurMBB->removeSuccessor(CB.FalseBB);
1377 DAG.setRoot(BrCond);
1378 } else {
1379 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001380 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001381 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001382
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001383 if (CB.FalseBB == NextBlock)
1384 DAG.setRoot(BrCond);
1385 else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001386 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001387 DAG.getBasicBlock(CB.FalseBB)));
1388 }
1389}
1390
1391/// visitJumpTable - Emit JumpTable node in the current MBB
1392void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1393 // Emit the code for the jump table
1394 assert(JT.Reg != -1U && "Should lower JT Header first!");
1395 MVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001396 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1397 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001398 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Scott Michelfdc40a02009-02-17 22:15:04 +00001399 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001400 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001401 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001402}
1403
1404/// visitJumpTableHeader - This function emits necessary code to produce index
1405/// in the JumpTable from switch case.
1406void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1407 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001408 // Subtract the lowest switch case value from the value being switched on and
1409 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001410 // difference between smallest and largest cases.
1411 SDValue SwitchOp = getValue(JTH.SValue);
1412 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001413 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001414 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001415
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001416 // The SDNode we just created, which holds the value being switched on minus
1417 // the the smallest case value, needs to be copied to a virtual register so it
1418 // can be used as an index into the jump table in a subsequent basic block.
1419 // This value may be smaller or larger than the target's pointer type, and
1420 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001421 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001422 SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001423 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001424 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001425 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001426 TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001427
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001428 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001429 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1430 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001431 JT.Reg = JumpTableReg;
1432
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001433 // Emit the range check for the jump table, and branch to the default block
1434 // for the switch statement if the value being switched on exceeds the largest
1435 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001436 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1437 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001438 DAG.getConstant(JTH.Last-JTH.First,VT),
1439 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001440
1441 // Set NextBlock to be the MBB immediately after the current one, if any.
1442 // This is used to avoid emitting unnecessary branches to the next block.
1443 MachineBasicBlock *NextBlock = 0;
1444 MachineFunction::iterator BBI = CurMBB;
1445 if (++BBI != CurMBB->getParent()->end())
1446 NextBlock = BBI;
1447
Dale Johannesen66978ee2009-01-31 02:22:37 +00001448 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001449 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001450 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001451
1452 if (JT.MBB == NextBlock)
1453 DAG.setRoot(BrCond);
1454 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001455 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001456 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001457}
1458
1459/// visitBitTestHeader - This function emits necessary code to produce value
1460/// suitable for "bit tests"
1461void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1462 // Subtract the minimum value
1463 SDValue SwitchOp = getValue(B.SValue);
1464 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001465 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001466 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001467
1468 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001469 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1470 TLI.getSetCCResultType(SUB.getValueType()),
1471 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001472 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001473
1474 SDValue ShiftOp;
Duncan Sands92abc622009-01-31 15:50:11 +00001475 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001476 ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001477 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001478 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001479 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001480 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001481
Duncan Sands92abc622009-01-31 15:50:11 +00001482 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001483 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1484 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001485
1486 // Set NextBlock to be the MBB immediately after the current one, if any.
1487 // This is used to avoid emitting unnecessary branches to the next block.
1488 MachineBasicBlock *NextBlock = 0;
1489 MachineFunction::iterator BBI = CurMBB;
1490 if (++BBI != CurMBB->getParent()->end())
1491 NextBlock = BBI;
1492
1493 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1494
1495 CurMBB->addSuccessor(B.Default);
1496 CurMBB->addSuccessor(MBB);
1497
Dale Johannesen66978ee2009-01-31 02:22:37 +00001498 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001499 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001500 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001501
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001502 if (MBB == NextBlock)
1503 DAG.setRoot(BrRange);
1504 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001505 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001506 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001507}
1508
1509/// visitBitTestCase - this function produces one "bit test"
1510void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1511 unsigned Reg,
1512 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001513 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001514 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001515 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001516 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001517 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001518 DAG.getConstant(1, TLI.getPointerTy()),
1519 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001520
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001521 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001522 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001523 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001524 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001525 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1526 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001527 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001528 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001529
1530 CurMBB->addSuccessor(B.TargetBB);
1531 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001532
Dale Johannesen66978ee2009-01-31 02:22:37 +00001533 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001534 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001535 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001536
1537 // Set NextBlock to be the MBB immediately after the current one, if any.
1538 // This is used to avoid emitting unnecessary branches to the next block.
1539 MachineBasicBlock *NextBlock = 0;
1540 MachineFunction::iterator BBI = CurMBB;
1541 if (++BBI != CurMBB->getParent()->end())
1542 NextBlock = BBI;
1543
1544 if (NextMBB == NextBlock)
1545 DAG.setRoot(BrAnd);
1546 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001547 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001548 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001549}
1550
1551void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1552 // Retrieve successors.
1553 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1554 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1555
Gabor Greifb67e6b32009-01-15 11:10:44 +00001556 const Value *Callee(I.getCalledValue());
1557 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001558 visitInlineAsm(&I);
1559 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001560 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001561
1562 // If the value of the invoke is used outside of its defining block, make it
1563 // available as a virtual register.
1564 if (!I.use_empty()) {
1565 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1566 if (VMI != FuncInfo.ValueMap.end())
1567 CopyValueToVirtualRegister(&I, VMI->second);
1568 }
1569
1570 // Update successor info
1571 CurMBB->addSuccessor(Return);
1572 CurMBB->addSuccessor(LandingPad);
1573
1574 // Drop into normal successor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001575 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001576 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001577 DAG.getBasicBlock(Return)));
1578}
1579
1580void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1581}
1582
1583/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1584/// small case ranges).
1585bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1586 CaseRecVector& WorkList,
1587 Value* SV,
1588 MachineBasicBlock* Default) {
1589 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001590
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001591 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001592 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001593 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001594 return false;
1595
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001596 // Get the MachineFunction which holds the current MBB. This is used when
1597 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001598 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001599
1600 // Figure out which block is immediately after the current one.
1601 MachineBasicBlock *NextBlock = 0;
1602 MachineFunction::iterator BBI = CR.CaseBB;
1603
1604 if (++BBI != CurMBB->getParent()->end())
1605 NextBlock = BBI;
1606
1607 // TODO: If any two of the cases has the same destination, and if one value
1608 // is the same as the other, but has one bit unset that the other has set,
1609 // use bit manipulation to do two compares at once. For example:
1610 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001611
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001612 // Rearrange the case blocks so that the last one falls through if possible.
1613 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1614 // The last case block won't fall through into 'NextBlock' if we emit the
1615 // branches in this order. See if rearranging a case value would help.
1616 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1617 if (I->BB == NextBlock) {
1618 std::swap(*I, BackCase);
1619 break;
1620 }
1621 }
1622 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001623
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001624 // Create a CaseBlock record representing a conditional branch to
1625 // the Case's target mbb if the value being switched on SV is equal
1626 // to C.
1627 MachineBasicBlock *CurBlock = CR.CaseBB;
1628 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1629 MachineBasicBlock *FallThrough;
1630 if (I != E-1) {
1631 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1632 CurMF->insert(BBI, FallThrough);
1633 } else {
1634 // If the last case doesn't match, go to the default block.
1635 FallThrough = Default;
1636 }
1637
1638 Value *RHS, *LHS, *MHS;
1639 ISD::CondCode CC;
1640 if (I->High == I->Low) {
1641 // This is just small small case range :) containing exactly 1 case
1642 CC = ISD::SETEQ;
1643 LHS = SV; RHS = I->High; MHS = NULL;
1644 } else {
1645 CC = ISD::SETLE;
1646 LHS = I->Low; MHS = SV; RHS = I->High;
1647 }
1648 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001649
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001650 // If emitting the first comparison, just call visitSwitchCase to emit the
1651 // code into the current block. Otherwise, push the CaseBlock onto the
1652 // vector to be later processed by SDISel, and insert the node's MBB
1653 // before the next MBB.
1654 if (CurBlock == CurMBB)
1655 visitSwitchCase(CB);
1656 else
1657 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001658
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001659 CurBlock = FallThrough;
1660 }
1661
1662 return true;
1663}
1664
1665static inline bool areJTsAllowed(const TargetLowering &TLI) {
1666 return !DisableJumpTables &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00001667 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1668 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001669}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001670
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001671static APInt ComputeRange(const APInt &First, const APInt &Last) {
1672 APInt LastExt(Last), FirstExt(First);
1673 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1674 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1675 return (LastExt - FirstExt + 1ULL);
1676}
1677
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001678/// handleJTSwitchCase - Emit jumptable for current switch case range
1679bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1680 CaseRecVector& WorkList,
1681 Value* SV,
1682 MachineBasicBlock* Default) {
1683 Case& FrontCase = *CR.Range.first;
1684 Case& BackCase = *(CR.Range.second-1);
1685
Anton Korobeynikov23218582008-12-23 22:25:27 +00001686 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1687 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001688
Anton Korobeynikov23218582008-12-23 22:25:27 +00001689 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001690 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1691 I!=E; ++I)
1692 TSize += I->size();
1693
1694 if (!areJTsAllowed(TLI) || TSize <= 3)
1695 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001696
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001697 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001698 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001699 if (Density < 0.4)
1700 return false;
1701
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001702 DEBUG(errs() << "Lowering jump table\n"
1703 << "First entry: " << First << ". Last entry: " << Last << '\n'
1704 << "Range: " << Range
1705 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001706
1707 // Get the MachineFunction which holds the current MBB. This is used when
1708 // inserting any additional MBBs necessary to represent the switch.
1709 MachineFunction *CurMF = CurMBB->getParent();
1710
1711 // Figure out which block is immediately after the current one.
1712 MachineBasicBlock *NextBlock = 0;
1713 MachineFunction::iterator BBI = CR.CaseBB;
1714
1715 if (++BBI != CurMBB->getParent()->end())
1716 NextBlock = BBI;
1717
1718 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1719
1720 // Create a new basic block to hold the code for loading the address
1721 // of the jump table, and jumping to it. Update successor information;
1722 // we will either branch to the default case for the switch, or the jump
1723 // table.
1724 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1725 CurMF->insert(BBI, JumpTableBB);
1726 CR.CaseBB->addSuccessor(Default);
1727 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001728
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001729 // Build a vector of destination BBs, corresponding to each target
1730 // of the jump table. If the value of the jump table slot corresponds to
1731 // a case statement, push the case's BB onto the vector, otherwise, push
1732 // the default BB.
1733 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001734 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001735 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001736 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1737 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1738
1739 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001740 DestBBs.push_back(I->BB);
1741 if (TEI==High)
1742 ++I;
1743 } else {
1744 DestBBs.push_back(Default);
1745 }
1746 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001747
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001748 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001749 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1750 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001751 E = DestBBs.end(); I != E; ++I) {
1752 if (!SuccsHandled[(*I)->getNumber()]) {
1753 SuccsHandled[(*I)->getNumber()] = true;
1754 JumpTableBB->addSuccessor(*I);
1755 }
1756 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001757
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001758 // Create a jump table index for this jump table, or return an existing
1759 // one.
1760 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001761
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001762 // Set the jump table information so that we can codegen it as a second
1763 // MachineBasicBlock
1764 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1765 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1766 if (CR.CaseBB == CurMBB)
1767 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001768
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001769 JTCases.push_back(JumpTableBlock(JTH, JT));
1770
1771 return true;
1772}
1773
1774/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1775/// 2 subtrees.
1776bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1777 CaseRecVector& WorkList,
1778 Value* SV,
1779 MachineBasicBlock* Default) {
1780 // Get the MachineFunction which holds the current MBB. This is used when
1781 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001782 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001783
1784 // Figure out which block is immediately after the current one.
1785 MachineBasicBlock *NextBlock = 0;
1786 MachineFunction::iterator BBI = CR.CaseBB;
1787
1788 if (++BBI != CurMBB->getParent()->end())
1789 NextBlock = BBI;
1790
1791 Case& FrontCase = *CR.Range.first;
1792 Case& BackCase = *(CR.Range.second-1);
1793 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1794
1795 // Size is the number of Cases represented by this range.
1796 unsigned Size = CR.Range.second - CR.Range.first;
1797
Anton Korobeynikov23218582008-12-23 22:25:27 +00001798 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1799 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001800 double FMetric = 0;
1801 CaseItr Pivot = CR.Range.first + Size/2;
1802
1803 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1804 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001805 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001806 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1807 I!=E; ++I)
1808 TSize += I->size();
1809
Anton Korobeynikov23218582008-12-23 22:25:27 +00001810 size_t LSize = FrontCase.size();
1811 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001812 DEBUG(errs() << "Selecting best pivot: \n"
1813 << "First: " << First << ", Last: " << Last <<'\n'
1814 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001815 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1816 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001817 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1818 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001819 APInt Range = ComputeRange(LEnd, RBegin);
1820 assert((Range - 2ULL).isNonNegative() &&
1821 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001822 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1823 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001824 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001825 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001826 DEBUG(errs() <<"=>Step\n"
1827 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1828 << "LDensity: " << LDensity
1829 << ", RDensity: " << RDensity << '\n'
1830 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001831 if (FMetric < Metric) {
1832 Pivot = J;
1833 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001834 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001835 }
1836
1837 LSize += J->size();
1838 RSize -= J->size();
1839 }
1840 if (areJTsAllowed(TLI)) {
1841 // If our case is dense we *really* should handle it earlier!
1842 assert((FMetric > 0) && "Should handle dense range earlier!");
1843 } else {
1844 Pivot = CR.Range.first + Size/2;
1845 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001846
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001847 CaseRange LHSR(CR.Range.first, Pivot);
1848 CaseRange RHSR(Pivot, CR.Range.second);
1849 Constant *C = Pivot->Low;
1850 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001851
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001852 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001853 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001854 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001855 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001856 // Pivot's Value, then we can branch directly to the LHS's Target,
1857 // rather than creating a leaf node for it.
1858 if ((LHSR.second - LHSR.first) == 1 &&
1859 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001860 cast<ConstantInt>(C)->getValue() ==
1861 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001862 TrueBB = LHSR.first->BB;
1863 } else {
1864 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1865 CurMF->insert(BBI, TrueBB);
1866 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1867 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001868
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001869 // Similar to the optimization above, if the Value being switched on is
1870 // known to be less than the Constant CR.LT, and the current Case Value
1871 // is CR.LT - 1, then we can branch directly to the target block for
1872 // the current Case Value, rather than emitting a RHS leaf node for it.
1873 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001874 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1875 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001876 FalseBB = RHSR.first->BB;
1877 } else {
1878 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1879 CurMF->insert(BBI, FalseBB);
1880 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1881 }
1882
1883 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001884 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001885 // Otherwise, branch to LHS.
1886 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1887
1888 if (CR.CaseBB == CurMBB)
1889 visitSwitchCase(CB);
1890 else
1891 SwitchCases.push_back(CB);
1892
1893 return true;
1894}
1895
1896/// handleBitTestsSwitchCase - if current case range has few destination and
1897/// range span less, than machine word bitwidth, encode case range into series
1898/// of masks and emit bit tests with these masks.
1899bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1900 CaseRecVector& WorkList,
1901 Value* SV,
1902 MachineBasicBlock* Default){
1903 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1904
1905 Case& FrontCase = *CR.Range.first;
1906 Case& BackCase = *(CR.Range.second-1);
1907
1908 // Get the MachineFunction which holds the current MBB. This is used when
1909 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001910 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001911
Anton Korobeynikov23218582008-12-23 22:25:27 +00001912 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001913 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1914 I!=E; ++I) {
1915 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001916 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001917 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001918
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001919 // Count unique destinations
1920 SmallSet<MachineBasicBlock*, 4> Dests;
1921 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1922 Dests.insert(I->BB);
1923 if (Dests.size() > 3)
1924 // Don't bother the code below, if there are too much unique destinations
1925 return false;
1926 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001927 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1928 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001929
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001930 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001931 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1932 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001933 APInt cmpRange = maxValue - minValue;
1934
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001935 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1936 << "Low bound: " << minValue << '\n'
1937 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001938
1939 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001940 (!(Dests.size() == 1 && numCmps >= 3) &&
1941 !(Dests.size() == 2 && numCmps >= 5) &&
1942 !(Dests.size() >= 3 && numCmps >= 6)))
1943 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001944
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001945 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001946 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1947
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001948 // Optimize the case where all the case values fit in a
1949 // word without having to subtract minValue. In this case,
1950 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001951 if (minValue.isNonNegative() &&
1952 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1953 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001954 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001955 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001956 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001957
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001958 CaseBitsVector CasesBits;
1959 unsigned i, count = 0;
1960
1961 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1962 MachineBasicBlock* Dest = I->BB;
1963 for (i = 0; i < count; ++i)
1964 if (Dest == CasesBits[i].BB)
1965 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001966
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001967 if (i == count) {
1968 assert((count < 3) && "Too much destinations to test!");
1969 CasesBits.push_back(CaseBits(0, Dest, 0));
1970 count++;
1971 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001972
1973 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1974 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1975
1976 uint64_t lo = (lowValue - lowBound).getZExtValue();
1977 uint64_t hi = (highValue - lowBound).getZExtValue();
1978
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001979 for (uint64_t j = lo; j <= hi; j++) {
1980 CasesBits[i].Mask |= 1ULL << j;
1981 CasesBits[i].Bits++;
1982 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001983
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001984 }
1985 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001986
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001987 BitTestInfo BTC;
1988
1989 // Figure out which block is immediately after the current one.
1990 MachineFunction::iterator BBI = CR.CaseBB;
1991 ++BBI;
1992
1993 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1994
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001995 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001996 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001997 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1998 << ", Bits: " << CasesBits[i].Bits
1999 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002000
2001 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2002 CurMF->insert(BBI, CaseBB);
2003 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2004 CaseBB,
2005 CasesBits[i].BB));
2006 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002007
2008 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002009 -1U, (CR.CaseBB == CurMBB),
2010 CR.CaseBB, Default, BTC);
2011
2012 if (CR.CaseBB == CurMBB)
2013 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002014
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002015 BitTestCases.push_back(BTB);
2016
2017 return true;
2018}
2019
2020
2021/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002022size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002023 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002024 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002025
2026 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002027 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002028 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2029 Cases.push_back(Case(SI.getSuccessorValue(i),
2030 SI.getSuccessorValue(i),
2031 SMBB));
2032 }
2033 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2034
2035 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002036 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002037 // Must recompute end() each iteration because it may be
2038 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002039 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2040 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2041 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002042 MachineBasicBlock* nextBB = J->BB;
2043 MachineBasicBlock* currentBB = I->BB;
2044
2045 // If the two neighboring cases go to the same destination, merge them
2046 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002047 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002048 I->High = J->High;
2049 J = Cases.erase(J);
2050 } else {
2051 I = J++;
2052 }
2053 }
2054
2055 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2056 if (I->Low != I->High)
2057 // A range counts double, since it requires two compares.
2058 ++numCmps;
2059 }
2060
2061 return numCmps;
2062}
2063
Anton Korobeynikov23218582008-12-23 22:25:27 +00002064void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002065 // Figure out which block is immediately after the current one.
2066 MachineBasicBlock *NextBlock = 0;
2067 MachineFunction::iterator BBI = CurMBB;
2068
2069 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2070
2071 // If there is only the default destination, branch to it if it is not the
2072 // next basic block. Otherwise, just fall through.
2073 if (SI.getNumOperands() == 2) {
2074 // Update machine-CFG edges.
2075
2076 // If this is not a fall-through branch, emit the branch.
2077 CurMBB->addSuccessor(Default);
2078 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002079 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002080 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002081 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002082 return;
2083 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002084
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002085 // If there are any non-default case statements, create a vector of Cases
2086 // representing each one, and sort the vector so that we can efficiently
2087 // create a binary search tree from them.
2088 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002089 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002090 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2091 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002092 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002093
2094 // Get the Value to be switched on and default basic blocks, which will be
2095 // inserted into CaseBlock records, representing basic blocks in the binary
2096 // search tree.
2097 Value *SV = SI.getOperand(0);
2098
2099 // Push the initial CaseRec onto the worklist
2100 CaseRecVector WorkList;
2101 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2102
2103 while (!WorkList.empty()) {
2104 // Grab a record representing a case range to process off the worklist
2105 CaseRec CR = WorkList.back();
2106 WorkList.pop_back();
2107
2108 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2109 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002110
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002111 // If the range has few cases (two or less) emit a series of specific
2112 // tests.
2113 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2114 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002115
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002116 // If the switch has more than 5 blocks, and at least 40% dense, and the
2117 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002118 // lowering the switch to a binary tree of conditional branches.
2119 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2120 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002121
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002122 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2123 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2124 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2125 }
2126}
2127
2128
2129void SelectionDAGLowering::visitSub(User &I) {
2130 // -0.0 - X --> fneg
2131 const Type *Ty = I.getType();
2132 if (isa<VectorType>(Ty)) {
2133 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2134 const VectorType *DestTy = cast<VectorType>(I.getType());
2135 const Type *ElTy = DestTy->getElementType();
2136 if (ElTy->isFloatingPoint()) {
2137 unsigned VL = DestTy->getNumElements();
2138 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2139 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2140 if (CV == CNZ) {
2141 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002142 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002143 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002144 return;
2145 }
2146 }
2147 }
2148 }
2149 if (Ty->isFloatingPoint()) {
2150 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2151 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2152 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002153 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002154 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002155 return;
2156 }
2157 }
2158
2159 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2160}
2161
2162void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2163 SDValue Op1 = getValue(I.getOperand(0));
2164 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002165
Scott Michelfdc40a02009-02-17 22:15:04 +00002166 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002167 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002168}
2169
2170void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2171 SDValue Op1 = getValue(I.getOperand(0));
2172 SDValue Op2 = getValue(I.getOperand(1));
2173 if (!isa<VectorType>(I.getType())) {
Duncan Sands92abc622009-01-31 15:50:11 +00002174 if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002175 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002176 TLI.getPointerTy(), Op2);
2177 else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002178 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002179 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002180 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002181
Scott Michelfdc40a02009-02-17 22:15:04 +00002182 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002183 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002184}
2185
2186void SelectionDAGLowering::visitICmp(User &I) {
2187 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2188 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2189 predicate = IC->getPredicate();
2190 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2191 predicate = ICmpInst::Predicate(IC->getPredicate());
2192 SDValue Op1 = getValue(I.getOperand(0));
2193 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002194 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002195 setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002196}
2197
2198void SelectionDAGLowering::visitFCmp(User &I) {
2199 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2200 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2201 predicate = FC->getPredicate();
2202 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2203 predicate = FCmpInst::Predicate(FC->getPredicate());
2204 SDValue Op1 = getValue(I.getOperand(0));
2205 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002206 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002207 setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002208}
2209
2210void SelectionDAGLowering::visitVICmp(User &I) {
2211 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2212 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2213 predicate = IC->getPredicate();
2214 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2215 predicate = ICmpInst::Predicate(IC->getPredicate());
2216 SDValue Op1 = getValue(I.getOperand(0));
2217 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002218 ISD::CondCode Opcode = getICmpCondCode(predicate);
Scott Michelfdc40a02009-02-17 22:15:04 +00002219 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
Dale Johannesenf5d97892009-02-04 01:48:28 +00002220 Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002221}
2222
2223void SelectionDAGLowering::visitVFCmp(User &I) {
2224 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2225 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2226 predicate = FC->getPredicate();
2227 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2228 predicate = FCmpInst::Predicate(FC->getPredicate());
2229 SDValue Op1 = getValue(I.getOperand(0));
2230 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002231 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002232 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002233
Dale Johannesenf5d97892009-02-04 01:48:28 +00002234 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002235}
2236
2237void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002238 SmallVector<MVT, 4> ValueVTs;
2239 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2240 unsigned NumValues = ValueVTs.size();
2241 if (NumValues != 0) {
2242 SmallVector<SDValue, 4> Values(NumValues);
2243 SDValue Cond = getValue(I.getOperand(0));
2244 SDValue TrueVal = getValue(I.getOperand(1));
2245 SDValue FalseVal = getValue(I.getOperand(2));
2246
2247 for (unsigned i = 0; i != NumValues; ++i)
Scott Michelfdc40a02009-02-17 22:15:04 +00002248 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002249 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002250 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2251 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2252
Scott Michelfdc40a02009-02-17 22:15:04 +00002253 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002254 DAG.getVTList(&ValueVTs[0], NumValues),
2255 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002256 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002257}
2258
2259
2260void SelectionDAGLowering::visitTrunc(User &I) {
2261 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2262 SDValue N = getValue(I.getOperand(0));
2263 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002264 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002265}
2266
2267void SelectionDAGLowering::visitZExt(User &I) {
2268 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2269 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2270 SDValue N = getValue(I.getOperand(0));
2271 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002272 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002273}
2274
2275void SelectionDAGLowering::visitSExt(User &I) {
2276 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2277 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2278 SDValue N = getValue(I.getOperand(0));
2279 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002280 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002281}
2282
2283void SelectionDAGLowering::visitFPTrunc(User &I) {
2284 // FPTrunc is never a no-op cast, no need to check
2285 SDValue N = getValue(I.getOperand(0));
2286 MVT DestVT = TLI.getValueType(I.getType());
Scott Michelfdc40a02009-02-17 22:15:04 +00002287 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002288 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002289}
2290
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002291void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002292 // FPTrunc is never a no-op cast, no need to check
2293 SDValue N = getValue(I.getOperand(0));
2294 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002295 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002296}
2297
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002298void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002299 // FPToUI is never a no-op cast, no need to check
2300 SDValue N = getValue(I.getOperand(0));
2301 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002302 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002303}
2304
2305void SelectionDAGLowering::visitFPToSI(User &I) {
2306 // FPToSI is never a no-op cast, no need to check
2307 SDValue N = getValue(I.getOperand(0));
2308 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002309 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002310}
2311
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002312void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002313 // UIToFP is never a no-op cast, no need to check
2314 SDValue N = getValue(I.getOperand(0));
2315 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002316 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002317}
2318
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002319void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002320 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002321 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::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002324}
2325
2326void SelectionDAGLowering::visitPtrToInt(User &I) {
2327 // What to do depends on the size of the integer and the size of the pointer.
2328 // We can either truncate, zero extend, or no-op, accordingly.
2329 SDValue N = getValue(I.getOperand(0));
2330 MVT SrcVT = N.getValueType();
2331 MVT DestVT = TLI.getValueType(I.getType());
2332 SDValue Result;
2333 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002334 Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002335 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002336 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Dale Johannesen66978ee2009-01-31 02:22:37 +00002337 Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002338 setValue(&I, Result);
2339}
2340
2341void SelectionDAGLowering::visitIntToPtr(User &I) {
2342 // What to do depends on the size of the integer and the size of the pointer.
2343 // We can either truncate, zero extend, or no-op, accordingly.
2344 SDValue N = getValue(I.getOperand(0));
2345 MVT SrcVT = N.getValueType();
2346 MVT DestVT = TLI.getValueType(I.getType());
2347 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002348 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002349 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002350 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Scott Michelfdc40a02009-02-17 22:15:04 +00002351 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002352 DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002353}
2354
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002355void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002356 SDValue N = getValue(I.getOperand(0));
2357 MVT DestVT = TLI.getValueType(I.getType());
2358
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002359 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002360 // is either a BIT_CONVERT or a no-op.
2361 if (DestVT != N.getValueType())
Scott Michelfdc40a02009-02-17 22:15:04 +00002362 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002363 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002364 else
2365 setValue(&I, N); // noop cast.
2366}
2367
2368void SelectionDAGLowering::visitInsertElement(User &I) {
2369 SDValue InVec = getValue(I.getOperand(0));
2370 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002371 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002372 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002373 getValue(I.getOperand(2)));
2374
Scott Michelfdc40a02009-02-17 22:15:04 +00002375 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002376 TLI.getValueType(I.getType()),
2377 InVec, InVal, InIdx));
2378}
2379
2380void SelectionDAGLowering::visitExtractElement(User &I) {
2381 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002382 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002383 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002384 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002385 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002386 TLI.getValueType(I.getType()), InVec, InIdx));
2387}
2388
Mon P Wangaeb06d22008-11-10 04:46:22 +00002389
2390// Utility for visitShuffleVector - Returns true if the mask is mask starting
2391// from SIndx and increasing to the element length (undefs are allowed).
2392static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002393 unsigned MaskNumElts = Mask.getNumOperands();
2394 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002395 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2396 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2397 if (Idx != i + SIndx)
2398 return false;
2399 }
2400 }
2401 return true;
2402}
2403
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002404void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002405 SDValue Src1 = getValue(I.getOperand(0));
2406 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002407 SDValue Mask = getValue(I.getOperand(2));
2408
Mon P Wangaeb06d22008-11-10 04:46:22 +00002409 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002410 MVT SrcVT = Src1.getValueType();
Mon P Wangc7849c22008-11-16 05:06:27 +00002411 int MaskNumElts = Mask.getNumOperands();
2412 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002413
Mon P Wangc7849c22008-11-16 05:06:27 +00002414 if (SrcNumElts == MaskNumElts) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002415 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002416 VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002417 return;
2418 }
2419
2420 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002421 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2422
2423 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2424 // Mask is longer than the source vectors and is a multiple of the source
2425 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002426 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002427 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2428 // The shuffle is concatenating two vectors together.
Scott Michelfdc40a02009-02-17 22:15:04 +00002429 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002430 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002431 return;
2432 }
2433
Mon P Wangc7849c22008-11-16 05:06:27 +00002434 // Pad both vectors with undefs to make them the same length as the mask.
2435 unsigned NumConcat = MaskNumElts / SrcNumElts;
Dale Johannesene8d72302009-02-06 23:05:02 +00002436 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002437
Mon P Wang230e4fa2008-11-21 04:25:21 +00002438 SDValue* MOps1 = new SDValue[NumConcat];
2439 SDValue* MOps2 = new SDValue[NumConcat];
2440 MOps1[0] = Src1;
2441 MOps2[0] = Src2;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002442 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002443 MOps1[i] = UndefVal;
2444 MOps2[i] = UndefVal;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002445 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002446 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002447 VT, MOps1, NumConcat);
Scott Michelfdc40a02009-02-17 22:15:04 +00002448 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002449 VT, MOps2, NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002450
2451 delete [] MOps1;
2452 delete [] MOps2;
2453
Mon P Wangaeb06d22008-11-10 04:46:22 +00002454 // Readjust mask for new input vector length.
2455 SmallVector<SDValue, 8> MappedOps;
Mon P Wangc7849c22008-11-16 05:06:27 +00002456 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002457 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2458 MappedOps.push_back(Mask.getOperand(i));
2459 } else {
Mon P Wangc7849c22008-11-16 05:06:27 +00002460 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2461 if (Idx < SrcNumElts)
2462 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2463 else
2464 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2465 MaskEltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002466 }
2467 }
Evan Chenga87008d2009-02-25 22:49:59 +00002468 Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2469 Mask.getValueType(),
2470 &MappedOps[0], MappedOps.size());
Mon P Wangaeb06d22008-11-10 04:46:22 +00002471
Scott Michelfdc40a02009-02-17 22:15:04 +00002472 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002473 VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002474 return;
2475 }
2476
Mon P Wangc7849c22008-11-16 05:06:27 +00002477 if (SrcNumElts > MaskNumElts) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002478 // Resulting vector is shorter than the incoming vector.
Mon P Wangc7849c22008-11-16 05:06:27 +00002479 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002480 // Shuffle extracts 1st vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002481 setValue(&I, Src1);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002482 return;
2483 }
2484
Mon P Wangc7849c22008-11-16 05:06:27 +00002485 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002486 // Shuffle extracts 2nd vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002487 setValue(&I, Src2);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002488 return;
2489 }
2490
Mon P Wangc7849c22008-11-16 05:06:27 +00002491 // Analyze the access pattern of the vector to see if we can extract
2492 // two subvectors and do the shuffle. The analysis is done by calculating
2493 // the range of elements the mask access on both vectors.
2494 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2495 int MaxRange[2] = {-1, -1};
2496
2497 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002498 SDValue Arg = Mask.getOperand(i);
2499 if (Arg.getOpcode() != ISD::UNDEF) {
2500 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002501 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2502 int Input = 0;
2503 if (Idx >= SrcNumElts) {
2504 Input = 1;
2505 Idx -= SrcNumElts;
2506 }
2507 if (Idx > MaxRange[Input])
2508 MaxRange[Input] = Idx;
2509 if (Idx < MinRange[Input])
2510 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002511 }
2512 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002513
Mon P Wangc7849c22008-11-16 05:06:27 +00002514 // Check if the access is smaller than the vector size and can we find
2515 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002516 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002517 int StartIdx[2]; // StartIdx to extract from
2518 for (int Input=0; Input < 2; ++Input) {
2519 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2520 RangeUse[Input] = 0; // Unused
2521 StartIdx[Input] = 0;
2522 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2523 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002524 // start index that is a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002525 if (MaxRange[Input] < MaskNumElts) {
2526 RangeUse[Input] = 1; // Extract from beginning of the vector
2527 StartIdx[Input] = 0;
2528 } else {
2529 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang6cce3da2008-11-23 04:35:05 +00002530 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002531 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002532 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002533 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002534 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002535 }
2536
2537 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002538 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002539 return;
2540 }
2541 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2542 // Extract appropriate subvector and generate a vector shuffle
2543 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002544 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002545 if (RangeUse[Input] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002546 Src = DAG.getUNDEF(VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002547 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002548 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002549 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002550 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002551 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002552 // Calculate new mask.
2553 SmallVector<SDValue, 8> MappedOps;
2554 for (int i = 0; i != MaskNumElts; ++i) {
2555 SDValue Arg = Mask.getOperand(i);
2556 if (Arg.getOpcode() == ISD::UNDEF) {
2557 MappedOps.push_back(Arg);
2558 } else {
2559 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2560 if (Idx < SrcNumElts)
2561 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2562 else {
2563 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2564 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002565 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002566 }
2567 }
Evan Chenga87008d2009-02-25 22:49:59 +00002568 Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2569 Mask.getValueType(),
2570 &MappedOps[0], MappedOps.size());
Scott Michelfdc40a02009-02-17 22:15:04 +00002571 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002572 VT, Src1, Src2, Mask));
Mon P Wangc7849c22008-11-16 05:06:27 +00002573 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002574 }
2575 }
2576
Mon P Wangc7849c22008-11-16 05:06:27 +00002577 // We can't use either concat vectors or extract subvectors so fall back to
2578 // replacing the shuffle with extract and build vector.
2579 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002580 MVT EltVT = VT.getVectorElementType();
2581 MVT PtrVT = TLI.getPointerTy();
2582 SmallVector<SDValue,8> Ops;
Mon P Wangc7849c22008-11-16 05:06:27 +00002583 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002584 SDValue Arg = Mask.getOperand(i);
2585 if (Arg.getOpcode() == ISD::UNDEF) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002586 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002587 } else {
2588 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002589 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2590 if (Idx < SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002591 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002592 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002593 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002594 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Scott Michelfdc40a02009-02-17 22:15:04 +00002595 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002596 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002597 }
2598 }
Evan Chenga87008d2009-02-25 22:49:59 +00002599 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2600 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002601}
2602
2603void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2604 const Value *Op0 = I.getOperand(0);
2605 const Value *Op1 = I.getOperand(1);
2606 const Type *AggTy = I.getType();
2607 const Type *ValTy = Op1->getType();
2608 bool IntoUndef = isa<UndefValue>(Op0);
2609 bool FromUndef = isa<UndefValue>(Op1);
2610
2611 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2612 I.idx_begin(), I.idx_end());
2613
2614 SmallVector<MVT, 4> AggValueVTs;
2615 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2616 SmallVector<MVT, 4> ValValueVTs;
2617 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2618
2619 unsigned NumAggValues = AggValueVTs.size();
2620 unsigned NumValValues = ValValueVTs.size();
2621 SmallVector<SDValue, 4> Values(NumAggValues);
2622
2623 SDValue Agg = getValue(Op0);
2624 SDValue Val = getValue(Op1);
2625 unsigned i = 0;
2626 // Copy the beginning value(s) from the original aggregate.
2627 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002628 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002629 SDValue(Agg.getNode(), Agg.getResNo() + i);
2630 // Copy values from the inserted value(s).
2631 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002632 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002633 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2634 // Copy remaining value(s) from the original aggregate.
2635 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002636 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002637 SDValue(Agg.getNode(), Agg.getResNo() + i);
2638
Scott Michelfdc40a02009-02-17 22:15:04 +00002639 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002640 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2641 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002642}
2643
2644void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2645 const Value *Op0 = I.getOperand(0);
2646 const Type *AggTy = Op0->getType();
2647 const Type *ValTy = I.getType();
2648 bool OutOfUndef = isa<UndefValue>(Op0);
2649
2650 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2651 I.idx_begin(), I.idx_end());
2652
2653 SmallVector<MVT, 4> ValValueVTs;
2654 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2655
2656 unsigned NumValValues = ValValueVTs.size();
2657 SmallVector<SDValue, 4> Values(NumValValues);
2658
2659 SDValue Agg = getValue(Op0);
2660 // Copy out the selected value(s).
2661 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2662 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002663 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002664 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002665 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002666
Scott Michelfdc40a02009-02-17 22:15:04 +00002667 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002668 DAG.getVTList(&ValValueVTs[0], NumValValues),
2669 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002670}
2671
2672
2673void SelectionDAGLowering::visitGetElementPtr(User &I) {
2674 SDValue N = getValue(I.getOperand(0));
2675 const Type *Ty = I.getOperand(0)->getType();
2676
2677 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2678 OI != E; ++OI) {
2679 Value *Idx = *OI;
2680 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2681 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2682 if (Field) {
2683 // N = N + Offset
2684 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002685 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002686 DAG.getIntPtrConstant(Offset));
2687 }
2688 Ty = StTy->getElementType(Field);
2689 } else {
2690 Ty = cast<SequentialType>(Ty)->getElementType();
2691
2692 // If this is a constant subscript, handle it quickly.
2693 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2694 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002695 uint64_t Offs =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002696 TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002697 SDValue OffsVal;
Evan Chengb1032a82009-02-09 20:54:38 +00002698 unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
Evan Cheng65b52df2009-02-09 21:01:06 +00002699 if (PtrBits < 64) {
2700 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2701 TLI.getPointerTy(),
2702 DAG.getConstant(Offs, MVT::i64));
2703 } else
Evan Chengb1032a82009-02-09 20:54:38 +00002704 OffsVal = DAG.getIntPtrConstant(Offs);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002705 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002706 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002707 continue;
2708 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002709
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002710 // N = N + Idx * ElementSize;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002711 uint64_t ElementSize = TD->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002712 SDValue IdxN = getValue(Idx);
2713
2714 // If the index is smaller or larger than intptr_t, truncate or extend
2715 // it.
2716 if (IdxN.getValueType().bitsLT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002717 IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002718 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002719 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002720 IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002721 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002722
2723 // If this is a multiply by a power of two, turn it into a shl
2724 // immediately. This is a very common case.
2725 if (ElementSize != 1) {
2726 if (isPowerOf2_64(ElementSize)) {
2727 unsigned Amt = Log2_64(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002728 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002729 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002730 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002731 } else {
2732 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002733 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002734 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002735 }
2736 }
2737
Scott Michelfdc40a02009-02-17 22:15:04 +00002738 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002739 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002740 }
2741 }
2742 setValue(&I, N);
2743}
2744
2745void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2746 // If this is a fixed sized alloca in the entry block of the function,
2747 // allocate it statically on the stack.
2748 if (FuncInfo.StaticAllocaMap.count(&I))
2749 return; // getValue will auto-populate this.
2750
2751 const Type *Ty = I.getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002752 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002753 unsigned Align =
2754 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2755 I.getAlignment());
2756
2757 SDValue AllocSize = getValue(I.getArraySize());
Chris Lattner0b18e592009-03-17 19:36:00 +00002758
2759 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2760 AllocSize,
2761 DAG.getConstant(TySize, AllocSize.getValueType()));
2762
2763
2764
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002765 MVT IntPtr = TLI.getPointerTy();
2766 if (IntPtr.bitsLT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002767 AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002768 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002769 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002770 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002771 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002772
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002773 // Handle alignment. If the requested alignment is less than or equal to
2774 // the stack alignment, ignore it. If the size is greater than or equal to
2775 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2776 unsigned StackAlign =
2777 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2778 if (Align <= StackAlign)
2779 Align = 0;
2780
2781 // Round the size of the allocation up to the stack alignment size
2782 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002783 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002784 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002785 DAG.getIntPtrConstant(StackAlign-1));
2786 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002787 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002788 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002789 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2790
2791 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2792 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2793 MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002794 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002795 VTs, 2, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002796 setValue(&I, DSA);
2797 DAG.setRoot(DSA.getValue(1));
2798
2799 // Inform the Frame Information that we have just allocated a variable-sized
2800 // object.
2801 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2802}
2803
2804void SelectionDAGLowering::visitLoad(LoadInst &I) {
2805 const Value *SV = I.getOperand(0);
2806 SDValue Ptr = getValue(SV);
2807
2808 const Type *Ty = I.getType();
2809 bool isVolatile = I.isVolatile();
2810 unsigned Alignment = I.getAlignment();
2811
2812 SmallVector<MVT, 4> ValueVTs;
2813 SmallVector<uint64_t, 4> Offsets;
2814 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2815 unsigned NumValues = ValueVTs.size();
2816 if (NumValues == 0)
2817 return;
2818
2819 SDValue Root;
2820 bool ConstantMemory = false;
2821 if (I.isVolatile())
2822 // Serialize volatile loads with other side effects.
2823 Root = getRoot();
2824 else if (AA->pointsToConstantMemory(SV)) {
2825 // Do not serialize (non-volatile) loads of constant memory with anything.
2826 Root = DAG.getEntryNode();
2827 ConstantMemory = true;
2828 } else {
2829 // Do not serialize non-volatile loads against each other.
2830 Root = DAG.getRoot();
2831 }
2832
2833 SmallVector<SDValue, 4> Values(NumValues);
2834 SmallVector<SDValue, 4> Chains(NumValues);
2835 MVT PtrVT = Ptr.getValueType();
2836 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002837 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Scott Michelfdc40a02009-02-17 22:15:04 +00002838 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002839 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002840 DAG.getConstant(Offsets[i], PtrVT)),
2841 SV, Offsets[i],
2842 isVolatile, Alignment);
2843 Values[i] = L;
2844 Chains[i] = L.getValue(1);
2845 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002846
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002847 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002848 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002849 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002850 &Chains[0], NumValues);
2851 if (isVolatile)
2852 DAG.setRoot(Chain);
2853 else
2854 PendingLoads.push_back(Chain);
2855 }
2856
Scott Michelfdc40a02009-02-17 22:15:04 +00002857 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002858 DAG.getVTList(&ValueVTs[0], NumValues),
2859 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002860}
2861
2862
2863void SelectionDAGLowering::visitStore(StoreInst &I) {
2864 Value *SrcV = I.getOperand(0);
2865 Value *PtrV = I.getOperand(1);
2866
2867 SmallVector<MVT, 4> ValueVTs;
2868 SmallVector<uint64_t, 4> Offsets;
2869 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2870 unsigned NumValues = ValueVTs.size();
2871 if (NumValues == 0)
2872 return;
2873
2874 // Get the lowered operands. Note that we do this after
2875 // checking if NumResults is zero, because with zero results
2876 // the operands won't have values in the map.
2877 SDValue Src = getValue(SrcV);
2878 SDValue Ptr = getValue(PtrV);
2879
2880 SDValue Root = getRoot();
2881 SmallVector<SDValue, 4> Chains(NumValues);
2882 MVT PtrVT = Ptr.getValueType();
2883 bool isVolatile = I.isVolatile();
2884 unsigned Alignment = I.getAlignment();
2885 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002886 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002887 SDValue(Src.getNode(), Src.getResNo() + i),
Scott Michelfdc40a02009-02-17 22:15:04 +00002888 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002889 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002890 DAG.getConstant(Offsets[i], PtrVT)),
2891 PtrV, Offsets[i],
2892 isVolatile, Alignment);
2893
Scott Michelfdc40a02009-02-17 22:15:04 +00002894 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002895 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002896}
2897
2898/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2899/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002900void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002901 unsigned Intrinsic) {
2902 bool HasChain = !I.doesNotAccessMemory();
2903 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2904
2905 // Build the operand list.
2906 SmallVector<SDValue, 8> Ops;
2907 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2908 if (OnlyLoad) {
2909 // We don't need to serialize loads against other loads.
2910 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002911 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002912 Ops.push_back(getRoot());
2913 }
2914 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002915
2916 // Info is set by getTgtMemInstrinsic
2917 TargetLowering::IntrinsicInfo Info;
2918 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2919
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002920 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002921 if (!IsTgtIntrinsic)
2922 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002923
2924 // Add all operands of the call to the operand list.
2925 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2926 SDValue Op = getValue(I.getOperand(i));
2927 assert(TLI.isTypeLegal(Op.getValueType()) &&
2928 "Intrinsic uses a non-legal type?");
2929 Ops.push_back(Op);
2930 }
2931
2932 std::vector<MVT> VTs;
2933 if (I.getType() != Type::VoidTy) {
2934 MVT VT = TLI.getValueType(I.getType());
2935 if (VT.isVector()) {
2936 const VectorType *DestTy = cast<VectorType>(I.getType());
2937 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002938
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002939 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2940 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2941 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002942
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002943 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2944 VTs.push_back(VT);
2945 }
2946 if (HasChain)
2947 VTs.push_back(MVT::Other);
2948
2949 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2950
2951 // Create the node.
2952 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002953 if (IsTgtIntrinsic) {
2954 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002955 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002956 VTList, VTs.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002957 &Ops[0], Ops.size(),
2958 Info.memVT, Info.ptrVal, Info.offset,
2959 Info.align, Info.vol,
2960 Info.readMem, Info.writeMem);
2961 }
2962 else if (!HasChain)
Scott Michelfdc40a02009-02-17 22:15:04 +00002963 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002964 VTList, VTs.size(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002965 &Ops[0], Ops.size());
2966 else if (I.getType() != Type::VoidTy)
Scott Michelfdc40a02009-02-17 22:15:04 +00002967 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002968 VTList, VTs.size(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002969 &Ops[0], Ops.size());
2970 else
Scott Michelfdc40a02009-02-17 22:15:04 +00002971 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002972 VTList, VTs.size(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002973 &Ops[0], Ops.size());
2974
2975 if (HasChain) {
2976 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2977 if (OnlyLoad)
2978 PendingLoads.push_back(Chain);
2979 else
2980 DAG.setRoot(Chain);
2981 }
2982 if (I.getType() != Type::VoidTy) {
2983 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2984 MVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002985 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002986 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002987 setValue(&I, Result);
2988 }
2989}
2990
2991/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2992static GlobalVariable *ExtractTypeInfo(Value *V) {
2993 V = V->stripPointerCasts();
2994 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2995 assert ((GV || isa<ConstantPointerNull>(V)) &&
2996 "TypeInfo must be a global variable or NULL");
2997 return GV;
2998}
2999
3000namespace llvm {
3001
3002/// AddCatchInfo - Extract the personality and type infos from an eh.selector
3003/// call, and add them to the specified machine basic block.
3004void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3005 MachineBasicBlock *MBB) {
3006 // Inform the MachineModuleInfo of the personality for this landing pad.
3007 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3008 assert(CE->getOpcode() == Instruction::BitCast &&
3009 isa<Function>(CE->getOperand(0)) &&
3010 "Personality should be a function");
3011 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3012
3013 // Gather all the type infos for this landing pad and pass them along to
3014 // MachineModuleInfo.
3015 std::vector<GlobalVariable *> TyInfo;
3016 unsigned N = I.getNumOperands();
3017
3018 for (unsigned i = N - 1; i > 2; --i) {
3019 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3020 unsigned FilterLength = CI->getZExtValue();
3021 unsigned FirstCatch = i + FilterLength + !FilterLength;
3022 assert (FirstCatch <= N && "Invalid filter length");
3023
3024 if (FirstCatch < N) {
3025 TyInfo.reserve(N - FirstCatch);
3026 for (unsigned j = FirstCatch; j < N; ++j)
3027 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3028 MMI->addCatchTypeInfo(MBB, TyInfo);
3029 TyInfo.clear();
3030 }
3031
3032 if (!FilterLength) {
3033 // Cleanup.
3034 MMI->addCleanup(MBB);
3035 } else {
3036 // Filter.
3037 TyInfo.reserve(FilterLength - 1);
3038 for (unsigned j = i + 1; j < FirstCatch; ++j)
3039 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3040 MMI->addFilterTypeInfo(MBB, TyInfo);
3041 TyInfo.clear();
3042 }
3043
3044 N = i;
3045 }
3046 }
3047
3048 if (N > 3) {
3049 TyInfo.reserve(N - 3);
3050 for (unsigned j = 3; j < N; ++j)
3051 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3052 MMI->addCatchTypeInfo(MBB, TyInfo);
3053 }
3054}
3055
3056}
3057
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003058/// GetSignificand - Get the significand and build it into a floating-point
3059/// number with exponent of 1:
3060///
3061/// Op = (Op & 0x007fffff) | 0x3f800000;
3062///
3063/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003064static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003065GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3066 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003067 DAG.getConstant(0x007fffff, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003068 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003069 DAG.getConstant(0x3f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003070 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003071}
3072
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003073/// GetExponent - Get the exponent:
3074///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003075/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003076///
3077/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003078static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003079GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3080 DebugLoc dl) {
3081 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003082 DAG.getConstant(0x7f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003083 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003084 DAG.getConstant(23, TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003085 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003086 DAG.getConstant(127, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003087 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003088}
3089
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003090/// getF32Constant - Get 32-bit floating point constant.
3091static SDValue
3092getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3093 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3094}
3095
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003096/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003097/// visitIntrinsicCall: I is a call instruction
3098/// Op is the associated NodeType for I
3099const char *
3100SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003101 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003102 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003103 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003104 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003105 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003106 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003107 getValue(I.getOperand(2)),
3108 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003109 setValue(&I, L);
3110 DAG.setRoot(L.getValue(1));
3111 return 0;
3112}
3113
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003114// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003115const char *
3116SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003117 SDValue Op1 = getValue(I.getOperand(1));
3118 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003119
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003120 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
3121 SDValue Ops[] = { Op1, Op2 };
Bill Wendling74c37652008-12-09 22:08:41 +00003122
Scott Michelfdc40a02009-02-17 22:15:04 +00003123 SDValue Result = DAG.getNode(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003124 DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
Bill Wendling74c37652008-12-09 22:08:41 +00003125
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003126 setValue(&I, Result);
3127 return 0;
3128}
Bill Wendling74c37652008-12-09 22:08:41 +00003129
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003130/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3131/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003132void
3133SelectionDAGLowering::visitExp(CallInst &I) {
3134 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003135 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003136
3137 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3138 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3139 SDValue Op = getValue(I.getOperand(1));
3140
3141 // Put the exponent in the right bit position for later addition to the
3142 // final result:
3143 //
3144 // #define LOG2OFe 1.4426950f
3145 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003146 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003147 getF32Constant(DAG, 0x3fb8aa3b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003148 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003149
3150 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003151 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3152 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003153
3154 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003155 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003156 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003157
3158 if (LimitFloatPrecision <= 6) {
3159 // For floating-point precision of 6:
3160 //
3161 // TwoToFractionalPartOfX =
3162 // 0.997535578f +
3163 // (0.735607626f + 0.252464424f * x) * x;
3164 //
3165 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003166 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003167 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003168 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003169 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003170 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3171 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003172 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003173 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003174
3175 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003176 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003177 TwoToFracPartOfX, IntegerPartOfX);
3178
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003179 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003180 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3181 // For floating-point precision of 12:
3182 //
3183 // TwoToFractionalPartOfX =
3184 // 0.999892986f +
3185 // (0.696457318f +
3186 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3187 //
3188 // 0.000107046256 error, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003189 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003190 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003191 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003192 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003193 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3194 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003195 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003196 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3197 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003198 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003199 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003200
3201 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003202 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003203 TwoToFracPartOfX, IntegerPartOfX);
3204
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003205 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003206 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3207 // For floating-point precision of 18:
3208 //
3209 // TwoToFractionalPartOfX =
3210 // 0.999999982f +
3211 // (0.693148872f +
3212 // (0.240227044f +
3213 // (0.554906021e-1f +
3214 // (0.961591928e-2f +
3215 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3216 //
3217 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003218 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003219 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003220 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003221 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003222 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3223 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003224 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003225 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3226 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003227 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003228 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3229 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003230 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003231 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3232 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003233 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003234 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3235 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003236 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003237 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003238 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003239
3240 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003241 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003242 TwoToFracPartOfX, IntegerPartOfX);
3243
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003244 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003245 }
3246 } else {
3247 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003248 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003249 getValue(I.getOperand(1)).getValueType(),
3250 getValue(I.getOperand(1)));
3251 }
3252
Dale Johannesen59e577f2008-09-05 18:38:42 +00003253 setValue(&I, result);
3254}
3255
Bill Wendling39150252008-09-09 20:39:27 +00003256/// visitLog - Lower a log intrinsic. Handles the special sequences for
3257/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003258void
3259SelectionDAGLowering::visitLog(CallInst &I) {
3260 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003261 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003262
3263 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3264 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3265 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003266 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003267
3268 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003269 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003270 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003271 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003272
3273 // Get the significand and build it into a floating-point number with
3274 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003275 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003276
3277 if (LimitFloatPrecision <= 6) {
3278 // For floating-point precision of 6:
3279 //
3280 // LogofMantissa =
3281 // -1.1609546f +
3282 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003283 //
Bill Wendling39150252008-09-09 20:39:27 +00003284 // error 0.0034276066, which is better than 8 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003285 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003286 getF32Constant(DAG, 0xbe74c456));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003287 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003288 getF32Constant(DAG, 0x3fb3a2b1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003289 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3290 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003291 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003292
Scott Michelfdc40a02009-02-17 22:15:04 +00003293 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003294 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003295 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3296 // For floating-point precision of 12:
3297 //
3298 // LogOfMantissa =
3299 // -1.7417939f +
3300 // (2.8212026f +
3301 // (-1.4699568f +
3302 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3303 //
3304 // error 0.000061011436, which is 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003305 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003306 getF32Constant(DAG, 0xbd67b6d6));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003307 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003308 getF32Constant(DAG, 0x3ee4f4b8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003309 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3310 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003311 getF32Constant(DAG, 0x3fbc278b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003312 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3313 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003314 getF32Constant(DAG, 0x40348e95));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003315 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3316 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003317 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003318
Scott Michelfdc40a02009-02-17 22:15:04 +00003319 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003320 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003321 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3322 // For floating-point precision of 18:
3323 //
3324 // LogOfMantissa =
3325 // -2.1072184f +
3326 // (4.2372794f +
3327 // (-3.7029485f +
3328 // (2.2781945f +
3329 // (-0.87823314f +
3330 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3331 //
3332 // error 0.0000023660568, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003333 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003334 getF32Constant(DAG, 0xbc91e5ac));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003335 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003336 getF32Constant(DAG, 0x3e4350aa));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003337 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3338 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003339 getF32Constant(DAG, 0x3f60d3e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003340 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3341 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003342 getF32Constant(DAG, 0x4011cdf0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003343 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3344 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003345 getF32Constant(DAG, 0x406cfd1c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003346 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3347 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003348 getF32Constant(DAG, 0x408797cb));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003349 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3350 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003351 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003352
Scott Michelfdc40a02009-02-17 22:15:04 +00003353 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003354 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003355 }
3356 } else {
3357 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003358 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003359 getValue(I.getOperand(1)).getValueType(),
3360 getValue(I.getOperand(1)));
3361 }
3362
Dale Johannesen59e577f2008-09-05 18:38:42 +00003363 setValue(&I, result);
3364}
3365
Bill Wendling3eb59402008-09-09 00:28:24 +00003366/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3367/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003368void
3369SelectionDAGLowering::visitLog2(CallInst &I) {
3370 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003371 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003372
Dale Johannesen853244f2008-09-05 23:49:37 +00003373 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003374 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3375 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003376 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003377
Bill Wendling39150252008-09-09 20:39:27 +00003378 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003379 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003380
3381 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003382 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003383 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003384
Bill Wendling3eb59402008-09-09 00:28:24 +00003385 // Different possible minimax approximations of significand in
3386 // floating-point for various degrees of accuracy over [1,2].
3387 if (LimitFloatPrecision <= 6) {
3388 // For floating-point precision of 6:
3389 //
3390 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3391 //
3392 // error 0.0049451742, which is more than 7 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003393 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003394 getF32Constant(DAG, 0xbeb08fe0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003395 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003396 getF32Constant(DAG, 0x40019463));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003397 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3398 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003399 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003400
Scott Michelfdc40a02009-02-17 22:15:04 +00003401 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003402 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003403 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3404 // For floating-point precision of 12:
3405 //
3406 // Log2ofMantissa =
3407 // -2.51285454f +
3408 // (4.07009056f +
3409 // (-2.12067489f +
3410 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003411 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003412 // error 0.0000876136000, which is better than 13 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003413 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003414 getF32Constant(DAG, 0xbda7262e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003415 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003416 getF32Constant(DAG, 0x3f25280b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003417 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3418 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003419 getF32Constant(DAG, 0x4007b923));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003420 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3421 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003422 getF32Constant(DAG, 0x40823e2f));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003423 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3424 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003425 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003426
Scott Michelfdc40a02009-02-17 22:15:04 +00003427 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003428 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003429 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3430 // For floating-point precision of 18:
3431 //
3432 // Log2ofMantissa =
3433 // -3.0400495f +
3434 // (6.1129976f +
3435 // (-5.3420409f +
3436 // (3.2865683f +
3437 // (-1.2669343f +
3438 // (0.27515199f -
3439 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3440 //
3441 // error 0.0000018516, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003442 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003443 getF32Constant(DAG, 0xbcd2769e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003444 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003445 getF32Constant(DAG, 0x3e8ce0b9));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003446 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3447 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003448 getF32Constant(DAG, 0x3fa22ae7));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003449 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3450 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003451 getF32Constant(DAG, 0x40525723));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003452 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3453 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003454 getF32Constant(DAG, 0x40aaf200));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003455 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3456 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003457 getF32Constant(DAG, 0x40c39dad));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003458 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3459 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003460 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003461
Scott Michelfdc40a02009-02-17 22:15:04 +00003462 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003463 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003464 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003465 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003466 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003467 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003468 getValue(I.getOperand(1)).getValueType(),
3469 getValue(I.getOperand(1)));
3470 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003471
Dale Johannesen59e577f2008-09-05 18:38:42 +00003472 setValue(&I, result);
3473}
3474
Bill Wendling3eb59402008-09-09 00:28:24 +00003475/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3476/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003477void
3478SelectionDAGLowering::visitLog10(CallInst &I) {
3479 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003480 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003481
Dale Johannesen852680a2008-09-05 21:27:19 +00003482 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003483 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3484 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003485 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003486
Bill Wendling39150252008-09-09 20:39:27 +00003487 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003488 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003489 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003490 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003491
3492 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003493 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003494 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003495
3496 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003497 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003498 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003499 // Log10ofMantissa =
3500 // -0.50419619f +
3501 // (0.60948995f - 0.10380950f * x) * x;
3502 //
3503 // error 0.0014886165, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003504 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003505 getF32Constant(DAG, 0xbdd49a13));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003506 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003507 getF32Constant(DAG, 0x3f1c0789));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003508 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3509 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003510 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003511
Scott Michelfdc40a02009-02-17 22:15:04 +00003512 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003513 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003514 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3515 // For floating-point precision of 12:
3516 //
3517 // Log10ofMantissa =
3518 // -0.64831180f +
3519 // (0.91751397f +
3520 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3521 //
3522 // error 0.00019228036, which is better than 12 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003523 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003524 getF32Constant(DAG, 0x3d431f31));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003525 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003526 getF32Constant(DAG, 0x3ea21fb2));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003527 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3528 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003529 getF32Constant(DAG, 0x3f6ae232));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003530 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3531 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003532 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003533
Scott Michelfdc40a02009-02-17 22:15:04 +00003534 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003535 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003536 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003537 // For floating-point precision of 18:
3538 //
3539 // Log10ofMantissa =
3540 // -0.84299375f +
3541 // (1.5327582f +
3542 // (-1.0688956f +
3543 // (0.49102474f +
3544 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3545 //
3546 // error 0.0000037995730, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003547 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003548 getF32Constant(DAG, 0x3c5d51ce));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003549 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003550 getF32Constant(DAG, 0x3e00685a));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003551 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3552 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003553 getF32Constant(DAG, 0x3efb6798));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003554 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3555 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003556 getF32Constant(DAG, 0x3f88d192));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003557 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3558 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003559 getF32Constant(DAG, 0x3fc4316c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003560 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3561 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003562 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003563
Scott Michelfdc40a02009-02-17 22:15:04 +00003564 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003565 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003566 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003567 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003568 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003569 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003570 getValue(I.getOperand(1)).getValueType(),
3571 getValue(I.getOperand(1)));
3572 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003573
Dale Johannesen59e577f2008-09-05 18:38:42 +00003574 setValue(&I, result);
3575}
3576
Bill Wendlinge10c8142008-09-09 22:39:21 +00003577/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3578/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003579void
3580SelectionDAGLowering::visitExp2(CallInst &I) {
3581 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003582 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003583
Dale Johannesen601d3c02008-09-05 01:48:15 +00003584 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003585 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3586 SDValue Op = getValue(I.getOperand(1));
3587
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003588 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003589
3590 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003591 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3592 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003593
3594 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003595 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003596 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003597
3598 if (LimitFloatPrecision <= 6) {
3599 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003600 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003601 // TwoToFractionalPartOfX =
3602 // 0.997535578f +
3603 // (0.735607626f + 0.252464424f * x) * x;
3604 //
3605 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003606 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003607 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003608 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003609 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003610 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3611 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003612 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003613 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003614 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003615 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003616
Scott Michelfdc40a02009-02-17 22:15:04 +00003617 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003618 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003619 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3620 // For floating-point precision of 12:
3621 //
3622 // TwoToFractionalPartOfX =
3623 // 0.999892986f +
3624 // (0.696457318f +
3625 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3626 //
3627 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003628 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003629 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003630 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003631 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003632 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3633 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003634 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003635 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3636 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003637 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003638 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003639 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003640 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003641
Scott Michelfdc40a02009-02-17 22:15:04 +00003642 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003643 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003644 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3645 // For floating-point precision of 18:
3646 //
3647 // TwoToFractionalPartOfX =
3648 // 0.999999982f +
3649 // (0.693148872f +
3650 // (0.240227044f +
3651 // (0.554906021e-1f +
3652 // (0.961591928e-2f +
3653 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3654 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003655 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003656 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003657 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003658 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003659 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3660 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003661 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003662 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3663 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003664 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003665 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3666 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003667 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003668 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3669 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003670 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003671 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3672 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003673 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003674 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003675 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003676 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003677
Scott Michelfdc40a02009-02-17 22:15:04 +00003678 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003679 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003680 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003681 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003682 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003683 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003684 getValue(I.getOperand(1)).getValueType(),
3685 getValue(I.getOperand(1)));
3686 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003687
Dale Johannesen601d3c02008-09-05 01:48:15 +00003688 setValue(&I, result);
3689}
3690
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003691/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3692/// limited-precision mode with x == 10.0f.
3693void
3694SelectionDAGLowering::visitPow(CallInst &I) {
3695 SDValue result;
3696 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003697 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003698 bool IsExp10 = false;
3699
3700 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003701 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003702 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3703 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3704 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3705 APFloat Ten(10.0f);
3706 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3707 }
3708 }
3709 }
3710
3711 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3712 SDValue Op = getValue(I.getOperand(2));
3713
3714 // Put the exponent in the right bit position for later addition to the
3715 // final result:
3716 //
3717 // #define LOG2OF10 3.3219281f
3718 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003719 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003720 getF32Constant(DAG, 0x40549a78));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003721 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003722
3723 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003724 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3725 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003726
3727 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003728 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003729 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003730
3731 if (LimitFloatPrecision <= 6) {
3732 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003733 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003734 // twoToFractionalPartOfX =
3735 // 0.997535578f +
3736 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003737 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003738 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003739 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003740 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003741 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003742 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003743 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3744 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003745 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003746 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003747 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003748 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003749
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003750 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3751 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003752 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3753 // For floating-point precision of 12:
3754 //
3755 // TwoToFractionalPartOfX =
3756 // 0.999892986f +
3757 // (0.696457318f +
3758 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3759 //
3760 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003761 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003762 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003763 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003764 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003765 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3766 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003767 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003768 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3769 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003770 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003771 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003772 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003773 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003774
Scott Michelfdc40a02009-02-17 22:15:04 +00003775 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003776 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003777 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3778 // For floating-point precision of 18:
3779 //
3780 // TwoToFractionalPartOfX =
3781 // 0.999999982f +
3782 // (0.693148872f +
3783 // (0.240227044f +
3784 // (0.554906021e-1f +
3785 // (0.961591928e-2f +
3786 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3787 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003788 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003789 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003790 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003791 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003792 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3793 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003794 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003795 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3796 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003797 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003798 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3799 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003800 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003801 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3802 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003803 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003804 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3805 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003806 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003807 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003808 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003809 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003810
Scott Michelfdc40a02009-02-17 22:15:04 +00003811 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003812 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003813 }
3814 } else {
3815 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003816 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003817 getValue(I.getOperand(1)).getValueType(),
3818 getValue(I.getOperand(1)),
3819 getValue(I.getOperand(2)));
3820 }
3821
3822 setValue(&I, result);
3823}
3824
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003825/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3826/// we want to emit this as a call to a named external function, return the name
3827/// otherwise lower it and return null.
3828const char *
3829SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003830 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003831 switch (Intrinsic) {
3832 default:
3833 // By default, turn this into a target intrinsic node.
3834 visitTargetIntrinsic(I, Intrinsic);
3835 return 0;
3836 case Intrinsic::vastart: visitVAStart(I); return 0;
3837 case Intrinsic::vaend: visitVAEnd(I); return 0;
3838 case Intrinsic::vacopy: visitVACopy(I); return 0;
3839 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003840 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003841 getValue(I.getOperand(1))));
3842 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003843 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003844 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003845 getValue(I.getOperand(1))));
3846 return 0;
3847 case Intrinsic::setjmp:
3848 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3849 break;
3850 case Intrinsic::longjmp:
3851 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3852 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003853 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003854 SDValue Op1 = getValue(I.getOperand(1));
3855 SDValue Op2 = getValue(I.getOperand(2));
3856 SDValue Op3 = getValue(I.getOperand(3));
3857 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003858 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003859 I.getOperand(1), 0, I.getOperand(2), 0));
3860 return 0;
3861 }
Chris Lattner824b9582008-11-21 16:42:48 +00003862 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003863 SDValue Op1 = getValue(I.getOperand(1));
3864 SDValue Op2 = getValue(I.getOperand(2));
3865 SDValue Op3 = getValue(I.getOperand(3));
3866 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003867 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003868 I.getOperand(1), 0));
3869 return 0;
3870 }
Chris Lattner824b9582008-11-21 16:42:48 +00003871 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003872 SDValue Op1 = getValue(I.getOperand(1));
3873 SDValue Op2 = getValue(I.getOperand(2));
3874 SDValue Op3 = getValue(I.getOperand(3));
3875 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3876
3877 // If the source and destination are known to not be aliases, we can
3878 // lower memmove as memcpy.
3879 uint64_t Size = -1ULL;
3880 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003881 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003882 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3883 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003884 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003885 I.getOperand(1), 0, I.getOperand(2), 0));
3886 return 0;
3887 }
3888
Dale Johannesena04b7572009-02-03 23:04:43 +00003889 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003890 I.getOperand(1), 0, I.getOperand(2), 0));
3891 return 0;
3892 }
3893 case Intrinsic::dbg_stoppoint: {
Devang Patel83489bb2009-01-13 00:35:13 +00003894 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003895 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003896 if (DW && DW->ValidDebugInfo(SPI.getContext())) {
Evan Chenge3d42322009-02-25 07:04:34 +00003897 MachineFunction &MF = DAG.getMachineFunction();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003898 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3899 SPI.getLine(),
3900 SPI.getColumn(),
Devang Patel83489bb2009-01-13 00:35:13 +00003901 SPI.getContext()));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003902 DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
Bill Wendling0582ae92009-03-13 04:39:26 +00003903 std::string Dir, FN;
3904 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
3905 CU.getFilename(FN));
Evan Chenge3d42322009-02-25 07:04:34 +00003906 unsigned idx = MF.getOrCreateDebugLocID(SrcFile,
3907 SPI.getLine(), SPI.getColumn());
Dale Johannesen66978ee2009-01-31 02:22:37 +00003908 setCurDebugLoc(DebugLoc::get(idx));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003909 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003910 return 0;
3911 }
3912 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003913 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003914 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Bill Wendling92c1e122009-02-13 02:16:35 +00003915 if (DW && DW->ValidDebugInfo(RSI.getContext())) {
3916 unsigned LabelID =
3917 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Bill Wendlingdfdacee2009-02-19 21:12:54 +00003918 if (Fast)
Bill Wendling86e6cb92009-02-17 01:04:54 +00003919 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3920 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003921 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003922
3923 return 0;
3924 }
3925 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003926 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003927 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Bill Wendling92c1e122009-02-13 02:16:35 +00003928 if (DW && DW->ValidDebugInfo(REI.getContext())) {
3929 unsigned LabelID =
3930 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
Bill Wendlingdfdacee2009-02-19 21:12:54 +00003931 if (Fast)
Bill Wendling86e6cb92009-02-17 01:04:54 +00003932 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3933 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003934 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003935
3936 return 0;
3937 }
3938 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003939 DwarfWriter *DW = DAG.getDwarfWriter();
3940 if (!DW) return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003941 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3942 Value *SP = FSI.getSubprogram();
Devang Patelcf3a4482009-01-15 23:41:32 +00003943 if (SP && DW->ValidDebugInfo(SP)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003944 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3945 // what (most?) gdb expects.
Evan Chenge3d42322009-02-25 07:04:34 +00003946 MachineFunction &MF = DAG.getMachineFunction();
Devang Patel83489bb2009-01-13 00:35:13 +00003947 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3948 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
Bill Wendling0582ae92009-03-13 04:39:26 +00003949 std::string Dir, FN;
3950 unsigned SrcFile = DW->getOrCreateSourceID(CompileUnit.getDirectory(Dir),
3951 CompileUnit.getFilename(FN));
Bill Wendling9bc96a52009-02-03 00:55:04 +00003952
Devang Patel20dd0462008-11-06 00:30:09 +00003953 // Record the source line but does not create a label for the normal
3954 // function start. It will be emitted at asm emission time. However,
3955 // create a label if this is a beginning of inlined function.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003956 unsigned Line = Subprogram.getLineNumber();
Bill Wendling92c1e122009-02-13 02:16:35 +00003957
Bill Wendling5aa49772009-02-24 02:35:30 +00003958 if (Fast) {
Bill Wendling86e6cb92009-02-17 01:04:54 +00003959 unsigned LabelID = DW->RecordSourceLine(Line, 0, SrcFile);
3960 if (DW->getRecordSourceLineCount() != 1)
3961 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3962 getRoot(), LabelID));
3963 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003964
Evan Chenge3d42322009-02-25 07:04:34 +00003965 setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003966 }
3967
3968 return 0;
3969 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003970 case Intrinsic::dbg_declare: {
Bill Wendling5aa49772009-02-24 02:35:30 +00003971 if (Fast) {
Bill Wendling86e6cb92009-02-17 01:04:54 +00003972 DwarfWriter *DW = DAG.getDwarfWriter();
3973 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3974 Value *Variable = DI.getVariable();
3975 if (DW && DW->ValidDebugInfo(Variable))
3976 DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
3977 getValue(DI.getAddress()), getValue(Variable)));
3978 } else {
3979 // FIXME: Do something sensible here when we support debug declare.
3980 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003981 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00003982 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003983 case Intrinsic::eh_exception: {
3984 if (!CurMBB->isLandingPad()) {
3985 // FIXME: Mark exception register as live in. Hack for PR1508.
3986 unsigned Reg = TLI.getExceptionAddressRegister();
3987 if (Reg) CurMBB->addLiveIn(Reg);
3988 }
3989 // Insert the EXCEPTIONADDR instruction.
3990 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3991 SDValue Ops[1];
3992 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003993 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003994 setValue(&I, Op);
3995 DAG.setRoot(Op.getValue(1));
3996 return 0;
3997 }
3998
3999 case Intrinsic::eh_selector_i32:
4000 case Intrinsic::eh_selector_i64: {
4001 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4002 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
4003 MVT::i32 : MVT::i64);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004004
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004005 if (MMI) {
4006 if (CurMBB->isLandingPad())
4007 AddCatchInfo(I, MMI, CurMBB);
4008 else {
4009#ifndef NDEBUG
4010 FuncInfo.CatchInfoLost.insert(&I);
4011#endif
4012 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4013 unsigned Reg = TLI.getExceptionSelectorRegister();
4014 if (Reg) CurMBB->addLiveIn(Reg);
4015 }
4016
4017 // Insert the EHSELECTION instruction.
4018 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4019 SDValue Ops[2];
4020 Ops[0] = getValue(I.getOperand(1));
4021 Ops[1] = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004022 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004023 setValue(&I, Op);
4024 DAG.setRoot(Op.getValue(1));
4025 } else {
4026 setValue(&I, DAG.getConstant(0, VT));
4027 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004028
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004029 return 0;
4030 }
4031
4032 case Intrinsic::eh_typeid_for_i32:
4033 case Intrinsic::eh_typeid_for_i64: {
4034 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4035 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4036 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004037
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004038 if (MMI) {
4039 // Find the type id for the given typeinfo.
4040 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4041
4042 unsigned TypeID = MMI->getTypeIDFor(GV);
4043 setValue(&I, DAG.getConstant(TypeID, VT));
4044 } else {
4045 // Return something different to eh_selector.
4046 setValue(&I, DAG.getConstant(1, VT));
4047 }
4048
4049 return 0;
4050 }
4051
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004052 case Intrinsic::eh_return_i32:
4053 case Intrinsic::eh_return_i64:
4054 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004055 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004056 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004057 MVT::Other,
4058 getControlRoot(),
4059 getValue(I.getOperand(1)),
4060 getValue(I.getOperand(2))));
4061 } else {
4062 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4063 }
4064
4065 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004066 case Intrinsic::eh_unwind_init:
4067 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4068 MMI->setCallsUnwindInit(true);
4069 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004070
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004071 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004072
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004073 case Intrinsic::eh_dwarf_cfa: {
4074 MVT VT = getValue(I.getOperand(1)).getValueType();
4075 SDValue CfaArg;
4076 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004077 CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004078 TLI.getPointerTy(), getValue(I.getOperand(1)));
4079 else
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004080 CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004081 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004082
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004083 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004084 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004085 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004086 TLI.getPointerTy()),
4087 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004088 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004089 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004090 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004091 TLI.getPointerTy(),
4092 DAG.getConstant(0,
4093 TLI.getPointerTy())),
4094 Offset));
4095 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004096 }
4097
Mon P Wang77cdf302008-11-10 20:54:11 +00004098 case Intrinsic::convertff:
4099 case Intrinsic::convertfsi:
4100 case Intrinsic::convertfui:
4101 case Intrinsic::convertsif:
4102 case Intrinsic::convertuif:
4103 case Intrinsic::convertss:
4104 case Intrinsic::convertsu:
4105 case Intrinsic::convertus:
4106 case Intrinsic::convertuu: {
4107 ISD::CvtCode Code = ISD::CVT_INVALID;
4108 switch (Intrinsic) {
4109 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4110 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4111 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4112 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4113 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4114 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4115 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4116 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4117 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4118 }
4119 MVT DestVT = TLI.getValueType(I.getType());
4120 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004121 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004122 DAG.getValueType(DestVT),
4123 DAG.getValueType(getValue(Op1).getValueType()),
4124 getValue(I.getOperand(2)),
4125 getValue(I.getOperand(3)),
4126 Code));
4127 return 0;
4128 }
4129
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004130 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004131 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004132 getValue(I.getOperand(1)).getValueType(),
4133 getValue(I.getOperand(1))));
4134 return 0;
4135 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004136 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004137 getValue(I.getOperand(1)).getValueType(),
4138 getValue(I.getOperand(1)),
4139 getValue(I.getOperand(2))));
4140 return 0;
4141 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004142 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004143 getValue(I.getOperand(1)).getValueType(),
4144 getValue(I.getOperand(1))));
4145 return 0;
4146 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004147 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004148 getValue(I.getOperand(1)).getValueType(),
4149 getValue(I.getOperand(1))));
4150 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004151 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004152 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004153 return 0;
4154 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004155 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004156 return 0;
4157 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004158 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004159 return 0;
4160 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004161 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004162 return 0;
4163 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004164 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004165 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004166 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004167 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004168 return 0;
4169 case Intrinsic::pcmarker: {
4170 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004171 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004172 return 0;
4173 }
4174 case Intrinsic::readcyclecounter: {
4175 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004176 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004177 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4178 &Op, 1);
4179 setValue(&I, Tmp);
4180 DAG.setRoot(Tmp.getValue(1));
4181 return 0;
4182 }
4183 case Intrinsic::part_select: {
4184 // Currently not implemented: just abort
4185 assert(0 && "part_select intrinsic not implemented");
4186 abort();
4187 }
4188 case Intrinsic::part_set: {
4189 // Currently not implemented: just abort
4190 assert(0 && "part_set intrinsic not implemented");
4191 abort();
4192 }
4193 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004194 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004195 getValue(I.getOperand(1)).getValueType(),
4196 getValue(I.getOperand(1))));
4197 return 0;
4198 case Intrinsic::cttz: {
4199 SDValue Arg = getValue(I.getOperand(1));
4200 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004201 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004202 setValue(&I, result);
4203 return 0;
4204 }
4205 case Intrinsic::ctlz: {
4206 SDValue Arg = getValue(I.getOperand(1));
4207 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004208 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004209 setValue(&I, result);
4210 return 0;
4211 }
4212 case Intrinsic::ctpop: {
4213 SDValue Arg = getValue(I.getOperand(1));
4214 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004215 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004216 setValue(&I, result);
4217 return 0;
4218 }
4219 case Intrinsic::stacksave: {
4220 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004221 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004222 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4223 setValue(&I, Tmp);
4224 DAG.setRoot(Tmp.getValue(1));
4225 return 0;
4226 }
4227 case Intrinsic::stackrestore: {
4228 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004229 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004230 return 0;
4231 }
Bill Wendling57344502008-11-18 11:01:33 +00004232 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004233 // Emit code into the DAG to store the stack guard onto the stack.
4234 MachineFunction &MF = DAG.getMachineFunction();
4235 MachineFrameInfo *MFI = MF.getFrameInfo();
4236 MVT PtrTy = TLI.getPointerTy();
4237
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004238 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4239 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004240
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004241 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004242 MFI->setStackProtectorIndex(FI);
4243
4244 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4245
4246 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004247 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Bill Wendlingb2a42982008-11-06 02:29:10 +00004248 PseudoSourceValue::getFixedStack(FI),
4249 0, true);
4250 setValue(&I, Result);
4251 DAG.setRoot(Result);
4252 return 0;
4253 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004254 case Intrinsic::var_annotation:
4255 // Discard annotate attributes
4256 return 0;
4257
4258 case Intrinsic::init_trampoline: {
4259 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4260
4261 SDValue Ops[6];
4262 Ops[0] = getRoot();
4263 Ops[1] = getValue(I.getOperand(1));
4264 Ops[2] = getValue(I.getOperand(2));
4265 Ops[3] = getValue(I.getOperand(3));
4266 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4267 Ops[5] = DAG.getSrcValue(F);
4268
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004269 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004270 DAG.getNodeValueTypes(TLI.getPointerTy(),
4271 MVT::Other), 2,
4272 Ops, 6);
4273
4274 setValue(&I, Tmp);
4275 DAG.setRoot(Tmp.getValue(1));
4276 return 0;
4277 }
4278
4279 case Intrinsic::gcroot:
4280 if (GFI) {
4281 Value *Alloca = I.getOperand(1);
4282 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004283
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004284 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4285 GFI->addStackRoot(FI->getIndex(), TypeMap);
4286 }
4287 return 0;
4288
4289 case Intrinsic::gcread:
4290 case Intrinsic::gcwrite:
4291 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4292 return 0;
4293
4294 case Intrinsic::flt_rounds: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004295 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004296 return 0;
4297 }
4298
4299 case Intrinsic::trap: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004300 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004301 return 0;
4302 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004303
Bill Wendlingef375462008-11-21 02:38:44 +00004304 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004305 return implVisitAluOverflow(I, ISD::UADDO);
4306 case Intrinsic::sadd_with_overflow:
4307 return implVisitAluOverflow(I, ISD::SADDO);
4308 case Intrinsic::usub_with_overflow:
4309 return implVisitAluOverflow(I, ISD::USUBO);
4310 case Intrinsic::ssub_with_overflow:
4311 return implVisitAluOverflow(I, ISD::SSUBO);
4312 case Intrinsic::umul_with_overflow:
4313 return implVisitAluOverflow(I, ISD::UMULO);
4314 case Intrinsic::smul_with_overflow:
4315 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004316
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004317 case Intrinsic::prefetch: {
4318 SDValue Ops[4];
4319 Ops[0] = getRoot();
4320 Ops[1] = getValue(I.getOperand(1));
4321 Ops[2] = getValue(I.getOperand(2));
4322 Ops[3] = getValue(I.getOperand(3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004323 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004324 return 0;
4325 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004326
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004327 case Intrinsic::memory_barrier: {
4328 SDValue Ops[6];
4329 Ops[0] = getRoot();
4330 for (int x = 1; x < 6; ++x)
4331 Ops[x] = getValue(I.getOperand(x));
4332
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004333 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004334 return 0;
4335 }
4336 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004337 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004338 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004339 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004340 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4341 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004342 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004343 getValue(I.getOperand(2)),
4344 getValue(I.getOperand(3)),
4345 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004346 setValue(&I, L);
4347 DAG.setRoot(L.getValue(1));
4348 return 0;
4349 }
4350 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004351 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004352 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004353 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004354 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004355 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004356 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004357 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004358 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004359 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004360 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004361 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004362 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004363 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004364 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004365 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004366 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004367 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004368 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004369 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004370 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004371 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004372 }
4373}
4374
4375
4376void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4377 bool IsTailCall,
4378 MachineBasicBlock *LandingPad) {
4379 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4380 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4381 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4382 unsigned BeginLabel = 0, EndLabel = 0;
4383
4384 TargetLowering::ArgListTy Args;
4385 TargetLowering::ArgListEntry Entry;
4386 Args.reserve(CS.arg_size());
4387 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4388 i != e; ++i) {
4389 SDValue ArgNode = getValue(*i);
4390 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4391
4392 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004393 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4394 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4395 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4396 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4397 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4398 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004399 Entry.Alignment = CS.getParamAlignment(attrInd);
4400 Args.push_back(Entry);
4401 }
4402
4403 if (LandingPad && MMI) {
4404 // Insert a label before the invoke call to mark the try range. This can be
4405 // used to detect deletion of the invoke via the MachineModuleInfo.
4406 BeginLabel = MMI->NextLabelID();
4407 // Both PendingLoads and PendingExports must be flushed here;
4408 // this call might not return.
4409 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004410 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4411 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004412 }
4413
4414 std::pair<SDValue,SDValue> Result =
4415 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004416 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004417 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4418 CS.paramHasAttr(0, Attribute::InReg),
4419 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004420 IsTailCall && PerformTailCallOpt,
Dale Johannesen66978ee2009-01-31 02:22:37 +00004421 Callee, Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004422 if (CS.getType() != Type::VoidTy)
4423 setValue(CS.getInstruction(), Result.first);
4424 DAG.setRoot(Result.second);
4425
4426 if (LandingPad && MMI) {
4427 // Insert a label at the end of the invoke call to mark the try range. This
4428 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4429 EndLabel = MMI->NextLabelID();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004430 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4431 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004432
4433 // Inform MachineModuleInfo of range.
4434 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4435 }
4436}
4437
4438
4439void SelectionDAGLowering::visitCall(CallInst &I) {
4440 const char *RenameFn = 0;
4441 if (Function *F = I.getCalledFunction()) {
4442 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004443 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4444 if (II) {
4445 if (unsigned IID = II->getIntrinsicID(F)) {
4446 RenameFn = visitIntrinsicCall(I, IID);
4447 if (!RenameFn)
4448 return;
4449 }
4450 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004451 if (unsigned IID = F->getIntrinsicID()) {
4452 RenameFn = visitIntrinsicCall(I, IID);
4453 if (!RenameFn)
4454 return;
4455 }
4456 }
4457
4458 // Check for well-known libc/libm calls. If the function is internal, it
4459 // can't be a library call.
4460 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004461 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004462 const char *NameStr = F->getNameStart();
4463 if (NameStr[0] == 'c' &&
4464 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4465 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4466 if (I.getNumOperands() == 3 && // Basic sanity checks.
4467 I.getOperand(1)->getType()->isFloatingPoint() &&
4468 I.getType() == I.getOperand(1)->getType() &&
4469 I.getType() == I.getOperand(2)->getType()) {
4470 SDValue LHS = getValue(I.getOperand(1));
4471 SDValue RHS = getValue(I.getOperand(2));
Scott Michelfdc40a02009-02-17 22:15:04 +00004472 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004473 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004474 return;
4475 }
4476 } else if (NameStr[0] == 'f' &&
4477 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4478 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4479 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4480 if (I.getNumOperands() == 2 && // Basic sanity checks.
4481 I.getOperand(1)->getType()->isFloatingPoint() &&
4482 I.getType() == I.getOperand(1)->getType()) {
4483 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004484 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004485 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004486 return;
4487 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004488 } else if (NameStr[0] == 's' &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004489 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4490 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4491 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4492 if (I.getNumOperands() == 2 && // Basic sanity checks.
4493 I.getOperand(1)->getType()->isFloatingPoint() &&
4494 I.getType() == I.getOperand(1)->getType()) {
4495 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004496 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004497 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004498 return;
4499 }
4500 } else if (NameStr[0] == 'c' &&
4501 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4502 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4503 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4504 if (I.getNumOperands() == 2 && // Basic sanity checks.
4505 I.getOperand(1)->getType()->isFloatingPoint() &&
4506 I.getType() == I.getOperand(1)->getType()) {
4507 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004508 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004509 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004510 return;
4511 }
4512 }
4513 }
4514 } else if (isa<InlineAsm>(I.getOperand(0))) {
4515 visitInlineAsm(&I);
4516 return;
4517 }
4518
4519 SDValue Callee;
4520 if (!RenameFn)
4521 Callee = getValue(I.getOperand(0));
4522 else
Bill Wendling056292f2008-09-16 21:48:12 +00004523 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004524
4525 LowerCallTo(&I, Callee, I.isTailCall());
4526}
4527
4528
4529/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004530/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004531/// Chain/Flag as the input and updates them for the output Chain/Flag.
4532/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004533SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004534 SDValue &Chain,
4535 SDValue *Flag) const {
4536 // Assemble the legal parts into the final values.
4537 SmallVector<SDValue, 4> Values(ValueVTs.size());
4538 SmallVector<SDValue, 8> Parts;
4539 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4540 // Copy the legal parts from the registers.
4541 MVT ValueVT = ValueVTs[Value];
4542 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4543 MVT RegisterVT = RegVTs[Value];
4544
4545 Parts.resize(NumRegs);
4546 for (unsigned i = 0; i != NumRegs; ++i) {
4547 SDValue P;
4548 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004549 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004550 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004551 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004552 *Flag = P.getValue(2);
4553 }
4554 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004555
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004556 // If the source register was virtual and if we know something about it,
4557 // add an assert node.
4558 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4559 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4560 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4561 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4562 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4563 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004564
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004565 unsigned RegSize = RegisterVT.getSizeInBits();
4566 unsigned NumSignBits = LOI.NumSignBits;
4567 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004568
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004569 // FIXME: We capture more information than the dag can represent. For
4570 // now, just use the tightest assertzext/assertsext possible.
4571 bool isSExt = true;
4572 MVT FromVT(MVT::Other);
4573 if (NumSignBits == RegSize)
4574 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4575 else if (NumZeroBits >= RegSize-1)
4576 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4577 else if (NumSignBits > RegSize-8)
4578 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4579 else if (NumZeroBits >= RegSize-9)
4580 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4581 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004582 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004583 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004584 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004585 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004586 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004587 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004588 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004589
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004590 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004591 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004592 RegisterVT, P, DAG.getValueType(FromVT));
4593
4594 }
4595 }
4596 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004597
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004598 Parts[i] = P;
4599 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004600
Scott Michelfdc40a02009-02-17 22:15:04 +00004601 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004602 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004603 Part += NumRegs;
4604 Parts.clear();
4605 }
4606
Dale Johannesen66978ee2009-01-31 02:22:37 +00004607 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004608 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4609 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004610}
4611
4612/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004613/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004614/// Chain/Flag as the input and updates them for the output Chain/Flag.
4615/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004616void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004617 SDValue &Chain, SDValue *Flag) const {
4618 // Get the list of the values's legal parts.
4619 unsigned NumRegs = Regs.size();
4620 SmallVector<SDValue, 8> Parts(NumRegs);
4621 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4622 MVT ValueVT = ValueVTs[Value];
4623 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4624 MVT RegisterVT = RegVTs[Value];
4625
Dale Johannesen66978ee2009-01-31 02:22:37 +00004626 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004627 &Parts[Part], NumParts, RegisterVT);
4628 Part += NumParts;
4629 }
4630
4631 // Copy the parts into the registers.
4632 SmallVector<SDValue, 8> Chains(NumRegs);
4633 for (unsigned i = 0; i != NumRegs; ++i) {
4634 SDValue Part;
4635 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004636 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004637 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004638 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004639 *Flag = Part.getValue(1);
4640 }
4641 Chains[i] = Part.getValue(0);
4642 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004643
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004644 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004645 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004646 // flagged to it. That is the CopyToReg nodes and the user are considered
4647 // a single scheduling unit. If we create a TokenFactor and return it as
4648 // chain, then the TokenFactor is both a predecessor (operand) of the
4649 // user as well as a successor (the TF operands are flagged to the user).
4650 // c1, f1 = CopyToReg
4651 // c2, f2 = CopyToReg
4652 // c3 = TokenFactor c1, c2
4653 // ...
4654 // = op c3, ..., f2
4655 Chain = Chains[NumRegs-1];
4656 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00004657 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004658}
4659
4660/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004661/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004662/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004663void RegsForValue::AddInlineAsmOperands(unsigned Code,
4664 bool HasMatching,unsigned MatchingIdx,
4665 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004666 std::vector<SDValue> &Ops) const {
4667 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Evan Cheng697cbbf2009-03-20 18:03:34 +00004668 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4669 unsigned Flag = Code | (Regs.size() << 3);
4670 if (HasMatching)
4671 Flag |= 0x80000000 | (MatchingIdx << 16);
4672 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004673 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4674 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4675 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004676 for (unsigned i = 0; i != NumRegs; ++i) {
4677 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004678 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004679 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004680 }
4681}
4682
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004683/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004684/// i.e. it isn't a stack pointer or some other special register, return the
4685/// register class for the register. Otherwise, return null.
4686static const TargetRegisterClass *
4687isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4688 const TargetLowering &TLI,
4689 const TargetRegisterInfo *TRI) {
4690 MVT FoundVT = MVT::Other;
4691 const TargetRegisterClass *FoundRC = 0;
4692 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4693 E = TRI->regclass_end(); RCI != E; ++RCI) {
4694 MVT ThisVT = MVT::Other;
4695
4696 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004697 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004698 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4699 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4700 I != E; ++I) {
4701 if (TLI.isTypeLegal(*I)) {
4702 // If we have already found this register in a different register class,
4703 // choose the one with the largest VT specified. For example, on
4704 // PowerPC, we favor f64 register classes over f32.
4705 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4706 ThisVT = *I;
4707 break;
4708 }
4709 }
4710 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004711
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004712 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004713
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004714 // NOTE: This isn't ideal. In particular, this might allocate the
4715 // frame pointer in functions that need it (due to them not being taken
4716 // out of allocation, because a variable sized allocation hasn't been seen
4717 // yet). This is a slight code pessimization, but should still work.
4718 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4719 E = RC->allocation_order_end(MF); I != E; ++I)
4720 if (*I == Reg) {
4721 // We found a matching register class. Keep looking at others in case
4722 // we find one with larger registers that this physreg is also in.
4723 FoundRC = RC;
4724 FoundVT = ThisVT;
4725 break;
4726 }
4727 }
4728 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004729}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004730
4731
4732namespace llvm {
4733/// AsmOperandInfo - This contains information for each constraint that we are
4734/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004735class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004736 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004737public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004738 /// CallOperand - If this is the result output operand or a clobber
4739 /// this is null, otherwise it is the incoming operand to the CallInst.
4740 /// This gets modified as the asm is processed.
4741 SDValue CallOperand;
4742
4743 /// AssignedRegs - If this is a register or register class operand, this
4744 /// contains the set of register corresponding to the operand.
4745 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004746
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004747 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4748 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4749 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004750
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004751 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4752 /// busy in OutputRegs/InputRegs.
4753 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004754 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004755 std::set<unsigned> &InputRegs,
4756 const TargetRegisterInfo &TRI) const {
4757 if (isOutReg) {
4758 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4759 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4760 }
4761 if (isInReg) {
4762 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4763 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4764 }
4765 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004766
Chris Lattner81249c92008-10-17 17:05:25 +00004767 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4768 /// corresponds to. If there is no Value* for this operand, it returns
4769 /// MVT::Other.
4770 MVT getCallOperandValMVT(const TargetLowering &TLI,
4771 const TargetData *TD) const {
4772 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004773
Chris Lattner81249c92008-10-17 17:05:25 +00004774 if (isa<BasicBlock>(CallOperandVal))
4775 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004776
Chris Lattner81249c92008-10-17 17:05:25 +00004777 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004778
Chris Lattner81249c92008-10-17 17:05:25 +00004779 // If this is an indirect operand, the operand is a pointer to the
4780 // accessed type.
4781 if (isIndirect)
4782 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004783
Chris Lattner81249c92008-10-17 17:05:25 +00004784 // If OpTy is not a single value, it may be a struct/union that we
4785 // can tile with integers.
4786 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4787 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4788 switch (BitSize) {
4789 default: break;
4790 case 1:
4791 case 8:
4792 case 16:
4793 case 32:
4794 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004795 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004796 OpTy = IntegerType::get(BitSize);
4797 break;
4798 }
4799 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004800
Chris Lattner81249c92008-10-17 17:05:25 +00004801 return TLI.getValueType(OpTy, true);
4802 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004803
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004804private:
4805 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4806 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004807 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004808 const TargetRegisterInfo &TRI) {
4809 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4810 Regs.insert(Reg);
4811 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4812 for (; *Aliases; ++Aliases)
4813 Regs.insert(*Aliases);
4814 }
4815};
4816} // end llvm namespace.
4817
4818
4819/// GetRegistersForValue - Assign registers (virtual or physical) for the
4820/// specified operand. We prefer to assign virtual registers, to allow the
4821/// register allocator handle the assignment process. However, if the asm uses
4822/// features that we can't model on machineinstrs, we have SDISel do the
4823/// allocation. This produces generally horrible, but correct, code.
4824///
4825/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004826/// Input and OutputRegs are the set of already allocated physical registers.
4827///
4828void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004829GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004830 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004831 std::set<unsigned> &InputRegs) {
4832 // Compute whether this value requires an input register, an output register,
4833 // or both.
4834 bool isOutReg = false;
4835 bool isInReg = false;
4836 switch (OpInfo.Type) {
4837 case InlineAsm::isOutput:
4838 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004839
4840 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004841 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004842 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004843 break;
4844 case InlineAsm::isInput:
4845 isInReg = true;
4846 isOutReg = false;
4847 break;
4848 case InlineAsm::isClobber:
4849 isOutReg = true;
4850 isInReg = true;
4851 break;
4852 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004853
4854
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004855 MachineFunction &MF = DAG.getMachineFunction();
4856 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004857
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004858 // If this is a constraint for a single physreg, or a constraint for a
4859 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004860 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004861 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4862 OpInfo.ConstraintVT);
4863
4864 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004865 if (OpInfo.ConstraintVT != MVT::Other) {
4866 // If this is a FP input in an integer register (or visa versa) insert a bit
4867 // cast of the input value. More generally, handle any case where the input
4868 // value disagrees with the register class we plan to stick this in.
4869 if (OpInfo.Type == InlineAsm::isInput &&
4870 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4871 // Try to convert to the first MVT that the reg class contains. If the
4872 // types are identical size, use a bitcast to convert (e.g. two differing
4873 // vector types).
4874 MVT RegVT = *PhysReg.second->vt_begin();
4875 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004876 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004877 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004878 OpInfo.ConstraintVT = RegVT;
4879 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4880 // If the input is a FP value and we want it in FP registers, do a
4881 // bitcast to the corresponding integer type. This turns an f64 value
4882 // into i64, which can be passed with two i32 values on a 32-bit
4883 // machine.
4884 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00004885 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004886 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004887 OpInfo.ConstraintVT = RegVT;
4888 }
4889 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004890
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004891 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004892 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004893
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004894 MVT RegVT;
4895 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004896
4897 // If this is a constraint for a specific physical register, like {r17},
4898 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004899 if (unsigned AssignedReg = PhysReg.first) {
4900 const TargetRegisterClass *RC = PhysReg.second;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004901 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004902 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004903
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004904 // Get the actual register value type. This is important, because the user
4905 // may have asked for (e.g.) the AX register in i32 type. We need to
4906 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004907 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004908
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004909 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004910 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004911
4912 // If this is an expanded reference, add the rest of the regs to Regs.
4913 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004914 TargetRegisterClass::iterator I = RC->begin();
4915 for (; *I != AssignedReg; ++I)
4916 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004917
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004918 // Already added the first reg.
4919 --NumRegs; ++I;
4920 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004921 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004922 Regs.push_back(*I);
4923 }
4924 }
4925 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4926 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4927 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4928 return;
4929 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004930
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004931 // Otherwise, if this was a reference to an LLVM register class, create vregs
4932 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00004933 if (const TargetRegisterClass *RC = PhysReg.second) {
4934 RegVT = *RC->vt_begin();
Evan Chengfb112882009-03-23 08:01:15 +00004935 if (OpInfo.ConstraintVT == MVT::Other)
4936 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004937
Evan Chengfb112882009-03-23 08:01:15 +00004938 // Create the appropriate number of virtual registers.
4939 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4940 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00004941 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004942
Evan Chengfb112882009-03-23 08:01:15 +00004943 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4944 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004945 }
Chris Lattnerfc9d1612009-03-24 15:22:11 +00004946
4947 // This is a reference to a register class that doesn't directly correspond
4948 // to an LLVM register class. Allocate NumRegs consecutive, available,
4949 // registers from the class.
4950 std::vector<unsigned> RegClassRegs
4951 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4952 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004953
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004954 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4955 unsigned NumAllocated = 0;
4956 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4957 unsigned Reg = RegClassRegs[i];
4958 // See if this register is available.
4959 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4960 (isInReg && InputRegs.count(Reg))) { // Already used.
4961 // Make sure we find consecutive registers.
4962 NumAllocated = 0;
4963 continue;
4964 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004965
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004966 // Check to see if this register is allocatable (i.e. don't give out the
4967 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00004968 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4969 if (!RC) { // Couldn't allocate this register.
4970 // Reset NumAllocated to make sure we return consecutive registers.
4971 NumAllocated = 0;
4972 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004973 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004974
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004975 // Okay, this register is good, we can use it.
4976 ++NumAllocated;
4977
4978 // If we allocated enough consecutive registers, succeed.
4979 if (NumAllocated == NumRegs) {
4980 unsigned RegStart = (i-NumAllocated)+1;
4981 unsigned RegEnd = i+1;
4982 // Mark all of the allocated registers used.
4983 for (unsigned i = RegStart; i != RegEnd; ++i)
4984 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004985
4986 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004987 OpInfo.ConstraintVT);
4988 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4989 return;
4990 }
4991 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004992
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004993 // Otherwise, we couldn't allocate enough registers for this.
4994}
4995
Evan Chengda43bcf2008-09-24 00:05:32 +00004996/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4997/// processed uses a memory 'm' constraint.
4998static bool
4999hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005000 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005001 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5002 InlineAsm::ConstraintInfo &CI = CInfos[i];
5003 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5004 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5005 if (CType == TargetLowering::C_Memory)
5006 return true;
5007 }
5008 }
5009
5010 return false;
5011}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005012
5013/// visitInlineAsm - Handle a call to an InlineAsm object.
5014///
5015void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5016 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5017
5018 /// ConstraintOperands - Information about all of the constraints.
5019 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005020
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005021 SDValue Chain = getRoot();
5022 SDValue Flag;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005023
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005024 std::set<unsigned> OutputRegs, InputRegs;
5025
5026 // Do a prepass over the constraints, canonicalizing them, and building up the
5027 // ConstraintOperands list.
5028 std::vector<InlineAsm::ConstraintInfo>
5029 ConstraintInfos = IA->ParseConstraints();
5030
Evan Chengda43bcf2008-09-24 00:05:32 +00005031 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005032
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005033 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5034 unsigned ResNo = 0; // ResNo - The result number of the next output.
5035 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5036 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5037 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005038
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005039 MVT OpVT = MVT::Other;
5040
5041 // Compute the value type for each operand.
5042 switch (OpInfo.Type) {
5043 case InlineAsm::isOutput:
5044 // Indirect outputs just consume an argument.
5045 if (OpInfo.isIndirect) {
5046 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5047 break;
5048 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005049
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005050 // The return value of the call is this value. As such, there is no
5051 // corresponding argument.
5052 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5053 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5054 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5055 } else {
5056 assert(ResNo == 0 && "Asm only has one result!");
5057 OpVT = TLI.getValueType(CS.getType());
5058 }
5059 ++ResNo;
5060 break;
5061 case InlineAsm::isInput:
5062 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5063 break;
5064 case InlineAsm::isClobber:
5065 // Nothing to do.
5066 break;
5067 }
5068
5069 // If this is an input or an indirect output, process the call argument.
5070 // BasicBlocks are labels, currently appearing only in asm's.
5071 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00005072 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005073 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005074 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005075 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005076 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005077
Chris Lattner81249c92008-10-17 17:05:25 +00005078 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005079 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005080
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005081 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005082 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005083
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005084 // Second pass over the constraints: compute which constraint option to use
5085 // and assign registers to constraints that want a specific physreg.
5086 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5087 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005088
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005089 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005090 // matching input. If their types mismatch, e.g. one is an integer, the
5091 // other is floating point, or their sizes are different, flag it as an
5092 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005093 if (OpInfo.hasMatchingInput()) {
5094 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5095 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005096 if ((OpInfo.ConstraintVT.isInteger() !=
5097 Input.ConstraintVT.isInteger()) ||
5098 (OpInfo.ConstraintVT.getSizeInBits() !=
5099 Input.ConstraintVT.getSizeInBits())) {
5100 cerr << "Unsupported asm: input constraint with a matching output "
5101 << "constraint of incompatible type!\n";
5102 exit(1);
5103 }
5104 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005105 }
5106 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005107
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005108 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005109 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005110
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005111 // If this is a memory input, and if the operand is not indirect, do what we
5112 // need to to provide an address for the memory input.
5113 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5114 !OpInfo.isIndirect) {
5115 assert(OpInfo.Type == InlineAsm::isInput &&
5116 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005117
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005118 // Memory operands really want the address of the value. If we don't have
5119 // an indirect input, put it in the constpool if we can, otherwise spill
5120 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005121
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005122 // If the operand is a float, integer, or vector constant, spill to a
5123 // constant pool entry to get its address.
5124 Value *OpVal = OpInfo.CallOperandVal;
5125 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5126 isa<ConstantVector>(OpVal)) {
5127 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5128 TLI.getPointerTy());
5129 } else {
5130 // Otherwise, create a stack slot and emit a store to it before the
5131 // asm.
5132 const Type *Ty = OpVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005133 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005134 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5135 MachineFunction &MF = DAG.getMachineFunction();
5136 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5137 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005138 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005139 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005140 OpInfo.CallOperand = StackSlot;
5141 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005142
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005143 // There is no longer a Value* corresponding to this operand.
5144 OpInfo.CallOperandVal = 0;
5145 // It is now an indirect operand.
5146 OpInfo.isIndirect = true;
5147 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005148
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005149 // If this constraint is for a specific register, allocate it before
5150 // anything else.
5151 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005152 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005153 }
5154 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005155
5156
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005157 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005158 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005159 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5160 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005161
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005162 // C_Register operands have already been allocated, Other/Memory don't need
5163 // to be.
5164 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005165 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005166 }
5167
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005168 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5169 std::vector<SDValue> AsmNodeOperands;
5170 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5171 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00005172 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005173
5174
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005175 // Loop over all of the inputs, copying the operand values into the
5176 // appropriate registers and processing the output regs.
5177 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005178
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005179 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5180 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005181
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005182 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5183 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5184
5185 switch (OpInfo.Type) {
5186 case InlineAsm::isOutput: {
5187 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5188 OpInfo.ConstraintType != TargetLowering::C_Register) {
5189 // Memory output, or 'other' output (e.g. 'X' constraint).
5190 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5191
5192 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005193 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5194 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005195 TLI.getPointerTy()));
5196 AsmNodeOperands.push_back(OpInfo.CallOperand);
5197 break;
5198 }
5199
5200 // Otherwise, this is a register or register class output.
5201
5202 // Copy the output from the appropriate register. Find a register that
5203 // we can use.
5204 if (OpInfo.AssignedRegs.Regs.empty()) {
5205 cerr << "Couldn't allocate output reg for constraint '"
5206 << OpInfo.ConstraintCode << "'!\n";
5207 exit(1);
5208 }
5209
5210 // If this is an indirect operand, store through the pointer after the
5211 // asm.
5212 if (OpInfo.isIndirect) {
5213 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5214 OpInfo.CallOperandVal));
5215 } else {
5216 // This is the result value of the call.
5217 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5218 // Concatenate this output onto the outputs list.
5219 RetValRegs.append(OpInfo.AssignedRegs);
5220 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005221
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005222 // Add information to the INLINEASM node to know that this register is
5223 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005224 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5225 6 /* EARLYCLOBBER REGDEF */ :
5226 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005227 false,
5228 0,
Dale Johannesen913d3df2008-09-12 17:49:03 +00005229 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005230 break;
5231 }
5232 case InlineAsm::isInput: {
5233 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005234
Chris Lattner6bdcda32008-10-17 16:47:46 +00005235 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005236 // If this is required to match an output register we have already set,
5237 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005238 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005239
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005240 // Scan until we find the definition we already emitted of this operand.
5241 // When we find it, create a RegsForValue operand.
5242 unsigned CurOp = 2; // The first operand.
5243 for (; OperandNo; --OperandNo) {
5244 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005245 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005246 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005247 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5248 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5249 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005250 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005251 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005252 }
5253
Evan Cheng697cbbf2009-03-20 18:03:34 +00005254 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005255 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005256 if ((OpFlag & 7) == 2 /*REGDEF*/
5257 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5258 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005259 RegsForValue MatchedRegs;
5260 MatchedRegs.TLI = &TLI;
5261 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Evan Chengfb112882009-03-23 08:01:15 +00005262 MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5263 MatchedRegs.RegVTs.push_back(RegVT);
5264 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005265 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005266 i != e; ++i)
5267 MatchedRegs.Regs.
5268 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005269
5270 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005271 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5272 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005273 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5274 true, OpInfo.getMatchedOperand(),
Evan Cheng697cbbf2009-03-20 18:03:34 +00005275 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005276 break;
5277 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005278 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5279 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5280 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005281 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005282 // See InlineAsm.h isUseOperandTiedToDef.
5283 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005284 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005285 TLI.getPointerTy()));
5286 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5287 break;
5288 }
5289 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005290
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005291 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005292 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005293 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005294
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005295 std::vector<SDValue> Ops;
5296 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005297 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005298 if (Ops.empty()) {
5299 cerr << "Invalid operand for inline asm constraint '"
5300 << OpInfo.ConstraintCode << "'!\n";
5301 exit(1);
5302 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005303
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005304 // Add information to the INLINEASM node to know about this input.
5305 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005306 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005307 TLI.getPointerTy()));
5308 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5309 break;
5310 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5311 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5312 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5313 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005314
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005315 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005316 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5317 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005318 TLI.getPointerTy()));
5319 AsmNodeOperands.push_back(InOperandVal);
5320 break;
5321 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005322
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005323 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5324 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5325 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005326 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005327 "Don't know how to handle indirect register inputs yet!");
5328
5329 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005330 if (OpInfo.AssignedRegs.Regs.empty()) {
5331 cerr << "Couldn't allocate output reg for constraint '"
5332 << OpInfo.ConstraintCode << "'!\n";
5333 exit(1);
5334 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005335
Dale Johannesen66978ee2009-01-31 02:22:37 +00005336 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5337 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005338
Evan Cheng697cbbf2009-03-20 18:03:34 +00005339 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Dale Johannesen86b49f82008-09-24 01:07:17 +00005340 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005341 break;
5342 }
5343 case InlineAsm::isClobber: {
5344 // Add the clobbered value to the operand list, so that the register
5345 // allocator is aware that the physreg got clobbered.
5346 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005347 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Evan Cheng697cbbf2009-03-20 18:03:34 +00005348 false, 0, DAG,AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005349 break;
5350 }
5351 }
5352 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005353
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005354 // Finish up input operands.
5355 AsmNodeOperands[0] = Chain;
5356 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005357
Dale Johannesen66978ee2009-01-31 02:22:37 +00005358 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005359 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5360 &AsmNodeOperands[0], AsmNodeOperands.size());
5361 Flag = Chain.getValue(1);
5362
5363 // If this asm returns a register value, copy the result from that register
5364 // and set it as the value of the call.
5365 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005366 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005367 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005368
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005369 // FIXME: Why don't we do this for inline asms with MRVs?
5370 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5371 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005372
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005373 // If any of the results of the inline asm is a vector, it may have the
5374 // wrong width/num elts. This can happen for register classes that can
5375 // contain multiple different value types. The preg or vreg allocated may
5376 // not have the same VT as was expected. Convert it to the right type
5377 // with bit_convert.
5378 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005379 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005380 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005381
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005382 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005383 ResultType.isInteger() && Val.getValueType().isInteger()) {
5384 // If a result value was tied to an input value, the computed result may
5385 // have a wider width than the expected result. Extract the relevant
5386 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005387 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005388 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005389
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005390 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005391 }
Dan Gohman95915732008-10-18 01:03:45 +00005392
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005393 setValue(CS.getInstruction(), Val);
5394 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005395
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005396 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005397
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005398 // Process indirect outputs, first output all of the flagged copies out of
5399 // physregs.
5400 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5401 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5402 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005403 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5404 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005405 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5406 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005407
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005408 // Emit the non-flagged stores from the physregs.
5409 SmallVector<SDValue, 8> OutChains;
5410 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005411 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005412 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005413 getValue(StoresToEmit[i].second),
5414 StoresToEmit[i].second, 0));
5415 if (!OutChains.empty())
Dale Johannesen66978ee2009-01-31 02:22:37 +00005416 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005417 &OutChains[0], OutChains.size());
5418 DAG.setRoot(Chain);
5419}
5420
5421
5422void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5423 SDValue Src = getValue(I.getOperand(0));
5424
Chris Lattner0b18e592009-03-17 19:36:00 +00005425 // Scale up by the type size in the original i32 type width. Various
5426 // mid-level optimizers may make assumptions about demanded bits etc from the
5427 // i32-ness of the optimizer: we do not want to promote to i64 and then
5428 // multiply on 64-bit targets.
5429 // FIXME: Malloc inst should go away: PR715.
5430 uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
5431 if (ElementSize != 1)
5432 Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5433 Src, DAG.getConstant(ElementSize, Src.getValueType()));
5434
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005435 MVT IntPtr = TLI.getPointerTy();
5436
5437 if (IntPtr.bitsLT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005438 Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005439 else if (IntPtr.bitsGT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005440 Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005441
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005442 TargetLowering::ArgListTy Args;
5443 TargetLowering::ArgListEntry Entry;
5444 Entry.Node = Src;
5445 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5446 Args.push_back(Entry);
5447
5448 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005449 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005450 CallingConv::C, PerformTailCallOpt,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005451 DAG.getExternalSymbol("malloc", IntPtr),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005452 Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005453 setValue(&I, Result.first); // Pointers always fit in registers
5454 DAG.setRoot(Result.second);
5455}
5456
5457void SelectionDAGLowering::visitFree(FreeInst &I) {
5458 TargetLowering::ArgListTy Args;
5459 TargetLowering::ArgListEntry Entry;
5460 Entry.Node = getValue(I.getOperand(0));
5461 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5462 Args.push_back(Entry);
5463 MVT IntPtr = TLI.getPointerTy();
5464 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005465 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005466 CallingConv::C, PerformTailCallOpt,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005467 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
Dale Johannesen66978ee2009-01-31 02:22:37 +00005468 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005469 DAG.setRoot(Result.second);
5470}
5471
5472void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005473 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005474 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005475 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005476 DAG.getSrcValue(I.getOperand(1))));
5477}
5478
5479void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005480 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5481 getRoot(), getValue(I.getOperand(0)),
5482 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005483 setValue(&I, V);
5484 DAG.setRoot(V.getValue(1));
5485}
5486
5487void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005488 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005489 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005490 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005491 DAG.getSrcValue(I.getOperand(1))));
5492}
5493
5494void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005495 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005496 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005497 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005498 getValue(I.getOperand(2)),
5499 DAG.getSrcValue(I.getOperand(1)),
5500 DAG.getSrcValue(I.getOperand(2))));
5501}
5502
5503/// TargetLowering::LowerArguments - This is the default LowerArguments
5504/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005505/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005506/// integrated into SDISel.
5507void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005508 SmallVectorImpl<SDValue> &ArgValues,
5509 DebugLoc dl) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005510 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5511 SmallVector<SDValue, 3+16> Ops;
5512 Ops.push_back(DAG.getRoot());
5513 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5514 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5515
5516 // Add one result value for each formal argument.
5517 SmallVector<MVT, 16> RetVals;
5518 unsigned j = 1;
5519 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5520 I != E; ++I, ++j) {
5521 SmallVector<MVT, 4> ValueVTs;
5522 ComputeValueVTs(*this, I->getType(), ValueVTs);
5523 for (unsigned Value = 0, NumValues = ValueVTs.size();
5524 Value != NumValues; ++Value) {
5525 MVT VT = ValueVTs[Value];
5526 const Type *ArgTy = VT.getTypeForMVT();
5527 ISD::ArgFlagsTy Flags;
5528 unsigned OriginalAlignment =
5529 getTargetData()->getABITypeAlignment(ArgTy);
5530
Devang Patel05988662008-09-25 21:00:45 +00005531 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005532 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005533 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005534 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005535 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005536 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005537 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005538 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005539 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005540 Flags.setByVal();
5541 const PointerType *Ty = cast<PointerType>(I->getType());
5542 const Type *ElementTy = Ty->getElementType();
5543 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005544 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005545 // For ByVal, alignment should be passed from FE. BE will guess if
5546 // this info is not there but there are cases it cannot get right.
5547 if (F.getParamAlignment(j))
5548 FrameAlign = F.getParamAlignment(j);
5549 Flags.setByValAlign(FrameAlign);
5550 Flags.setByValSize(FrameSize);
5551 }
Devang Patel05988662008-09-25 21:00:45 +00005552 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005553 Flags.setNest();
5554 Flags.setOrigAlign(OriginalAlignment);
5555
5556 MVT RegisterVT = getRegisterType(VT);
5557 unsigned NumRegs = getNumRegisters(VT);
5558 for (unsigned i = 0; i != NumRegs; ++i) {
5559 RetVals.push_back(RegisterVT);
5560 ISD::ArgFlagsTy MyFlags = Flags;
5561 if (NumRegs > 1 && i == 0)
5562 MyFlags.setSplit();
5563 // if it isn't first piece, alignment must be 1
5564 else if (i > 0)
5565 MyFlags.setOrigAlign(1);
5566 Ops.push_back(DAG.getArgFlags(MyFlags));
5567 }
5568 }
5569 }
5570
5571 RetVals.push_back(MVT::Other);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005572
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005573 // Create the node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005574 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005575 DAG.getVTList(&RetVals[0], RetVals.size()),
5576 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005577
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005578 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5579 // allows exposing the loads that may be part of the argument access to the
5580 // first DAGCombiner pass.
5581 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005582
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005583 // The number of results should match up, except that the lowered one may have
5584 // an extra flag result.
5585 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5586 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5587 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5588 && "Lowering produced unexpected number of results!");
5589
5590 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5591 if (Result != TmpRes.getNode() && Result->use_empty()) {
5592 HandleSDNode Dummy(DAG.getRoot());
5593 DAG.RemoveDeadNode(Result);
5594 }
5595
5596 Result = TmpRes.getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005597
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005598 unsigned NumArgRegs = Result->getNumValues() - 1;
5599 DAG.setRoot(SDValue(Result, NumArgRegs));
5600
5601 // Set up the return result vector.
5602 unsigned i = 0;
5603 unsigned Idx = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005604 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005605 ++I, ++Idx) {
5606 SmallVector<MVT, 4> ValueVTs;
5607 ComputeValueVTs(*this, I->getType(), ValueVTs);
5608 for (unsigned Value = 0, NumValues = ValueVTs.size();
5609 Value != NumValues; ++Value) {
5610 MVT VT = ValueVTs[Value];
5611 MVT PartVT = getRegisterType(VT);
5612
5613 unsigned NumParts = getNumRegisters(VT);
5614 SmallVector<SDValue, 4> Parts(NumParts);
5615 for (unsigned j = 0; j != NumParts; ++j)
5616 Parts[j] = SDValue(Result, i++);
5617
5618 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005619 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005620 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005621 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005622 AssertOp = ISD::AssertZext;
5623
Dale Johannesen66978ee2009-01-31 02:22:37 +00005624 ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5625 PartVT, VT, AssertOp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005626 }
5627 }
5628 assert(i == NumArgRegs && "Argument register count mismatch!");
5629}
5630
5631
5632/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5633/// implementation, which just inserts an ISD::CALL node, which is later custom
5634/// lowered by the target to something concrete. FIXME: When all targets are
5635/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5636std::pair<SDValue, SDValue>
5637TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5638 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005639 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005640 unsigned CallingConv, bool isTailCall,
5641 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005642 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005643 assert((!isTailCall || PerformTailCallOpt) &&
5644 "isTailCall set when tail-call optimizations are disabled!");
5645
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005646 SmallVector<SDValue, 32> Ops;
5647 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005648 Ops.push_back(Callee);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005649
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005650 // Handle all of the outgoing arguments.
5651 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5652 SmallVector<MVT, 4> ValueVTs;
5653 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5654 for (unsigned Value = 0, NumValues = ValueVTs.size();
5655 Value != NumValues; ++Value) {
5656 MVT VT = ValueVTs[Value];
5657 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005658 SDValue Op = SDValue(Args[i].Node.getNode(),
5659 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005660 ISD::ArgFlagsTy Flags;
5661 unsigned OriginalAlignment =
5662 getTargetData()->getABITypeAlignment(ArgTy);
5663
5664 if (Args[i].isZExt)
5665 Flags.setZExt();
5666 if (Args[i].isSExt)
5667 Flags.setSExt();
5668 if (Args[i].isInReg)
5669 Flags.setInReg();
5670 if (Args[i].isSRet)
5671 Flags.setSRet();
5672 if (Args[i].isByVal) {
5673 Flags.setByVal();
5674 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5675 const Type *ElementTy = Ty->getElementType();
5676 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005677 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005678 // For ByVal, alignment should come from FE. BE will guess if this
5679 // info is not there but there are cases it cannot get right.
5680 if (Args[i].Alignment)
5681 FrameAlign = Args[i].Alignment;
5682 Flags.setByValAlign(FrameAlign);
5683 Flags.setByValSize(FrameSize);
5684 }
5685 if (Args[i].isNest)
5686 Flags.setNest();
5687 Flags.setOrigAlign(OriginalAlignment);
5688
5689 MVT PartVT = getRegisterType(VT);
5690 unsigned NumParts = getNumRegisters(VT);
5691 SmallVector<SDValue, 4> Parts(NumParts);
5692 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5693
5694 if (Args[i].isSExt)
5695 ExtendKind = ISD::SIGN_EXTEND;
5696 else if (Args[i].isZExt)
5697 ExtendKind = ISD::ZERO_EXTEND;
5698
Dale Johannesen66978ee2009-01-31 02:22:37 +00005699 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005700
5701 for (unsigned i = 0; i != NumParts; ++i) {
5702 // if it isn't first piece, alignment must be 1
5703 ISD::ArgFlagsTy MyFlags = Flags;
5704 if (NumParts > 1 && i == 0)
5705 MyFlags.setSplit();
5706 else if (i != 0)
5707 MyFlags.setOrigAlign(1);
5708
5709 Ops.push_back(Parts[i]);
5710 Ops.push_back(DAG.getArgFlags(MyFlags));
5711 }
5712 }
5713 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005714
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005715 // Figure out the result value types. We start by making a list of
5716 // the potentially illegal return value types.
5717 SmallVector<MVT, 4> LoweredRetTys;
5718 SmallVector<MVT, 4> RetTys;
5719 ComputeValueVTs(*this, RetTy, RetTys);
5720
5721 // Then we translate that to a list of legal types.
5722 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5723 MVT VT = RetTys[I];
5724 MVT RegisterVT = getRegisterType(VT);
5725 unsigned NumRegs = getNumRegisters(VT);
5726 for (unsigned i = 0; i != NumRegs; ++i)
5727 LoweredRetTys.push_back(RegisterVT);
5728 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005729
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005730 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005731
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005732 // Create the CALL node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005733 SDValue Res = DAG.getCall(CallingConv, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005734 isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005735 DAG.getVTList(&LoweredRetTys[0],
5736 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005737 &Ops[0], Ops.size()
5738 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005739 Chain = Res.getValue(LoweredRetTys.size() - 1);
5740
5741 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005742 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005743 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5744
5745 if (RetSExt)
5746 AssertOp = ISD::AssertSext;
5747 else if (RetZExt)
5748 AssertOp = ISD::AssertZext;
5749
5750 SmallVector<SDValue, 4> ReturnValues;
5751 unsigned RegNo = 0;
5752 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5753 MVT VT = RetTys[I];
5754 MVT RegisterVT = getRegisterType(VT);
5755 unsigned NumRegs = getNumRegisters(VT);
5756 unsigned RegNoEnd = NumRegs + RegNo;
5757 SmallVector<SDValue, 4> Results;
5758 for (; RegNo != RegNoEnd; ++RegNo)
5759 Results.push_back(Res.getValue(RegNo));
5760 SDValue ReturnValue =
Dale Johannesen66978ee2009-01-31 02:22:37 +00005761 getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005762 AssertOp);
5763 ReturnValues.push_back(ReturnValue);
5764 }
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005765 Res = DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00005766 DAG.getVTList(&RetTys[0], RetTys.size()),
5767 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005768 }
5769
5770 return std::make_pair(Res, Chain);
5771}
5772
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005773void TargetLowering::LowerOperationWrapper(SDNode *N,
5774 SmallVectorImpl<SDValue> &Results,
5775 SelectionDAG &DAG) {
5776 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005777 if (Res.getNode())
5778 Results.push_back(Res);
5779}
5780
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005781SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5782 assert(0 && "LowerOperation not implemented for this target!");
5783 abort();
5784 return SDValue();
5785}
5786
5787
5788void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5789 SDValue Op = getValue(V);
5790 assert((Op.getOpcode() != ISD::CopyFromReg ||
5791 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5792 "Copy from a reg to the same reg!");
5793 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5794
5795 RegsForValue RFV(TLI, Reg, V->getType());
5796 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005797 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005798 PendingExports.push_back(Chain);
5799}
5800
5801#include "llvm/CodeGen/SelectionDAGISel.h"
5802
5803void SelectionDAGISel::
5804LowerArguments(BasicBlock *LLVMBB) {
5805 // If this is the entry block, emit arguments.
5806 Function &F = *LLVMBB->getParent();
5807 SDValue OldRoot = SDL->DAG.getRoot();
5808 SmallVector<SDValue, 16> Args;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005809 TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005810
5811 unsigned a = 0;
5812 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5813 AI != E; ++AI) {
5814 SmallVector<MVT, 4> ValueVTs;
5815 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5816 unsigned NumValues = ValueVTs.size();
5817 if (!AI->use_empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005818 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
Dale Johannesen4be0bdf2009-02-05 00:20:09 +00005819 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005820 // If this argument is live outside of the entry block, insert a copy from
5821 // whereever we got it to the vreg that other BB's will reference it as.
5822 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5823 if (VMI != FuncInfo->ValueMap.end()) {
5824 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5825 }
5826 }
5827 a += NumValues;
5828 }
5829
5830 // Finally, if the target has anything special to do, allow it to do so.
5831 // FIXME: this should insert code into the DAG!
5832 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5833}
5834
5835/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5836/// ensure constants are generated when needed. Remember the virtual registers
5837/// that need to be added to the Machine PHI nodes as input. We cannot just
5838/// directly add them, because expansion might result in multiple MBB's for one
5839/// BB. As such, the start of the BB might correspond to a different MBB than
5840/// the end.
5841///
5842void
5843SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5844 TerminatorInst *TI = LLVMBB->getTerminator();
5845
5846 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5847
5848 // Check successor nodes' PHI nodes that expect a constant to be available
5849 // from this block.
5850 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5851 BasicBlock *SuccBB = TI->getSuccessor(succ);
5852 if (!isa<PHINode>(SuccBB->begin())) continue;
5853 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005854
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005855 // If this terminator has multiple identical successors (common for
5856 // switches), only handle each succ once.
5857 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005858
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005859 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5860 PHINode *PN;
5861
5862 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5863 // nodes and Machine PHI nodes, but the incoming operands have not been
5864 // emitted yet.
5865 for (BasicBlock::iterator I = SuccBB->begin();
5866 (PN = dyn_cast<PHINode>(I)); ++I) {
5867 // Ignore dead phi's.
5868 if (PN->use_empty()) continue;
5869
5870 unsigned Reg;
5871 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5872
5873 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5874 unsigned &RegOut = SDL->ConstantsOut[C];
5875 if (RegOut == 0) {
5876 RegOut = FuncInfo->CreateRegForValue(C);
5877 SDL->CopyValueToVirtualRegister(C, RegOut);
5878 }
5879 Reg = RegOut;
5880 } else {
5881 Reg = FuncInfo->ValueMap[PHIOp];
5882 if (Reg == 0) {
5883 assert(isa<AllocaInst>(PHIOp) &&
5884 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5885 "Didn't codegen value into a register!??");
5886 Reg = FuncInfo->CreateRegForValue(PHIOp);
5887 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5888 }
5889 }
5890
5891 // Remember that this register needs to added to the machine PHI node as
5892 // the input for this MBB.
5893 SmallVector<MVT, 4> ValueVTs;
5894 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5895 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5896 MVT VT = ValueVTs[vti];
5897 unsigned NumRegisters = TLI.getNumRegisters(VT);
5898 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5899 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5900 Reg += NumRegisters;
5901 }
5902 }
5903 }
5904 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005905}
5906
Dan Gohman3df24e62008-09-03 23:12:08 +00005907/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5908/// supports legal types, and it emits MachineInstrs directly instead of
5909/// creating SelectionDAG nodes.
5910///
5911bool
5912SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5913 FastISel *F) {
5914 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005915
Dan Gohman3df24e62008-09-03 23:12:08 +00005916 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5917 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5918
5919 // Check successor nodes' PHI nodes that expect a constant to be available
5920 // from this block.
5921 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5922 BasicBlock *SuccBB = TI->getSuccessor(succ);
5923 if (!isa<PHINode>(SuccBB->begin())) continue;
5924 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005925
Dan Gohman3df24e62008-09-03 23:12:08 +00005926 // If this terminator has multiple identical successors (common for
5927 // switches), only handle each succ once.
5928 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005929
Dan Gohman3df24e62008-09-03 23:12:08 +00005930 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5931 PHINode *PN;
5932
5933 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5934 // nodes and Machine PHI nodes, but the incoming operands have not been
5935 // emitted yet.
5936 for (BasicBlock::iterator I = SuccBB->begin();
5937 (PN = dyn_cast<PHINode>(I)); ++I) {
5938 // Ignore dead phi's.
5939 if (PN->use_empty()) continue;
5940
5941 // Only handle legal types. Two interesting things to note here. First,
5942 // by bailing out early, we may leave behind some dead instructions,
5943 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5944 // own moves. Second, this check is necessary becuase FastISel doesn't
5945 // use CreateRegForValue to create registers, so it always creates
5946 // exactly one register for each non-void instruction.
5947 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5948 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005949 // Promote MVT::i1.
5950 if (VT == MVT::i1)
5951 VT = TLI.getTypeToTransformTo(VT);
5952 else {
5953 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5954 return false;
5955 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005956 }
5957
5958 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5959
5960 unsigned Reg = F->getRegForValue(PHIOp);
5961 if (Reg == 0) {
5962 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5963 return false;
5964 }
5965 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5966 }
5967 }
5968
5969 return true;
5970}