blob: fd5fcbb1aad18d07fcebeae61c7908d0d89e7d53 [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 }
Dan Gohman5e5558b2009-04-23 22:50:03 +0000138 // Interpret void as zero return values.
139 if (Ty == Type::VoidTy)
140 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000141 // Base case: we can get an MVT for this LLVM IR type.
142 ValueVTs.push_back(TLI.getValueType(Ty));
143 if (Offsets)
144 Offsets->push_back(StartingOffset);
145}
146
Dan Gohman2a7c6712008-09-03 23:18:39 +0000147namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000148 /// RegsForValue - This struct represents the registers (physical or virtual)
149 /// that a particular set of values is assigned, and the type information about
150 /// the value. The most common situation is to represent one value at a time,
151 /// but struct or array values are handled element-wise as multiple values.
152 /// The splitting of aggregates is performed recursively, so that we never
153 /// have aggregate-typed registers. The values at this point do not necessarily
154 /// have legal types, so each value may require one or more registers of some
155 /// legal type.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000156 ///
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000157 struct VISIBILITY_HIDDEN RegsForValue {
158 /// TLI - The TargetLowering object.
159 ///
160 const TargetLowering *TLI;
161
162 /// ValueVTs - The value types of the values, which may not be legal, and
163 /// may need be promoted or synthesized from one or more registers.
164 ///
165 SmallVector<MVT, 4> ValueVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000166
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000167 /// RegVTs - The value types of the registers. This is the same size as
168 /// ValueVTs and it records, for each value, what the type of the assigned
169 /// register or registers are. (Individual values are never synthesized
170 /// from more than one type of register.)
171 ///
172 /// With virtual registers, the contents of RegVTs is redundant with TLI's
173 /// getRegisterType member function, however when with physical registers
174 /// it is necessary to have a separate record of the types.
175 ///
176 SmallVector<MVT, 4> RegVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000177
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000178 /// Regs - This list holds the registers assigned to the values.
179 /// Each legal or promoted value requires one register, and each
180 /// expanded value requires multiple registers.
181 ///
182 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000183
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000184 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000185
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000186 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000187 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000188 MVT regvt, MVT valuevt)
189 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
190 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000191 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000192 const SmallVector<MVT, 4> &regvts,
193 const SmallVector<MVT, 4> &valuevts)
194 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
195 RegsForValue(const TargetLowering &tli,
196 unsigned Reg, const Type *Ty) : TLI(&tli) {
197 ComputeValueVTs(tli, Ty, ValueVTs);
198
199 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
200 MVT ValueVT = ValueVTs[Value];
201 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
202 MVT RegisterVT = TLI->getRegisterType(ValueVT);
203 for (unsigned i = 0; i != NumRegs; ++i)
204 Regs.push_back(Reg + i);
205 RegVTs.push_back(RegisterVT);
206 Reg += NumRegs;
207 }
208 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000209
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000210 /// append - Add the specified values to this one.
211 void append(const RegsForValue &RHS) {
212 TLI = RHS.TLI;
213 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
214 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
215 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
216 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000217
218
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000219 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000220 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000221 /// Chain/Flag as the input and updates them for the output Chain/Flag.
222 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000223 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000224 SDValue &Chain, SDValue *Flag) const;
225
226 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000227 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000228 /// Chain/Flag as the input and updates them for the output Chain/Flag.
229 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000230 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000231 SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000232
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000233 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Evan Cheng697cbbf2009-03-20 18:03:34 +0000234 /// operand list. This adds the code marker, matching input operand index
235 /// (if applicable), and includes the number of values added into it.
236 void AddInlineAsmOperands(unsigned Code,
237 bool HasMatching, unsigned MatchingIdx,
238 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000239 };
240}
241
242/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000243/// PHI nodes or outside of the basic block that defines it, or used by a
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000244/// switch or atomic instruction, which may expand to multiple basic blocks.
245static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
246 if (isa<PHINode>(I)) return true;
247 BasicBlock *BB = I->getParent();
248 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Dan Gohman8e5c0da2009-04-09 02:33:36 +0000249 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000250 return true;
251 return false;
252}
253
254/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
255/// entry block, return true. This includes arguments used by switches, since
256/// the switch may expand into multiple basic blocks.
257static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
258 // With FastISel active, we may be splitting blocks, so force creation
259 // of virtual registers for all non-dead arguments.
Dan Gohman33134c42008-09-25 17:05:24 +0000260 // Don't force virtual registers for byval arguments though, because
261 // fast-isel can't handle those in all cases.
262 if (EnableFastISel && !A->hasByValAttr())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000263 return A->use_empty();
264
265 BasicBlock *Entry = A->getParent()->begin();
266 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
267 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
268 return false; // Use not in entry block.
269 return true;
270}
271
272FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
273 : TLI(tli) {
274}
275
276void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000277 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000278 bool EnableFastISel) {
279 Fn = &fn;
280 MF = &mf;
281 RegInfo = &MF->getRegInfo();
282
283 // Create a vreg for each argument register that is not dead and is used
284 // outside of the entry block for the function.
285 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
286 AI != E; ++AI)
287 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
288 InitializeRegForValue(AI);
289
290 // Initialize the mapping of values to registers. This is only set up for
291 // instruction values that are used outside of the block that defines
292 // them.
293 Function::iterator BB = Fn->begin(), EB = Fn->end();
294 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
295 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
296 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
297 const Type *Ty = AI->getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000298 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000299 unsigned Align =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000300 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
301 AI->getAlignment());
302
303 TySize *= CUI->getZExtValue(); // Get total allocated size.
304 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
305 StaticAllocaMap[AI] =
306 MF->getFrameInfo()->CreateStackObject(TySize, Align);
307 }
308
309 for (; BB != EB; ++BB)
310 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
311 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
312 if (!isa<AllocaInst>(I) ||
313 !StaticAllocaMap.count(cast<AllocaInst>(I)))
314 InitializeRegForValue(I);
315
316 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
317 // also creates the initial PHI MachineInstrs, though none of the input
318 // operands are populated.
319 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
320 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
321 MBBMap[BB] = MBB;
322 MF->push_back(MBB);
323
324 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
325 // appropriate.
326 PHINode *PN;
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000327 DebugLoc DL;
328 for (BasicBlock::iterator
329 I = BB->begin(), E = BB->end(); I != E; ++I) {
330 if (CallInst *CI = dyn_cast<CallInst>(I)) {
331 if (Function *F = CI->getCalledFunction()) {
332 switch (F->getIntrinsicID()) {
333 default: break;
334 case Intrinsic::dbg_stoppoint: {
335 DwarfWriter *DW = DAG.getDwarfWriter();
336 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
337
Devang Patel48c7fa22009-04-13 18:13:16 +0000338 if (DW && DW->ValidDebugInfo(SPI->getContext(), false)) {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000339 DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
Bill Wendling0582ae92009-03-13 04:39:26 +0000340 std::string Dir, FN;
341 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
342 CU.getFilename(FN));
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000343 unsigned idx = MF->getOrCreateDebugLocID(SrcFile,
Scott Michelfdc40a02009-02-17 22:15:04 +0000344 SPI->getLine(),
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000345 SPI->getColumn());
346 DL = DebugLoc::get(idx);
347 }
348
349 break;
350 }
351 case Intrinsic::dbg_func_start: {
352 DwarfWriter *DW = DAG.getDwarfWriter();
353 if (DW) {
354 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
355 Value *SP = FSI->getSubprogram();
356
Devang Patel48c7fa22009-04-13 18:13:16 +0000357 if (DW->ValidDebugInfo(SP, false)) {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000358 DISubprogram Subprogram(cast<GlobalVariable>(SP));
359 DICompileUnit CU(Subprogram.getCompileUnit());
Bill Wendling0582ae92009-03-13 04:39:26 +0000360 std::string Dir, FN;
361 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
362 CU.getFilename(FN));
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000363 unsigned Line = Subprogram.getLineNumber();
364 DL = DebugLoc::get(MF->getOrCreateDebugLocID(SrcFile, Line, 0));
365 }
366 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000367
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000368 break;
369 }
370 }
371 }
372 }
373
374 PN = dyn_cast<PHINode>(I);
375 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000376
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000377 unsigned PHIReg = ValueMap[PN];
378 assert(PHIReg && "PHI node does not have an assigned virtual register!");
379
380 SmallVector<MVT, 4> ValueVTs;
381 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
382 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
383 MVT VT = ValueVTs[vti];
384 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000385 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000386 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000387 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000388 PHIReg += NumRegisters;
389 }
390 }
391 }
392}
393
394unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
395 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
396}
397
398/// CreateRegForValue - Allocate the appropriate number of virtual registers of
399/// the correctly promoted or expanded types. Assign these registers
400/// consecutive vreg numbers and return the first assigned number.
401///
402/// In the case that the given value has struct or array type, this function
403/// will assign registers for each member or element.
404///
405unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
406 SmallVector<MVT, 4> ValueVTs;
407 ComputeValueVTs(TLI, V->getType(), ValueVTs);
408
409 unsigned FirstReg = 0;
410 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
411 MVT ValueVT = ValueVTs[Value];
412 MVT RegisterVT = TLI.getRegisterType(ValueVT);
413
414 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
415 for (unsigned i = 0; i != NumRegs; ++i) {
416 unsigned R = MakeReg(RegisterVT);
417 if (!FirstReg) FirstReg = R;
418 }
419 }
420 return FirstReg;
421}
422
423/// getCopyFromParts - Create a value that contains the specified legal parts
424/// combined into the value they represent. If the parts combine to a type
425/// larger then ValueVT then AssertOp can be used to specify whether the extra
426/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
427/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000428static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
429 const SDValue *Parts,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000430 unsigned NumParts, MVT PartVT, MVT ValueVT,
431 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000432 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000434 SDValue Val = Parts[0];
435
436 if (NumParts > 1) {
437 // Assemble the value from multiple parts.
438 if (!ValueVT.isVector()) {
439 unsigned PartBits = PartVT.getSizeInBits();
440 unsigned ValueBits = ValueVT.getSizeInBits();
441
442 // Assemble the power of 2 part.
443 unsigned RoundParts = NumParts & (NumParts - 1) ?
444 1 << Log2_32(NumParts) : NumParts;
445 unsigned RoundBits = PartBits * RoundParts;
446 MVT RoundVT = RoundBits == ValueBits ?
447 ValueVT : MVT::getIntegerVT(RoundBits);
448 SDValue Lo, Hi;
449
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000450 MVT HalfVT = ValueVT.isInteger() ?
451 MVT::getIntegerVT(RoundBits/2) :
452 MVT::getFloatingPointVT(RoundBits/2);
453
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000454 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000455 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
456 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000457 PartVT, HalfVT);
458 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000459 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
460 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000461 }
462 if (TLI.isBigEndian())
463 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000464 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000465
466 if (RoundParts < NumParts) {
467 // Assemble the trailing non-power-of-2 part.
468 unsigned OddParts = NumParts - RoundParts;
469 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Scott Michelfdc40a02009-02-17 22:15:04 +0000470 Hi = getCopyFromParts(DAG, dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000471 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000472
473 // Combine the round and odd parts.
474 Lo = Val;
475 if (TLI.isBigEndian())
476 std::swap(Lo, Hi);
477 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000478 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
479 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000480 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000481 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000482 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
483 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000484 }
485 } else {
486 // Handle a multi-element vector.
487 MVT IntermediateVT, RegisterVT;
488 unsigned NumIntermediates;
489 unsigned NumRegs =
490 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
491 RegisterVT);
492 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
493 NumParts = NumRegs; // Silence a compiler warning.
494 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
495 assert(RegisterVT == Parts[0].getValueType() &&
496 "Part type doesn't match part!");
497
498 // Assemble the parts into intermediate operands.
499 SmallVector<SDValue, 8> Ops(NumIntermediates);
500 if (NumIntermediates == NumParts) {
501 // If the register was not expanded, truncate or copy the value,
502 // as appropriate.
503 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000504 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000505 PartVT, IntermediateVT);
506 } else if (NumParts > 0) {
507 // If the intermediate type was expanded, build the intermediate operands
508 // from the parts.
509 assert(NumParts % NumIntermediates == 0 &&
510 "Must expand into a divisible number of parts!");
511 unsigned Factor = NumParts / NumIntermediates;
512 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000513 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000514 PartVT, IntermediateVT);
515 }
516
517 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
518 // operands.
519 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000520 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000521 ValueVT, &Ops[0], NumIntermediates);
522 }
523 }
524
525 // There is now one part, held in Val. Correct it to match ValueVT.
526 PartVT = Val.getValueType();
527
528 if (PartVT == ValueVT)
529 return Val;
530
531 if (PartVT.isVector()) {
532 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000533 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000534 }
535
536 if (ValueVT.isVector()) {
537 assert(ValueVT.getVectorElementType() == PartVT &&
538 ValueVT.getVectorNumElements() == 1 &&
539 "Only trivial scalar-to-vector conversions should get here!");
Evan Chenga87008d2009-02-25 22:49:59 +0000540 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000541 }
542
543 if (PartVT.isInteger() &&
544 ValueVT.isInteger()) {
545 if (ValueVT.bitsLT(PartVT)) {
546 // For a truncate, see if we have any information to
547 // indicate whether the truncated bits will always be
548 // zero or sign-extension.
549 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000550 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000551 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000552 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000553 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000554 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000555 }
556 }
557
558 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
559 if (ValueVT.bitsLT(Val.getValueType()))
560 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000561 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000562 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000563 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000564 }
565
566 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000567 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000568
569 assert(0 && "Unknown mismatch!");
570 return SDValue();
571}
572
573/// getCopyToParts - Create a series of nodes that contain the specified value
574/// split into legal parts. If the parts contain more bits than Val, then, for
575/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000576static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Chris Lattner01426e12008-10-21 00:45:36 +0000577 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000578 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000579 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000580 MVT PtrVT = TLI.getPointerTy();
581 MVT ValueVT = Val.getValueType();
582 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000583 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000584 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
585
586 if (!NumParts)
587 return;
588
589 if (!ValueVT.isVector()) {
590 if (PartVT == ValueVT) {
591 assert(NumParts == 1 && "No-op copy with multiple parts!");
592 Parts[0] = Val;
593 return;
594 }
595
596 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
597 // If the parts cover more bits than the value has, promote the value.
598 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
599 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000600 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000601 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
602 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000603 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000604 } else {
605 assert(0 && "Unknown mismatch!");
606 }
607 } else if (PartBits == ValueVT.getSizeInBits()) {
608 // Different types of the same size.
609 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000610 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000611 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
612 // If the parts cover less bits than value has, truncate the value.
613 if (PartVT.isInteger() && ValueVT.isInteger()) {
614 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000615 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000616 } else {
617 assert(0 && "Unknown mismatch!");
618 }
619 }
620
621 // The value may have changed - recompute ValueVT.
622 ValueVT = Val.getValueType();
623 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
624 "Failed to tile the value with PartVT!");
625
626 if (NumParts == 1) {
627 assert(PartVT == ValueVT && "Type conversion failed!");
628 Parts[0] = Val;
629 return;
630 }
631
632 // Expand the value into multiple parts.
633 if (NumParts & (NumParts - 1)) {
634 // The number of parts is not a power of 2. Split off and copy the tail.
635 assert(PartVT.isInteger() && ValueVT.isInteger() &&
636 "Do not know what to expand to!");
637 unsigned RoundParts = 1 << Log2_32(NumParts);
638 unsigned RoundBits = RoundParts * PartBits;
639 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000640 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000641 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000642 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000643 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000644 if (TLI.isBigEndian())
645 // The odd parts were reversed by getCopyToParts - unreverse them.
646 std::reverse(Parts + RoundParts, Parts + NumParts);
647 NumParts = RoundParts;
648 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000649 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000650 }
651
652 // The number of parts is a power of 2. Repeatedly bisect the value using
653 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000654 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000655 MVT::getIntegerVT(ValueVT.getSizeInBits()),
656 Val);
657 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
658 for (unsigned i = 0; i < NumParts; i += StepSize) {
659 unsigned ThisBits = StepSize * PartBits / 2;
660 MVT ThisVT = MVT::getIntegerVT (ThisBits);
661 SDValue &Part0 = Parts[i];
662 SDValue &Part1 = Parts[i+StepSize/2];
663
Scott Michelfdc40a02009-02-17 22:15:04 +0000664 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000665 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000666 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000667 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000668 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000669 DAG.getConstant(0, PtrVT));
670
671 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000672 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000673 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000674 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000675 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000676 }
677 }
678 }
679
680 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000681 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000682
683 return;
684 }
685
686 // Vector ValueVT.
687 if (NumParts == 1) {
688 if (PartVT != ValueVT) {
689 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000690 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000691 } else {
692 assert(ValueVT.getVectorElementType() == PartVT &&
693 ValueVT.getVectorNumElements() == 1 &&
694 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000695 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000696 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000697 DAG.getConstant(0, PtrVT));
698 }
699 }
700
701 Parts[0] = Val;
702 return;
703 }
704
705 // Handle a multi-element vector.
706 MVT IntermediateVT, RegisterVT;
707 unsigned NumIntermediates;
Dan Gohmane9530ec2009-01-15 16:58:17 +0000708 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000709 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
710 RegisterVT);
711 unsigned NumElements = ValueVT.getVectorNumElements();
712
713 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
714 NumParts = NumRegs; // Silence a compiler warning.
715 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
716
717 // Split the vector into intermediate operands.
718 SmallVector<SDValue, 8> Ops(NumIntermediates);
719 for (unsigned i = 0; i != NumIntermediates; ++i)
720 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000721 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000722 IntermediateVT, Val,
723 DAG.getConstant(i * (NumElements / NumIntermediates),
724 PtrVT));
725 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000726 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000727 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000728 DAG.getConstant(i, PtrVT));
729
730 // Split the intermediate operands into legal parts.
731 if (NumParts == NumIntermediates) {
732 // If the register was not expanded, promote or copy the value,
733 // as appropriate.
734 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000735 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000736 } else if (NumParts > 0) {
737 // If the intermediate type was expanded, split each the value into
738 // legal parts.
739 assert(NumParts % NumIntermediates == 0 &&
740 "Must expand into a divisible number of parts!");
741 unsigned Factor = NumParts / NumIntermediates;
742 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000743 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000744 }
745}
746
747
748void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
749 AA = &aa;
750 GFI = gfi;
751 TD = DAG.getTarget().getTargetData();
752}
753
754/// clear - Clear out the curret SelectionDAG and the associated
755/// state and prepare this SelectionDAGLowering object to be used
756/// for a new block. This doesn't clear out information about
757/// additional blocks that are needed to complete switch lowering
758/// or PHI node updating; that information is cleared out as it is
759/// consumed.
760void SelectionDAGLowering::clear() {
761 NodeMap.clear();
762 PendingLoads.clear();
763 PendingExports.clear();
764 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000765 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000766}
767
768/// getRoot - Return the current virtual root of the Selection DAG,
769/// flushing any PendingLoad items. This must be done before emitting
770/// a store or any other node that may need to be ordered after any
771/// prior load instructions.
772///
773SDValue SelectionDAGLowering::getRoot() {
774 if (PendingLoads.empty())
775 return DAG.getRoot();
776
777 if (PendingLoads.size() == 1) {
778 SDValue Root = PendingLoads[0];
779 DAG.setRoot(Root);
780 PendingLoads.clear();
781 return Root;
782 }
783
784 // Otherwise, we have to make a token factor node.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000785 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000786 &PendingLoads[0], PendingLoads.size());
787 PendingLoads.clear();
788 DAG.setRoot(Root);
789 return Root;
790}
791
792/// getControlRoot - Similar to getRoot, but instead of flushing all the
793/// PendingLoad items, flush all the PendingExports items. It is necessary
794/// to do this before emitting a terminator instruction.
795///
796SDValue SelectionDAGLowering::getControlRoot() {
797 SDValue Root = DAG.getRoot();
798
799 if (PendingExports.empty())
800 return Root;
801
802 // Turn all of the CopyToReg chains into one factored node.
803 if (Root.getOpcode() != ISD::EntryToken) {
804 unsigned i = 0, e = PendingExports.size();
805 for (; i != e; ++i) {
806 assert(PendingExports[i].getNode()->getNumOperands() > 1);
807 if (PendingExports[i].getNode()->getOperand(0) == Root)
808 break; // Don't add the root if we already indirectly depend on it.
809 }
810
811 if (i == e)
812 PendingExports.push_back(Root);
813 }
814
Dale Johannesen66978ee2009-01-31 02:22:37 +0000815 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000816 &PendingExports[0],
817 PendingExports.size());
818 PendingExports.clear();
819 DAG.setRoot(Root);
820 return Root;
821}
822
823void SelectionDAGLowering::visit(Instruction &I) {
824 visit(I.getOpcode(), I);
825}
826
827void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
828 // Note: this doesn't use InstVisitor, because it has to work with
829 // ConstantExpr's in addition to instructions.
830 switch (Opcode) {
831 default: assert(0 && "Unknown instruction type encountered!");
832 abort();
833 // Build the switch statement using the Instruction.def file.
834#define HANDLE_INST(NUM, OPCODE, CLASS) \
835 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
836#include "llvm/Instruction.def"
837 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000838}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000839
840void SelectionDAGLowering::visitAdd(User &I) {
841 if (I.getType()->isFPOrFPVector())
842 visitBinary(I, ISD::FADD);
843 else
844 visitBinary(I, ISD::ADD);
845}
846
847void SelectionDAGLowering::visitMul(User &I) {
848 if (I.getType()->isFPOrFPVector())
849 visitBinary(I, ISD::FMUL);
850 else
851 visitBinary(I, ISD::MUL);
852}
853
854SDValue SelectionDAGLowering::getValue(const Value *V) {
855 SDValue &N = NodeMap[V];
856 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000857
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000858 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
859 MVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000860
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000861 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000862 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000863
864 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
865 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000866
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000867 if (isa<ConstantPointerNull>(C))
868 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000869
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000870 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000871 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000872
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000873 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
874 !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000875 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000876
877 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
878 visit(CE->getOpcode(), *CE);
879 SDValue N1 = NodeMap[V];
880 assert(N1.getNode() && "visit didn't populate the ValueMap!");
881 return N1;
882 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000883
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000884 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
885 SmallVector<SDValue, 4> Constants;
886 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
887 OI != OE; ++OI) {
888 SDNode *Val = getValue(*OI).getNode();
889 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
890 Constants.push_back(SDValue(Val, i));
891 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000892 return DAG.getMergeValues(&Constants[0], Constants.size(),
893 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000894 }
895
896 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
897 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
898 "Unknown struct or array constant!");
899
900 SmallVector<MVT, 4> ValueVTs;
901 ComputeValueVTs(TLI, C->getType(), ValueVTs);
902 unsigned NumElts = ValueVTs.size();
903 if (NumElts == 0)
904 return SDValue(); // empty struct
905 SmallVector<SDValue, 4> Constants(NumElts);
906 for (unsigned i = 0; i != NumElts; ++i) {
907 MVT EltVT = ValueVTs[i];
908 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000909 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000910 else if (EltVT.isFloatingPoint())
911 Constants[i] = DAG.getConstantFP(0, EltVT);
912 else
913 Constants[i] = DAG.getConstant(0, EltVT);
914 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000915 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000916 }
917
918 const VectorType *VecTy = cast<VectorType>(V->getType());
919 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000920
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000921 // Now that we know the number and type of the elements, get that number of
922 // elements into the Ops array based on what kind of constant it is.
923 SmallVector<SDValue, 16> Ops;
924 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
925 for (unsigned i = 0; i != NumElements; ++i)
926 Ops.push_back(getValue(CP->getOperand(i)));
927 } else {
928 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
929 "Unknown vector constant!");
930 MVT EltVT = TLI.getValueType(VecTy->getElementType());
931
932 SDValue Op;
933 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000934 Op = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000935 else if (EltVT.isFloatingPoint())
936 Op = DAG.getConstantFP(0, EltVT);
937 else
938 Op = DAG.getConstant(0, EltVT);
939 Ops.assign(NumElements, Op);
940 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000941
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000942 // Create a BUILD_VECTOR node.
Evan Chenga87008d2009-02-25 22:49:59 +0000943 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
944 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000945 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000946
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000947 // If this is a static alloca, generate it as the frameindex instead of
948 // computation.
949 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
950 DenseMap<const AllocaInst*, int>::iterator SI =
951 FuncInfo.StaticAllocaMap.find(AI);
952 if (SI != FuncInfo.StaticAllocaMap.end())
953 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
954 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000955
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000956 unsigned InReg = FuncInfo.ValueMap[V];
957 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000958
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000959 RegsForValue RFV(TLI, InReg, V->getType());
960 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000961 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000962}
963
964
965void SelectionDAGLowering::visitRet(ReturnInst &I) {
966 if (I.getNumOperands() == 0) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000967 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000968 MVT::Other, getControlRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000969 return;
970 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000971
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000972 SmallVector<SDValue, 8> NewValues;
973 NewValues.push_back(getControlRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000974 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000975 SmallVector<MVT, 4> ValueVTs;
976 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000977 unsigned NumValues = ValueVTs.size();
978 if (NumValues == 0) continue;
979
980 SDValue RetOp = getValue(I.getOperand(i));
981 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000982 MVT VT = ValueVTs[j];
983
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000984 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000985
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000986 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000987 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000988 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000989 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000990 ExtendKind = ISD::ZERO_EXTEND;
991
Evan Cheng3927f432009-03-25 20:20:11 +0000992 // FIXME: C calling convention requires the return type to be promoted to
993 // at least 32-bit. But this is not necessary for non-C calling
994 // conventions. The frontend should mark functions whose return values
995 // require promoting with signext or zeroext attributes.
996 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
997 MVT MinVT = TLI.getRegisterType(MVT::i32);
998 if (VT.bitsLT(MinVT))
999 VT = MinVT;
1000 }
1001
1002 unsigned NumParts = TLI.getNumRegisters(VT);
1003 MVT PartVT = TLI.getRegisterType(VT);
1004 SmallVector<SDValue, 4> Parts(NumParts);
Dale Johannesen66978ee2009-01-31 02:22:37 +00001005 getCopyToParts(DAG, getCurDebugLoc(),
1006 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001007 &Parts[0], NumParts, PartVT, ExtendKind);
1008
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001009 // 'inreg' on function refers to return value
1010 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +00001011 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001012 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001013 for (unsigned i = 0; i < NumParts; ++i) {
1014 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001015 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001016 }
1017 }
1018 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00001019 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001020 &NewValues[0], NewValues.size()));
1021}
1022
1023/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1024/// the current basic block, add it to ValueMap now so that we'll get a
1025/// CopyTo/FromReg.
1026void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1027 // No need to export constants.
1028 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001029
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001030 // Already exported?
1031 if (FuncInfo.isExportedInst(V)) return;
1032
1033 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1034 CopyValueToVirtualRegister(V, Reg);
1035}
1036
1037bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1038 const BasicBlock *FromBB) {
1039 // The operands of the setcc have to be in this block. We don't know
1040 // how to export them from some other block.
1041 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1042 // Can export from current BB.
1043 if (VI->getParent() == FromBB)
1044 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001045
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001046 // Is already exported, noop.
1047 return FuncInfo.isExportedInst(V);
1048 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001049
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001050 // If this is an argument, we can export it if the BB is the entry block or
1051 // if it is already exported.
1052 if (isa<Argument>(V)) {
1053 if (FromBB == &FromBB->getParent()->getEntryBlock())
1054 return true;
1055
1056 // Otherwise, can only export this if it is already exported.
1057 return FuncInfo.isExportedInst(V);
1058 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001059
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001060 // Otherwise, constants can always be exported.
1061 return true;
1062}
1063
1064static bool InBlock(const Value *V, const BasicBlock *BB) {
1065 if (const Instruction *I = dyn_cast<Instruction>(V))
1066 return I->getParent() == BB;
1067 return true;
1068}
1069
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001070/// getFCmpCondCode - Return the ISD condition code corresponding to
1071/// the given LLVM IR floating-point condition code. This includes
1072/// consideration of global floating-point math flags.
1073///
1074static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1075 ISD::CondCode FPC, FOC;
1076 switch (Pred) {
1077 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1078 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1079 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1080 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1081 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1082 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1083 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1084 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1085 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1086 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1087 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1088 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1089 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1090 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1091 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1092 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1093 default:
1094 assert(0 && "Invalid FCmp predicate opcode!");
1095 FOC = FPC = ISD::SETFALSE;
1096 break;
1097 }
1098 if (FiniteOnlyFPMath())
1099 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001100 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001101 return FPC;
1102}
1103
1104/// getICmpCondCode - Return the ISD condition code corresponding to
1105/// the given LLVM IR integer condition code.
1106///
1107static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1108 switch (Pred) {
1109 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1110 case ICmpInst::ICMP_NE: return ISD::SETNE;
1111 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1112 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1113 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1114 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1115 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1116 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1117 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1118 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1119 default:
1120 assert(0 && "Invalid ICmp predicate opcode!");
1121 return ISD::SETNE;
1122 }
1123}
1124
Dan Gohmanc2277342008-10-17 21:16:08 +00001125/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1126/// This function emits a branch and is used at the leaves of an OR or an
1127/// AND operator tree.
1128///
1129void
1130SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1131 MachineBasicBlock *TBB,
1132 MachineBasicBlock *FBB,
1133 MachineBasicBlock *CurBB) {
1134 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001135
Dan Gohmanc2277342008-10-17 21:16:08 +00001136 // If the leaf of the tree is a comparison, merge the condition into
1137 // the caseblock.
1138 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1139 // The operands of the cmp have to be in this block. We don't know
1140 // how to export them from some other block. If this is the first block
1141 // of the sequence, no exporting is needed.
1142 if (CurBB == CurMBB ||
1143 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1144 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001145 ISD::CondCode Condition;
1146 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001147 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001148 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001149 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001150 } else {
1151 Condition = ISD::SETEQ; // silence warning.
1152 assert(0 && "Unknown compare instruction");
1153 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001154
1155 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001156 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1157 SwitchCases.push_back(CB);
1158 return;
1159 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001160 }
1161
1162 // Create a CaseBlock record representing this branch.
1163 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1164 NULL, TBB, FBB, CurBB);
1165 SwitchCases.push_back(CB);
1166}
1167
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001168/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001169void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1170 MachineBasicBlock *TBB,
1171 MachineBasicBlock *FBB,
1172 MachineBasicBlock *CurBB,
1173 unsigned Opc) {
1174 // If this node is not part of the or/and tree, emit it as a branch.
1175 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001176 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001177 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1178 BOp->getParent() != CurBB->getBasicBlock() ||
1179 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1180 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1181 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001182 return;
1183 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001184
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001185 // Create TmpBB after CurBB.
1186 MachineFunction::iterator BBI = CurBB;
1187 MachineFunction &MF = DAG.getMachineFunction();
1188 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1189 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001190
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001191 if (Opc == Instruction::Or) {
1192 // Codegen X | Y as:
1193 // jmp_if_X TBB
1194 // jmp TmpBB
1195 // TmpBB:
1196 // jmp_if_Y TBB
1197 // jmp FBB
1198 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001199
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001200 // Emit the LHS condition.
1201 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001202
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001203 // Emit the RHS condition into TmpBB.
1204 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1205 } else {
1206 assert(Opc == Instruction::And && "Unknown merge op!");
1207 // Codegen X & Y as:
1208 // jmp_if_X TmpBB
1209 // jmp FBB
1210 // TmpBB:
1211 // jmp_if_Y TBB
1212 // jmp FBB
1213 //
1214 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001215
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001216 // Emit the LHS condition.
1217 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001218
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001219 // Emit the RHS condition into TmpBB.
1220 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1221 }
1222}
1223
1224/// If the set of cases should be emitted as a series of branches, return true.
1225/// If we should emit this as a bunch of and/or'd together conditions, return
1226/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001227bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001228SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1229 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001230
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001231 // If this is two comparisons of the same values or'd or and'd together, they
1232 // will get folded into a single comparison, so don't emit two blocks.
1233 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1234 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1235 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1236 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1237 return false;
1238 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001239
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001240 return true;
1241}
1242
1243void SelectionDAGLowering::visitBr(BranchInst &I) {
1244 // Update machine-CFG edges.
1245 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1246
1247 // Figure out which block is immediately after the current one.
1248 MachineBasicBlock *NextBlock = 0;
1249 MachineFunction::iterator BBI = CurMBB;
1250 if (++BBI != CurMBB->getParent()->end())
1251 NextBlock = BBI;
1252
1253 if (I.isUnconditional()) {
1254 // Update machine-CFG edges.
1255 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001256
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001257 // If this is not a fall-through branch, emit the branch.
1258 if (Succ0MBB != NextBlock)
Scott Michelfdc40a02009-02-17 22:15:04 +00001259 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001260 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001261 DAG.getBasicBlock(Succ0MBB)));
1262 return;
1263 }
1264
1265 // If this condition is one of the special cases we handle, do special stuff
1266 // now.
1267 Value *CondVal = I.getCondition();
1268 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1269
1270 // If this is a series of conditions that are or'd or and'd together, emit
1271 // this as a sequence of branches instead of setcc's with and/or operations.
1272 // For example, instead of something like:
1273 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001274 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001275 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001276 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001277 // or C, F
1278 // jnz foo
1279 // Emit:
1280 // cmp A, B
1281 // je foo
1282 // cmp D, E
1283 // jle foo
1284 //
1285 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001286 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001287 (BOp->getOpcode() == Instruction::And ||
1288 BOp->getOpcode() == Instruction::Or)) {
1289 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1290 // If the compares in later blocks need to use values not currently
1291 // exported from this block, export them now. This block should always
1292 // be the first entry.
1293 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001294
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001295 // Allow some cases to be rejected.
1296 if (ShouldEmitAsBranches(SwitchCases)) {
1297 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1298 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1299 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1300 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001301
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001302 // Emit the branch for this block.
1303 visitSwitchCase(SwitchCases[0]);
1304 SwitchCases.erase(SwitchCases.begin());
1305 return;
1306 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001307
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001308 // Okay, we decided not to do this, remove any inserted MBB's and clear
1309 // SwitchCases.
1310 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1311 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001312
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001313 SwitchCases.clear();
1314 }
1315 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001316
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001317 // Create a CaseBlock record representing this branch.
1318 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1319 NULL, Succ0MBB, Succ1MBB, CurMBB);
1320 // Use visitSwitchCase to actually insert the fast branch sequence for this
1321 // cond branch.
1322 visitSwitchCase(CB);
1323}
1324
1325/// visitSwitchCase - Emits the necessary code to represent a single node in
1326/// the binary search tree resulting from lowering a switch instruction.
1327void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1328 SDValue Cond;
1329 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001330 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001331
1332 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001333 if (CB.CmpMHS == NULL) {
1334 // Fold "(X == true)" to X and "(X == false)" to !X to
1335 // handle common cases produced by branch lowering.
1336 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1337 Cond = CondLHS;
1338 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1339 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001340 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001341 } else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001342 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001343 } else {
1344 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1345
Anton Korobeynikov23218582008-12-23 22:25:27 +00001346 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1347 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001348
1349 SDValue CmpOp = getValue(CB.CmpMHS);
1350 MVT VT = CmpOp.getValueType();
1351
1352 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00001353 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001354 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001355 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001356 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001357 VT, CmpOp, DAG.getConstant(Low, VT));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001358 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001359 DAG.getConstant(High-Low, VT), ISD::SETULE);
1360 }
1361 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001362
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001363 // Update successor info
1364 CurMBB->addSuccessor(CB.TrueBB);
1365 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001366
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001367 // Set NextBlock to be the MBB immediately after the current one, if any.
1368 // This is used to avoid emitting unnecessary branches to the next block.
1369 MachineBasicBlock *NextBlock = 0;
1370 MachineFunction::iterator BBI = CurMBB;
1371 if (++BBI != CurMBB->getParent()->end())
1372 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001373
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001374 // If the lhs block is the next block, invert the condition so that we can
1375 // fall through to the lhs instead of the rhs block.
1376 if (CB.TrueBB == NextBlock) {
1377 std::swap(CB.TrueBB, CB.FalseBB);
1378 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001379 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001380 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001381 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001382 MVT::Other, getControlRoot(), Cond,
1383 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001384
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001385 // If the branch was constant folded, fix up the CFG.
1386 if (BrCond.getOpcode() == ISD::BR) {
1387 CurMBB->removeSuccessor(CB.FalseBB);
1388 DAG.setRoot(BrCond);
1389 } else {
1390 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001391 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001392 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001393
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001394 if (CB.FalseBB == NextBlock)
1395 DAG.setRoot(BrCond);
1396 else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001397 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001398 DAG.getBasicBlock(CB.FalseBB)));
1399 }
1400}
1401
1402/// visitJumpTable - Emit JumpTable node in the current MBB
1403void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1404 // Emit the code for the jump table
1405 assert(JT.Reg != -1U && "Should lower JT Header first!");
1406 MVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001407 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1408 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001409 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Scott Michelfdc40a02009-02-17 22:15:04 +00001410 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001411 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001412 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001413}
1414
1415/// visitJumpTableHeader - This function emits necessary code to produce index
1416/// in the JumpTable from switch case.
1417void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1418 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001419 // Subtract the lowest switch case value from the value being switched on and
1420 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001421 // difference between smallest and largest cases.
1422 SDValue SwitchOp = getValue(JTH.SValue);
1423 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001424 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001425 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001426
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001427 // The SDNode we just created, which holds the value being switched on minus
1428 // the the smallest case value, needs to be copied to a virtual register so it
1429 // can be used as an index into the jump table in a subsequent basic block.
1430 // This value may be smaller or larger than the target's pointer type, and
1431 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001432 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001433 SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001434 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001435 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001436 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001437 TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001438
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001439 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001440 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1441 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001442 JT.Reg = JumpTableReg;
1443
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001444 // Emit the range check for the jump table, and branch to the default block
1445 // for the switch statement if the value being switched on exceeds the largest
1446 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001447 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1448 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001449 DAG.getConstant(JTH.Last-JTH.First,VT),
1450 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001451
1452 // Set NextBlock to be the MBB immediately after the current one, if any.
1453 // This is used to avoid emitting unnecessary branches to the next block.
1454 MachineBasicBlock *NextBlock = 0;
1455 MachineFunction::iterator BBI = CurMBB;
1456 if (++BBI != CurMBB->getParent()->end())
1457 NextBlock = BBI;
1458
Dale Johannesen66978ee2009-01-31 02:22:37 +00001459 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001460 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001461 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001462
1463 if (JT.MBB == NextBlock)
1464 DAG.setRoot(BrCond);
1465 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001466 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001467 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001468}
1469
1470/// visitBitTestHeader - This function emits necessary code to produce value
1471/// suitable for "bit tests"
1472void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1473 // Subtract the minimum value
1474 SDValue SwitchOp = getValue(B.SValue);
1475 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001476 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001477 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001478
1479 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001480 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1481 TLI.getSetCCResultType(SUB.getValueType()),
1482 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001483 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001484
1485 SDValue ShiftOp;
Duncan Sands92abc622009-01-31 15:50:11 +00001486 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001487 ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001488 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001489 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001490 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001491 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001492
Duncan Sands92abc622009-01-31 15:50:11 +00001493 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001494 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1495 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001496
1497 // Set NextBlock to be the MBB immediately after the current one, if any.
1498 // This is used to avoid emitting unnecessary branches to the next block.
1499 MachineBasicBlock *NextBlock = 0;
1500 MachineFunction::iterator BBI = CurMBB;
1501 if (++BBI != CurMBB->getParent()->end())
1502 NextBlock = BBI;
1503
1504 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1505
1506 CurMBB->addSuccessor(B.Default);
1507 CurMBB->addSuccessor(MBB);
1508
Dale Johannesen66978ee2009-01-31 02:22:37 +00001509 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001510 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001511 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001512
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001513 if (MBB == NextBlock)
1514 DAG.setRoot(BrRange);
1515 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001516 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001517 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001518}
1519
1520/// visitBitTestCase - this function produces one "bit test"
1521void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1522 unsigned Reg,
1523 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001524 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001525 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001526 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001527 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001528 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001529 DAG.getConstant(1, TLI.getPointerTy()),
1530 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001531
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001532 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001533 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001534 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001535 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001536 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1537 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001538 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001539 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001540
1541 CurMBB->addSuccessor(B.TargetBB);
1542 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001543
Dale Johannesen66978ee2009-01-31 02:22:37 +00001544 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001545 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001546 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001547
1548 // Set NextBlock to be the MBB immediately after the current one, if any.
1549 // This is used to avoid emitting unnecessary branches to the next block.
1550 MachineBasicBlock *NextBlock = 0;
1551 MachineFunction::iterator BBI = CurMBB;
1552 if (++BBI != CurMBB->getParent()->end())
1553 NextBlock = BBI;
1554
1555 if (NextMBB == NextBlock)
1556 DAG.setRoot(BrAnd);
1557 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001558 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001559 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001560}
1561
1562void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1563 // Retrieve successors.
1564 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1565 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1566
Gabor Greifb67e6b32009-01-15 11:10:44 +00001567 const Value *Callee(I.getCalledValue());
1568 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001569 visitInlineAsm(&I);
1570 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001571 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001572
1573 // If the value of the invoke is used outside of its defining block, make it
1574 // available as a virtual register.
1575 if (!I.use_empty()) {
1576 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1577 if (VMI != FuncInfo.ValueMap.end())
1578 CopyValueToVirtualRegister(&I, VMI->second);
1579 }
1580
1581 // Update successor info
1582 CurMBB->addSuccessor(Return);
1583 CurMBB->addSuccessor(LandingPad);
1584
1585 // Drop into normal successor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001586 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001587 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001588 DAG.getBasicBlock(Return)));
1589}
1590
1591void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1592}
1593
1594/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1595/// small case ranges).
1596bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1597 CaseRecVector& WorkList,
1598 Value* SV,
1599 MachineBasicBlock* Default) {
1600 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001601
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001602 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001603 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001604 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001605 return false;
1606
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001607 // Get the MachineFunction which holds the current MBB. This is used when
1608 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001609 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001610
1611 // Figure out which block is immediately after the current one.
1612 MachineBasicBlock *NextBlock = 0;
1613 MachineFunction::iterator BBI = CR.CaseBB;
1614
1615 if (++BBI != CurMBB->getParent()->end())
1616 NextBlock = BBI;
1617
1618 // TODO: If any two of the cases has the same destination, and if one value
1619 // is the same as the other, but has one bit unset that the other has set,
1620 // use bit manipulation to do two compares at once. For example:
1621 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001622
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001623 // Rearrange the case blocks so that the last one falls through if possible.
1624 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1625 // The last case block won't fall through into 'NextBlock' if we emit the
1626 // branches in this order. See if rearranging a case value would help.
1627 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1628 if (I->BB == NextBlock) {
1629 std::swap(*I, BackCase);
1630 break;
1631 }
1632 }
1633 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001634
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001635 // Create a CaseBlock record representing a conditional branch to
1636 // the Case's target mbb if the value being switched on SV is equal
1637 // to C.
1638 MachineBasicBlock *CurBlock = CR.CaseBB;
1639 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1640 MachineBasicBlock *FallThrough;
1641 if (I != E-1) {
1642 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1643 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001644
1645 // Put SV in a virtual register to make it available from the new blocks.
1646 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001647 } else {
1648 // If the last case doesn't match, go to the default block.
1649 FallThrough = Default;
1650 }
1651
1652 Value *RHS, *LHS, *MHS;
1653 ISD::CondCode CC;
1654 if (I->High == I->Low) {
1655 // This is just small small case range :) containing exactly 1 case
1656 CC = ISD::SETEQ;
1657 LHS = SV; RHS = I->High; MHS = NULL;
1658 } else {
1659 CC = ISD::SETLE;
1660 LHS = I->Low; MHS = SV; RHS = I->High;
1661 }
1662 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001663
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001664 // If emitting the first comparison, just call visitSwitchCase to emit the
1665 // code into the current block. Otherwise, push the CaseBlock onto the
1666 // vector to be later processed by SDISel, and insert the node's MBB
1667 // before the next MBB.
1668 if (CurBlock == CurMBB)
1669 visitSwitchCase(CB);
1670 else
1671 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001672
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001673 CurBlock = FallThrough;
1674 }
1675
1676 return true;
1677}
1678
1679static inline bool areJTsAllowed(const TargetLowering &TLI) {
1680 return !DisableJumpTables &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00001681 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1682 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001683}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001684
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001685static APInt ComputeRange(const APInt &First, const APInt &Last) {
1686 APInt LastExt(Last), FirstExt(First);
1687 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1688 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1689 return (LastExt - FirstExt + 1ULL);
1690}
1691
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001692/// handleJTSwitchCase - Emit jumptable for current switch case range
1693bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1694 CaseRecVector& WorkList,
1695 Value* SV,
1696 MachineBasicBlock* Default) {
1697 Case& FrontCase = *CR.Range.first;
1698 Case& BackCase = *(CR.Range.second-1);
1699
Anton Korobeynikov23218582008-12-23 22:25:27 +00001700 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1701 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001702
Anton Korobeynikov23218582008-12-23 22:25:27 +00001703 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001704 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1705 I!=E; ++I)
1706 TSize += I->size();
1707
1708 if (!areJTsAllowed(TLI) || TSize <= 3)
1709 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001710
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001711 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001712 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001713 if (Density < 0.4)
1714 return false;
1715
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001716 DEBUG(errs() << "Lowering jump table\n"
1717 << "First entry: " << First << ". Last entry: " << Last << '\n'
1718 << "Range: " << Range
1719 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001720
1721 // Get the MachineFunction which holds the current MBB. This is used when
1722 // inserting any additional MBBs necessary to represent the switch.
1723 MachineFunction *CurMF = CurMBB->getParent();
1724
1725 // Figure out which block is immediately after the current one.
1726 MachineBasicBlock *NextBlock = 0;
1727 MachineFunction::iterator BBI = CR.CaseBB;
1728
1729 if (++BBI != CurMBB->getParent()->end())
1730 NextBlock = BBI;
1731
1732 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1733
1734 // Create a new basic block to hold the code for loading the address
1735 // of the jump table, and jumping to it. Update successor information;
1736 // we will either branch to the default case for the switch, or the jump
1737 // table.
1738 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1739 CurMF->insert(BBI, JumpTableBB);
1740 CR.CaseBB->addSuccessor(Default);
1741 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001742
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001743 // Build a vector of destination BBs, corresponding to each target
1744 // of the jump table. If the value of the jump table slot corresponds to
1745 // a case statement, push the case's BB onto the vector, otherwise, push
1746 // the default BB.
1747 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001748 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001749 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001750 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1751 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1752
1753 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001754 DestBBs.push_back(I->BB);
1755 if (TEI==High)
1756 ++I;
1757 } else {
1758 DestBBs.push_back(Default);
1759 }
1760 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001761
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001762 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001763 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1764 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001765 E = DestBBs.end(); I != E; ++I) {
1766 if (!SuccsHandled[(*I)->getNumber()]) {
1767 SuccsHandled[(*I)->getNumber()] = true;
1768 JumpTableBB->addSuccessor(*I);
1769 }
1770 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001771
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001772 // Create a jump table index for this jump table, or return an existing
1773 // one.
1774 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001775
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001776 // Set the jump table information so that we can codegen it as a second
1777 // MachineBasicBlock
1778 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1779 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1780 if (CR.CaseBB == CurMBB)
1781 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001782
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001783 JTCases.push_back(JumpTableBlock(JTH, JT));
1784
1785 return true;
1786}
1787
1788/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1789/// 2 subtrees.
1790bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1791 CaseRecVector& WorkList,
1792 Value* SV,
1793 MachineBasicBlock* Default) {
1794 // Get the MachineFunction which holds the current MBB. This is used when
1795 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001796 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001797
1798 // Figure out which block is immediately after the current one.
1799 MachineBasicBlock *NextBlock = 0;
1800 MachineFunction::iterator BBI = CR.CaseBB;
1801
1802 if (++BBI != CurMBB->getParent()->end())
1803 NextBlock = BBI;
1804
1805 Case& FrontCase = *CR.Range.first;
1806 Case& BackCase = *(CR.Range.second-1);
1807 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1808
1809 // Size is the number of Cases represented by this range.
1810 unsigned Size = CR.Range.second - CR.Range.first;
1811
Anton Korobeynikov23218582008-12-23 22:25:27 +00001812 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1813 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001814 double FMetric = 0;
1815 CaseItr Pivot = CR.Range.first + Size/2;
1816
1817 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1818 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001819 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001820 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1821 I!=E; ++I)
1822 TSize += I->size();
1823
Anton Korobeynikov23218582008-12-23 22:25:27 +00001824 size_t LSize = FrontCase.size();
1825 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001826 DEBUG(errs() << "Selecting best pivot: \n"
1827 << "First: " << First << ", Last: " << Last <<'\n'
1828 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001829 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1830 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001831 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1832 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001833 APInt Range = ComputeRange(LEnd, RBegin);
1834 assert((Range - 2ULL).isNonNegative() &&
1835 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001836 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1837 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001838 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001839 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001840 DEBUG(errs() <<"=>Step\n"
1841 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1842 << "LDensity: " << LDensity
1843 << ", RDensity: " << RDensity << '\n'
1844 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001845 if (FMetric < Metric) {
1846 Pivot = J;
1847 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001848 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001849 }
1850
1851 LSize += J->size();
1852 RSize -= J->size();
1853 }
1854 if (areJTsAllowed(TLI)) {
1855 // If our case is dense we *really* should handle it earlier!
1856 assert((FMetric > 0) && "Should handle dense range earlier!");
1857 } else {
1858 Pivot = CR.Range.first + Size/2;
1859 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001860
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001861 CaseRange LHSR(CR.Range.first, Pivot);
1862 CaseRange RHSR(Pivot, CR.Range.second);
1863 Constant *C = Pivot->Low;
1864 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001865
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001866 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001867 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001868 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001869 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001870 // Pivot's Value, then we can branch directly to the LHS's Target,
1871 // rather than creating a leaf node for it.
1872 if ((LHSR.second - LHSR.first) == 1 &&
1873 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001874 cast<ConstantInt>(C)->getValue() ==
1875 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001876 TrueBB = LHSR.first->BB;
1877 } else {
1878 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1879 CurMF->insert(BBI, TrueBB);
1880 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001881
1882 // Put SV in a virtual register to make it available from the new blocks.
1883 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001884 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001885
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001886 // Similar to the optimization above, if the Value being switched on is
1887 // known to be less than the Constant CR.LT, and the current Case Value
1888 // is CR.LT - 1, then we can branch directly to the target block for
1889 // the current Case Value, rather than emitting a RHS leaf node for it.
1890 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001891 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1892 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001893 FalseBB = RHSR.first->BB;
1894 } else {
1895 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1896 CurMF->insert(BBI, FalseBB);
1897 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001898
1899 // Put SV in a virtual register to make it available from the new blocks.
1900 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001901 }
1902
1903 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001904 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001905 // Otherwise, branch to LHS.
1906 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1907
1908 if (CR.CaseBB == CurMBB)
1909 visitSwitchCase(CB);
1910 else
1911 SwitchCases.push_back(CB);
1912
1913 return true;
1914}
1915
1916/// handleBitTestsSwitchCase - if current case range has few destination and
1917/// range span less, than machine word bitwidth, encode case range into series
1918/// of masks and emit bit tests with these masks.
1919bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1920 CaseRecVector& WorkList,
1921 Value* SV,
1922 MachineBasicBlock* Default){
1923 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1924
1925 Case& FrontCase = *CR.Range.first;
1926 Case& BackCase = *(CR.Range.second-1);
1927
1928 // Get the MachineFunction which holds the current MBB. This is used when
1929 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001930 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001931
Anton Korobeynikov23218582008-12-23 22:25:27 +00001932 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001933 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1934 I!=E; ++I) {
1935 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001936 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001937 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001938
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001939 // Count unique destinations
1940 SmallSet<MachineBasicBlock*, 4> Dests;
1941 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1942 Dests.insert(I->BB);
1943 if (Dests.size() > 3)
1944 // Don't bother the code below, if there are too much unique destinations
1945 return false;
1946 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001947 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1948 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001949
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001950 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001951 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1952 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001953 APInt cmpRange = maxValue - minValue;
1954
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001955 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1956 << "Low bound: " << minValue << '\n'
1957 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001958
1959 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001960 (!(Dests.size() == 1 && numCmps >= 3) &&
1961 !(Dests.size() == 2 && numCmps >= 5) &&
1962 !(Dests.size() >= 3 && numCmps >= 6)))
1963 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001964
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001965 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001966 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1967
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001968 // Optimize the case where all the case values fit in a
1969 // word without having to subtract minValue. In this case,
1970 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001971 if (minValue.isNonNegative() &&
1972 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1973 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001974 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001975 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001976 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001977
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001978 CaseBitsVector CasesBits;
1979 unsigned i, count = 0;
1980
1981 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1982 MachineBasicBlock* Dest = I->BB;
1983 for (i = 0; i < count; ++i)
1984 if (Dest == CasesBits[i].BB)
1985 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001986
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001987 if (i == count) {
1988 assert((count < 3) && "Too much destinations to test!");
1989 CasesBits.push_back(CaseBits(0, Dest, 0));
1990 count++;
1991 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001992
1993 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1994 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1995
1996 uint64_t lo = (lowValue - lowBound).getZExtValue();
1997 uint64_t hi = (highValue - lowBound).getZExtValue();
1998
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001999 for (uint64_t j = lo; j <= hi; j++) {
2000 CasesBits[i].Mask |= 1ULL << j;
2001 CasesBits[i].Bits++;
2002 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002003
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002004 }
2005 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00002006
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002007 BitTestInfo BTC;
2008
2009 // Figure out which block is immediately after the current one.
2010 MachineFunction::iterator BBI = CR.CaseBB;
2011 ++BBI;
2012
2013 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2014
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002015 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002016 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002017 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2018 << ", Bits: " << CasesBits[i].Bits
2019 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002020
2021 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2022 CurMF->insert(BBI, CaseBB);
2023 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2024 CaseBB,
2025 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002026
2027 // Put SV in a virtual register to make it available from the new blocks.
2028 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002029 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002030
2031 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002032 -1U, (CR.CaseBB == CurMBB),
2033 CR.CaseBB, Default, BTC);
2034
2035 if (CR.CaseBB == CurMBB)
2036 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002037
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002038 BitTestCases.push_back(BTB);
2039
2040 return true;
2041}
2042
2043
2044/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002045size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002046 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002047 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002048
2049 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002050 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002051 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2052 Cases.push_back(Case(SI.getSuccessorValue(i),
2053 SI.getSuccessorValue(i),
2054 SMBB));
2055 }
2056 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2057
2058 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002059 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002060 // Must recompute end() each iteration because it may be
2061 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002062 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2063 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2064 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002065 MachineBasicBlock* nextBB = J->BB;
2066 MachineBasicBlock* currentBB = I->BB;
2067
2068 // If the two neighboring cases go to the same destination, merge them
2069 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002070 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002071 I->High = J->High;
2072 J = Cases.erase(J);
2073 } else {
2074 I = J++;
2075 }
2076 }
2077
2078 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2079 if (I->Low != I->High)
2080 // A range counts double, since it requires two compares.
2081 ++numCmps;
2082 }
2083
2084 return numCmps;
2085}
2086
Anton Korobeynikov23218582008-12-23 22:25:27 +00002087void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002088 // Figure out which block is immediately after the current one.
2089 MachineBasicBlock *NextBlock = 0;
2090 MachineFunction::iterator BBI = CurMBB;
2091
2092 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2093
2094 // If there is only the default destination, branch to it if it is not the
2095 // next basic block. Otherwise, just fall through.
2096 if (SI.getNumOperands() == 2) {
2097 // Update machine-CFG edges.
2098
2099 // If this is not a fall-through branch, emit the branch.
2100 CurMBB->addSuccessor(Default);
2101 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002102 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002103 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002104 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002105 return;
2106 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002107
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002108 // If there are any non-default case statements, create a vector of Cases
2109 // representing each one, and sort the vector so that we can efficiently
2110 // create a binary search tree from them.
2111 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002112 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002113 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2114 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002115 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002116
2117 // Get the Value to be switched on and default basic blocks, which will be
2118 // inserted into CaseBlock records, representing basic blocks in the binary
2119 // search tree.
2120 Value *SV = SI.getOperand(0);
2121
2122 // Push the initial CaseRec onto the worklist
2123 CaseRecVector WorkList;
2124 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2125
2126 while (!WorkList.empty()) {
2127 // Grab a record representing a case range to process off the worklist
2128 CaseRec CR = WorkList.back();
2129 WorkList.pop_back();
2130
2131 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2132 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002133
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002134 // If the range has few cases (two or less) emit a series of specific
2135 // tests.
2136 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2137 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002138
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002139 // If the switch has more than 5 blocks, and at least 40% dense, and the
2140 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002141 // lowering the switch to a binary tree of conditional branches.
2142 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2143 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002144
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002145 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2146 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2147 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2148 }
2149}
2150
2151
2152void SelectionDAGLowering::visitSub(User &I) {
2153 // -0.0 - X --> fneg
2154 const Type *Ty = I.getType();
2155 if (isa<VectorType>(Ty)) {
2156 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2157 const VectorType *DestTy = cast<VectorType>(I.getType());
2158 const Type *ElTy = DestTy->getElementType();
2159 if (ElTy->isFloatingPoint()) {
2160 unsigned VL = DestTy->getNumElements();
2161 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2162 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2163 if (CV == CNZ) {
2164 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002165 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002166 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002167 return;
2168 }
2169 }
2170 }
2171 }
2172 if (Ty->isFloatingPoint()) {
2173 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2174 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2175 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002176 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002177 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002178 return;
2179 }
2180 }
2181
2182 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2183}
2184
2185void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2186 SDValue Op1 = getValue(I.getOperand(0));
2187 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002188
Scott Michelfdc40a02009-02-17 22:15:04 +00002189 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002190 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002191}
2192
2193void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2194 SDValue Op1 = getValue(I.getOperand(0));
2195 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman57fc82d2009-04-09 03:51:29 +00002196 if (!isa<VectorType>(I.getType()) &&
2197 Op2.getValueType() != TLI.getShiftAmountTy()) {
2198 // If the operand is smaller than the shift count type, promote it.
2199 if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2200 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2201 TLI.getShiftAmountTy(), Op2);
2202 // If the operand is larger than the shift count type but the shift
2203 // count type has enough bits to represent any shift value, truncate
2204 // it now. This is a common case and it exposes the truncate to
2205 // optimization early.
2206 else if (TLI.getShiftAmountTy().getSizeInBits() >=
2207 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2208 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2209 TLI.getShiftAmountTy(), Op2);
2210 // Otherwise we'll need to temporarily settle for some other
2211 // convenient type; type legalization will make adjustments as
2212 // needed.
2213 else if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002214 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002215 TLI.getPointerTy(), Op2);
2216 else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002217 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002218 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002219 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002220
Scott Michelfdc40a02009-02-17 22:15:04 +00002221 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002222 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002223}
2224
2225void SelectionDAGLowering::visitICmp(User &I) {
2226 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2227 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2228 predicate = IC->getPredicate();
2229 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2230 predicate = ICmpInst::Predicate(IC->getPredicate());
2231 SDValue Op1 = getValue(I.getOperand(0));
2232 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002233 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002234 setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002235}
2236
2237void SelectionDAGLowering::visitFCmp(User &I) {
2238 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2239 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2240 predicate = FC->getPredicate();
2241 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2242 predicate = FCmpInst::Predicate(FC->getPredicate());
2243 SDValue Op1 = getValue(I.getOperand(0));
2244 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002245 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002246 setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002247}
2248
2249void SelectionDAGLowering::visitVICmp(User &I) {
2250 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2251 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2252 predicate = IC->getPredicate();
2253 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2254 predicate = ICmpInst::Predicate(IC->getPredicate());
2255 SDValue Op1 = getValue(I.getOperand(0));
2256 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002257 ISD::CondCode Opcode = getICmpCondCode(predicate);
Scott Michelfdc40a02009-02-17 22:15:04 +00002258 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
Dale Johannesenf5d97892009-02-04 01:48:28 +00002259 Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002260}
2261
2262void SelectionDAGLowering::visitVFCmp(User &I) {
2263 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2264 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2265 predicate = FC->getPredicate();
2266 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2267 predicate = FCmpInst::Predicate(FC->getPredicate());
2268 SDValue Op1 = getValue(I.getOperand(0));
2269 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002270 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002271 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002272
Dale Johannesenf5d97892009-02-04 01:48:28 +00002273 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002274}
2275
2276void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002277 SmallVector<MVT, 4> ValueVTs;
2278 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2279 unsigned NumValues = ValueVTs.size();
2280 if (NumValues != 0) {
2281 SmallVector<SDValue, 4> Values(NumValues);
2282 SDValue Cond = getValue(I.getOperand(0));
2283 SDValue TrueVal = getValue(I.getOperand(1));
2284 SDValue FalseVal = getValue(I.getOperand(2));
2285
2286 for (unsigned i = 0; i != NumValues; ++i)
Scott Michelfdc40a02009-02-17 22:15:04 +00002287 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002288 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002289 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2290 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2291
Scott Michelfdc40a02009-02-17 22:15:04 +00002292 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002293 DAG.getVTList(&ValueVTs[0], NumValues),
2294 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002295 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002296}
2297
2298
2299void SelectionDAGLowering::visitTrunc(User &I) {
2300 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2301 SDValue N = getValue(I.getOperand(0));
2302 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002303 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002304}
2305
2306void SelectionDAGLowering::visitZExt(User &I) {
2307 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2308 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2309 SDValue N = getValue(I.getOperand(0));
2310 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002311 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002312}
2313
2314void SelectionDAGLowering::visitSExt(User &I) {
2315 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2316 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2317 SDValue N = getValue(I.getOperand(0));
2318 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002319 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002320}
2321
2322void SelectionDAGLowering::visitFPTrunc(User &I) {
2323 // FPTrunc is never a no-op cast, no need to check
2324 SDValue N = getValue(I.getOperand(0));
2325 MVT DestVT = TLI.getValueType(I.getType());
Scott Michelfdc40a02009-02-17 22:15:04 +00002326 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002327 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002328}
2329
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002330void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002331 // FPTrunc is never a no-op cast, no need to check
2332 SDValue N = getValue(I.getOperand(0));
2333 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002334 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002335}
2336
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002337void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002338 // FPToUI is never a no-op cast, no need to check
2339 SDValue N = getValue(I.getOperand(0));
2340 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002341 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002342}
2343
2344void SelectionDAGLowering::visitFPToSI(User &I) {
2345 // FPToSI is never a no-op cast, no need to check
2346 SDValue N = getValue(I.getOperand(0));
2347 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002348 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002349}
2350
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002351void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002352 // UIToFP is never a no-op cast, no need to check
2353 SDValue N = getValue(I.getOperand(0));
2354 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002355 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002356}
2357
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002358void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002359 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002360 SDValue N = getValue(I.getOperand(0));
2361 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002362 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002363}
2364
2365void SelectionDAGLowering::visitPtrToInt(User &I) {
2366 // What to do depends on the size of the integer and the size of the pointer.
2367 // We can either truncate, zero extend, or no-op, accordingly.
2368 SDValue N = getValue(I.getOperand(0));
2369 MVT SrcVT = N.getValueType();
2370 MVT DestVT = TLI.getValueType(I.getType());
2371 SDValue Result;
2372 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002373 Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002374 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002375 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Dale Johannesen66978ee2009-01-31 02:22:37 +00002376 Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002377 setValue(&I, Result);
2378}
2379
2380void SelectionDAGLowering::visitIntToPtr(User &I) {
2381 // What to do depends on the size of the integer and the size of the pointer.
2382 // We can either truncate, zero extend, or no-op, accordingly.
2383 SDValue N = getValue(I.getOperand(0));
2384 MVT SrcVT = N.getValueType();
2385 MVT DestVT = TLI.getValueType(I.getType());
2386 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002387 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002388 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002389 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Scott Michelfdc40a02009-02-17 22:15:04 +00002390 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002391 DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002392}
2393
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002394void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002395 SDValue N = getValue(I.getOperand(0));
2396 MVT DestVT = TLI.getValueType(I.getType());
2397
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002398 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002399 // is either a BIT_CONVERT or a no-op.
2400 if (DestVT != N.getValueType())
Scott Michelfdc40a02009-02-17 22:15:04 +00002401 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002402 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002403 else
2404 setValue(&I, N); // noop cast.
2405}
2406
2407void SelectionDAGLowering::visitInsertElement(User &I) {
2408 SDValue InVec = getValue(I.getOperand(0));
2409 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002410 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002411 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002412 getValue(I.getOperand(2)));
2413
Scott Michelfdc40a02009-02-17 22:15:04 +00002414 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002415 TLI.getValueType(I.getType()),
2416 InVec, InVal, InIdx));
2417}
2418
2419void SelectionDAGLowering::visitExtractElement(User &I) {
2420 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002421 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002422 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002423 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002424 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002425 TLI.getValueType(I.getType()), InVec, InIdx));
2426}
2427
Mon P Wangaeb06d22008-11-10 04:46:22 +00002428
2429// Utility for visitShuffleVector - Returns true if the mask is mask starting
2430// from SIndx and increasing to the element length (undefs are allowed).
2431static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002432 unsigned MaskNumElts = Mask.getNumOperands();
2433 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002434 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2435 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2436 if (Idx != i + SIndx)
2437 return false;
2438 }
2439 }
2440 return true;
2441}
2442
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002443void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002444 SDValue Src1 = getValue(I.getOperand(0));
2445 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002446 SDValue Mask = getValue(I.getOperand(2));
2447
Mon P Wangaeb06d22008-11-10 04:46:22 +00002448 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002449 MVT SrcVT = Src1.getValueType();
Mon P Wangc7849c22008-11-16 05:06:27 +00002450 int MaskNumElts = Mask.getNumOperands();
2451 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002452
Mon P Wangc7849c22008-11-16 05:06:27 +00002453 if (SrcNumElts == MaskNumElts) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002454 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002455 VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002456 return;
2457 }
2458
2459 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002460 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2461
2462 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2463 // Mask is longer than the source vectors and is a multiple of the source
2464 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002465 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002466 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2467 // The shuffle is concatenating two vectors together.
Scott Michelfdc40a02009-02-17 22:15:04 +00002468 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002469 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002470 return;
2471 }
2472
Mon P Wangc7849c22008-11-16 05:06:27 +00002473 // Pad both vectors with undefs to make them the same length as the mask.
2474 unsigned NumConcat = MaskNumElts / SrcNumElts;
Dale Johannesene8d72302009-02-06 23:05:02 +00002475 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002476
Mon P Wang230e4fa2008-11-21 04:25:21 +00002477 SDValue* MOps1 = new SDValue[NumConcat];
2478 SDValue* MOps2 = new SDValue[NumConcat];
2479 MOps1[0] = Src1;
2480 MOps2[0] = Src2;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002481 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002482 MOps1[i] = UndefVal;
2483 MOps2[i] = UndefVal;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002484 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002485 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002486 VT, MOps1, NumConcat);
Scott Michelfdc40a02009-02-17 22:15:04 +00002487 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002488 VT, MOps2, NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002489
2490 delete [] MOps1;
2491 delete [] MOps2;
2492
Mon P Wangaeb06d22008-11-10 04:46:22 +00002493 // Readjust mask for new input vector length.
2494 SmallVector<SDValue, 8> MappedOps;
Mon P Wangc7849c22008-11-16 05:06:27 +00002495 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002496 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2497 MappedOps.push_back(Mask.getOperand(i));
2498 } else {
Mon P Wangc7849c22008-11-16 05:06:27 +00002499 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2500 if (Idx < SrcNumElts)
2501 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2502 else
2503 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2504 MaskEltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002505 }
2506 }
Evan Chenga87008d2009-02-25 22:49:59 +00002507 Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2508 Mask.getValueType(),
2509 &MappedOps[0], MappedOps.size());
Mon P Wangaeb06d22008-11-10 04:46:22 +00002510
Scott Michelfdc40a02009-02-17 22:15:04 +00002511 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002512 VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002513 return;
2514 }
2515
Mon P Wangc7849c22008-11-16 05:06:27 +00002516 if (SrcNumElts > MaskNumElts) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002517 // Resulting vector is shorter than the incoming vector.
Mon P Wangc7849c22008-11-16 05:06:27 +00002518 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002519 // Shuffle extracts 1st vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002520 setValue(&I, Src1);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002521 return;
2522 }
2523
Mon P Wangc7849c22008-11-16 05:06:27 +00002524 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002525 // Shuffle extracts 2nd vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002526 setValue(&I, Src2);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002527 return;
2528 }
2529
Mon P Wangc7849c22008-11-16 05:06:27 +00002530 // Analyze the access pattern of the vector to see if we can extract
2531 // two subvectors and do the shuffle. The analysis is done by calculating
2532 // the range of elements the mask access on both vectors.
2533 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2534 int MaxRange[2] = {-1, -1};
2535
2536 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002537 SDValue Arg = Mask.getOperand(i);
2538 if (Arg.getOpcode() != ISD::UNDEF) {
2539 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002540 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2541 int Input = 0;
2542 if (Idx >= SrcNumElts) {
2543 Input = 1;
2544 Idx -= SrcNumElts;
2545 }
2546 if (Idx > MaxRange[Input])
2547 MaxRange[Input] = Idx;
2548 if (Idx < MinRange[Input])
2549 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002550 }
2551 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002552
Mon P Wangc7849c22008-11-16 05:06:27 +00002553 // Check if the access is smaller than the vector size and can we find
2554 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002555 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002556 int StartIdx[2]; // StartIdx to extract from
2557 for (int Input=0; Input < 2; ++Input) {
2558 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2559 RangeUse[Input] = 0; // Unused
2560 StartIdx[Input] = 0;
2561 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2562 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002563 // start index that is a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002564 if (MaxRange[Input] < MaskNumElts) {
2565 RangeUse[Input] = 1; // Extract from beginning of the vector
2566 StartIdx[Input] = 0;
2567 } else {
2568 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang6cce3da2008-11-23 04:35:05 +00002569 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002570 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002571 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002572 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002573 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002574 }
2575
2576 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002577 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002578 return;
2579 }
2580 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2581 // Extract appropriate subvector and generate a vector shuffle
2582 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002583 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002584 if (RangeUse[Input] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002585 Src = DAG.getUNDEF(VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002586 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002587 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002588 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002589 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002590 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002591 // Calculate new mask.
2592 SmallVector<SDValue, 8> MappedOps;
2593 for (int i = 0; i != MaskNumElts; ++i) {
2594 SDValue Arg = Mask.getOperand(i);
2595 if (Arg.getOpcode() == ISD::UNDEF) {
2596 MappedOps.push_back(Arg);
2597 } else {
2598 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2599 if (Idx < SrcNumElts)
2600 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2601 else {
2602 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2603 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002604 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002605 }
2606 }
Evan Chenga87008d2009-02-25 22:49:59 +00002607 Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2608 Mask.getValueType(),
2609 &MappedOps[0], MappedOps.size());
Scott Michelfdc40a02009-02-17 22:15:04 +00002610 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002611 VT, Src1, Src2, Mask));
Mon P Wangc7849c22008-11-16 05:06:27 +00002612 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002613 }
2614 }
2615
Mon P Wangc7849c22008-11-16 05:06:27 +00002616 // We can't use either concat vectors or extract subvectors so fall back to
2617 // replacing the shuffle with extract and build vector.
2618 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002619 MVT EltVT = VT.getVectorElementType();
2620 MVT PtrVT = TLI.getPointerTy();
2621 SmallVector<SDValue,8> Ops;
Mon P Wangc7849c22008-11-16 05:06:27 +00002622 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002623 SDValue Arg = Mask.getOperand(i);
2624 if (Arg.getOpcode() == ISD::UNDEF) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002625 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002626 } else {
2627 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002628 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2629 if (Idx < SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002630 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002631 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002632 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002633 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Scott Michelfdc40a02009-02-17 22:15:04 +00002634 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002635 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002636 }
2637 }
Evan Chenga87008d2009-02-25 22:49:59 +00002638 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2639 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002640}
2641
2642void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2643 const Value *Op0 = I.getOperand(0);
2644 const Value *Op1 = I.getOperand(1);
2645 const Type *AggTy = I.getType();
2646 const Type *ValTy = Op1->getType();
2647 bool IntoUndef = isa<UndefValue>(Op0);
2648 bool FromUndef = isa<UndefValue>(Op1);
2649
2650 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2651 I.idx_begin(), I.idx_end());
2652
2653 SmallVector<MVT, 4> AggValueVTs;
2654 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2655 SmallVector<MVT, 4> ValValueVTs;
2656 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2657
2658 unsigned NumAggValues = AggValueVTs.size();
2659 unsigned NumValValues = ValValueVTs.size();
2660 SmallVector<SDValue, 4> Values(NumAggValues);
2661
2662 SDValue Agg = getValue(Op0);
2663 SDValue Val = getValue(Op1);
2664 unsigned i = 0;
2665 // Copy the beginning value(s) from the original aggregate.
2666 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002667 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002668 SDValue(Agg.getNode(), Agg.getResNo() + i);
2669 // Copy values from the inserted value(s).
2670 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002671 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002672 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2673 // Copy remaining value(s) from the original aggregate.
2674 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002675 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002676 SDValue(Agg.getNode(), Agg.getResNo() + i);
2677
Scott Michelfdc40a02009-02-17 22:15:04 +00002678 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002679 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2680 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002681}
2682
2683void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2684 const Value *Op0 = I.getOperand(0);
2685 const Type *AggTy = Op0->getType();
2686 const Type *ValTy = I.getType();
2687 bool OutOfUndef = isa<UndefValue>(Op0);
2688
2689 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2690 I.idx_begin(), I.idx_end());
2691
2692 SmallVector<MVT, 4> ValValueVTs;
2693 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2694
2695 unsigned NumValValues = ValValueVTs.size();
2696 SmallVector<SDValue, 4> Values(NumValValues);
2697
2698 SDValue Agg = getValue(Op0);
2699 // Copy out the selected value(s).
2700 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2701 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002702 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002703 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002704 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002705
Scott Michelfdc40a02009-02-17 22:15:04 +00002706 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002707 DAG.getVTList(&ValValueVTs[0], NumValValues),
2708 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002709}
2710
2711
2712void SelectionDAGLowering::visitGetElementPtr(User &I) {
2713 SDValue N = getValue(I.getOperand(0));
2714 const Type *Ty = I.getOperand(0)->getType();
2715
2716 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2717 OI != E; ++OI) {
2718 Value *Idx = *OI;
2719 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2720 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2721 if (Field) {
2722 // N = N + Offset
2723 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002724 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002725 DAG.getIntPtrConstant(Offset));
2726 }
2727 Ty = StTy->getElementType(Field);
2728 } else {
2729 Ty = cast<SequentialType>(Ty)->getElementType();
2730
2731 // If this is a constant subscript, handle it quickly.
2732 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2733 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002734 uint64_t Offs =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002735 TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002736 SDValue OffsVal;
Evan Chengb1032a82009-02-09 20:54:38 +00002737 unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
Evan Cheng65b52df2009-02-09 21:01:06 +00002738 if (PtrBits < 64) {
2739 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2740 TLI.getPointerTy(),
2741 DAG.getConstant(Offs, MVT::i64));
2742 } else
Evan Chengb1032a82009-02-09 20:54:38 +00002743 OffsVal = DAG.getIntPtrConstant(Offs);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002744 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002745 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002746 continue;
2747 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002748
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002749 // N = N + Idx * ElementSize;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002750 uint64_t ElementSize = TD->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002751 SDValue IdxN = getValue(Idx);
2752
2753 // If the index is smaller or larger than intptr_t, truncate or extend
2754 // it.
2755 if (IdxN.getValueType().bitsLT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002756 IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002757 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002758 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002759 IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002760 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002761
2762 // If this is a multiply by a power of two, turn it into a shl
2763 // immediately. This is a very common case.
2764 if (ElementSize != 1) {
2765 if (isPowerOf2_64(ElementSize)) {
2766 unsigned Amt = Log2_64(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002767 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002768 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002769 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002770 } else {
2771 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002772 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002773 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002774 }
2775 }
2776
Scott Michelfdc40a02009-02-17 22:15:04 +00002777 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002778 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002779 }
2780 }
2781 setValue(&I, N);
2782}
2783
2784void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2785 // If this is a fixed sized alloca in the entry block of the function,
2786 // allocate it statically on the stack.
2787 if (FuncInfo.StaticAllocaMap.count(&I))
2788 return; // getValue will auto-populate this.
2789
2790 const Type *Ty = I.getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002791 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002792 unsigned Align =
2793 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2794 I.getAlignment());
2795
2796 SDValue AllocSize = getValue(I.getArraySize());
Chris Lattner0b18e592009-03-17 19:36:00 +00002797
2798 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2799 AllocSize,
2800 DAG.getConstant(TySize, AllocSize.getValueType()));
2801
2802
2803
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002804 MVT IntPtr = TLI.getPointerTy();
2805 if (IntPtr.bitsLT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002806 AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002807 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002808 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002809 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002810 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002811
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002812 // Handle alignment. If the requested alignment is less than or equal to
2813 // the stack alignment, ignore it. If the size is greater than or equal to
2814 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2815 unsigned StackAlign =
2816 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2817 if (Align <= StackAlign)
2818 Align = 0;
2819
2820 // Round the size of the allocation up to the stack alignment size
2821 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002822 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002823 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002824 DAG.getIntPtrConstant(StackAlign-1));
2825 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002826 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002827 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002828 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2829
2830 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Dan Gohmanfc166572009-04-09 23:54:40 +00002831 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002832 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002833 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002834 setValue(&I, DSA);
2835 DAG.setRoot(DSA.getValue(1));
2836
2837 // Inform the Frame Information that we have just allocated a variable-sized
2838 // object.
2839 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2840}
2841
2842void SelectionDAGLowering::visitLoad(LoadInst &I) {
2843 const Value *SV = I.getOperand(0);
2844 SDValue Ptr = getValue(SV);
2845
2846 const Type *Ty = I.getType();
2847 bool isVolatile = I.isVolatile();
2848 unsigned Alignment = I.getAlignment();
2849
2850 SmallVector<MVT, 4> ValueVTs;
2851 SmallVector<uint64_t, 4> Offsets;
2852 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2853 unsigned NumValues = ValueVTs.size();
2854 if (NumValues == 0)
2855 return;
2856
2857 SDValue Root;
2858 bool ConstantMemory = false;
2859 if (I.isVolatile())
2860 // Serialize volatile loads with other side effects.
2861 Root = getRoot();
2862 else if (AA->pointsToConstantMemory(SV)) {
2863 // Do not serialize (non-volatile) loads of constant memory with anything.
2864 Root = DAG.getEntryNode();
2865 ConstantMemory = true;
2866 } else {
2867 // Do not serialize non-volatile loads against each other.
2868 Root = DAG.getRoot();
2869 }
2870
2871 SmallVector<SDValue, 4> Values(NumValues);
2872 SmallVector<SDValue, 4> Chains(NumValues);
2873 MVT PtrVT = Ptr.getValueType();
2874 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002875 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Scott Michelfdc40a02009-02-17 22:15:04 +00002876 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002877 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002878 DAG.getConstant(Offsets[i], PtrVT)),
2879 SV, Offsets[i],
2880 isVolatile, Alignment);
2881 Values[i] = L;
2882 Chains[i] = L.getValue(1);
2883 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002884
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002885 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002886 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002887 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002888 &Chains[0], NumValues);
2889 if (isVolatile)
2890 DAG.setRoot(Chain);
2891 else
2892 PendingLoads.push_back(Chain);
2893 }
2894
Scott Michelfdc40a02009-02-17 22:15:04 +00002895 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002896 DAG.getVTList(&ValueVTs[0], NumValues),
2897 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002898}
2899
2900
2901void SelectionDAGLowering::visitStore(StoreInst &I) {
2902 Value *SrcV = I.getOperand(0);
2903 Value *PtrV = I.getOperand(1);
2904
2905 SmallVector<MVT, 4> ValueVTs;
2906 SmallVector<uint64_t, 4> Offsets;
2907 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2908 unsigned NumValues = ValueVTs.size();
2909 if (NumValues == 0)
2910 return;
2911
2912 // Get the lowered operands. Note that we do this after
2913 // checking if NumResults is zero, because with zero results
2914 // the operands won't have values in the map.
2915 SDValue Src = getValue(SrcV);
2916 SDValue Ptr = getValue(PtrV);
2917
2918 SDValue Root = getRoot();
2919 SmallVector<SDValue, 4> Chains(NumValues);
2920 MVT PtrVT = Ptr.getValueType();
2921 bool isVolatile = I.isVolatile();
2922 unsigned Alignment = I.getAlignment();
2923 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002924 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002925 SDValue(Src.getNode(), Src.getResNo() + i),
Scott Michelfdc40a02009-02-17 22:15:04 +00002926 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002927 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002928 DAG.getConstant(Offsets[i], PtrVT)),
2929 PtrV, Offsets[i],
2930 isVolatile, Alignment);
2931
Scott Michelfdc40a02009-02-17 22:15:04 +00002932 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002933 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002934}
2935
2936/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2937/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002938void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002939 unsigned Intrinsic) {
2940 bool HasChain = !I.doesNotAccessMemory();
2941 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2942
2943 // Build the operand list.
2944 SmallVector<SDValue, 8> Ops;
2945 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2946 if (OnlyLoad) {
2947 // We don't need to serialize loads against other loads.
2948 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002949 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002950 Ops.push_back(getRoot());
2951 }
2952 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002953
2954 // Info is set by getTgtMemInstrinsic
2955 TargetLowering::IntrinsicInfo Info;
2956 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2957
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002958 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002959 if (!IsTgtIntrinsic)
2960 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002961
2962 // Add all operands of the call to the operand list.
2963 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2964 SDValue Op = getValue(I.getOperand(i));
2965 assert(TLI.isTypeLegal(Op.getValueType()) &&
2966 "Intrinsic uses a non-legal type?");
2967 Ops.push_back(Op);
2968 }
2969
Dan Gohmanfc166572009-04-09 23:54:40 +00002970 std::vector<MVT> VTArray;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002971 if (I.getType() != Type::VoidTy) {
2972 MVT VT = TLI.getValueType(I.getType());
2973 if (VT.isVector()) {
2974 const VectorType *DestTy = cast<VectorType>(I.getType());
2975 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002976
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002977 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2978 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2979 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002980
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002981 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
Dan Gohmanfc166572009-04-09 23:54:40 +00002982 VTArray.push_back(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002983 }
2984 if (HasChain)
Dan Gohmanfc166572009-04-09 23:54:40 +00002985 VTArray.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002986
Dan Gohmanfc166572009-04-09 23:54:40 +00002987 SDVTList VTs = DAG.getVTList(&VTArray[0], VTArray.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002988
2989 // Create the node.
2990 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002991 if (IsTgtIntrinsic) {
2992 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002993 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002994 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002995 Info.memVT, Info.ptrVal, Info.offset,
2996 Info.align, Info.vol,
2997 Info.readMem, Info.writeMem);
2998 }
2999 else if (!HasChain)
Scott Michelfdc40a02009-02-17 22:15:04 +00003000 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003001 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003002 else if (I.getType() != Type::VoidTy)
Scott Michelfdc40a02009-02-17 22:15:04 +00003003 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003004 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003005 else
Scott Michelfdc40a02009-02-17 22:15:04 +00003006 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003007 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003008
3009 if (HasChain) {
3010 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3011 if (OnlyLoad)
3012 PendingLoads.push_back(Chain);
3013 else
3014 DAG.setRoot(Chain);
3015 }
3016 if (I.getType() != Type::VoidTy) {
3017 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3018 MVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003019 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003020 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003021 setValue(&I, Result);
3022 }
3023}
3024
3025/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3026static GlobalVariable *ExtractTypeInfo(Value *V) {
3027 V = V->stripPointerCasts();
3028 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3029 assert ((GV || isa<ConstantPointerNull>(V)) &&
3030 "TypeInfo must be a global variable or NULL");
3031 return GV;
3032}
3033
3034namespace llvm {
3035
3036/// AddCatchInfo - Extract the personality and type infos from an eh.selector
3037/// call, and add them to the specified machine basic block.
3038void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3039 MachineBasicBlock *MBB) {
3040 // Inform the MachineModuleInfo of the personality for this landing pad.
3041 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3042 assert(CE->getOpcode() == Instruction::BitCast &&
3043 isa<Function>(CE->getOperand(0)) &&
3044 "Personality should be a function");
3045 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3046
3047 // Gather all the type infos for this landing pad and pass them along to
3048 // MachineModuleInfo.
3049 std::vector<GlobalVariable *> TyInfo;
3050 unsigned N = I.getNumOperands();
3051
3052 for (unsigned i = N - 1; i > 2; --i) {
3053 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3054 unsigned FilterLength = CI->getZExtValue();
3055 unsigned FirstCatch = i + FilterLength + !FilterLength;
3056 assert (FirstCatch <= N && "Invalid filter length");
3057
3058 if (FirstCatch < N) {
3059 TyInfo.reserve(N - FirstCatch);
3060 for (unsigned j = FirstCatch; j < N; ++j)
3061 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3062 MMI->addCatchTypeInfo(MBB, TyInfo);
3063 TyInfo.clear();
3064 }
3065
3066 if (!FilterLength) {
3067 // Cleanup.
3068 MMI->addCleanup(MBB);
3069 } else {
3070 // Filter.
3071 TyInfo.reserve(FilterLength - 1);
3072 for (unsigned j = i + 1; j < FirstCatch; ++j)
3073 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3074 MMI->addFilterTypeInfo(MBB, TyInfo);
3075 TyInfo.clear();
3076 }
3077
3078 N = i;
3079 }
3080 }
3081
3082 if (N > 3) {
3083 TyInfo.reserve(N - 3);
3084 for (unsigned j = 3; j < N; ++j)
3085 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3086 MMI->addCatchTypeInfo(MBB, TyInfo);
3087 }
3088}
3089
3090}
3091
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003092/// GetSignificand - Get the significand and build it into a floating-point
3093/// number with exponent of 1:
3094///
3095/// Op = (Op & 0x007fffff) | 0x3f800000;
3096///
3097/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003098static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003099GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3100 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003101 DAG.getConstant(0x007fffff, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003102 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003103 DAG.getConstant(0x3f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003104 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003105}
3106
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003107/// GetExponent - Get the exponent:
3108///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003109/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003110///
3111/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003112static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003113GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3114 DebugLoc dl) {
3115 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003116 DAG.getConstant(0x7f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003117 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003118 DAG.getConstant(23, TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003119 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003120 DAG.getConstant(127, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003121 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003122}
3123
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003124/// getF32Constant - Get 32-bit floating point constant.
3125static SDValue
3126getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3127 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3128}
3129
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003130/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003131/// visitIntrinsicCall: I is a call instruction
3132/// Op is the associated NodeType for I
3133const char *
3134SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003135 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003136 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003137 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003138 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003139 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003140 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003141 getValue(I.getOperand(2)),
3142 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003143 setValue(&I, L);
3144 DAG.setRoot(L.getValue(1));
3145 return 0;
3146}
3147
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003148// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003149const char *
3150SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003151 SDValue Op1 = getValue(I.getOperand(1));
3152 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003153
Dan Gohmanfc166572009-04-09 23:54:40 +00003154 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3155 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
Bill Wendling74c37652008-12-09 22:08:41 +00003156
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003157 setValue(&I, Result);
3158 return 0;
3159}
Bill Wendling74c37652008-12-09 22:08:41 +00003160
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003161/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3162/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003163void
3164SelectionDAGLowering::visitExp(CallInst &I) {
3165 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003166 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003167
3168 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3169 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3170 SDValue Op = getValue(I.getOperand(1));
3171
3172 // Put the exponent in the right bit position for later addition to the
3173 // final result:
3174 //
3175 // #define LOG2OFe 1.4426950f
3176 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003177 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003178 getF32Constant(DAG, 0x3fb8aa3b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003179 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003180
3181 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003182 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3183 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003184
3185 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003186 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003187 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003188
3189 if (LimitFloatPrecision <= 6) {
3190 // For floating-point precision of 6:
3191 //
3192 // TwoToFractionalPartOfX =
3193 // 0.997535578f +
3194 // (0.735607626f + 0.252464424f * x) * x;
3195 //
3196 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003197 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003198 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003199 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003200 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003201 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3202 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003203 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003204 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003205
3206 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003207 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003208 TwoToFracPartOfX, IntegerPartOfX);
3209
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003210 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003211 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3212 // For floating-point precision of 12:
3213 //
3214 // TwoToFractionalPartOfX =
3215 // 0.999892986f +
3216 // (0.696457318f +
3217 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3218 //
3219 // 0.000107046256 error, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003220 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003221 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003222 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003223 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003224 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3225 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003226 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003227 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3228 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003229 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003230 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003231
3232 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003233 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003234 TwoToFracPartOfX, IntegerPartOfX);
3235
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003236 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003237 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3238 // For floating-point precision of 18:
3239 //
3240 // TwoToFractionalPartOfX =
3241 // 0.999999982f +
3242 // (0.693148872f +
3243 // (0.240227044f +
3244 // (0.554906021e-1f +
3245 // (0.961591928e-2f +
3246 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3247 //
3248 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003249 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003250 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003251 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003252 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003253 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3254 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003255 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003256 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3257 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003258 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003259 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3260 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003261 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003262 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3263 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003264 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003265 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3266 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003267 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003268 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003269 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003270
3271 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003272 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003273 TwoToFracPartOfX, IntegerPartOfX);
3274
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003275 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003276 }
3277 } else {
3278 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003279 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003280 getValue(I.getOperand(1)).getValueType(),
3281 getValue(I.getOperand(1)));
3282 }
3283
Dale Johannesen59e577f2008-09-05 18:38:42 +00003284 setValue(&I, result);
3285}
3286
Bill Wendling39150252008-09-09 20:39:27 +00003287/// visitLog - Lower a log intrinsic. Handles the special sequences for
3288/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003289void
3290SelectionDAGLowering::visitLog(CallInst &I) {
3291 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003292 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003293
3294 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3295 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3296 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003297 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003298
3299 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003300 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003301 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003302 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003303
3304 // Get the significand and build it into a floating-point number with
3305 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003306 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003307
3308 if (LimitFloatPrecision <= 6) {
3309 // For floating-point precision of 6:
3310 //
3311 // LogofMantissa =
3312 // -1.1609546f +
3313 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003314 //
Bill Wendling39150252008-09-09 20:39:27 +00003315 // error 0.0034276066, which is better than 8 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003316 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003317 getF32Constant(DAG, 0xbe74c456));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003318 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003319 getF32Constant(DAG, 0x3fb3a2b1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003320 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3321 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003322 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003323
Scott Michelfdc40a02009-02-17 22:15:04 +00003324 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003325 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003326 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3327 // For floating-point precision of 12:
3328 //
3329 // LogOfMantissa =
3330 // -1.7417939f +
3331 // (2.8212026f +
3332 // (-1.4699568f +
3333 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3334 //
3335 // error 0.000061011436, which is 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003336 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003337 getF32Constant(DAG, 0xbd67b6d6));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003338 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003339 getF32Constant(DAG, 0x3ee4f4b8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003340 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3341 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003342 getF32Constant(DAG, 0x3fbc278b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003343 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3344 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003345 getF32Constant(DAG, 0x40348e95));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003346 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3347 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003348 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003349
Scott Michelfdc40a02009-02-17 22:15:04 +00003350 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003351 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003352 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3353 // For floating-point precision of 18:
3354 //
3355 // LogOfMantissa =
3356 // -2.1072184f +
3357 // (4.2372794f +
3358 // (-3.7029485f +
3359 // (2.2781945f +
3360 // (-0.87823314f +
3361 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3362 //
3363 // error 0.0000023660568, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003364 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003365 getF32Constant(DAG, 0xbc91e5ac));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003366 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003367 getF32Constant(DAG, 0x3e4350aa));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003368 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3369 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003370 getF32Constant(DAG, 0x3f60d3e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003371 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3372 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003373 getF32Constant(DAG, 0x4011cdf0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003374 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3375 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003376 getF32Constant(DAG, 0x406cfd1c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003377 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3378 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003379 getF32Constant(DAG, 0x408797cb));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003380 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3381 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003382 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003383
Scott Michelfdc40a02009-02-17 22:15:04 +00003384 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003385 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003386 }
3387 } else {
3388 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003389 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003390 getValue(I.getOperand(1)).getValueType(),
3391 getValue(I.getOperand(1)));
3392 }
3393
Dale Johannesen59e577f2008-09-05 18:38:42 +00003394 setValue(&I, result);
3395}
3396
Bill Wendling3eb59402008-09-09 00:28:24 +00003397/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3398/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003399void
3400SelectionDAGLowering::visitLog2(CallInst &I) {
3401 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003402 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003403
Dale Johannesen853244f2008-09-05 23:49:37 +00003404 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003405 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3406 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003407 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003408
Bill Wendling39150252008-09-09 20:39:27 +00003409 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003410 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003411
3412 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003413 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003414 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003415
Bill Wendling3eb59402008-09-09 00:28:24 +00003416 // Different possible minimax approximations of significand in
3417 // floating-point for various degrees of accuracy over [1,2].
3418 if (LimitFloatPrecision <= 6) {
3419 // For floating-point precision of 6:
3420 //
3421 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3422 //
3423 // error 0.0049451742, which is more than 7 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003424 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003425 getF32Constant(DAG, 0xbeb08fe0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003426 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003427 getF32Constant(DAG, 0x40019463));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003428 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3429 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003430 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003431
Scott Michelfdc40a02009-02-17 22:15:04 +00003432 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003433 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003434 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3435 // For floating-point precision of 12:
3436 //
3437 // Log2ofMantissa =
3438 // -2.51285454f +
3439 // (4.07009056f +
3440 // (-2.12067489f +
3441 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003442 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003443 // error 0.0000876136000, which is better than 13 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003444 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003445 getF32Constant(DAG, 0xbda7262e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003446 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003447 getF32Constant(DAG, 0x3f25280b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003448 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3449 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003450 getF32Constant(DAG, 0x4007b923));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003451 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3452 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003453 getF32Constant(DAG, 0x40823e2f));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003454 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3455 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003456 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003457
Scott Michelfdc40a02009-02-17 22:15:04 +00003458 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003459 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003460 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3461 // For floating-point precision of 18:
3462 //
3463 // Log2ofMantissa =
3464 // -3.0400495f +
3465 // (6.1129976f +
3466 // (-5.3420409f +
3467 // (3.2865683f +
3468 // (-1.2669343f +
3469 // (0.27515199f -
3470 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3471 //
3472 // error 0.0000018516, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003473 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003474 getF32Constant(DAG, 0xbcd2769e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003475 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003476 getF32Constant(DAG, 0x3e8ce0b9));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003477 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3478 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003479 getF32Constant(DAG, 0x3fa22ae7));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003480 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3481 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003482 getF32Constant(DAG, 0x40525723));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003483 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3484 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003485 getF32Constant(DAG, 0x40aaf200));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003486 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3487 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003488 getF32Constant(DAG, 0x40c39dad));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003489 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3490 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003491 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003492
Scott Michelfdc40a02009-02-17 22:15:04 +00003493 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003494 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003495 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003496 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003497 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003498 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003499 getValue(I.getOperand(1)).getValueType(),
3500 getValue(I.getOperand(1)));
3501 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003502
Dale Johannesen59e577f2008-09-05 18:38:42 +00003503 setValue(&I, result);
3504}
3505
Bill Wendling3eb59402008-09-09 00:28:24 +00003506/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3507/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003508void
3509SelectionDAGLowering::visitLog10(CallInst &I) {
3510 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003511 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003512
Dale Johannesen852680a2008-09-05 21:27:19 +00003513 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003514 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3515 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003516 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003517
Bill Wendling39150252008-09-09 20:39:27 +00003518 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003519 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003520 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003521 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003522
3523 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003524 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003525 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003526
3527 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003528 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003529 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003530 // Log10ofMantissa =
3531 // -0.50419619f +
3532 // (0.60948995f - 0.10380950f * x) * x;
3533 //
3534 // error 0.0014886165, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003535 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003536 getF32Constant(DAG, 0xbdd49a13));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003537 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003538 getF32Constant(DAG, 0x3f1c0789));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003539 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3540 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003541 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003542
Scott Michelfdc40a02009-02-17 22:15:04 +00003543 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003544 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003545 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3546 // For floating-point precision of 12:
3547 //
3548 // Log10ofMantissa =
3549 // -0.64831180f +
3550 // (0.91751397f +
3551 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3552 //
3553 // error 0.00019228036, which is better than 12 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003554 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003555 getF32Constant(DAG, 0x3d431f31));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003556 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003557 getF32Constant(DAG, 0x3ea21fb2));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003558 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3559 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003560 getF32Constant(DAG, 0x3f6ae232));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003561 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3562 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003563 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003564
Scott Michelfdc40a02009-02-17 22:15:04 +00003565 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003566 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003567 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003568 // For floating-point precision of 18:
3569 //
3570 // Log10ofMantissa =
3571 // -0.84299375f +
3572 // (1.5327582f +
3573 // (-1.0688956f +
3574 // (0.49102474f +
3575 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3576 //
3577 // error 0.0000037995730, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003578 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003579 getF32Constant(DAG, 0x3c5d51ce));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003580 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003581 getF32Constant(DAG, 0x3e00685a));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003582 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3583 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003584 getF32Constant(DAG, 0x3efb6798));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003585 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3586 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003587 getF32Constant(DAG, 0x3f88d192));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003588 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3589 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003590 getF32Constant(DAG, 0x3fc4316c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003591 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3592 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003593 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003594
Scott Michelfdc40a02009-02-17 22:15:04 +00003595 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003596 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003597 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003598 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003599 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003600 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003601 getValue(I.getOperand(1)).getValueType(),
3602 getValue(I.getOperand(1)));
3603 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003604
Dale Johannesen59e577f2008-09-05 18:38:42 +00003605 setValue(&I, result);
3606}
3607
Bill Wendlinge10c8142008-09-09 22:39:21 +00003608/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3609/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003610void
3611SelectionDAGLowering::visitExp2(CallInst &I) {
3612 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003613 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003614
Dale Johannesen601d3c02008-09-05 01:48:15 +00003615 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003616 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3617 SDValue Op = getValue(I.getOperand(1));
3618
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003619 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003620
3621 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003622 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3623 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003624
3625 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003626 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003627 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003628
3629 if (LimitFloatPrecision <= 6) {
3630 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003631 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003632 // TwoToFractionalPartOfX =
3633 // 0.997535578f +
3634 // (0.735607626f + 0.252464424f * x) * x;
3635 //
3636 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003637 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003638 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003639 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003640 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003641 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3642 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003643 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003644 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003645 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003646 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003647
Scott Michelfdc40a02009-02-17 22:15:04 +00003648 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003649 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003650 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3651 // For floating-point precision of 12:
3652 //
3653 // TwoToFractionalPartOfX =
3654 // 0.999892986f +
3655 // (0.696457318f +
3656 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3657 //
3658 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003659 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003660 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003661 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003662 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003663 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3664 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003665 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003666 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3667 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003668 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003669 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003670 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003671 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003672
Scott Michelfdc40a02009-02-17 22:15:04 +00003673 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003674 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003675 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3676 // For floating-point precision of 18:
3677 //
3678 // TwoToFractionalPartOfX =
3679 // 0.999999982f +
3680 // (0.693148872f +
3681 // (0.240227044f +
3682 // (0.554906021e-1f +
3683 // (0.961591928e-2f +
3684 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3685 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003686 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003687 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003688 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003689 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003690 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3691 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003692 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003693 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3694 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003695 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003696 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3697 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003698 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003699 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3700 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003701 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003702 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3703 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003704 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003705 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003706 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003707 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003708
Scott Michelfdc40a02009-02-17 22:15:04 +00003709 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003710 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003711 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003712 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003713 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003714 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003715 getValue(I.getOperand(1)).getValueType(),
3716 getValue(I.getOperand(1)));
3717 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003718
Dale Johannesen601d3c02008-09-05 01:48:15 +00003719 setValue(&I, result);
3720}
3721
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003722/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3723/// limited-precision mode with x == 10.0f.
3724void
3725SelectionDAGLowering::visitPow(CallInst &I) {
3726 SDValue result;
3727 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003728 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003729 bool IsExp10 = false;
3730
3731 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003732 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003733 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3734 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3735 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3736 APFloat Ten(10.0f);
3737 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3738 }
3739 }
3740 }
3741
3742 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3743 SDValue Op = getValue(I.getOperand(2));
3744
3745 // Put the exponent in the right bit position for later addition to the
3746 // final result:
3747 //
3748 // #define LOG2OF10 3.3219281f
3749 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003750 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003751 getF32Constant(DAG, 0x40549a78));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003752 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003753
3754 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003755 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3756 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003757
3758 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003759 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003760 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003761
3762 if (LimitFloatPrecision <= 6) {
3763 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003764 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003765 // twoToFractionalPartOfX =
3766 // 0.997535578f +
3767 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003768 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003769 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003770 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003771 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003772 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003773 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003774 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3775 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003776 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003777 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003778 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003779 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003780
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003781 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3782 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003783 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3784 // For floating-point precision of 12:
3785 //
3786 // TwoToFractionalPartOfX =
3787 // 0.999892986f +
3788 // (0.696457318f +
3789 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3790 //
3791 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003792 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003793 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003794 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003795 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003796 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3797 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003798 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003799 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3800 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003801 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003802 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003803 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003804 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003805
Scott Michelfdc40a02009-02-17 22:15:04 +00003806 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003807 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003808 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3809 // For floating-point precision of 18:
3810 //
3811 // TwoToFractionalPartOfX =
3812 // 0.999999982f +
3813 // (0.693148872f +
3814 // (0.240227044f +
3815 // (0.554906021e-1f +
3816 // (0.961591928e-2f +
3817 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3818 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003819 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003820 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003821 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003822 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003823 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3824 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003825 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003826 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3827 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003828 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003829 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3830 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003831 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003832 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3833 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003834 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003835 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3836 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003837 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003838 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003839 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003840 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003841
Scott Michelfdc40a02009-02-17 22:15:04 +00003842 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003843 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003844 }
3845 } else {
3846 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003847 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003848 getValue(I.getOperand(1)).getValueType(),
3849 getValue(I.getOperand(1)),
3850 getValue(I.getOperand(2)));
3851 }
3852
3853 setValue(&I, result);
3854}
3855
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003856/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3857/// we want to emit this as a call to a named external function, return the name
3858/// otherwise lower it and return null.
3859const char *
3860SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003861 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003862 switch (Intrinsic) {
3863 default:
3864 // By default, turn this into a target intrinsic node.
3865 visitTargetIntrinsic(I, Intrinsic);
3866 return 0;
3867 case Intrinsic::vastart: visitVAStart(I); return 0;
3868 case Intrinsic::vaend: visitVAEnd(I); return 0;
3869 case Intrinsic::vacopy: visitVACopy(I); return 0;
3870 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003871 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003872 getValue(I.getOperand(1))));
3873 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003874 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003875 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003876 getValue(I.getOperand(1))));
3877 return 0;
3878 case Intrinsic::setjmp:
3879 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3880 break;
3881 case Intrinsic::longjmp:
3882 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3883 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003884 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003885 SDValue Op1 = getValue(I.getOperand(1));
3886 SDValue Op2 = getValue(I.getOperand(2));
3887 SDValue Op3 = getValue(I.getOperand(3));
3888 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003889 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003890 I.getOperand(1), 0, I.getOperand(2), 0));
3891 return 0;
3892 }
Chris Lattner824b9582008-11-21 16:42:48 +00003893 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003894 SDValue Op1 = getValue(I.getOperand(1));
3895 SDValue Op2 = getValue(I.getOperand(2));
3896 SDValue Op3 = getValue(I.getOperand(3));
3897 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003898 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003899 I.getOperand(1), 0));
3900 return 0;
3901 }
Chris Lattner824b9582008-11-21 16:42:48 +00003902 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003903 SDValue Op1 = getValue(I.getOperand(1));
3904 SDValue Op2 = getValue(I.getOperand(2));
3905 SDValue Op3 = getValue(I.getOperand(3));
3906 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3907
3908 // If the source and destination are known to not be aliases, we can
3909 // lower memmove as memcpy.
3910 uint64_t Size = -1ULL;
3911 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003912 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003913 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3914 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003915 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003916 I.getOperand(1), 0, I.getOperand(2), 0));
3917 return 0;
3918 }
3919
Dale Johannesena04b7572009-02-03 23:04:43 +00003920 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003921 I.getOperand(1), 0, I.getOperand(2), 0));
3922 return 0;
3923 }
3924 case Intrinsic::dbg_stoppoint: {
Devang Patel83489bb2009-01-13 00:35:13 +00003925 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003926 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Devang Patel48c7fa22009-04-13 18:13:16 +00003927 if (DW && DW->ValidDebugInfo(SPI.getContext(), Fast)) {
Evan Chenge3d42322009-02-25 07:04:34 +00003928 MachineFunction &MF = DAG.getMachineFunction();
Dale Johannesenbeaec4c2009-03-25 17:36:08 +00003929 if (Fast)
3930 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3931 SPI.getLine(),
3932 SPI.getColumn(),
3933 SPI.getContext()));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003934 DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
Bill Wendling0582ae92009-03-13 04:39:26 +00003935 std::string Dir, FN;
3936 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
3937 CU.getFilename(FN));
Evan Chenge3d42322009-02-25 07:04:34 +00003938 unsigned idx = MF.getOrCreateDebugLocID(SrcFile,
3939 SPI.getLine(), SPI.getColumn());
Dale Johannesen66978ee2009-01-31 02:22:37 +00003940 setCurDebugLoc(DebugLoc::get(idx));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003941 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003942 return 0;
3943 }
3944 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003945 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003946 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Devang Patel48c7fa22009-04-13 18:13:16 +00003947 if (DW && DW->ValidDebugInfo(RSI.getContext(), Fast)) {
Bill Wendling92c1e122009-02-13 02:16:35 +00003948 unsigned LabelID =
3949 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Devang Patel48c7fa22009-04-13 18:13:16 +00003950 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3951 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003952 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003953
3954 return 0;
3955 }
3956 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003957 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003958 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patel48c7fa22009-04-13 18:13:16 +00003959 if (DW && DW->ValidDebugInfo(REI.getContext(), Fast)) {
Devang Patel0f7fef32009-04-13 17:02:03 +00003960
3961 MachineFunction &MF = DAG.getMachineFunction();
3962 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
3963 std::string SPName;
3964 Subprogram.getLinkageName(SPName);
3965 if (!SPName.empty()
3966 && strcmp(SPName.c_str(), MF.getFunction()->getNameStart())) {
Devang Patel16f2ffd2009-04-16 02:33:41 +00003967 // This is end of inlined function. Debugging information for
3968 // inlined function is not handled yet (only supported by FastISel).
3969 if (Fast) {
3970 unsigned ID = DW->RecordInlinedFnEnd(Subprogram);
3971 if (ID != 0)
Devang Patel02f8c412009-04-16 17:55:30 +00003972 // Returned ID is 0 if this is unbalanced "end of inlined
3973 // scope". This could happen if optimizer eats dbg intrinsics
3974 // or "beginning of inlined scope" is not recoginized due to
3975 // missing location info. In such cases, do ignore this region.end.
Devang Patel16f2ffd2009-04-16 02:33:41 +00003976 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3977 getRoot(), ID));
3978 }
Devang Patel0f7fef32009-04-13 17:02:03 +00003979 return 0;
3980 }
3981
Bill Wendling92c1e122009-02-13 02:16:35 +00003982 unsigned LabelID =
3983 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
Devang Patel48c7fa22009-04-13 18:13:16 +00003984 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3985 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003986 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003987
3988 return 0;
3989 }
3990 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003991 DwarfWriter *DW = DAG.getDwarfWriter();
3992 if (!DW) return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003993 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3994 Value *SP = FSI.getSubprogram();
Devang Patel48c7fa22009-04-13 18:13:16 +00003995 if (SP && DW->ValidDebugInfo(SP, Fast)) {
Devang Patel16f2ffd2009-04-16 02:33:41 +00003996 MachineFunction &MF = DAG.getMachineFunction();
Bill Wendling5aa49772009-02-24 02:35:30 +00003997 if (Fast) {
Devang Patel16f2ffd2009-04-16 02:33:41 +00003998 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is what
3999 // (most?) gdb expects.
4000 DebugLoc PrevLoc = CurDebugLoc;
4001 DISubprogram Subprogram(cast<GlobalVariable>(SP));
4002 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
4003 std::string Dir, FN;
4004 unsigned SrcFile = DW->getOrCreateSourceID(CompileUnit.getDirectory(Dir),
4005 CompileUnit.getFilename(FN));
4006
4007 if (!Subprogram.describes(MF.getFunction())) {
4008 // This is a beginning of an inlined function.
4009
Devang Patel02f8c412009-04-16 17:55:30 +00004010 // If llvm.dbg.func.start is seen in a new block before any
4011 // llvm.dbg.stoppoint intrinsic then the location info is unknown.
4012 // FIXME : Why DebugLoc is reset at the beginning of each block ?
4013 if (PrevLoc.isUnknown())
4014 return 0;
4015
Devang Patel16f2ffd2009-04-16 02:33:41 +00004016 // Record the source line.
4017 unsigned Line = Subprogram.getLineNumber();
4018 unsigned LabelID = DW->RecordSourceLine(Line, 0, SrcFile);
4019 setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
4020
Bill Wendling86e6cb92009-02-17 01:04:54 +00004021 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
4022 getRoot(), LabelID));
Devang Patel16f2ffd2009-04-16 02:33:41 +00004023 DebugLocTuple PrevLocTpl = MF.getDebugLocTuple(PrevLoc);
4024 DW->RecordInlinedFnStart(&FSI, Subprogram, LabelID,
4025 PrevLocTpl.Src,
4026 PrevLocTpl.Line,
4027 PrevLocTpl.Col);
4028 } else {
4029 // Record the source line.
4030 unsigned Line = Subprogram.getLineNumber();
4031 setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
Devang Patel906caf22009-04-16 15:07:09 +00004032 DW->RecordSourceLine(Line, 0, SrcFile);
Devang Patel16f2ffd2009-04-16 02:33:41 +00004033 // llvm.dbg.func_start also defines beginning of function scope.
4034 DW->RecordRegionStart(cast<GlobalVariable>(FSI.getSubprogram()));
4035 }
4036 } else {
4037 DISubprogram Subprogram(cast<GlobalVariable>(SP));
4038
4039 std::string SPName;
4040 Subprogram.getLinkageName(SPName);
4041 if (!SPName.empty()
4042 && strcmp(SPName.c_str(), MF.getFunction()->getNameStart())) {
4043 // This is beginning of inlined function. Debugging information for
4044 // inlined function is not handled yet (only supported by FastISel).
4045 return 0;
4046 }
4047
4048 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
4049 // what (most?) gdb expects.
4050 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
4051 std::string Dir, FN;
4052 unsigned SrcFile = DW->getOrCreateSourceID(CompileUnit.getDirectory(Dir),
4053 CompileUnit.getFilename(FN));
4054
4055 // Record the source line but does not create a label for the normal
4056 // function start. It will be emitted at asm emission time. However,
4057 // create a label if this is a beginning of inlined function.
4058 unsigned Line = Subprogram.getLineNumber();
4059 setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
4060 // FIXME - Start new region because llvm.dbg.func_start also defines
4061 // beginning of function scope.
4062 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004063 }
4064
4065 return 0;
4066 }
Bill Wendling92c1e122009-02-13 02:16:35 +00004067 case Intrinsic::dbg_declare: {
Bill Wendling5aa49772009-02-24 02:35:30 +00004068 if (Fast) {
Bill Wendling86e6cb92009-02-17 01:04:54 +00004069 DwarfWriter *DW = DAG.getDwarfWriter();
4070 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4071 Value *Variable = DI.getVariable();
Devang Patel48c7fa22009-04-13 18:13:16 +00004072 if (DW && DW->ValidDebugInfo(Variable, Fast))
Bill Wendling86e6cb92009-02-17 01:04:54 +00004073 DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
4074 getValue(DI.getAddress()), getValue(Variable)));
4075 } else {
4076 // FIXME: Do something sensible here when we support debug declare.
4077 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004078 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00004079 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004080 case Intrinsic::eh_exception: {
4081 if (!CurMBB->isLandingPad()) {
4082 // FIXME: Mark exception register as live in. Hack for PR1508.
4083 unsigned Reg = TLI.getExceptionAddressRegister();
4084 if (Reg) CurMBB->addLiveIn(Reg);
4085 }
4086 // Insert the EXCEPTIONADDR instruction.
4087 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4088 SDValue Ops[1];
4089 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004090 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004091 setValue(&I, Op);
4092 DAG.setRoot(Op.getValue(1));
4093 return 0;
4094 }
4095
4096 case Intrinsic::eh_selector_i32:
4097 case Intrinsic::eh_selector_i64: {
4098 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4099 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
4100 MVT::i32 : MVT::i64);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004101
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004102 if (MMI) {
4103 if (CurMBB->isLandingPad())
4104 AddCatchInfo(I, MMI, CurMBB);
4105 else {
4106#ifndef NDEBUG
4107 FuncInfo.CatchInfoLost.insert(&I);
4108#endif
4109 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4110 unsigned Reg = TLI.getExceptionSelectorRegister();
4111 if (Reg) CurMBB->addLiveIn(Reg);
4112 }
4113
4114 // Insert the EHSELECTION instruction.
4115 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4116 SDValue Ops[2];
4117 Ops[0] = getValue(I.getOperand(1));
4118 Ops[1] = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004119 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004120 setValue(&I, Op);
4121 DAG.setRoot(Op.getValue(1));
4122 } else {
4123 setValue(&I, DAG.getConstant(0, VT));
4124 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004125
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004126 return 0;
4127 }
4128
4129 case Intrinsic::eh_typeid_for_i32:
4130 case Intrinsic::eh_typeid_for_i64: {
4131 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4132 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4133 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004134
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004135 if (MMI) {
4136 // Find the type id for the given typeinfo.
4137 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4138
4139 unsigned TypeID = MMI->getTypeIDFor(GV);
4140 setValue(&I, DAG.getConstant(TypeID, VT));
4141 } else {
4142 // Return something different to eh_selector.
4143 setValue(&I, DAG.getConstant(1, VT));
4144 }
4145
4146 return 0;
4147 }
4148
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004149 case Intrinsic::eh_return_i32:
4150 case Intrinsic::eh_return_i64:
4151 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004152 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004153 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004154 MVT::Other,
4155 getControlRoot(),
4156 getValue(I.getOperand(1)),
4157 getValue(I.getOperand(2))));
4158 } else {
4159 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4160 }
4161
4162 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004163 case Intrinsic::eh_unwind_init:
4164 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4165 MMI->setCallsUnwindInit(true);
4166 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004167
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004168 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004169
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004170 case Intrinsic::eh_dwarf_cfa: {
4171 MVT VT = getValue(I.getOperand(1)).getValueType();
4172 SDValue CfaArg;
4173 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004174 CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004175 TLI.getPointerTy(), getValue(I.getOperand(1)));
4176 else
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004177 CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004178 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004179
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004180 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004181 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004182 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004183 TLI.getPointerTy()),
4184 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004185 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004186 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004187 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004188 TLI.getPointerTy(),
4189 DAG.getConstant(0,
4190 TLI.getPointerTy())),
4191 Offset));
4192 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004193 }
4194
Mon P Wang77cdf302008-11-10 20:54:11 +00004195 case Intrinsic::convertff:
4196 case Intrinsic::convertfsi:
4197 case Intrinsic::convertfui:
4198 case Intrinsic::convertsif:
4199 case Intrinsic::convertuif:
4200 case Intrinsic::convertss:
4201 case Intrinsic::convertsu:
4202 case Intrinsic::convertus:
4203 case Intrinsic::convertuu: {
4204 ISD::CvtCode Code = ISD::CVT_INVALID;
4205 switch (Intrinsic) {
4206 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4207 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4208 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4209 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4210 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4211 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4212 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4213 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4214 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4215 }
4216 MVT DestVT = TLI.getValueType(I.getType());
4217 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004218 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004219 DAG.getValueType(DestVT),
4220 DAG.getValueType(getValue(Op1).getValueType()),
4221 getValue(I.getOperand(2)),
4222 getValue(I.getOperand(3)),
4223 Code));
4224 return 0;
4225 }
4226
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004227 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004228 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004229 getValue(I.getOperand(1)).getValueType(),
4230 getValue(I.getOperand(1))));
4231 return 0;
4232 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004233 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004234 getValue(I.getOperand(1)).getValueType(),
4235 getValue(I.getOperand(1)),
4236 getValue(I.getOperand(2))));
4237 return 0;
4238 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004239 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004240 getValue(I.getOperand(1)).getValueType(),
4241 getValue(I.getOperand(1))));
4242 return 0;
4243 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004244 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004245 getValue(I.getOperand(1)).getValueType(),
4246 getValue(I.getOperand(1))));
4247 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004248 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004249 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004250 return 0;
4251 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004252 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004253 return 0;
4254 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004255 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004256 return 0;
4257 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004258 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004259 return 0;
4260 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004261 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004262 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004263 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004264 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004265 return 0;
4266 case Intrinsic::pcmarker: {
4267 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004268 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004269 return 0;
4270 }
4271 case Intrinsic::readcyclecounter: {
4272 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004273 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004274 DAG.getVTList(MVT::i64, MVT::Other),
4275 &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004276 setValue(&I, Tmp);
4277 DAG.setRoot(Tmp.getValue(1));
4278 return 0;
4279 }
4280 case Intrinsic::part_select: {
4281 // Currently not implemented: just abort
4282 assert(0 && "part_select intrinsic not implemented");
4283 abort();
4284 }
4285 case Intrinsic::part_set: {
4286 // Currently not implemented: just abort
4287 assert(0 && "part_set intrinsic not implemented");
4288 abort();
4289 }
4290 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004291 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004292 getValue(I.getOperand(1)).getValueType(),
4293 getValue(I.getOperand(1))));
4294 return 0;
4295 case Intrinsic::cttz: {
4296 SDValue Arg = getValue(I.getOperand(1));
4297 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004298 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004299 setValue(&I, result);
4300 return 0;
4301 }
4302 case Intrinsic::ctlz: {
4303 SDValue Arg = getValue(I.getOperand(1));
4304 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004305 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004306 setValue(&I, result);
4307 return 0;
4308 }
4309 case Intrinsic::ctpop: {
4310 SDValue Arg = getValue(I.getOperand(1));
4311 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004312 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004313 setValue(&I, result);
4314 return 0;
4315 }
4316 case Intrinsic::stacksave: {
4317 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004318 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004319 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004320 setValue(&I, Tmp);
4321 DAG.setRoot(Tmp.getValue(1));
4322 return 0;
4323 }
4324 case Intrinsic::stackrestore: {
4325 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004326 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004327 return 0;
4328 }
Bill Wendling57344502008-11-18 11:01:33 +00004329 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004330 // Emit code into the DAG to store the stack guard onto the stack.
4331 MachineFunction &MF = DAG.getMachineFunction();
4332 MachineFrameInfo *MFI = MF.getFrameInfo();
4333 MVT PtrTy = TLI.getPointerTy();
4334
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004335 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4336 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004337
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004338 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004339 MFI->setStackProtectorIndex(FI);
4340
4341 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4342
4343 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004344 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Bill Wendlingb2a42982008-11-06 02:29:10 +00004345 PseudoSourceValue::getFixedStack(FI),
4346 0, true);
4347 setValue(&I, Result);
4348 DAG.setRoot(Result);
4349 return 0;
4350 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004351 case Intrinsic::var_annotation:
4352 // Discard annotate attributes
4353 return 0;
4354
4355 case Intrinsic::init_trampoline: {
4356 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4357
4358 SDValue Ops[6];
4359 Ops[0] = getRoot();
4360 Ops[1] = getValue(I.getOperand(1));
4361 Ops[2] = getValue(I.getOperand(2));
4362 Ops[3] = getValue(I.getOperand(3));
4363 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4364 Ops[5] = DAG.getSrcValue(F);
4365
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004366 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004367 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4368 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004369
4370 setValue(&I, Tmp);
4371 DAG.setRoot(Tmp.getValue(1));
4372 return 0;
4373 }
4374
4375 case Intrinsic::gcroot:
4376 if (GFI) {
4377 Value *Alloca = I.getOperand(1);
4378 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004379
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004380 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4381 GFI->addStackRoot(FI->getIndex(), TypeMap);
4382 }
4383 return 0;
4384
4385 case Intrinsic::gcread:
4386 case Intrinsic::gcwrite:
4387 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4388 return 0;
4389
4390 case Intrinsic::flt_rounds: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004391 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004392 return 0;
4393 }
4394
4395 case Intrinsic::trap: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004396 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004397 return 0;
4398 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004399
Bill Wendlingef375462008-11-21 02:38:44 +00004400 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004401 return implVisitAluOverflow(I, ISD::UADDO);
4402 case Intrinsic::sadd_with_overflow:
4403 return implVisitAluOverflow(I, ISD::SADDO);
4404 case Intrinsic::usub_with_overflow:
4405 return implVisitAluOverflow(I, ISD::USUBO);
4406 case Intrinsic::ssub_with_overflow:
4407 return implVisitAluOverflow(I, ISD::SSUBO);
4408 case Intrinsic::umul_with_overflow:
4409 return implVisitAluOverflow(I, ISD::UMULO);
4410 case Intrinsic::smul_with_overflow:
4411 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004412
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004413 case Intrinsic::prefetch: {
4414 SDValue Ops[4];
4415 Ops[0] = getRoot();
4416 Ops[1] = getValue(I.getOperand(1));
4417 Ops[2] = getValue(I.getOperand(2));
4418 Ops[3] = getValue(I.getOperand(3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004419 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004420 return 0;
4421 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004422
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004423 case Intrinsic::memory_barrier: {
4424 SDValue Ops[6];
4425 Ops[0] = getRoot();
4426 for (int x = 1; x < 6; ++x)
4427 Ops[x] = getValue(I.getOperand(x));
4428
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004429 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004430 return 0;
4431 }
4432 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004433 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004434 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004435 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004436 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4437 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004438 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004439 getValue(I.getOperand(2)),
4440 getValue(I.getOperand(3)),
4441 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004442 setValue(&I, L);
4443 DAG.setRoot(L.getValue(1));
4444 return 0;
4445 }
4446 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004447 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004448 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004449 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004450 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004451 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004452 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004453 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004454 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004455 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004456 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004457 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004458 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004459 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004460 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004461 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004462 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004463 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004464 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004465 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004466 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004467 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004468 }
4469}
4470
4471
4472void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4473 bool IsTailCall,
4474 MachineBasicBlock *LandingPad) {
4475 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4476 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4477 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4478 unsigned BeginLabel = 0, EndLabel = 0;
4479
4480 TargetLowering::ArgListTy Args;
4481 TargetLowering::ArgListEntry Entry;
4482 Args.reserve(CS.arg_size());
4483 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4484 i != e; ++i) {
4485 SDValue ArgNode = getValue(*i);
4486 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4487
4488 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004489 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4490 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4491 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4492 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4493 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4494 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004495 Entry.Alignment = CS.getParamAlignment(attrInd);
4496 Args.push_back(Entry);
4497 }
4498
4499 if (LandingPad && MMI) {
4500 // Insert a label before the invoke call to mark the try range. This can be
4501 // used to detect deletion of the invoke via the MachineModuleInfo.
4502 BeginLabel = MMI->NextLabelID();
4503 // Both PendingLoads and PendingExports must be flushed here;
4504 // this call might not return.
4505 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004506 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4507 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004508 }
4509
4510 std::pair<SDValue,SDValue> Result =
4511 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004512 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004513 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4514 CS.paramHasAttr(0, Attribute::InReg),
4515 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004516 IsTailCall && PerformTailCallOpt,
Dale Johannesen66978ee2009-01-31 02:22:37 +00004517 Callee, Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004518 if (CS.getType() != Type::VoidTy)
4519 setValue(CS.getInstruction(), Result.first);
4520 DAG.setRoot(Result.second);
4521
4522 if (LandingPad && MMI) {
4523 // Insert a label at the end of the invoke call to mark the try range. This
4524 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4525 EndLabel = MMI->NextLabelID();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004526 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4527 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004528
4529 // Inform MachineModuleInfo of range.
4530 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4531 }
4532}
4533
4534
4535void SelectionDAGLowering::visitCall(CallInst &I) {
4536 const char *RenameFn = 0;
4537 if (Function *F = I.getCalledFunction()) {
4538 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004539 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4540 if (II) {
4541 if (unsigned IID = II->getIntrinsicID(F)) {
4542 RenameFn = visitIntrinsicCall(I, IID);
4543 if (!RenameFn)
4544 return;
4545 }
4546 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004547 if (unsigned IID = F->getIntrinsicID()) {
4548 RenameFn = visitIntrinsicCall(I, IID);
4549 if (!RenameFn)
4550 return;
4551 }
4552 }
4553
4554 // Check for well-known libc/libm calls. If the function is internal, it
4555 // can't be a library call.
4556 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004557 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004558 const char *NameStr = F->getNameStart();
4559 if (NameStr[0] == 'c' &&
4560 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4561 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4562 if (I.getNumOperands() == 3 && // Basic sanity checks.
4563 I.getOperand(1)->getType()->isFloatingPoint() &&
4564 I.getType() == I.getOperand(1)->getType() &&
4565 I.getType() == I.getOperand(2)->getType()) {
4566 SDValue LHS = getValue(I.getOperand(1));
4567 SDValue RHS = getValue(I.getOperand(2));
Scott Michelfdc40a02009-02-17 22:15:04 +00004568 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004569 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004570 return;
4571 }
4572 } else if (NameStr[0] == 'f' &&
4573 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4574 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4575 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4576 if (I.getNumOperands() == 2 && // Basic sanity checks.
4577 I.getOperand(1)->getType()->isFloatingPoint() &&
4578 I.getType() == I.getOperand(1)->getType()) {
4579 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004580 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004581 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004582 return;
4583 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004584 } else if (NameStr[0] == 's' &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004585 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4586 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4587 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4588 if (I.getNumOperands() == 2 && // Basic sanity checks.
4589 I.getOperand(1)->getType()->isFloatingPoint() &&
4590 I.getType() == I.getOperand(1)->getType()) {
4591 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004592 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004593 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004594 return;
4595 }
4596 } else if (NameStr[0] == 'c' &&
4597 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4598 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4599 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4600 if (I.getNumOperands() == 2 && // Basic sanity checks.
4601 I.getOperand(1)->getType()->isFloatingPoint() &&
4602 I.getType() == I.getOperand(1)->getType()) {
4603 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004604 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004605 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004606 return;
4607 }
4608 }
4609 }
4610 } else if (isa<InlineAsm>(I.getOperand(0))) {
4611 visitInlineAsm(&I);
4612 return;
4613 }
4614
4615 SDValue Callee;
4616 if (!RenameFn)
4617 Callee = getValue(I.getOperand(0));
4618 else
Bill Wendling056292f2008-09-16 21:48:12 +00004619 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004620
4621 LowerCallTo(&I, Callee, I.isTailCall());
4622}
4623
4624
4625/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004626/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004627/// Chain/Flag as the input and updates them for the output Chain/Flag.
4628/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004629SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004630 SDValue &Chain,
4631 SDValue *Flag) const {
4632 // Assemble the legal parts into the final values.
4633 SmallVector<SDValue, 4> Values(ValueVTs.size());
4634 SmallVector<SDValue, 8> Parts;
4635 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4636 // Copy the legal parts from the registers.
4637 MVT ValueVT = ValueVTs[Value];
4638 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4639 MVT RegisterVT = RegVTs[Value];
4640
4641 Parts.resize(NumRegs);
4642 for (unsigned i = 0; i != NumRegs; ++i) {
4643 SDValue P;
4644 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004645 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004646 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004647 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004648 *Flag = P.getValue(2);
4649 }
4650 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004651
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004652 // If the source register was virtual and if we know something about it,
4653 // add an assert node.
4654 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4655 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4656 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4657 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4658 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4659 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004660
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004661 unsigned RegSize = RegisterVT.getSizeInBits();
4662 unsigned NumSignBits = LOI.NumSignBits;
4663 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004664
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004665 // FIXME: We capture more information than the dag can represent. For
4666 // now, just use the tightest assertzext/assertsext possible.
4667 bool isSExt = true;
4668 MVT FromVT(MVT::Other);
4669 if (NumSignBits == RegSize)
4670 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4671 else if (NumZeroBits >= RegSize-1)
4672 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4673 else if (NumSignBits > RegSize-8)
4674 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004675 else if (NumZeroBits >= RegSize-8)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004676 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4677 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004678 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004679 else if (NumZeroBits >= RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004680 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004681 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004682 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004683 else if (NumZeroBits >= RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004684 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004685
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004686 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004687 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004688 RegisterVT, P, DAG.getValueType(FromVT));
4689
4690 }
4691 }
4692 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004693
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004694 Parts[i] = P;
4695 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004696
Scott Michelfdc40a02009-02-17 22:15:04 +00004697 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004698 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004699 Part += NumRegs;
4700 Parts.clear();
4701 }
4702
Dale Johannesen66978ee2009-01-31 02:22:37 +00004703 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004704 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4705 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004706}
4707
4708/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004709/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004710/// Chain/Flag as the input and updates them for the output Chain/Flag.
4711/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004712void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004713 SDValue &Chain, SDValue *Flag) const {
4714 // Get the list of the values's legal parts.
4715 unsigned NumRegs = Regs.size();
4716 SmallVector<SDValue, 8> Parts(NumRegs);
4717 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4718 MVT ValueVT = ValueVTs[Value];
4719 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4720 MVT RegisterVT = RegVTs[Value];
4721
Dale Johannesen66978ee2009-01-31 02:22:37 +00004722 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004723 &Parts[Part], NumParts, RegisterVT);
4724 Part += NumParts;
4725 }
4726
4727 // Copy the parts into the registers.
4728 SmallVector<SDValue, 8> Chains(NumRegs);
4729 for (unsigned i = 0; i != NumRegs; ++i) {
4730 SDValue Part;
4731 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004732 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004733 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004734 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004735 *Flag = Part.getValue(1);
4736 }
4737 Chains[i] = Part.getValue(0);
4738 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004739
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004740 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004741 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004742 // flagged to it. That is the CopyToReg nodes and the user are considered
4743 // a single scheduling unit. If we create a TokenFactor and return it as
4744 // chain, then the TokenFactor is both a predecessor (operand) of the
4745 // user as well as a successor (the TF operands are flagged to the user).
4746 // c1, f1 = CopyToReg
4747 // c2, f2 = CopyToReg
4748 // c3 = TokenFactor c1, c2
4749 // ...
4750 // = op c3, ..., f2
4751 Chain = Chains[NumRegs-1];
4752 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00004753 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004754}
4755
4756/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004757/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004758/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004759void RegsForValue::AddInlineAsmOperands(unsigned Code,
4760 bool HasMatching,unsigned MatchingIdx,
4761 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004762 std::vector<SDValue> &Ops) const {
4763 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Evan Cheng697cbbf2009-03-20 18:03:34 +00004764 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4765 unsigned Flag = Code | (Regs.size() << 3);
4766 if (HasMatching)
4767 Flag |= 0x80000000 | (MatchingIdx << 16);
4768 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004769 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4770 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4771 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004772 for (unsigned i = 0; i != NumRegs; ++i) {
4773 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004774 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004775 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004776 }
4777}
4778
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004779/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004780/// i.e. it isn't a stack pointer or some other special register, return the
4781/// register class for the register. Otherwise, return null.
4782static const TargetRegisterClass *
4783isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4784 const TargetLowering &TLI,
4785 const TargetRegisterInfo *TRI) {
4786 MVT FoundVT = MVT::Other;
4787 const TargetRegisterClass *FoundRC = 0;
4788 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4789 E = TRI->regclass_end(); RCI != E; ++RCI) {
4790 MVT ThisVT = MVT::Other;
4791
4792 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004793 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004794 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4795 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4796 I != E; ++I) {
4797 if (TLI.isTypeLegal(*I)) {
4798 // If we have already found this register in a different register class,
4799 // choose the one with the largest VT specified. For example, on
4800 // PowerPC, we favor f64 register classes over f32.
4801 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4802 ThisVT = *I;
4803 break;
4804 }
4805 }
4806 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004807
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004808 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004809
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004810 // NOTE: This isn't ideal. In particular, this might allocate the
4811 // frame pointer in functions that need it (due to them not being taken
4812 // out of allocation, because a variable sized allocation hasn't been seen
4813 // yet). This is a slight code pessimization, but should still work.
4814 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4815 E = RC->allocation_order_end(MF); I != E; ++I)
4816 if (*I == Reg) {
4817 // We found a matching register class. Keep looking at others in case
4818 // we find one with larger registers that this physreg is also in.
4819 FoundRC = RC;
4820 FoundVT = ThisVT;
4821 break;
4822 }
4823 }
4824 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004825}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004826
4827
4828namespace llvm {
4829/// AsmOperandInfo - This contains information for each constraint that we are
4830/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004831class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004832 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004833public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004834 /// CallOperand - If this is the result output operand or a clobber
4835 /// this is null, otherwise it is the incoming operand to the CallInst.
4836 /// This gets modified as the asm is processed.
4837 SDValue CallOperand;
4838
4839 /// AssignedRegs - If this is a register or register class operand, this
4840 /// contains the set of register corresponding to the operand.
4841 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004842
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004843 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4844 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4845 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004846
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004847 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4848 /// busy in OutputRegs/InputRegs.
4849 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004850 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004851 std::set<unsigned> &InputRegs,
4852 const TargetRegisterInfo &TRI) const {
4853 if (isOutReg) {
4854 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4855 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4856 }
4857 if (isInReg) {
4858 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4859 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4860 }
4861 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004862
Chris Lattner81249c92008-10-17 17:05:25 +00004863 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4864 /// corresponds to. If there is no Value* for this operand, it returns
4865 /// MVT::Other.
4866 MVT getCallOperandValMVT(const TargetLowering &TLI,
4867 const TargetData *TD) const {
4868 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004869
Chris Lattner81249c92008-10-17 17:05:25 +00004870 if (isa<BasicBlock>(CallOperandVal))
4871 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004872
Chris Lattner81249c92008-10-17 17:05:25 +00004873 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004874
Chris Lattner81249c92008-10-17 17:05:25 +00004875 // If this is an indirect operand, the operand is a pointer to the
4876 // accessed type.
4877 if (isIndirect)
4878 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004879
Chris Lattner81249c92008-10-17 17:05:25 +00004880 // If OpTy is not a single value, it may be a struct/union that we
4881 // can tile with integers.
4882 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4883 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4884 switch (BitSize) {
4885 default: break;
4886 case 1:
4887 case 8:
4888 case 16:
4889 case 32:
4890 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004891 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004892 OpTy = IntegerType::get(BitSize);
4893 break;
4894 }
4895 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004896
Chris Lattner81249c92008-10-17 17:05:25 +00004897 return TLI.getValueType(OpTy, true);
4898 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004899
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004900private:
4901 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4902 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004903 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004904 const TargetRegisterInfo &TRI) {
4905 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4906 Regs.insert(Reg);
4907 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4908 for (; *Aliases; ++Aliases)
4909 Regs.insert(*Aliases);
4910 }
4911};
4912} // end llvm namespace.
4913
4914
4915/// GetRegistersForValue - Assign registers (virtual or physical) for the
4916/// specified operand. We prefer to assign virtual registers, to allow the
4917/// register allocator handle the assignment process. However, if the asm uses
4918/// features that we can't model on machineinstrs, we have SDISel do the
4919/// allocation. This produces generally horrible, but correct, code.
4920///
4921/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004922/// Input and OutputRegs are the set of already allocated physical registers.
4923///
4924void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004925GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004926 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004927 std::set<unsigned> &InputRegs) {
4928 // Compute whether this value requires an input register, an output register,
4929 // or both.
4930 bool isOutReg = false;
4931 bool isInReg = false;
4932 switch (OpInfo.Type) {
4933 case InlineAsm::isOutput:
4934 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004935
4936 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004937 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004938 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004939 break;
4940 case InlineAsm::isInput:
4941 isInReg = true;
4942 isOutReg = false;
4943 break;
4944 case InlineAsm::isClobber:
4945 isOutReg = true;
4946 isInReg = true;
4947 break;
4948 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004949
4950
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004951 MachineFunction &MF = DAG.getMachineFunction();
4952 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004953
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004954 // If this is a constraint for a single physreg, or a constraint for a
4955 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004956 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004957 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4958 OpInfo.ConstraintVT);
4959
4960 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004961 if (OpInfo.ConstraintVT != MVT::Other) {
4962 // If this is a FP input in an integer register (or visa versa) insert a bit
4963 // cast of the input value. More generally, handle any case where the input
4964 // value disagrees with the register class we plan to stick this in.
4965 if (OpInfo.Type == InlineAsm::isInput &&
4966 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4967 // Try to convert to the first MVT that the reg class contains. If the
4968 // types are identical size, use a bitcast to convert (e.g. two differing
4969 // vector types).
4970 MVT RegVT = *PhysReg.second->vt_begin();
4971 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004972 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004973 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004974 OpInfo.ConstraintVT = RegVT;
4975 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4976 // If the input is a FP value and we want it in FP registers, do a
4977 // bitcast to the corresponding integer type. This turns an f64 value
4978 // into i64, which can be passed with two i32 values on a 32-bit
4979 // machine.
4980 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00004981 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004982 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004983 OpInfo.ConstraintVT = RegVT;
4984 }
4985 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004986
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004987 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004988 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004989
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004990 MVT RegVT;
4991 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004992
4993 // If this is a constraint for a specific physical register, like {r17},
4994 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004995 if (unsigned AssignedReg = PhysReg.first) {
4996 const TargetRegisterClass *RC = PhysReg.second;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004997 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004998 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004999
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005000 // Get the actual register value type. This is important, because the user
5001 // may have asked for (e.g.) the AX register in i32 type. We need to
5002 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005003 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005004
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005005 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005006 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005007
5008 // If this is an expanded reference, add the rest of the regs to Regs.
5009 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005010 TargetRegisterClass::iterator I = RC->begin();
5011 for (; *I != AssignedReg; ++I)
5012 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005013
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005014 // Already added the first reg.
5015 --NumRegs; ++I;
5016 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005017 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005018 Regs.push_back(*I);
5019 }
5020 }
5021 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5022 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5023 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5024 return;
5025 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005026
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005027 // Otherwise, if this was a reference to an LLVM register class, create vregs
5028 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005029 if (const TargetRegisterClass *RC = PhysReg.second) {
5030 RegVT = *RC->vt_begin();
Evan Chengfb112882009-03-23 08:01:15 +00005031 if (OpInfo.ConstraintVT == MVT::Other)
5032 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005033
Evan Chengfb112882009-03-23 08:01:15 +00005034 // Create the appropriate number of virtual registers.
5035 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5036 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005037 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005038
Evan Chengfb112882009-03-23 08:01:15 +00005039 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5040 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005041 }
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005042
5043 // This is a reference to a register class that doesn't directly correspond
5044 // to an LLVM register class. Allocate NumRegs consecutive, available,
5045 // registers from the class.
5046 std::vector<unsigned> RegClassRegs
5047 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5048 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005049
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005050 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5051 unsigned NumAllocated = 0;
5052 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5053 unsigned Reg = RegClassRegs[i];
5054 // See if this register is available.
5055 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5056 (isInReg && InputRegs.count(Reg))) { // Already used.
5057 // Make sure we find consecutive registers.
5058 NumAllocated = 0;
5059 continue;
5060 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005061
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005062 // Check to see if this register is allocatable (i.e. don't give out the
5063 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005064 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5065 if (!RC) { // Couldn't allocate this register.
5066 // Reset NumAllocated to make sure we return consecutive registers.
5067 NumAllocated = 0;
5068 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005069 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005070
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005071 // Okay, this register is good, we can use it.
5072 ++NumAllocated;
5073
5074 // If we allocated enough consecutive registers, succeed.
5075 if (NumAllocated == NumRegs) {
5076 unsigned RegStart = (i-NumAllocated)+1;
5077 unsigned RegEnd = i+1;
5078 // Mark all of the allocated registers used.
5079 for (unsigned i = RegStart; i != RegEnd; ++i)
5080 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005081
5082 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005083 OpInfo.ConstraintVT);
5084 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5085 return;
5086 }
5087 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005088
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005089 // Otherwise, we couldn't allocate enough registers for this.
5090}
5091
Evan Chengda43bcf2008-09-24 00:05:32 +00005092/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5093/// processed uses a memory 'm' constraint.
5094static bool
5095hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005096 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005097 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5098 InlineAsm::ConstraintInfo &CI = CInfos[i];
5099 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5100 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5101 if (CType == TargetLowering::C_Memory)
5102 return true;
5103 }
5104 }
5105
5106 return false;
5107}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005108
5109/// visitInlineAsm - Handle a call to an InlineAsm object.
5110///
5111void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5112 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5113
5114 /// ConstraintOperands - Information about all of the constraints.
5115 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005116
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005117 // We won't need to flush pending loads if this asm doesn't touch
5118 // memory and is nonvolatile.
5119 SDValue Chain = IA->hasSideEffects() ? getRoot() : DAG.getRoot();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005120 SDValue Flag;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005121
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005122 std::set<unsigned> OutputRegs, InputRegs;
5123
5124 // Do a prepass over the constraints, canonicalizing them, and building up the
5125 // ConstraintOperands list.
5126 std::vector<InlineAsm::ConstraintInfo>
5127 ConstraintInfos = IA->ParseConstraints();
5128
Evan Chengda43bcf2008-09-24 00:05:32 +00005129 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005130 // Flush pending loads if this touches memory (includes clobbering it).
5131 // It's possible this is overly conservative.
5132 if (hasMemory)
5133 Chain = getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005134
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005135 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5136 unsigned ResNo = 0; // ResNo - The result number of the next output.
5137 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5138 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5139 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005140
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005141 MVT OpVT = MVT::Other;
5142
5143 // Compute the value type for each operand.
5144 switch (OpInfo.Type) {
5145 case InlineAsm::isOutput:
5146 // Indirect outputs just consume an argument.
5147 if (OpInfo.isIndirect) {
5148 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5149 break;
5150 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005151
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005152 // The return value of the call is this value. As such, there is no
5153 // corresponding argument.
5154 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5155 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5156 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5157 } else {
5158 assert(ResNo == 0 && "Asm only has one result!");
5159 OpVT = TLI.getValueType(CS.getType());
5160 }
5161 ++ResNo;
5162 break;
5163 case InlineAsm::isInput:
5164 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5165 break;
5166 case InlineAsm::isClobber:
5167 // Nothing to do.
5168 break;
5169 }
5170
5171 // If this is an input or an indirect output, process the call argument.
5172 // BasicBlocks are labels, currently appearing only in asm's.
5173 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00005174 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005175 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005176 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005177 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005178 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005179
Chris Lattner81249c92008-10-17 17:05:25 +00005180 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005181 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005182
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005183 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005184 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005185
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005186 // Second pass over the constraints: compute which constraint option to use
5187 // and assign registers to constraints that want a specific physreg.
5188 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5189 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005190
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005191 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005192 // matching input. If their types mismatch, e.g. one is an integer, the
5193 // other is floating point, or their sizes are different, flag it as an
5194 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005195 if (OpInfo.hasMatchingInput()) {
5196 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5197 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005198 if ((OpInfo.ConstraintVT.isInteger() !=
5199 Input.ConstraintVT.isInteger()) ||
5200 (OpInfo.ConstraintVT.getSizeInBits() !=
5201 Input.ConstraintVT.getSizeInBits())) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005202 cerr << "llvm: error: Unsupported asm: input constraint with a "
5203 << "matching output constraint of incompatible type!\n";
Evan Cheng09dc9c02008-12-16 18:21:39 +00005204 exit(1);
5205 }
5206 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005207 }
5208 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005209
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005210 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005211 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005212
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005213 // If this is a memory input, and if the operand is not indirect, do what we
5214 // need to to provide an address for the memory input.
5215 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5216 !OpInfo.isIndirect) {
5217 assert(OpInfo.Type == InlineAsm::isInput &&
5218 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005219
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005220 // Memory operands really want the address of the value. If we don't have
5221 // an indirect input, put it in the constpool if we can, otherwise spill
5222 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005223
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005224 // If the operand is a float, integer, or vector constant, spill to a
5225 // constant pool entry to get its address.
5226 Value *OpVal = OpInfo.CallOperandVal;
5227 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5228 isa<ConstantVector>(OpVal)) {
5229 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5230 TLI.getPointerTy());
5231 } else {
5232 // Otherwise, create a stack slot and emit a store to it before the
5233 // asm.
5234 const Type *Ty = OpVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005235 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005236 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5237 MachineFunction &MF = DAG.getMachineFunction();
5238 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5239 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005240 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005241 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005242 OpInfo.CallOperand = StackSlot;
5243 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005244
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005245 // There is no longer a Value* corresponding to this operand.
5246 OpInfo.CallOperandVal = 0;
5247 // It is now an indirect operand.
5248 OpInfo.isIndirect = true;
5249 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005250
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005251 // If this constraint is for a specific register, allocate it before
5252 // anything else.
5253 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005254 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005255 }
5256 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005257
5258
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005259 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005260 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005261 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5262 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005263
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005264 // C_Register operands have already been allocated, Other/Memory don't need
5265 // to be.
5266 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005267 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005268 }
5269
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005270 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5271 std::vector<SDValue> AsmNodeOperands;
5272 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5273 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00005274 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005275
5276
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005277 // Loop over all of the inputs, copying the operand values into the
5278 // appropriate registers and processing the output regs.
5279 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005280
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005281 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5282 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005283
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005284 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5285 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5286
5287 switch (OpInfo.Type) {
5288 case InlineAsm::isOutput: {
5289 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5290 OpInfo.ConstraintType != TargetLowering::C_Register) {
5291 // Memory output, or 'other' output (e.g. 'X' constraint).
5292 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5293
5294 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005295 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5296 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005297 TLI.getPointerTy()));
5298 AsmNodeOperands.push_back(OpInfo.CallOperand);
5299 break;
5300 }
5301
5302 // Otherwise, this is a register or register class output.
5303
5304 // Copy the output from the appropriate register. Find a register that
5305 // we can use.
5306 if (OpInfo.AssignedRegs.Regs.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005307 cerr << "llvm: error: Couldn't allocate output reg for constraint '"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005308 << OpInfo.ConstraintCode << "'!\n";
5309 exit(1);
5310 }
5311
5312 // If this is an indirect operand, store through the pointer after the
5313 // asm.
5314 if (OpInfo.isIndirect) {
5315 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5316 OpInfo.CallOperandVal));
5317 } else {
5318 // This is the result value of the call.
5319 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5320 // Concatenate this output onto the outputs list.
5321 RetValRegs.append(OpInfo.AssignedRegs);
5322 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005323
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005324 // Add information to the INLINEASM node to know that this register is
5325 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005326 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5327 6 /* EARLYCLOBBER REGDEF */ :
5328 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005329 false,
5330 0,
Dale Johannesen913d3df2008-09-12 17:49:03 +00005331 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005332 break;
5333 }
5334 case InlineAsm::isInput: {
5335 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005336
Chris Lattner6bdcda32008-10-17 16:47:46 +00005337 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005338 // If this is required to match an output register we have already set,
5339 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005340 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005341
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005342 // Scan until we find the definition we already emitted of this operand.
5343 // When we find it, create a RegsForValue operand.
5344 unsigned CurOp = 2; // The first operand.
5345 for (; OperandNo; --OperandNo) {
5346 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005347 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005348 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005349 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5350 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5351 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005352 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005353 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005354 }
5355
Evan Cheng697cbbf2009-03-20 18:03:34 +00005356 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005357 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005358 if ((OpFlag & 7) == 2 /*REGDEF*/
5359 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5360 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005361 RegsForValue MatchedRegs;
5362 MatchedRegs.TLI = &TLI;
5363 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Evan Chengfb112882009-03-23 08:01:15 +00005364 MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5365 MatchedRegs.RegVTs.push_back(RegVT);
5366 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005367 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005368 i != e; ++i)
5369 MatchedRegs.Regs.
5370 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005371
5372 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005373 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5374 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005375 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5376 true, OpInfo.getMatchedOperand(),
Evan Cheng697cbbf2009-03-20 18:03:34 +00005377 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005378 break;
5379 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005380 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5381 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5382 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005383 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005384 // See InlineAsm.h isUseOperandTiedToDef.
5385 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005386 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005387 TLI.getPointerTy()));
5388 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5389 break;
5390 }
5391 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005392
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005393 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005394 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005395 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005396
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005397 std::vector<SDValue> Ops;
5398 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005399 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005400 if (Ops.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005401 cerr << "llvm: error: Invalid operand for inline asm constraint '"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005402 << OpInfo.ConstraintCode << "'!\n";
5403 exit(1);
5404 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005405
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005406 // Add information to the INLINEASM node to know about this input.
5407 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005408 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005409 TLI.getPointerTy()));
5410 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5411 break;
5412 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5413 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5414 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5415 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005416
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005417 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005418 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5419 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005420 TLI.getPointerTy()));
5421 AsmNodeOperands.push_back(InOperandVal);
5422 break;
5423 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005424
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005425 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5426 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5427 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005428 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005429 "Don't know how to handle indirect register inputs yet!");
5430
5431 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005432 if (OpInfo.AssignedRegs.Regs.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005433 cerr << "llvm: error: Couldn't allocate output reg for constraint '"
Evan Chengaa765b82008-09-25 00:14:04 +00005434 << OpInfo.ConstraintCode << "'!\n";
5435 exit(1);
5436 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005437
Dale Johannesen66978ee2009-01-31 02:22:37 +00005438 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5439 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005440
Evan Cheng697cbbf2009-03-20 18:03:34 +00005441 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Dale Johannesen86b49f82008-09-24 01:07:17 +00005442 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005443 break;
5444 }
5445 case InlineAsm::isClobber: {
5446 // Add the clobbered value to the operand list, so that the register
5447 // allocator is aware that the physreg got clobbered.
5448 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005449 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Evan Cheng697cbbf2009-03-20 18:03:34 +00005450 false, 0, DAG,AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005451 break;
5452 }
5453 }
5454 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005455
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005456 // Finish up input operands.
5457 AsmNodeOperands[0] = Chain;
5458 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005459
Dale Johannesen66978ee2009-01-31 02:22:37 +00005460 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00005461 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005462 &AsmNodeOperands[0], AsmNodeOperands.size());
5463 Flag = Chain.getValue(1);
5464
5465 // If this asm returns a register value, copy the result from that register
5466 // and set it as the value of the call.
5467 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005468 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005469 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005470
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005471 // FIXME: Why don't we do this for inline asms with MRVs?
5472 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5473 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005474
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005475 // If any of the results of the inline asm is a vector, it may have the
5476 // wrong width/num elts. This can happen for register classes that can
5477 // contain multiple different value types. The preg or vreg allocated may
5478 // not have the same VT as was expected. Convert it to the right type
5479 // with bit_convert.
5480 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005481 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005482 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005483
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005484 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005485 ResultType.isInteger() && Val.getValueType().isInteger()) {
5486 // If a result value was tied to an input value, the computed result may
5487 // have a wider width than the expected result. Extract the relevant
5488 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005489 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005490 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005491
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005492 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005493 }
Dan Gohman95915732008-10-18 01:03:45 +00005494
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005495 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005496 // Don't need to use this as a chain in this case.
5497 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5498 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005499 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005500
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005501 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005502
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005503 // Process indirect outputs, first output all of the flagged copies out of
5504 // physregs.
5505 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5506 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5507 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005508 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5509 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005510 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5511 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005512
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005513 // Emit the non-flagged stores from the physregs.
5514 SmallVector<SDValue, 8> OutChains;
5515 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005516 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005517 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005518 getValue(StoresToEmit[i].second),
5519 StoresToEmit[i].second, 0));
5520 if (!OutChains.empty())
Dale Johannesen66978ee2009-01-31 02:22:37 +00005521 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005522 &OutChains[0], OutChains.size());
5523 DAG.setRoot(Chain);
5524}
5525
5526
5527void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5528 SDValue Src = getValue(I.getOperand(0));
5529
Chris Lattner0b18e592009-03-17 19:36:00 +00005530 // Scale up by the type size in the original i32 type width. Various
5531 // mid-level optimizers may make assumptions about demanded bits etc from the
5532 // i32-ness of the optimizer: we do not want to promote to i64 and then
5533 // multiply on 64-bit targets.
5534 // FIXME: Malloc inst should go away: PR715.
5535 uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
5536 if (ElementSize != 1)
5537 Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5538 Src, DAG.getConstant(ElementSize, Src.getValueType()));
5539
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005540 MVT IntPtr = TLI.getPointerTy();
5541
5542 if (IntPtr.bitsLT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005543 Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005544 else if (IntPtr.bitsGT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005545 Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005546
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005547 TargetLowering::ArgListTy Args;
5548 TargetLowering::ArgListEntry Entry;
5549 Entry.Node = Src;
5550 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5551 Args.push_back(Entry);
5552
5553 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005554 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005555 CallingConv::C, PerformTailCallOpt,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005556 DAG.getExternalSymbol("malloc", IntPtr),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005557 Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005558 setValue(&I, Result.first); // Pointers always fit in registers
5559 DAG.setRoot(Result.second);
5560}
5561
5562void SelectionDAGLowering::visitFree(FreeInst &I) {
5563 TargetLowering::ArgListTy Args;
5564 TargetLowering::ArgListEntry Entry;
5565 Entry.Node = getValue(I.getOperand(0));
5566 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5567 Args.push_back(Entry);
5568 MVT IntPtr = TLI.getPointerTy();
5569 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005570 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005571 CallingConv::C, PerformTailCallOpt,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005572 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
Dale Johannesen66978ee2009-01-31 02:22:37 +00005573 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005574 DAG.setRoot(Result.second);
5575}
5576
5577void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005578 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005579 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005580 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005581 DAG.getSrcValue(I.getOperand(1))));
5582}
5583
5584void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005585 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5586 getRoot(), getValue(I.getOperand(0)),
5587 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005588 setValue(&I, V);
5589 DAG.setRoot(V.getValue(1));
5590}
5591
5592void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005593 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005594 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005595 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005596 DAG.getSrcValue(I.getOperand(1))));
5597}
5598
5599void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005600 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005601 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005602 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005603 getValue(I.getOperand(2)),
5604 DAG.getSrcValue(I.getOperand(1)),
5605 DAG.getSrcValue(I.getOperand(2))));
5606}
5607
5608/// TargetLowering::LowerArguments - This is the default LowerArguments
5609/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005610/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005611/// integrated into SDISel.
5612void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005613 SmallVectorImpl<SDValue> &ArgValues,
5614 DebugLoc dl) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005615 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5616 SmallVector<SDValue, 3+16> Ops;
5617 Ops.push_back(DAG.getRoot());
5618 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5619 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5620
5621 // Add one result value for each formal argument.
5622 SmallVector<MVT, 16> RetVals;
5623 unsigned j = 1;
5624 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5625 I != E; ++I, ++j) {
5626 SmallVector<MVT, 4> ValueVTs;
5627 ComputeValueVTs(*this, I->getType(), ValueVTs);
5628 for (unsigned Value = 0, NumValues = ValueVTs.size();
5629 Value != NumValues; ++Value) {
5630 MVT VT = ValueVTs[Value];
5631 const Type *ArgTy = VT.getTypeForMVT();
5632 ISD::ArgFlagsTy Flags;
5633 unsigned OriginalAlignment =
5634 getTargetData()->getABITypeAlignment(ArgTy);
5635
Devang Patel05988662008-09-25 21:00:45 +00005636 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005637 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005638 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005639 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005640 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005641 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005642 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005643 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005644 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005645 Flags.setByVal();
5646 const PointerType *Ty = cast<PointerType>(I->getType());
5647 const Type *ElementTy = Ty->getElementType();
5648 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005649 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005650 // For ByVal, alignment should be passed from FE. BE will guess if
5651 // this info is not there but there are cases it cannot get right.
5652 if (F.getParamAlignment(j))
5653 FrameAlign = F.getParamAlignment(j);
5654 Flags.setByValAlign(FrameAlign);
5655 Flags.setByValSize(FrameSize);
5656 }
Devang Patel05988662008-09-25 21:00:45 +00005657 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005658 Flags.setNest();
5659 Flags.setOrigAlign(OriginalAlignment);
5660
5661 MVT RegisterVT = getRegisterType(VT);
5662 unsigned NumRegs = getNumRegisters(VT);
5663 for (unsigned i = 0; i != NumRegs; ++i) {
5664 RetVals.push_back(RegisterVT);
5665 ISD::ArgFlagsTy MyFlags = Flags;
5666 if (NumRegs > 1 && i == 0)
5667 MyFlags.setSplit();
5668 // if it isn't first piece, alignment must be 1
5669 else if (i > 0)
5670 MyFlags.setOrigAlign(1);
5671 Ops.push_back(DAG.getArgFlags(MyFlags));
5672 }
5673 }
5674 }
5675
5676 RetVals.push_back(MVT::Other);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005677
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005678 // Create the node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005679 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005680 DAG.getVTList(&RetVals[0], RetVals.size()),
5681 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005682
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005683 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5684 // allows exposing the loads that may be part of the argument access to the
5685 // first DAGCombiner pass.
5686 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005687
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005688 // The number of results should match up, except that the lowered one may have
5689 // an extra flag result.
5690 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5691 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5692 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5693 && "Lowering produced unexpected number of results!");
5694
5695 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5696 if (Result != TmpRes.getNode() && Result->use_empty()) {
5697 HandleSDNode Dummy(DAG.getRoot());
5698 DAG.RemoveDeadNode(Result);
5699 }
5700
5701 Result = TmpRes.getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005702
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005703 unsigned NumArgRegs = Result->getNumValues() - 1;
5704 DAG.setRoot(SDValue(Result, NumArgRegs));
5705
5706 // Set up the return result vector.
5707 unsigned i = 0;
5708 unsigned Idx = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005709 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005710 ++I, ++Idx) {
5711 SmallVector<MVT, 4> ValueVTs;
5712 ComputeValueVTs(*this, I->getType(), ValueVTs);
5713 for (unsigned Value = 0, NumValues = ValueVTs.size();
5714 Value != NumValues; ++Value) {
5715 MVT VT = ValueVTs[Value];
5716 MVT PartVT = getRegisterType(VT);
5717
5718 unsigned NumParts = getNumRegisters(VT);
5719 SmallVector<SDValue, 4> Parts(NumParts);
5720 for (unsigned j = 0; j != NumParts; ++j)
5721 Parts[j] = SDValue(Result, i++);
5722
5723 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005724 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005725 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005726 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005727 AssertOp = ISD::AssertZext;
5728
Dale Johannesen66978ee2009-01-31 02:22:37 +00005729 ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5730 PartVT, VT, AssertOp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005731 }
5732 }
5733 assert(i == NumArgRegs && "Argument register count mismatch!");
5734}
5735
5736
5737/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5738/// implementation, which just inserts an ISD::CALL node, which is later custom
5739/// lowered by the target to something concrete. FIXME: When all targets are
5740/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5741std::pair<SDValue, SDValue>
5742TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5743 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005744 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005745 unsigned CallingConv, bool isTailCall,
5746 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005747 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005748 assert((!isTailCall || PerformTailCallOpt) &&
5749 "isTailCall set when tail-call optimizations are disabled!");
5750
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005751 SmallVector<SDValue, 32> Ops;
5752 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005753 Ops.push_back(Callee);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005754
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005755 // Handle all of the outgoing arguments.
5756 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5757 SmallVector<MVT, 4> ValueVTs;
5758 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5759 for (unsigned Value = 0, NumValues = ValueVTs.size();
5760 Value != NumValues; ++Value) {
5761 MVT VT = ValueVTs[Value];
5762 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005763 SDValue Op = SDValue(Args[i].Node.getNode(),
5764 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005765 ISD::ArgFlagsTy Flags;
5766 unsigned OriginalAlignment =
5767 getTargetData()->getABITypeAlignment(ArgTy);
5768
5769 if (Args[i].isZExt)
5770 Flags.setZExt();
5771 if (Args[i].isSExt)
5772 Flags.setSExt();
5773 if (Args[i].isInReg)
5774 Flags.setInReg();
5775 if (Args[i].isSRet)
5776 Flags.setSRet();
5777 if (Args[i].isByVal) {
5778 Flags.setByVal();
5779 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5780 const Type *ElementTy = Ty->getElementType();
5781 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005782 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005783 // For ByVal, alignment should come from FE. BE will guess if this
5784 // info is not there but there are cases it cannot get right.
5785 if (Args[i].Alignment)
5786 FrameAlign = Args[i].Alignment;
5787 Flags.setByValAlign(FrameAlign);
5788 Flags.setByValSize(FrameSize);
5789 }
5790 if (Args[i].isNest)
5791 Flags.setNest();
5792 Flags.setOrigAlign(OriginalAlignment);
5793
5794 MVT PartVT = getRegisterType(VT);
5795 unsigned NumParts = getNumRegisters(VT);
5796 SmallVector<SDValue, 4> Parts(NumParts);
5797 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5798
5799 if (Args[i].isSExt)
5800 ExtendKind = ISD::SIGN_EXTEND;
5801 else if (Args[i].isZExt)
5802 ExtendKind = ISD::ZERO_EXTEND;
5803
Dale Johannesen66978ee2009-01-31 02:22:37 +00005804 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005805
5806 for (unsigned i = 0; i != NumParts; ++i) {
5807 // if it isn't first piece, alignment must be 1
5808 ISD::ArgFlagsTy MyFlags = Flags;
5809 if (NumParts > 1 && i == 0)
5810 MyFlags.setSplit();
5811 else if (i != 0)
5812 MyFlags.setOrigAlign(1);
5813
5814 Ops.push_back(Parts[i]);
5815 Ops.push_back(DAG.getArgFlags(MyFlags));
5816 }
5817 }
5818 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005819
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005820 // Figure out the result value types. We start by making a list of
5821 // the potentially illegal return value types.
5822 SmallVector<MVT, 4> LoweredRetTys;
5823 SmallVector<MVT, 4> RetTys;
5824 ComputeValueVTs(*this, RetTy, RetTys);
5825
5826 // Then we translate that to a list of legal types.
5827 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5828 MVT VT = RetTys[I];
5829 MVT RegisterVT = getRegisterType(VT);
5830 unsigned NumRegs = getNumRegisters(VT);
5831 for (unsigned i = 0; i != NumRegs; ++i)
5832 LoweredRetTys.push_back(RegisterVT);
5833 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005834
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005835 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005836
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005837 // Create the CALL node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005838 SDValue Res = DAG.getCall(CallingConv, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005839 isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005840 DAG.getVTList(&LoweredRetTys[0],
5841 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005842 &Ops[0], Ops.size()
5843 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005844 Chain = Res.getValue(LoweredRetTys.size() - 1);
5845
5846 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005847 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005848 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5849
5850 if (RetSExt)
5851 AssertOp = ISD::AssertSext;
5852 else if (RetZExt)
5853 AssertOp = ISD::AssertZext;
5854
5855 SmallVector<SDValue, 4> ReturnValues;
5856 unsigned RegNo = 0;
5857 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5858 MVT VT = RetTys[I];
5859 MVT RegisterVT = getRegisterType(VT);
5860 unsigned NumRegs = getNumRegisters(VT);
5861 unsigned RegNoEnd = NumRegs + RegNo;
5862 SmallVector<SDValue, 4> Results;
5863 for (; RegNo != RegNoEnd; ++RegNo)
5864 Results.push_back(Res.getValue(RegNo));
5865 SDValue ReturnValue =
Dale Johannesen66978ee2009-01-31 02:22:37 +00005866 getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005867 AssertOp);
5868 ReturnValues.push_back(ReturnValue);
5869 }
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005870 Res = DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00005871 DAG.getVTList(&RetTys[0], RetTys.size()),
5872 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005873 }
5874
5875 return std::make_pair(Res, Chain);
5876}
5877
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005878void TargetLowering::LowerOperationWrapper(SDNode *N,
5879 SmallVectorImpl<SDValue> &Results,
5880 SelectionDAG &DAG) {
5881 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005882 if (Res.getNode())
5883 Results.push_back(Res);
5884}
5885
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005886SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5887 assert(0 && "LowerOperation not implemented for this target!");
5888 abort();
5889 return SDValue();
5890}
5891
5892
5893void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5894 SDValue Op = getValue(V);
5895 assert((Op.getOpcode() != ISD::CopyFromReg ||
5896 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5897 "Copy from a reg to the same reg!");
5898 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5899
5900 RegsForValue RFV(TLI, Reg, V->getType());
5901 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005902 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005903 PendingExports.push_back(Chain);
5904}
5905
5906#include "llvm/CodeGen/SelectionDAGISel.h"
5907
5908void SelectionDAGISel::
5909LowerArguments(BasicBlock *LLVMBB) {
5910 // If this is the entry block, emit arguments.
5911 Function &F = *LLVMBB->getParent();
5912 SDValue OldRoot = SDL->DAG.getRoot();
5913 SmallVector<SDValue, 16> Args;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005914 TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005915
5916 unsigned a = 0;
5917 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5918 AI != E; ++AI) {
5919 SmallVector<MVT, 4> ValueVTs;
5920 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5921 unsigned NumValues = ValueVTs.size();
5922 if (!AI->use_empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005923 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
Dale Johannesen4be0bdf2009-02-05 00:20:09 +00005924 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005925 // If this argument is live outside of the entry block, insert a copy from
5926 // whereever we got it to the vreg that other BB's will reference it as.
5927 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5928 if (VMI != FuncInfo->ValueMap.end()) {
5929 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5930 }
5931 }
5932 a += NumValues;
5933 }
5934
5935 // Finally, if the target has anything special to do, allow it to do so.
5936 // FIXME: this should insert code into the DAG!
5937 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5938}
5939
5940/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5941/// ensure constants are generated when needed. Remember the virtual registers
5942/// that need to be added to the Machine PHI nodes as input. We cannot just
5943/// directly add them, because expansion might result in multiple MBB's for one
5944/// BB. As such, the start of the BB might correspond to a different MBB than
5945/// the end.
5946///
5947void
5948SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5949 TerminatorInst *TI = LLVMBB->getTerminator();
5950
5951 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5952
5953 // Check successor nodes' PHI nodes that expect a constant to be available
5954 // from this block.
5955 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5956 BasicBlock *SuccBB = TI->getSuccessor(succ);
5957 if (!isa<PHINode>(SuccBB->begin())) continue;
5958 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005959
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005960 // If this terminator has multiple identical successors (common for
5961 // switches), only handle each succ once.
5962 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005963
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005964 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5965 PHINode *PN;
5966
5967 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5968 // nodes and Machine PHI nodes, but the incoming operands have not been
5969 // emitted yet.
5970 for (BasicBlock::iterator I = SuccBB->begin();
5971 (PN = dyn_cast<PHINode>(I)); ++I) {
5972 // Ignore dead phi's.
5973 if (PN->use_empty()) continue;
5974
5975 unsigned Reg;
5976 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5977
5978 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5979 unsigned &RegOut = SDL->ConstantsOut[C];
5980 if (RegOut == 0) {
5981 RegOut = FuncInfo->CreateRegForValue(C);
5982 SDL->CopyValueToVirtualRegister(C, RegOut);
5983 }
5984 Reg = RegOut;
5985 } else {
5986 Reg = FuncInfo->ValueMap[PHIOp];
5987 if (Reg == 0) {
5988 assert(isa<AllocaInst>(PHIOp) &&
5989 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5990 "Didn't codegen value into a register!??");
5991 Reg = FuncInfo->CreateRegForValue(PHIOp);
5992 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5993 }
5994 }
5995
5996 // Remember that this register needs to added to the machine PHI node as
5997 // the input for this MBB.
5998 SmallVector<MVT, 4> ValueVTs;
5999 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6000 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6001 MVT VT = ValueVTs[vti];
6002 unsigned NumRegisters = TLI.getNumRegisters(VT);
6003 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6004 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6005 Reg += NumRegisters;
6006 }
6007 }
6008 }
6009 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006010}
6011
Dan Gohman3df24e62008-09-03 23:12:08 +00006012/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6013/// supports legal types, and it emits MachineInstrs directly instead of
6014/// creating SelectionDAG nodes.
6015///
6016bool
6017SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6018 FastISel *F) {
6019 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006020
Dan Gohman3df24e62008-09-03 23:12:08 +00006021 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6022 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
6023
6024 // Check successor nodes' PHI nodes that expect a constant to be available
6025 // from this block.
6026 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6027 BasicBlock *SuccBB = TI->getSuccessor(succ);
6028 if (!isa<PHINode>(SuccBB->begin())) continue;
6029 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006030
Dan Gohman3df24e62008-09-03 23:12:08 +00006031 // If this terminator has multiple identical successors (common for
6032 // switches), only handle each succ once.
6033 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006034
Dan Gohman3df24e62008-09-03 23:12:08 +00006035 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6036 PHINode *PN;
6037
6038 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6039 // nodes and Machine PHI nodes, but the incoming operands have not been
6040 // emitted yet.
6041 for (BasicBlock::iterator I = SuccBB->begin();
6042 (PN = dyn_cast<PHINode>(I)); ++I) {
6043 // Ignore dead phi's.
6044 if (PN->use_empty()) continue;
6045
6046 // Only handle legal types. Two interesting things to note here. First,
6047 // by bailing out early, we may leave behind some dead instructions,
6048 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6049 // own moves. Second, this check is necessary becuase FastISel doesn't
6050 // use CreateRegForValue to create registers, so it always creates
6051 // exactly one register for each non-void instruction.
6052 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6053 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00006054 // Promote MVT::i1.
6055 if (VT == MVT::i1)
6056 VT = TLI.getTypeToTransformTo(VT);
6057 else {
6058 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6059 return false;
6060 }
Dan Gohman3df24e62008-09-03 23:12:08 +00006061 }
6062
6063 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6064
6065 unsigned Reg = F->getRegForValue(PHIOp);
6066 if (Reg == 0) {
6067 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6068 return false;
6069 }
6070 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
6071 }
6072 }
6073
6074 return true;
6075}