blob: 7690220ddb3bb154d0878d6823598bea5a8db77b [file] [log] [blame]
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001//===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "SelectionDAGBuild.h"
16#include "llvm/ADT/BitVector.h"
Dan Gohman5b229802008-09-04 20:49:27 +000017#include "llvm/ADT/SmallSet.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000018#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Constants.h"
20#include "llvm/CallingConv.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/InlineAsm.h"
25#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/IntrinsicInst.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000028#include "llvm/Module.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000029#include "llvm/CodeGen/FastISel.h"
30#include "llvm/CodeGen/GCStrategy.h"
31#include "llvm/CodeGen/GCMetadata.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineFrameInfo.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000038#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000039#include "llvm/CodeGen/SelectionDAG.h"
Devang Patel83489bb2009-01-13 00:35:13 +000040#include "llvm/CodeGen/DwarfWriter.h"
41#include "llvm/Analysis/DebugInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000042#include "llvm/Target/TargetRegisterInfo.h"
43#include "llvm/Target/TargetData.h"
44#include "llvm/Target/TargetFrameInfo.h"
45#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesen49de9822009-02-05 01:49:45 +000046#include "llvm/Target/TargetIntrinsicInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000047#include "llvm/Target/TargetLowering.h"
48#include "llvm/Target/TargetMachine.h"
49#include "llvm/Target/TargetOptions.h"
50#include "llvm/Support/Compiler.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000051#include "llvm/Support/CommandLine.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000052#include "llvm/Support/Debug.h"
53#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000054#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000055#include <algorithm>
56using namespace llvm;
57
Dale Johannesen601d3c02008-09-05 01:48:15 +000058/// LimitFloatPrecision - Generate low-precision inline sequences for
59/// some float libcalls (6, 8 or 12 bits).
60static unsigned LimitFloatPrecision;
61
62static cl::opt<unsigned, true>
63LimitFPPrecision("limit-float-precision",
64 cl::desc("Generate low-precision inline sequences "
65 "for some float libcalls"),
66 cl::location(LimitFloatPrecision),
67 cl::init(0));
68
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000069/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
Dan Gohman2c91d102009-01-06 22:53:52 +000070/// of insertvalue or extractvalue indices that identify a member, return
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000071/// the linearized index of the start of the member.
72///
73static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
74 const unsigned *Indices,
75 const unsigned *IndicesEnd,
76 unsigned CurIndex = 0) {
77 // Base case: We're done.
78 if (Indices && Indices == IndicesEnd)
79 return CurIndex;
80
81 // Given a struct type, recursively traverse the elements.
82 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
83 for (StructType::element_iterator EB = STy->element_begin(),
84 EI = EB,
85 EE = STy->element_end();
86 EI != EE; ++EI) {
87 if (Indices && *Indices == unsigned(EI - EB))
88 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
89 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
90 }
Dan Gohman2c91d102009-01-06 22:53:52 +000091 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000092 }
93 // Given an array type, recursively traverse the elements.
94 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
95 const Type *EltTy = ATy->getElementType();
96 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
97 if (Indices && *Indices == i)
98 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
99 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
100 }
Dan Gohman2c91d102009-01-06 22:53:52 +0000101 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000102 }
103 // We haven't found the type we're looking for, so keep searching.
104 return CurIndex + 1;
105}
106
107/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
108/// MVTs that represent all the individual underlying
109/// non-aggregate types that comprise it.
110///
111/// If Offsets is non-null, it points to a vector to be filled in
112/// with the in-memory offsets of each of the individual values.
113///
114static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
115 SmallVectorImpl<MVT> &ValueVTs,
116 SmallVectorImpl<uint64_t> *Offsets = 0,
117 uint64_t StartingOffset = 0) {
118 // Given a struct type, recursively traverse the elements.
119 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
120 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
121 for (StructType::element_iterator EB = STy->element_begin(),
122 EI = EB,
123 EE = STy->element_end();
124 EI != EE; ++EI)
125 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
126 StartingOffset + SL->getElementOffset(EI - EB));
127 return;
128 }
129 // Given an array type, recursively traverse the elements.
130 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
131 const Type *EltTy = ATy->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000132 uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000133 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
134 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
135 StartingOffset + i * EltSize);
136 return;
137 }
138 // Base case: we can get an MVT for this LLVM IR type.
139 ValueVTs.push_back(TLI.getValueType(Ty));
140 if (Offsets)
141 Offsets->push_back(StartingOffset);
142}
143
Dan Gohman2a7c6712008-09-03 23:18:39 +0000144namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000145 /// RegsForValue - This struct represents the registers (physical or virtual)
146 /// that a particular set of values is assigned, and the type information about
147 /// the value. The most common situation is to represent one value at a time,
148 /// but struct or array values are handled element-wise as multiple values.
149 /// The splitting of aggregates is performed recursively, so that we never
150 /// have aggregate-typed registers. The values at this point do not necessarily
151 /// have legal types, so each value may require one or more registers of some
152 /// legal type.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000153 ///
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000154 struct VISIBILITY_HIDDEN RegsForValue {
155 /// TLI - The TargetLowering object.
156 ///
157 const TargetLowering *TLI;
158
159 /// ValueVTs - The value types of the values, which may not be legal, and
160 /// may need be promoted or synthesized from one or more registers.
161 ///
162 SmallVector<MVT, 4> ValueVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000163
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000164 /// RegVTs - The value types of the registers. This is the same size as
165 /// ValueVTs and it records, for each value, what the type of the assigned
166 /// register or registers are. (Individual values are never synthesized
167 /// from more than one type of register.)
168 ///
169 /// With virtual registers, the contents of RegVTs is redundant with TLI's
170 /// getRegisterType member function, however when with physical registers
171 /// it is necessary to have a separate record of the types.
172 ///
173 SmallVector<MVT, 4> RegVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000174
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000175 /// Regs - This list holds the registers assigned to the values.
176 /// Each legal or promoted value requires one register, and each
177 /// expanded value requires multiple registers.
178 ///
179 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000180
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000181 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000182
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000183 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000184 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000185 MVT regvt, MVT valuevt)
186 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
187 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000188 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000189 const SmallVector<MVT, 4> &regvts,
190 const SmallVector<MVT, 4> &valuevts)
191 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
192 RegsForValue(const TargetLowering &tli,
193 unsigned Reg, const Type *Ty) : TLI(&tli) {
194 ComputeValueVTs(tli, Ty, ValueVTs);
195
196 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
197 MVT ValueVT = ValueVTs[Value];
198 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
199 MVT RegisterVT = TLI->getRegisterType(ValueVT);
200 for (unsigned i = 0; i != NumRegs; ++i)
201 Regs.push_back(Reg + i);
202 RegVTs.push_back(RegisterVT);
203 Reg += NumRegs;
204 }
205 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000206
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000207 /// append - Add the specified values to this one.
208 void append(const RegsForValue &RHS) {
209 TLI = RHS.TLI;
210 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
211 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
212 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
213 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000214
215
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000216 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000217 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000218 /// Chain/Flag as the input and updates them for the output Chain/Flag.
219 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000220 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000221 SDValue &Chain, SDValue *Flag) const;
222
223 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000224 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000225 /// Chain/Flag as the input and updates them for the output Chain/Flag.
226 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000227 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000228 SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000229
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000230 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000231 /// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000232 /// values added into it.
233 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
234 std::vector<SDValue> &Ops) const;
235 };
236}
237
238/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000239/// PHI nodes or outside of the basic block that defines it, or used by a
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000240/// switch or atomic instruction, which may expand to multiple basic blocks.
241static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
242 if (isa<PHINode>(I)) return true;
243 BasicBlock *BB = I->getParent();
244 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
245 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
246 // FIXME: Remove switchinst special case.
247 isa<SwitchInst>(*UI))
248 return true;
249 return false;
250}
251
252/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
253/// entry block, return true. This includes arguments used by switches, since
254/// the switch may expand into multiple basic blocks.
255static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
256 // With FastISel active, we may be splitting blocks, so force creation
257 // of virtual registers for all non-dead arguments.
Dan Gohman33134c42008-09-25 17:05:24 +0000258 // Don't force virtual registers for byval arguments though, because
259 // fast-isel can't handle those in all cases.
260 if (EnableFastISel && !A->hasByValAttr())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000261 return A->use_empty();
262
263 BasicBlock *Entry = A->getParent()->begin();
264 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
265 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
266 return false; // Use not in entry block.
267 return true;
268}
269
270FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
271 : TLI(tli) {
272}
273
274void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000275 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000276 bool EnableFastISel) {
277 Fn = &fn;
278 MF = &mf;
279 RegInfo = &MF->getRegInfo();
280
281 // Create a vreg for each argument register that is not dead and is used
282 // outside of the entry block for the function.
283 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
284 AI != E; ++AI)
285 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
286 InitializeRegForValue(AI);
287
288 // Initialize the mapping of values to registers. This is only set up for
289 // instruction values that are used outside of the block that defines
290 // them.
291 Function::iterator BB = Fn->begin(), EB = Fn->end();
292 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
293 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
294 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
295 const Type *Ty = AI->getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000296 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000297 unsigned Align =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000298 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
299 AI->getAlignment());
300
301 TySize *= CUI->getZExtValue(); // Get total allocated size.
302 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
303 StaticAllocaMap[AI] =
304 MF->getFrameInfo()->CreateStackObject(TySize, Align);
305 }
306
307 for (; BB != EB; ++BB)
308 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
309 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
310 if (!isa<AllocaInst>(I) ||
311 !StaticAllocaMap.count(cast<AllocaInst>(I)))
312 InitializeRegForValue(I);
313
314 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
315 // also creates the initial PHI MachineInstrs, though none of the input
316 // operands are populated.
317 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
318 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
319 MBBMap[BB] = MBB;
320 MF->push_back(MBB);
321
322 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
323 // appropriate.
324 PHINode *PN;
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000325 DebugLoc DL;
326 for (BasicBlock::iterator
327 I = BB->begin(), E = BB->end(); I != E; ++I) {
328 if (CallInst *CI = dyn_cast<CallInst>(I)) {
329 if (Function *F = CI->getCalledFunction()) {
330 switch (F->getIntrinsicID()) {
331 default: break;
332 case Intrinsic::dbg_stoppoint: {
333 DwarfWriter *DW = DAG.getDwarfWriter();
334 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
335
336 if (DW && DW->ValidDebugInfo(SPI->getContext())) {
337 DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
338 unsigned SrcFile = DW->RecordSource(CU.getDirectory(),
339 CU.getFilename());
340 unsigned idx = MF->getOrCreateDebugLocID(SrcFile,
341 SPI->getLine(),
342 SPI->getColumn());
343 DL = DebugLoc::get(idx);
344 }
345
346 break;
347 }
348 case Intrinsic::dbg_func_start: {
349 DwarfWriter *DW = DAG.getDwarfWriter();
350 if (DW) {
351 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
352 Value *SP = FSI->getSubprogram();
353
354 if (DW->ValidDebugInfo(SP)) {
355 DISubprogram Subprogram(cast<GlobalVariable>(SP));
356 DICompileUnit CU(Subprogram.getCompileUnit());
357 unsigned SrcFile = DW->RecordSource(CU.getDirectory(),
358 CU.getFilename());
359 unsigned Line = Subprogram.getLineNumber();
360 DL = DebugLoc::get(MF->getOrCreateDebugLocID(SrcFile, Line, 0));
361 }
362 }
363
364 break;
365 }
366 }
367 }
368 }
369
370 PN = dyn_cast<PHINode>(I);
371 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000372
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000373 unsigned PHIReg = ValueMap[PN];
374 assert(PHIReg && "PHI node does not have an assigned virtual register!");
375
376 SmallVector<MVT, 4> ValueVTs;
377 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
378 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
379 MVT VT = ValueVTs[vti];
380 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000381 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000382 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000383 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000384 PHIReg += NumRegisters;
385 }
386 }
387 }
388}
389
390unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
391 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
392}
393
394/// CreateRegForValue - Allocate the appropriate number of virtual registers of
395/// the correctly promoted or expanded types. Assign these registers
396/// consecutive vreg numbers and return the first assigned number.
397///
398/// In the case that the given value has struct or array type, this function
399/// will assign registers for each member or element.
400///
401unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
402 SmallVector<MVT, 4> ValueVTs;
403 ComputeValueVTs(TLI, V->getType(), ValueVTs);
404
405 unsigned FirstReg = 0;
406 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
407 MVT ValueVT = ValueVTs[Value];
408 MVT RegisterVT = TLI.getRegisterType(ValueVT);
409
410 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
411 for (unsigned i = 0; i != NumRegs; ++i) {
412 unsigned R = MakeReg(RegisterVT);
413 if (!FirstReg) FirstReg = R;
414 }
415 }
416 return FirstReg;
417}
418
419/// getCopyFromParts - Create a value that contains the specified legal parts
420/// combined into the value they represent. If the parts combine to a type
421/// larger then ValueVT then AssertOp can be used to specify whether the extra
422/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
423/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000424static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
425 const SDValue *Parts,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000426 unsigned NumParts, MVT PartVT, MVT ValueVT,
427 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000428 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000429 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000430 SDValue Val = Parts[0];
431
432 if (NumParts > 1) {
433 // Assemble the value from multiple parts.
434 if (!ValueVT.isVector()) {
435 unsigned PartBits = PartVT.getSizeInBits();
436 unsigned ValueBits = ValueVT.getSizeInBits();
437
438 // Assemble the power of 2 part.
439 unsigned RoundParts = NumParts & (NumParts - 1) ?
440 1 << Log2_32(NumParts) : NumParts;
441 unsigned RoundBits = PartBits * RoundParts;
442 MVT RoundVT = RoundBits == ValueBits ?
443 ValueVT : MVT::getIntegerVT(RoundBits);
444 SDValue Lo, Hi;
445
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000446 MVT HalfVT = ValueVT.isInteger() ?
447 MVT::getIntegerVT(RoundBits/2) :
448 MVT::getFloatingPointVT(RoundBits/2);
449
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000450 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000451 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
452 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000453 PartVT, HalfVT);
454 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000455 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
456 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000457 }
458 if (TLI.isBigEndian())
459 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000460 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000461
462 if (RoundParts < NumParts) {
463 // Assemble the trailing non-power-of-2 part.
464 unsigned OddParts = NumParts - RoundParts;
465 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000466 Hi = getCopyFromParts(DAG, dl,
467 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000468
469 // Combine the round and odd parts.
470 Lo = Val;
471 if (TLI.isBigEndian())
472 std::swap(Lo, Hi);
473 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000474 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
475 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000476 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000477 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000478 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
479 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000480 }
481 } else {
482 // Handle a multi-element vector.
483 MVT IntermediateVT, RegisterVT;
484 unsigned NumIntermediates;
485 unsigned NumRegs =
486 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
487 RegisterVT);
488 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
489 NumParts = NumRegs; // Silence a compiler warning.
490 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
491 assert(RegisterVT == Parts[0].getValueType() &&
492 "Part type doesn't match part!");
493
494 // Assemble the parts into intermediate operands.
495 SmallVector<SDValue, 8> Ops(NumIntermediates);
496 if (NumIntermediates == NumParts) {
497 // If the register was not expanded, truncate or copy the value,
498 // as appropriate.
499 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000500 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000501 PartVT, IntermediateVT);
502 } else if (NumParts > 0) {
503 // If the intermediate type was expanded, build the intermediate operands
504 // from the parts.
505 assert(NumParts % NumIntermediates == 0 &&
506 "Must expand into a divisible number of parts!");
507 unsigned Factor = NumParts / NumIntermediates;
508 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000509 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000510 PartVT, IntermediateVT);
511 }
512
513 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
514 // operands.
515 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000516 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000517 ValueVT, &Ops[0], NumIntermediates);
518 }
519 }
520
521 // There is now one part, held in Val. Correct it to match ValueVT.
522 PartVT = Val.getValueType();
523
524 if (PartVT == ValueVT)
525 return Val;
526
527 if (PartVT.isVector()) {
528 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000529 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000530 }
531
532 if (ValueVT.isVector()) {
533 assert(ValueVT.getVectorElementType() == PartVT &&
534 ValueVT.getVectorNumElements() == 1 &&
535 "Only trivial scalar-to-vector conversions should get here!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000536 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000537 }
538
539 if (PartVT.isInteger() &&
540 ValueVT.isInteger()) {
541 if (ValueVT.bitsLT(PartVT)) {
542 // For a truncate, see if we have any information to
543 // indicate whether the truncated bits will always be
544 // zero or sign-extension.
545 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000546 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000547 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000548 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000549 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000550 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000551 }
552 }
553
554 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
555 if (ValueVT.bitsLT(Val.getValueType()))
556 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000557 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000558 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000559 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000560 }
561
562 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000563 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000564
565 assert(0 && "Unknown mismatch!");
566 return SDValue();
567}
568
569/// getCopyToParts - Create a series of nodes that contain the specified value
570/// split into legal parts. If the parts contain more bits than Val, then, for
571/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000572static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Chris Lattner01426e12008-10-21 00:45:36 +0000573 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000574 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000575 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000576 MVT PtrVT = TLI.getPointerTy();
577 MVT ValueVT = Val.getValueType();
578 unsigned PartBits = PartVT.getSizeInBits();
579 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
580
581 if (!NumParts)
582 return;
583
584 if (!ValueVT.isVector()) {
585 if (PartVT == ValueVT) {
586 assert(NumParts == 1 && "No-op copy with multiple parts!");
587 Parts[0] = Val;
588 return;
589 }
590
591 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
592 // If the parts cover more bits than the value has, promote the value.
593 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
594 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000595 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000596 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
597 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000598 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000599 } else {
600 assert(0 && "Unknown mismatch!");
601 }
602 } else if (PartBits == ValueVT.getSizeInBits()) {
603 // Different types of the same size.
604 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000605 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000606 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
607 // If the parts cover less bits than value has, truncate the value.
608 if (PartVT.isInteger() && ValueVT.isInteger()) {
609 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000610 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000611 } else {
612 assert(0 && "Unknown mismatch!");
613 }
614 }
615
616 // The value may have changed - recompute ValueVT.
617 ValueVT = Val.getValueType();
618 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
619 "Failed to tile the value with PartVT!");
620
621 if (NumParts == 1) {
622 assert(PartVT == ValueVT && "Type conversion failed!");
623 Parts[0] = Val;
624 return;
625 }
626
627 // Expand the value into multiple parts.
628 if (NumParts & (NumParts - 1)) {
629 // The number of parts is not a power of 2. Split off and copy the tail.
630 assert(PartVT.isInteger() && ValueVT.isInteger() &&
631 "Do not know what to expand to!");
632 unsigned RoundParts = 1 << Log2_32(NumParts);
633 unsigned RoundBits = RoundParts * PartBits;
634 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000635 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000636 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000637 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000638 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000639 if (TLI.isBigEndian())
640 // The odd parts were reversed by getCopyToParts - unreverse them.
641 std::reverse(Parts + RoundParts, Parts + NumParts);
642 NumParts = RoundParts;
643 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000644 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000645 }
646
647 // The number of parts is a power of 2. Repeatedly bisect the value using
648 // EXTRACT_ELEMENT.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000649 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000650 MVT::getIntegerVT(ValueVT.getSizeInBits()),
651 Val);
652 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
653 for (unsigned i = 0; i < NumParts; i += StepSize) {
654 unsigned ThisBits = StepSize * PartBits / 2;
655 MVT ThisVT = MVT::getIntegerVT (ThisBits);
656 SDValue &Part0 = Parts[i];
657 SDValue &Part1 = Parts[i+StepSize/2];
658
Dale Johannesen66978ee2009-01-31 02:22:37 +0000659 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000660 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000661 DAG.getConstant(1, PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000662 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000663 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000664 DAG.getConstant(0, PtrVT));
665
666 if (ThisBits == PartBits && ThisVT != PartVT) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000667 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000668 PartVT, Part0);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000669 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000670 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000671 }
672 }
673 }
674
675 if (TLI.isBigEndian())
676 std::reverse(Parts, Parts + NumParts);
677
678 return;
679 }
680
681 // Vector ValueVT.
682 if (NumParts == 1) {
683 if (PartVT != ValueVT) {
684 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000685 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000686 } else {
687 assert(ValueVT.getVectorElementType() == PartVT &&
688 ValueVT.getVectorNumElements() == 1 &&
689 "Only trivial vector-to-scalar conversions should get here!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000690 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000691 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000692 DAG.getConstant(0, PtrVT));
693 }
694 }
695
696 Parts[0] = Val;
697 return;
698 }
699
700 // Handle a multi-element vector.
701 MVT IntermediateVT, RegisterVT;
702 unsigned NumIntermediates;
Dan Gohmane9530ec2009-01-15 16:58:17 +0000703 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000704 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
705 RegisterVT);
706 unsigned NumElements = ValueVT.getVectorNumElements();
707
708 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
709 NumParts = NumRegs; // Silence a compiler warning.
710 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
711
712 // Split the vector into intermediate operands.
713 SmallVector<SDValue, 8> Ops(NumIntermediates);
714 for (unsigned i = 0; i != NumIntermediates; ++i)
715 if (IntermediateVT.isVector())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000716 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000717 IntermediateVT, Val,
718 DAG.getConstant(i * (NumElements / NumIntermediates),
719 PtrVT));
720 else
Dale Johannesen66978ee2009-01-31 02:22:37 +0000721 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000722 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000723 DAG.getConstant(i, PtrVT));
724
725 // Split the intermediate operands into legal parts.
726 if (NumParts == NumIntermediates) {
727 // If the register was not expanded, promote or copy the value,
728 // as appropriate.
729 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000730 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000731 } else if (NumParts > 0) {
732 // If the intermediate type was expanded, split each the value into
733 // legal parts.
734 assert(NumParts % NumIntermediates == 0 &&
735 "Must expand into a divisible number of parts!");
736 unsigned Factor = NumParts / NumIntermediates;
737 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000738 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000739 }
740}
741
742
743void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
744 AA = &aa;
745 GFI = gfi;
746 TD = DAG.getTarget().getTargetData();
747}
748
749/// clear - Clear out the curret SelectionDAG and the associated
750/// state and prepare this SelectionDAGLowering object to be used
751/// for a new block. This doesn't clear out information about
752/// additional blocks that are needed to complete switch lowering
753/// or PHI node updating; that information is cleared out as it is
754/// consumed.
755void SelectionDAGLowering::clear() {
756 NodeMap.clear();
757 PendingLoads.clear();
758 PendingExports.clear();
759 DAG.clear();
760}
761
762/// getRoot - Return the current virtual root of the Selection DAG,
763/// flushing any PendingLoad items. This must be done before emitting
764/// a store or any other node that may need to be ordered after any
765/// prior load instructions.
766///
767SDValue SelectionDAGLowering::getRoot() {
768 if (PendingLoads.empty())
769 return DAG.getRoot();
770
771 if (PendingLoads.size() == 1) {
772 SDValue Root = PendingLoads[0];
773 DAG.setRoot(Root);
774 PendingLoads.clear();
775 return Root;
776 }
777
778 // Otherwise, we have to make a token factor node.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000779 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000780 &PendingLoads[0], PendingLoads.size());
781 PendingLoads.clear();
782 DAG.setRoot(Root);
783 return Root;
784}
785
786/// getControlRoot - Similar to getRoot, but instead of flushing all the
787/// PendingLoad items, flush all the PendingExports items. It is necessary
788/// to do this before emitting a terminator instruction.
789///
790SDValue SelectionDAGLowering::getControlRoot() {
791 SDValue Root = DAG.getRoot();
792
793 if (PendingExports.empty())
794 return Root;
795
796 // Turn all of the CopyToReg chains into one factored node.
797 if (Root.getOpcode() != ISD::EntryToken) {
798 unsigned i = 0, e = PendingExports.size();
799 for (; i != e; ++i) {
800 assert(PendingExports[i].getNode()->getNumOperands() > 1);
801 if (PendingExports[i].getNode()->getOperand(0) == Root)
802 break; // Don't add the root if we already indirectly depend on it.
803 }
804
805 if (i == e)
806 PendingExports.push_back(Root);
807 }
808
Dale Johannesen66978ee2009-01-31 02:22:37 +0000809 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000810 &PendingExports[0],
811 PendingExports.size());
812 PendingExports.clear();
813 DAG.setRoot(Root);
814 return Root;
815}
816
817void SelectionDAGLowering::visit(Instruction &I) {
818 visit(I.getOpcode(), I);
819}
820
821void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
822 // Note: this doesn't use InstVisitor, because it has to work with
823 // ConstantExpr's in addition to instructions.
824 switch (Opcode) {
825 default: assert(0 && "Unknown instruction type encountered!");
826 abort();
827 // Build the switch statement using the Instruction.def file.
828#define HANDLE_INST(NUM, OPCODE, CLASS) \
829 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
830#include "llvm/Instruction.def"
831 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000832}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000833
834void SelectionDAGLowering::visitAdd(User &I) {
835 if (I.getType()->isFPOrFPVector())
836 visitBinary(I, ISD::FADD);
837 else
838 visitBinary(I, ISD::ADD);
839}
840
841void SelectionDAGLowering::visitMul(User &I) {
842 if (I.getType()->isFPOrFPVector())
843 visitBinary(I, ISD::FMUL);
844 else
845 visitBinary(I, ISD::MUL);
846}
847
848SDValue SelectionDAGLowering::getValue(const Value *V) {
849 SDValue &N = NodeMap[V];
850 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000851
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000852 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
853 MVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000854
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000855 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000856 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000857
858 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
859 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000860
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000861 if (isa<ConstantPointerNull>(C))
862 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000863
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000864 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000865 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000866
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000867 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
868 !V->getType()->isAggregateType())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000869 return N = DAG.getNode(ISD::UNDEF, getCurDebugLoc(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000870
871 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
872 visit(CE->getOpcode(), *CE);
873 SDValue N1 = NodeMap[V];
874 assert(N1.getNode() && "visit didn't populate the ValueMap!");
875 return N1;
876 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000877
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000878 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
879 SmallVector<SDValue, 4> Constants;
880 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
881 OI != OE; ++OI) {
882 SDNode *Val = getValue(*OI).getNode();
883 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
884 Constants.push_back(SDValue(Val, i));
885 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000886 return DAG.getMergeValues(&Constants[0], Constants.size(),
887 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000888 }
889
890 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
891 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
892 "Unknown struct or array constant!");
893
894 SmallVector<MVT, 4> ValueVTs;
895 ComputeValueVTs(TLI, C->getType(), ValueVTs);
896 unsigned NumElts = ValueVTs.size();
897 if (NumElts == 0)
898 return SDValue(); // empty struct
899 SmallVector<SDValue, 4> Constants(NumElts);
900 for (unsigned i = 0; i != NumElts; ++i) {
901 MVT EltVT = ValueVTs[i];
902 if (isa<UndefValue>(C))
Dale Johannesen66978ee2009-01-31 02:22:37 +0000903 Constants[i] = DAG.getNode(ISD::UNDEF, getCurDebugLoc(), EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000904 else if (EltVT.isFloatingPoint())
905 Constants[i] = DAG.getConstantFP(0, EltVT);
906 else
907 Constants[i] = DAG.getConstant(0, EltVT);
908 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000909 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000910 }
911
912 const VectorType *VecTy = cast<VectorType>(V->getType());
913 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000914
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000915 // Now that we know the number and type of the elements, get that number of
916 // elements into the Ops array based on what kind of constant it is.
917 SmallVector<SDValue, 16> Ops;
918 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
919 for (unsigned i = 0; i != NumElements; ++i)
920 Ops.push_back(getValue(CP->getOperand(i)));
921 } else {
922 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
923 "Unknown vector constant!");
924 MVT EltVT = TLI.getValueType(VecTy->getElementType());
925
926 SDValue Op;
927 if (isa<UndefValue>(C))
Dale Johannesen66978ee2009-01-31 02:22:37 +0000928 Op = DAG.getNode(ISD::UNDEF, getCurDebugLoc(), EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000929 else if (EltVT.isFloatingPoint())
930 Op = DAG.getConstantFP(0, EltVT);
931 else
932 Op = DAG.getConstant(0, EltVT);
933 Ops.assign(NumElements, Op);
934 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000935
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000936 // Create a BUILD_VECTOR node.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000937 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000938 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000939 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000940
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000941 // If this is a static alloca, generate it as the frameindex instead of
942 // computation.
943 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
944 DenseMap<const AllocaInst*, int>::iterator SI =
945 FuncInfo.StaticAllocaMap.find(AI);
946 if (SI != FuncInfo.StaticAllocaMap.end())
947 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
948 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000949
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000950 unsigned InReg = FuncInfo.ValueMap[V];
951 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000952
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000953 RegsForValue RFV(TLI, InReg, V->getType());
954 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000955 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000956}
957
958
959void SelectionDAGLowering::visitRet(ReturnInst &I) {
960 if (I.getNumOperands() == 0) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000961 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000962 MVT::Other, getControlRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000963 return;
964 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000965
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000966 SmallVector<SDValue, 8> NewValues;
967 NewValues.push_back(getControlRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000968 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000969 SmallVector<MVT, 4> ValueVTs;
970 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000971 unsigned NumValues = ValueVTs.size();
972 if (NumValues == 0) continue;
973
974 SDValue RetOp = getValue(I.getOperand(i));
975 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000976 MVT VT = ValueVTs[j];
977
978 // FIXME: C calling convention requires the return type to be promoted to
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000979 // at least 32-bit. But this is not necessary for non-C calling
980 // conventions.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000981 if (VT.isInteger()) {
982 MVT MinVT = TLI.getRegisterType(MVT::i32);
983 if (VT.bitsLT(MinVT))
984 VT = MinVT;
985 }
986
987 unsigned NumParts = TLI.getNumRegisters(VT);
988 MVT PartVT = TLI.getRegisterType(VT);
989 SmallVector<SDValue, 4> Parts(NumParts);
990 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000991
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000992 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000993 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000994 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000995 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000996 ExtendKind = ISD::ZERO_EXTEND;
997
Dale Johannesen66978ee2009-01-31 02:22:37 +0000998 getCopyToParts(DAG, getCurDebugLoc(),
999 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001000 &Parts[0], NumParts, PartVT, ExtendKind);
1001
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001002 // 'inreg' on function refers to return value
1003 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +00001004 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001005 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001006 for (unsigned i = 0; i < NumParts; ++i) {
1007 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001008 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001009 }
1010 }
1011 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00001012 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001013 &NewValues[0], NewValues.size()));
1014}
1015
1016/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1017/// the current basic block, add it to ValueMap now so that we'll get a
1018/// CopyTo/FromReg.
1019void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1020 // No need to export constants.
1021 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001022
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001023 // Already exported?
1024 if (FuncInfo.isExportedInst(V)) return;
1025
1026 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1027 CopyValueToVirtualRegister(V, Reg);
1028}
1029
1030bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1031 const BasicBlock *FromBB) {
1032 // The operands of the setcc have to be in this block. We don't know
1033 // how to export them from some other block.
1034 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1035 // Can export from current BB.
1036 if (VI->getParent() == FromBB)
1037 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001038
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001039 // Is already exported, noop.
1040 return FuncInfo.isExportedInst(V);
1041 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001042
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001043 // If this is an argument, we can export it if the BB is the entry block or
1044 // if it is already exported.
1045 if (isa<Argument>(V)) {
1046 if (FromBB == &FromBB->getParent()->getEntryBlock())
1047 return true;
1048
1049 // Otherwise, can only export this if it is already exported.
1050 return FuncInfo.isExportedInst(V);
1051 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001052
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001053 // Otherwise, constants can always be exported.
1054 return true;
1055}
1056
1057static bool InBlock(const Value *V, const BasicBlock *BB) {
1058 if (const Instruction *I = dyn_cast<Instruction>(V))
1059 return I->getParent() == BB;
1060 return true;
1061}
1062
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001063/// getFCmpCondCode - Return the ISD condition code corresponding to
1064/// the given LLVM IR floating-point condition code. This includes
1065/// consideration of global floating-point math flags.
1066///
1067static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1068 ISD::CondCode FPC, FOC;
1069 switch (Pred) {
1070 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1071 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1072 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1073 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1074 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1075 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1076 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1077 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1078 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1079 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1080 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1081 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1082 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1083 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1084 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1085 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1086 default:
1087 assert(0 && "Invalid FCmp predicate opcode!");
1088 FOC = FPC = ISD::SETFALSE;
1089 break;
1090 }
1091 if (FiniteOnlyFPMath())
1092 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001093 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001094 return FPC;
1095}
1096
1097/// getICmpCondCode - Return the ISD condition code corresponding to
1098/// the given LLVM IR integer condition code.
1099///
1100static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1101 switch (Pred) {
1102 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1103 case ICmpInst::ICMP_NE: return ISD::SETNE;
1104 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1105 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1106 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1107 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1108 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1109 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1110 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1111 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1112 default:
1113 assert(0 && "Invalid ICmp predicate opcode!");
1114 return ISD::SETNE;
1115 }
1116}
1117
Dan Gohmanc2277342008-10-17 21:16:08 +00001118/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1119/// This function emits a branch and is used at the leaves of an OR or an
1120/// AND operator tree.
1121///
1122void
1123SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1124 MachineBasicBlock *TBB,
1125 MachineBasicBlock *FBB,
1126 MachineBasicBlock *CurBB) {
1127 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001128
Dan Gohmanc2277342008-10-17 21:16:08 +00001129 // If the leaf of the tree is a comparison, merge the condition into
1130 // the caseblock.
1131 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1132 // The operands of the cmp have to be in this block. We don't know
1133 // how to export them from some other block. If this is the first block
1134 // of the sequence, no exporting is needed.
1135 if (CurBB == CurMBB ||
1136 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1137 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001138 ISD::CondCode Condition;
1139 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001140 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001141 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001142 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001143 } else {
1144 Condition = ISD::SETEQ; // silence warning.
1145 assert(0 && "Unknown compare instruction");
1146 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001147
1148 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001149 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1150 SwitchCases.push_back(CB);
1151 return;
1152 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001153 }
1154
1155 // Create a CaseBlock record representing this branch.
1156 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1157 NULL, TBB, FBB, CurBB);
1158 SwitchCases.push_back(CB);
1159}
1160
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001161/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001162void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1163 MachineBasicBlock *TBB,
1164 MachineBasicBlock *FBB,
1165 MachineBasicBlock *CurBB,
1166 unsigned Opc) {
1167 // If this node is not part of the or/and tree, emit it as a branch.
1168 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001169 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001170 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1171 BOp->getParent() != CurBB->getBasicBlock() ||
1172 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1173 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1174 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001175 return;
1176 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001177
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001178 // Create TmpBB after CurBB.
1179 MachineFunction::iterator BBI = CurBB;
1180 MachineFunction &MF = DAG.getMachineFunction();
1181 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1182 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001183
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001184 if (Opc == Instruction::Or) {
1185 // Codegen X | Y as:
1186 // jmp_if_X TBB
1187 // jmp TmpBB
1188 // TmpBB:
1189 // jmp_if_Y TBB
1190 // jmp FBB
1191 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001192
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001193 // Emit the LHS condition.
1194 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001195
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001196 // Emit the RHS condition into TmpBB.
1197 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1198 } else {
1199 assert(Opc == Instruction::And && "Unknown merge op!");
1200 // Codegen X & Y as:
1201 // jmp_if_X TmpBB
1202 // jmp FBB
1203 // TmpBB:
1204 // jmp_if_Y TBB
1205 // jmp FBB
1206 //
1207 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001208
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001209 // Emit the LHS condition.
1210 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001211
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001212 // Emit the RHS condition into TmpBB.
1213 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1214 }
1215}
1216
1217/// If the set of cases should be emitted as a series of branches, return true.
1218/// If we should emit this as a bunch of and/or'd together conditions, return
1219/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001220bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001221SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1222 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001223
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001224 // If this is two comparisons of the same values or'd or and'd together, they
1225 // will get folded into a single comparison, so don't emit two blocks.
1226 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1227 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1228 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1229 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1230 return false;
1231 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001232
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001233 return true;
1234}
1235
1236void SelectionDAGLowering::visitBr(BranchInst &I) {
1237 // Update machine-CFG edges.
1238 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1239
1240 // Figure out which block is immediately after the current one.
1241 MachineBasicBlock *NextBlock = 0;
1242 MachineFunction::iterator BBI = CurMBB;
1243 if (++BBI != CurMBB->getParent()->end())
1244 NextBlock = BBI;
1245
1246 if (I.isUnconditional()) {
1247 // Update machine-CFG edges.
1248 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001249
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001250 // If this is not a fall-through branch, emit the branch.
1251 if (Succ0MBB != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00001252 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001253 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001254 DAG.getBasicBlock(Succ0MBB)));
1255 return;
1256 }
1257
1258 // If this condition is one of the special cases we handle, do special stuff
1259 // now.
1260 Value *CondVal = I.getCondition();
1261 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1262
1263 // If this is a series of conditions that are or'd or and'd together, emit
1264 // this as a sequence of branches instead of setcc's with and/or operations.
1265 // For example, instead of something like:
1266 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001267 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001268 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001269 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001270 // or C, F
1271 // jnz foo
1272 // Emit:
1273 // cmp A, B
1274 // je foo
1275 // cmp D, E
1276 // jle foo
1277 //
1278 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001279 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001280 (BOp->getOpcode() == Instruction::And ||
1281 BOp->getOpcode() == Instruction::Or)) {
1282 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1283 // If the compares in later blocks need to use values not currently
1284 // exported from this block, export them now. This block should always
1285 // be the first entry.
1286 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001287
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001288 // Allow some cases to be rejected.
1289 if (ShouldEmitAsBranches(SwitchCases)) {
1290 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1291 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1292 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1293 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001294
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001295 // Emit the branch for this block.
1296 visitSwitchCase(SwitchCases[0]);
1297 SwitchCases.erase(SwitchCases.begin());
1298 return;
1299 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001300
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001301 // Okay, we decided not to do this, remove any inserted MBB's and clear
1302 // SwitchCases.
1303 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1304 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001305
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001306 SwitchCases.clear();
1307 }
1308 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001309
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001310 // Create a CaseBlock record representing this branch.
1311 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1312 NULL, Succ0MBB, Succ1MBB, CurMBB);
1313 // Use visitSwitchCase to actually insert the fast branch sequence for this
1314 // cond branch.
1315 visitSwitchCase(CB);
1316}
1317
1318/// visitSwitchCase - Emits the necessary code to represent a single node in
1319/// the binary search tree resulting from lowering a switch instruction.
1320void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1321 SDValue Cond;
1322 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001323 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001324
1325 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001326 if (CB.CmpMHS == NULL) {
1327 // Fold "(X == true)" to X and "(X == false)" to !X to
1328 // handle common cases produced by branch lowering.
1329 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1330 Cond = CondLHS;
1331 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1332 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001333 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001334 } else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001335 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001336 } else {
1337 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1338
Anton Korobeynikov23218582008-12-23 22:25:27 +00001339 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1340 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001341
1342 SDValue CmpOp = getValue(CB.CmpMHS);
1343 MVT VT = CmpOp.getValueType();
1344
1345 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001346 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1347 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001348 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001349 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001350 VT, CmpOp, DAG.getConstant(Low, VT));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001351 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001352 DAG.getConstant(High-Low, VT), ISD::SETULE);
1353 }
1354 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001355
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001356 // Update successor info
1357 CurMBB->addSuccessor(CB.TrueBB);
1358 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001359
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001360 // Set NextBlock to be the MBB immediately after the current one, if any.
1361 // This is used to avoid emitting unnecessary branches to the next block.
1362 MachineBasicBlock *NextBlock = 0;
1363 MachineFunction::iterator BBI = CurMBB;
1364 if (++BBI != CurMBB->getParent()->end())
1365 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001366
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001367 // If the lhs block is the next block, invert the condition so that we can
1368 // fall through to the lhs instead of the rhs block.
1369 if (CB.TrueBB == NextBlock) {
1370 std::swap(CB.TrueBB, CB.FalseBB);
1371 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001372 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001373 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001374 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001375 MVT::Other, getControlRoot(), Cond,
1376 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001377
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001378 // If the branch was constant folded, fix up the CFG.
1379 if (BrCond.getOpcode() == ISD::BR) {
1380 CurMBB->removeSuccessor(CB.FalseBB);
1381 DAG.setRoot(BrCond);
1382 } else {
1383 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001384 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001385 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001386
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001387 if (CB.FalseBB == NextBlock)
1388 DAG.setRoot(BrCond);
1389 else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001390 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001391 DAG.getBasicBlock(CB.FalseBB)));
1392 }
1393}
1394
1395/// visitJumpTable - Emit JumpTable node in the current MBB
1396void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1397 // Emit the code for the jump table
1398 assert(JT.Reg != -1U && "Should lower JT Header first!");
1399 MVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001400 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1401 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001402 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00001403 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001404 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001405 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001406}
1407
1408/// visitJumpTableHeader - This function emits necessary code to produce index
1409/// in the JumpTable from switch case.
1410void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1411 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001412 // Subtract the lowest switch case value from the value being switched on and
1413 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001414 // difference between smallest and largest cases.
1415 SDValue SwitchOp = getValue(JTH.SValue);
1416 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001417 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001418 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001419
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001420 // The SDNode we just created, which holds the value being switched on minus
1421 // the the smallest case value, needs to be copied to a virtual register so it
1422 // can be used as an index into the jump table in a subsequent basic block.
1423 // This value may be smaller or larger than the target's pointer type, and
1424 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001425 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00001426 SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001427 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001428 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001429 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001430 TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001431
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001432 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001433 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1434 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001435 JT.Reg = JumpTableReg;
1436
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001437 // Emit the range check for the jump table, and branch to the default block
1438 // for the switch statement if the value being switched on exceeds the largest
1439 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001440 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1441 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001442 DAG.getConstant(JTH.Last-JTH.First,VT),
1443 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001444
1445 // Set NextBlock to be the MBB immediately after the current one, if any.
1446 // This is used to avoid emitting unnecessary branches to the next block.
1447 MachineBasicBlock *NextBlock = 0;
1448 MachineFunction::iterator BBI = CurMBB;
1449 if (++BBI != CurMBB->getParent()->end())
1450 NextBlock = BBI;
1451
Dale Johannesen66978ee2009-01-31 02:22:37 +00001452 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001453 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001454 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001455
1456 if (JT.MBB == NextBlock)
1457 DAG.setRoot(BrCond);
1458 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001459 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001460 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001461}
1462
1463/// visitBitTestHeader - This function emits necessary code to produce value
1464/// suitable for "bit tests"
1465void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1466 // Subtract the minimum value
1467 SDValue SwitchOp = getValue(B.SValue);
1468 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001469 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001470 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001471
1472 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001473 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1474 TLI.getSetCCResultType(SUB.getValueType()),
1475 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001476 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001477
1478 SDValue ShiftOp;
Duncan Sands92abc622009-01-31 15:50:11 +00001479 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00001480 ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001481 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001482 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001483 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001484 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001485
Duncan Sands92abc622009-01-31 15:50:11 +00001486 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001487 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1488 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001489
1490 // Set NextBlock to be the MBB immediately after the current one, if any.
1491 // This is used to avoid emitting unnecessary branches to the next block.
1492 MachineBasicBlock *NextBlock = 0;
1493 MachineFunction::iterator BBI = CurMBB;
1494 if (++BBI != CurMBB->getParent()->end())
1495 NextBlock = BBI;
1496
1497 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1498
1499 CurMBB->addSuccessor(B.Default);
1500 CurMBB->addSuccessor(MBB);
1501
Dale Johannesen66978ee2009-01-31 02:22:37 +00001502 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001503 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001504 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001505
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001506 if (MBB == NextBlock)
1507 DAG.setRoot(BrRange);
1508 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001509 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001510 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001511}
1512
1513/// visitBitTestCase - this function produces one "bit test"
1514void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1515 unsigned Reg,
1516 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001517 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001518 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001519 TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00001520 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001521 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001522 DAG.getConstant(1, TLI.getPointerTy()),
1523 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001524
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001525 // Emit bit tests and jumps
Dale Johannesen66978ee2009-01-31 02:22:37 +00001526 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001527 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001528 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001529 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1530 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001531 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001532 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001533
1534 CurMBB->addSuccessor(B.TargetBB);
1535 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001536
Dale Johannesen66978ee2009-01-31 02:22:37 +00001537 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001538 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001539 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001540
1541 // Set NextBlock to be the MBB immediately after the current one, if any.
1542 // This is used to avoid emitting unnecessary branches to the next block.
1543 MachineBasicBlock *NextBlock = 0;
1544 MachineFunction::iterator BBI = CurMBB;
1545 if (++BBI != CurMBB->getParent()->end())
1546 NextBlock = BBI;
1547
1548 if (NextMBB == NextBlock)
1549 DAG.setRoot(BrAnd);
1550 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001551 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001552 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001553}
1554
1555void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1556 // Retrieve successors.
1557 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1558 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1559
Gabor Greifb67e6b32009-01-15 11:10:44 +00001560 const Value *Callee(I.getCalledValue());
1561 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001562 visitInlineAsm(&I);
1563 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001564 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001565
1566 // If the value of the invoke is used outside of its defining block, make it
1567 // available as a virtual register.
1568 if (!I.use_empty()) {
1569 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1570 if (VMI != FuncInfo.ValueMap.end())
1571 CopyValueToVirtualRegister(&I, VMI->second);
1572 }
1573
1574 // Update successor info
1575 CurMBB->addSuccessor(Return);
1576 CurMBB->addSuccessor(LandingPad);
1577
1578 // Drop into normal successor.
Dale Johannesen66978ee2009-01-31 02:22:37 +00001579 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001580 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001581 DAG.getBasicBlock(Return)));
1582}
1583
1584void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1585}
1586
1587/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1588/// small case ranges).
1589bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1590 CaseRecVector& WorkList,
1591 Value* SV,
1592 MachineBasicBlock* Default) {
1593 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001594
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001595 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001596 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001597 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001598 return false;
1599
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001600 // Get the MachineFunction which holds the current MBB. This is used when
1601 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001602 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001603
1604 // Figure out which block is immediately after the current one.
1605 MachineBasicBlock *NextBlock = 0;
1606 MachineFunction::iterator BBI = CR.CaseBB;
1607
1608 if (++BBI != CurMBB->getParent()->end())
1609 NextBlock = BBI;
1610
1611 // TODO: If any two of the cases has the same destination, and if one value
1612 // is the same as the other, but has one bit unset that the other has set,
1613 // use bit manipulation to do two compares at once. For example:
1614 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001615
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001616 // Rearrange the case blocks so that the last one falls through if possible.
1617 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1618 // The last case block won't fall through into 'NextBlock' if we emit the
1619 // branches in this order. See if rearranging a case value would help.
1620 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1621 if (I->BB == NextBlock) {
1622 std::swap(*I, BackCase);
1623 break;
1624 }
1625 }
1626 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001627
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001628 // Create a CaseBlock record representing a conditional branch to
1629 // the Case's target mbb if the value being switched on SV is equal
1630 // to C.
1631 MachineBasicBlock *CurBlock = CR.CaseBB;
1632 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1633 MachineBasicBlock *FallThrough;
1634 if (I != E-1) {
1635 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1636 CurMF->insert(BBI, FallThrough);
1637 } else {
1638 // If the last case doesn't match, go to the default block.
1639 FallThrough = Default;
1640 }
1641
1642 Value *RHS, *LHS, *MHS;
1643 ISD::CondCode CC;
1644 if (I->High == I->Low) {
1645 // This is just small small case range :) containing exactly 1 case
1646 CC = ISD::SETEQ;
1647 LHS = SV; RHS = I->High; MHS = NULL;
1648 } else {
1649 CC = ISD::SETLE;
1650 LHS = I->Low; MHS = SV; RHS = I->High;
1651 }
1652 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001653
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001654 // If emitting the first comparison, just call visitSwitchCase to emit the
1655 // code into the current block. Otherwise, push the CaseBlock onto the
1656 // vector to be later processed by SDISel, and insert the node's MBB
1657 // before the next MBB.
1658 if (CurBlock == CurMBB)
1659 visitSwitchCase(CB);
1660 else
1661 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001662
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001663 CurBlock = FallThrough;
1664 }
1665
1666 return true;
1667}
1668
1669static inline bool areJTsAllowed(const TargetLowering &TLI) {
1670 return !DisableJumpTables &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00001671 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1672 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001673}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001674
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001675static APInt ComputeRange(const APInt &First, const APInt &Last) {
1676 APInt LastExt(Last), FirstExt(First);
1677 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1678 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1679 return (LastExt - FirstExt + 1ULL);
1680}
1681
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001682/// handleJTSwitchCase - Emit jumptable for current switch case range
1683bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1684 CaseRecVector& WorkList,
1685 Value* SV,
1686 MachineBasicBlock* Default) {
1687 Case& FrontCase = *CR.Range.first;
1688 Case& BackCase = *(CR.Range.second-1);
1689
Anton Korobeynikov23218582008-12-23 22:25:27 +00001690 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1691 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001692
Anton Korobeynikov23218582008-12-23 22:25:27 +00001693 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001694 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1695 I!=E; ++I)
1696 TSize += I->size();
1697
1698 if (!areJTsAllowed(TLI) || TSize <= 3)
1699 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001700
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001701 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001702 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001703 if (Density < 0.4)
1704 return false;
1705
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001706 DEBUG(errs() << "Lowering jump table\n"
1707 << "First entry: " << First << ". Last entry: " << Last << '\n'
1708 << "Range: " << Range
1709 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001710
1711 // Get the MachineFunction which holds the current MBB. This is used when
1712 // inserting any additional MBBs necessary to represent the switch.
1713 MachineFunction *CurMF = CurMBB->getParent();
1714
1715 // Figure out which block is immediately after the current one.
1716 MachineBasicBlock *NextBlock = 0;
1717 MachineFunction::iterator BBI = CR.CaseBB;
1718
1719 if (++BBI != CurMBB->getParent()->end())
1720 NextBlock = BBI;
1721
1722 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1723
1724 // Create a new basic block to hold the code for loading the address
1725 // of the jump table, and jumping to it. Update successor information;
1726 // we will either branch to the default case for the switch, or the jump
1727 // table.
1728 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1729 CurMF->insert(BBI, JumpTableBB);
1730 CR.CaseBB->addSuccessor(Default);
1731 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001732
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001733 // Build a vector of destination BBs, corresponding to each target
1734 // of the jump table. If the value of the jump table slot corresponds to
1735 // a case statement, push the case's BB onto the vector, otherwise, push
1736 // the default BB.
1737 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001738 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001739 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001740 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1741 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1742
1743 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001744 DestBBs.push_back(I->BB);
1745 if (TEI==High)
1746 ++I;
1747 } else {
1748 DestBBs.push_back(Default);
1749 }
1750 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001751
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001752 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001753 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1754 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001755 E = DestBBs.end(); I != E; ++I) {
1756 if (!SuccsHandled[(*I)->getNumber()]) {
1757 SuccsHandled[(*I)->getNumber()] = true;
1758 JumpTableBB->addSuccessor(*I);
1759 }
1760 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001761
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001762 // Create a jump table index for this jump table, or return an existing
1763 // one.
1764 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001765
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001766 // Set the jump table information so that we can codegen it as a second
1767 // MachineBasicBlock
1768 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1769 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1770 if (CR.CaseBB == CurMBB)
1771 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001772
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001773 JTCases.push_back(JumpTableBlock(JTH, JT));
1774
1775 return true;
1776}
1777
1778/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1779/// 2 subtrees.
1780bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1781 CaseRecVector& WorkList,
1782 Value* SV,
1783 MachineBasicBlock* Default) {
1784 // Get the MachineFunction which holds the current MBB. This is used when
1785 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001786 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001787
1788 // Figure out which block is immediately after the current one.
1789 MachineBasicBlock *NextBlock = 0;
1790 MachineFunction::iterator BBI = CR.CaseBB;
1791
1792 if (++BBI != CurMBB->getParent()->end())
1793 NextBlock = BBI;
1794
1795 Case& FrontCase = *CR.Range.first;
1796 Case& BackCase = *(CR.Range.second-1);
1797 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1798
1799 // Size is the number of Cases represented by this range.
1800 unsigned Size = CR.Range.second - CR.Range.first;
1801
Anton Korobeynikov23218582008-12-23 22:25:27 +00001802 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1803 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001804 double FMetric = 0;
1805 CaseItr Pivot = CR.Range.first + Size/2;
1806
1807 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1808 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001809 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001810 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1811 I!=E; ++I)
1812 TSize += I->size();
1813
Anton Korobeynikov23218582008-12-23 22:25:27 +00001814 size_t LSize = FrontCase.size();
1815 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001816 DEBUG(errs() << "Selecting best pivot: \n"
1817 << "First: " << First << ", Last: " << Last <<'\n'
1818 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001819 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1820 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001821 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1822 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001823 APInt Range = ComputeRange(LEnd, RBegin);
1824 assert((Range - 2ULL).isNonNegative() &&
1825 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001826 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1827 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001828 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001829 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001830 DEBUG(errs() <<"=>Step\n"
1831 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1832 << "LDensity: " << LDensity
1833 << ", RDensity: " << RDensity << '\n'
1834 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001835 if (FMetric < Metric) {
1836 Pivot = J;
1837 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001838 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001839 }
1840
1841 LSize += J->size();
1842 RSize -= J->size();
1843 }
1844 if (areJTsAllowed(TLI)) {
1845 // If our case is dense we *really* should handle it earlier!
1846 assert((FMetric > 0) && "Should handle dense range earlier!");
1847 } else {
1848 Pivot = CR.Range.first + Size/2;
1849 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001850
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001851 CaseRange LHSR(CR.Range.first, Pivot);
1852 CaseRange RHSR(Pivot, CR.Range.second);
1853 Constant *C = Pivot->Low;
1854 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001855
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001856 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001857 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001858 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001859 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001860 // Pivot's Value, then we can branch directly to the LHS's Target,
1861 // rather than creating a leaf node for it.
1862 if ((LHSR.second - LHSR.first) == 1 &&
1863 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001864 cast<ConstantInt>(C)->getValue() ==
1865 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001866 TrueBB = LHSR.first->BB;
1867 } else {
1868 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1869 CurMF->insert(BBI, TrueBB);
1870 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1871 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001872
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001873 // Similar to the optimization above, if the Value being switched on is
1874 // known to be less than the Constant CR.LT, and the current Case Value
1875 // is CR.LT - 1, then we can branch directly to the target block for
1876 // the current Case Value, rather than emitting a RHS leaf node for it.
1877 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001878 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1879 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001880 FalseBB = RHSR.first->BB;
1881 } else {
1882 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1883 CurMF->insert(BBI, FalseBB);
1884 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1885 }
1886
1887 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001888 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001889 // Otherwise, branch to LHS.
1890 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1891
1892 if (CR.CaseBB == CurMBB)
1893 visitSwitchCase(CB);
1894 else
1895 SwitchCases.push_back(CB);
1896
1897 return true;
1898}
1899
1900/// handleBitTestsSwitchCase - if current case range has few destination and
1901/// range span less, than machine word bitwidth, encode case range into series
1902/// of masks and emit bit tests with these masks.
1903bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1904 CaseRecVector& WorkList,
1905 Value* SV,
1906 MachineBasicBlock* Default){
1907 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1908
1909 Case& FrontCase = *CR.Range.first;
1910 Case& BackCase = *(CR.Range.second-1);
1911
1912 // Get the MachineFunction which holds the current MBB. This is used when
1913 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001914 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001915
Anton Korobeynikov23218582008-12-23 22:25:27 +00001916 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001917 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1918 I!=E; ++I) {
1919 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001920 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001921 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001922
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001923 // Count unique destinations
1924 SmallSet<MachineBasicBlock*, 4> Dests;
1925 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1926 Dests.insert(I->BB);
1927 if (Dests.size() > 3)
1928 // Don't bother the code below, if there are too much unique destinations
1929 return false;
1930 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001931 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1932 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001933
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001934 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001935 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1936 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001937 APInt cmpRange = maxValue - minValue;
1938
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001939 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1940 << "Low bound: " << minValue << '\n'
1941 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001942
1943 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001944 (!(Dests.size() == 1 && numCmps >= 3) &&
1945 !(Dests.size() == 2 && numCmps >= 5) &&
1946 !(Dests.size() >= 3 && numCmps >= 6)))
1947 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001948
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001949 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001950 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1951
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001952 // Optimize the case where all the case values fit in a
1953 // word without having to subtract minValue. In this case,
1954 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001955 if (minValue.isNonNegative() &&
1956 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1957 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001958 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001959 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001960 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001961
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001962 CaseBitsVector CasesBits;
1963 unsigned i, count = 0;
1964
1965 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1966 MachineBasicBlock* Dest = I->BB;
1967 for (i = 0; i < count; ++i)
1968 if (Dest == CasesBits[i].BB)
1969 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001970
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001971 if (i == count) {
1972 assert((count < 3) && "Too much destinations to test!");
1973 CasesBits.push_back(CaseBits(0, Dest, 0));
1974 count++;
1975 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001976
1977 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1978 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1979
1980 uint64_t lo = (lowValue - lowBound).getZExtValue();
1981 uint64_t hi = (highValue - lowBound).getZExtValue();
1982
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001983 for (uint64_t j = lo; j <= hi; j++) {
1984 CasesBits[i].Mask |= 1ULL << j;
1985 CasesBits[i].Bits++;
1986 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001987
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001988 }
1989 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001990
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001991 BitTestInfo BTC;
1992
1993 // Figure out which block is immediately after the current one.
1994 MachineFunction::iterator BBI = CR.CaseBB;
1995 ++BBI;
1996
1997 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1998
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001999 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002000 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002001 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2002 << ", Bits: " << CasesBits[i].Bits
2003 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002004
2005 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2006 CurMF->insert(BBI, CaseBB);
2007 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2008 CaseBB,
2009 CasesBits[i].BB));
2010 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002011
2012 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002013 -1U, (CR.CaseBB == CurMBB),
2014 CR.CaseBB, Default, BTC);
2015
2016 if (CR.CaseBB == CurMBB)
2017 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002018
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002019 BitTestCases.push_back(BTB);
2020
2021 return true;
2022}
2023
2024
2025/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002026size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002027 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002028 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002029
2030 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002031 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002032 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2033 Cases.push_back(Case(SI.getSuccessorValue(i),
2034 SI.getSuccessorValue(i),
2035 SMBB));
2036 }
2037 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2038
2039 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002040 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002041 // Must recompute end() each iteration because it may be
2042 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002043 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2044 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2045 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002046 MachineBasicBlock* nextBB = J->BB;
2047 MachineBasicBlock* currentBB = I->BB;
2048
2049 // If the two neighboring cases go to the same destination, merge them
2050 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002051 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002052 I->High = J->High;
2053 J = Cases.erase(J);
2054 } else {
2055 I = J++;
2056 }
2057 }
2058
2059 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2060 if (I->Low != I->High)
2061 // A range counts double, since it requires two compares.
2062 ++numCmps;
2063 }
2064
2065 return numCmps;
2066}
2067
Anton Korobeynikov23218582008-12-23 22:25:27 +00002068void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002069 // Figure out which block is immediately after the current one.
2070 MachineBasicBlock *NextBlock = 0;
2071 MachineFunction::iterator BBI = CurMBB;
2072
2073 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2074
2075 // If there is only the default destination, branch to it if it is not the
2076 // next basic block. Otherwise, just fall through.
2077 if (SI.getNumOperands() == 2) {
2078 // Update machine-CFG edges.
2079
2080 // If this is not a fall-through branch, emit the branch.
2081 CurMBB->addSuccessor(Default);
2082 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002083 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002084 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002085 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002086 return;
2087 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002088
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002089 // If there are any non-default case statements, create a vector of Cases
2090 // representing each one, and sort the vector so that we can efficiently
2091 // create a binary search tree from them.
2092 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002093 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002094 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2095 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002096 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002097
2098 // Get the Value to be switched on and default basic blocks, which will be
2099 // inserted into CaseBlock records, representing basic blocks in the binary
2100 // search tree.
2101 Value *SV = SI.getOperand(0);
2102
2103 // Push the initial CaseRec onto the worklist
2104 CaseRecVector WorkList;
2105 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2106
2107 while (!WorkList.empty()) {
2108 // Grab a record representing a case range to process off the worklist
2109 CaseRec CR = WorkList.back();
2110 WorkList.pop_back();
2111
2112 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2113 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002114
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002115 // If the range has few cases (two or less) emit a series of specific
2116 // tests.
2117 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2118 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002119
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002120 // If the switch has more than 5 blocks, and at least 40% dense, and the
2121 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002122 // lowering the switch to a binary tree of conditional branches.
2123 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2124 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002125
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002126 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2127 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2128 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2129 }
2130}
2131
2132
2133void SelectionDAGLowering::visitSub(User &I) {
2134 // -0.0 - X --> fneg
2135 const Type *Ty = I.getType();
2136 if (isa<VectorType>(Ty)) {
2137 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2138 const VectorType *DestTy = cast<VectorType>(I.getType());
2139 const Type *ElTy = DestTy->getElementType();
2140 if (ElTy->isFloatingPoint()) {
2141 unsigned VL = DestTy->getNumElements();
2142 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2143 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2144 if (CV == CNZ) {
2145 SDValue Op2 = getValue(I.getOperand(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002146 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002147 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002148 return;
2149 }
2150 }
2151 }
2152 }
2153 if (Ty->isFloatingPoint()) {
2154 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2155 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2156 SDValue Op2 = getValue(I.getOperand(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002157 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002158 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002159 return;
2160 }
2161 }
2162
2163 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2164}
2165
2166void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2167 SDValue Op1 = getValue(I.getOperand(0));
2168 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002169
Dale Johannesen66978ee2009-01-31 02:22:37 +00002170 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002171 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002172}
2173
2174void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2175 SDValue Op1 = getValue(I.getOperand(0));
2176 SDValue Op2 = getValue(I.getOperand(1));
2177 if (!isa<VectorType>(I.getType())) {
Duncan Sands92abc622009-01-31 15:50:11 +00002178 if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002179 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002180 TLI.getPointerTy(), Op2);
2181 else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002182 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002183 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002184 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002185
Dale Johannesen66978ee2009-01-31 02:22:37 +00002186 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002187 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002188}
2189
2190void SelectionDAGLowering::visitICmp(User &I) {
2191 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2192 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2193 predicate = IC->getPredicate();
2194 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2195 predicate = ICmpInst::Predicate(IC->getPredicate());
2196 SDValue Op1 = getValue(I.getOperand(0));
2197 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002198 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002199 setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002200}
2201
2202void SelectionDAGLowering::visitFCmp(User &I) {
2203 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2204 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2205 predicate = FC->getPredicate();
2206 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2207 predicate = FCmpInst::Predicate(FC->getPredicate());
2208 SDValue Op1 = getValue(I.getOperand(0));
2209 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002210 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002211 setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002212}
2213
2214void SelectionDAGLowering::visitVICmp(User &I) {
2215 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2216 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2217 predicate = IC->getPredicate();
2218 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2219 predicate = ICmpInst::Predicate(IC->getPredicate());
2220 SDValue Op1 = getValue(I.getOperand(0));
2221 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002222 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002223 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
2224 Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002225}
2226
2227void SelectionDAGLowering::visitVFCmp(User &I) {
2228 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2229 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2230 predicate = FC->getPredicate();
2231 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2232 predicate = FCmpInst::Predicate(FC->getPredicate());
2233 SDValue Op1 = getValue(I.getOperand(0));
2234 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002235 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002236 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002237
Dale Johannesenf5d97892009-02-04 01:48:28 +00002238 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002239}
2240
2241void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002242 SmallVector<MVT, 4> ValueVTs;
2243 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2244 unsigned NumValues = ValueVTs.size();
2245 if (NumValues != 0) {
2246 SmallVector<SDValue, 4> Values(NumValues);
2247 SDValue Cond = getValue(I.getOperand(0));
2248 SDValue TrueVal = getValue(I.getOperand(1));
2249 SDValue FalseVal = getValue(I.getOperand(2));
2250
2251 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002252 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002253 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002254 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2255 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2256
Dale Johannesen66978ee2009-01-31 02:22:37 +00002257 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002258 DAG.getVTList(&ValueVTs[0], NumValues),
2259 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002260 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002261}
2262
2263
2264void SelectionDAGLowering::visitTrunc(User &I) {
2265 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2266 SDValue N = getValue(I.getOperand(0));
2267 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002268 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002269}
2270
2271void SelectionDAGLowering::visitZExt(User &I) {
2272 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2273 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2274 SDValue N = getValue(I.getOperand(0));
2275 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002276 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002277}
2278
2279void SelectionDAGLowering::visitSExt(User &I) {
2280 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2281 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2282 SDValue N = getValue(I.getOperand(0));
2283 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002284 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002285}
2286
2287void SelectionDAGLowering::visitFPTrunc(User &I) {
2288 // FPTrunc is never a no-op cast, no need to check
2289 SDValue N = getValue(I.getOperand(0));
2290 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002291 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002292 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002293}
2294
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002295void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002296 // FPTrunc is never a no-op cast, no need to check
2297 SDValue N = getValue(I.getOperand(0));
2298 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002299 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002300}
2301
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002302void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002303 // FPToUI is never a no-op cast, no need to check
2304 SDValue N = getValue(I.getOperand(0));
2305 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002306 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002307}
2308
2309void SelectionDAGLowering::visitFPToSI(User &I) {
2310 // FPToSI is never a no-op cast, no need to check
2311 SDValue N = getValue(I.getOperand(0));
2312 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002313 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002314}
2315
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002316void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002317 // UIToFP is never a no-op cast, no need to check
2318 SDValue N = getValue(I.getOperand(0));
2319 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002320 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002321}
2322
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002323void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002324 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002325 SDValue N = getValue(I.getOperand(0));
2326 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002327 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002328}
2329
2330void SelectionDAGLowering::visitPtrToInt(User &I) {
2331 // What to do depends on the size of the integer and the size of the pointer.
2332 // We can either truncate, zero extend, or no-op, accordingly.
2333 SDValue N = getValue(I.getOperand(0));
2334 MVT SrcVT = N.getValueType();
2335 MVT DestVT = TLI.getValueType(I.getType());
2336 SDValue Result;
2337 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002338 Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002339 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002340 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Dale Johannesen66978ee2009-01-31 02:22:37 +00002341 Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002342 setValue(&I, Result);
2343}
2344
2345void SelectionDAGLowering::visitIntToPtr(User &I) {
2346 // What to do depends on the size of the integer and the size of the pointer.
2347 // We can either truncate, zero extend, or no-op, accordingly.
2348 SDValue N = getValue(I.getOperand(0));
2349 MVT SrcVT = N.getValueType();
2350 MVT DestVT = TLI.getValueType(I.getType());
2351 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002352 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002353 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002354 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Dale Johannesen66978ee2009-01-31 02:22:37 +00002355 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002356 DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002357}
2358
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002359void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002360 SDValue N = getValue(I.getOperand(0));
2361 MVT DestVT = TLI.getValueType(I.getType());
2362
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002363 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002364 // is either a BIT_CONVERT or a no-op.
2365 if (DestVT != N.getValueType())
Dale Johannesen66978ee2009-01-31 02:22:37 +00002366 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002367 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002368 else
2369 setValue(&I, N); // noop cast.
2370}
2371
2372void SelectionDAGLowering::visitInsertElement(User &I) {
2373 SDValue InVec = getValue(I.getOperand(0));
2374 SDValue InVal = getValue(I.getOperand(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002375 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002376 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002377 getValue(I.getOperand(2)));
2378
Dale Johannesen66978ee2009-01-31 02:22:37 +00002379 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002380 TLI.getValueType(I.getType()),
2381 InVec, InVal, InIdx));
2382}
2383
2384void SelectionDAGLowering::visitExtractElement(User &I) {
2385 SDValue InVec = getValue(I.getOperand(0));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002386 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002387 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002388 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002389 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002390 TLI.getValueType(I.getType()), InVec, InIdx));
2391}
2392
Mon P Wangaeb06d22008-11-10 04:46:22 +00002393
2394// Utility for visitShuffleVector - Returns true if the mask is mask starting
2395// from SIndx and increasing to the element length (undefs are allowed).
2396static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002397 unsigned MaskNumElts = Mask.getNumOperands();
2398 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002399 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2400 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2401 if (Idx != i + SIndx)
2402 return false;
2403 }
2404 }
2405 return true;
2406}
2407
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002408void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002409 SDValue Src1 = getValue(I.getOperand(0));
2410 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002411 SDValue Mask = getValue(I.getOperand(2));
2412
Mon P Wangaeb06d22008-11-10 04:46:22 +00002413 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002414 MVT SrcVT = Src1.getValueType();
Mon P Wangc7849c22008-11-16 05:06:27 +00002415 int MaskNumElts = Mask.getNumOperands();
2416 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002417
Mon P Wangc7849c22008-11-16 05:06:27 +00002418 if (SrcNumElts == MaskNumElts) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002419 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002420 VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002421 return;
2422 }
2423
2424 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002425 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2426
2427 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2428 // Mask is longer than the source vectors and is a multiple of the source
2429 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002430 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002431 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2432 // The shuffle is concatenating two vectors together.
Dale Johannesen66978ee2009-01-31 02:22:37 +00002433 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002434 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002435 return;
2436 }
2437
Mon P Wangc7849c22008-11-16 05:06:27 +00002438 // Pad both vectors with undefs to make them the same length as the mask.
2439 unsigned NumConcat = MaskNumElts / SrcNumElts;
Dale Johannesen66978ee2009-01-31 02:22:37 +00002440 SDValue UndefVal = DAG.getNode(ISD::UNDEF, getCurDebugLoc(), SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002441
Mon P Wang230e4fa2008-11-21 04:25:21 +00002442 SDValue* MOps1 = new SDValue[NumConcat];
2443 SDValue* MOps2 = new SDValue[NumConcat];
2444 MOps1[0] = Src1;
2445 MOps2[0] = Src2;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002446 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002447 MOps1[i] = UndefVal;
2448 MOps2[i] = UndefVal;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002449 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00002450 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002451 VT, MOps1, NumConcat);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002452 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002453 VT, MOps2, NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002454
2455 delete [] MOps1;
2456 delete [] MOps2;
2457
Mon P Wangaeb06d22008-11-10 04:46:22 +00002458 // Readjust mask for new input vector length.
2459 SmallVector<SDValue, 8> MappedOps;
Mon P Wangc7849c22008-11-16 05:06:27 +00002460 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002461 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2462 MappedOps.push_back(Mask.getOperand(i));
2463 } else {
Mon P Wangc7849c22008-11-16 05:06:27 +00002464 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2465 if (Idx < SrcNumElts)
2466 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2467 else
2468 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2469 MaskEltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002470 }
2471 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00002472 Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002473 Mask.getValueType(),
Mon P Wangaeb06d22008-11-10 04:46:22 +00002474 &MappedOps[0], MappedOps.size());
2475
Dale Johannesen66978ee2009-01-31 02:22:37 +00002476 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002477 VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002478 return;
2479 }
2480
Mon P Wangc7849c22008-11-16 05:06:27 +00002481 if (SrcNumElts > MaskNumElts) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002482 // Resulting vector is shorter than the incoming vector.
Mon P Wangc7849c22008-11-16 05:06:27 +00002483 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002484 // Shuffle extracts 1st vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002485 setValue(&I, Src1);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002486 return;
2487 }
2488
Mon P Wangc7849c22008-11-16 05:06:27 +00002489 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002490 // Shuffle extracts 2nd vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002491 setValue(&I, Src2);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002492 return;
2493 }
2494
Mon P Wangc7849c22008-11-16 05:06:27 +00002495 // Analyze the access pattern of the vector to see if we can extract
2496 // two subvectors and do the shuffle. The analysis is done by calculating
2497 // the range of elements the mask access on both vectors.
2498 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2499 int MaxRange[2] = {-1, -1};
2500
2501 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002502 SDValue Arg = Mask.getOperand(i);
2503 if (Arg.getOpcode() != ISD::UNDEF) {
2504 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002505 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2506 int Input = 0;
2507 if (Idx >= SrcNumElts) {
2508 Input = 1;
2509 Idx -= SrcNumElts;
2510 }
2511 if (Idx > MaxRange[Input])
2512 MaxRange[Input] = Idx;
2513 if (Idx < MinRange[Input])
2514 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002515 }
2516 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002517
Mon P Wangc7849c22008-11-16 05:06:27 +00002518 // Check if the access is smaller than the vector size and can we find
2519 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002520 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002521 int StartIdx[2]; // StartIdx to extract from
2522 for (int Input=0; Input < 2; ++Input) {
2523 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2524 RangeUse[Input] = 0; // Unused
2525 StartIdx[Input] = 0;
2526 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2527 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002528 // start index that is a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002529 if (MaxRange[Input] < MaskNumElts) {
2530 RangeUse[Input] = 1; // Extract from beginning of the vector
2531 StartIdx[Input] = 0;
2532 } else {
2533 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang6cce3da2008-11-23 04:35:05 +00002534 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002535 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002536 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002537 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002538 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002539 }
2540
2541 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002542 setValue(&I, DAG.getNode(ISD::UNDEF,
Dale Johannesen66978ee2009-01-31 02:22:37 +00002543 getCurDebugLoc(), VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002544 return;
2545 }
2546 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2547 // Extract appropriate subvector and generate a vector shuffle
2548 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002549 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002550 if (RangeUse[Input] == 0) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002551 Src = DAG.getNode(ISD::UNDEF, getCurDebugLoc(), VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002552 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002553 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002554 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002555 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002556 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002557 // Calculate new mask.
2558 SmallVector<SDValue, 8> MappedOps;
2559 for (int i = 0; i != MaskNumElts; ++i) {
2560 SDValue Arg = Mask.getOperand(i);
2561 if (Arg.getOpcode() == ISD::UNDEF) {
2562 MappedOps.push_back(Arg);
2563 } else {
2564 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2565 if (Idx < SrcNumElts)
2566 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2567 else {
2568 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2569 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002570 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002571 }
2572 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00002573 Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002574 Mask.getValueType(),
Mon P Wangc7849c22008-11-16 05:06:27 +00002575 &MappedOps[0], MappedOps.size());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002576 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002577 VT, Src1, Src2, Mask));
Mon P Wangc7849c22008-11-16 05:06:27 +00002578 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002579 }
2580 }
2581
Mon P Wangc7849c22008-11-16 05:06:27 +00002582 // We can't use either concat vectors or extract subvectors so fall back to
2583 // replacing the shuffle with extract and build vector.
2584 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002585 MVT EltVT = VT.getVectorElementType();
2586 MVT PtrVT = TLI.getPointerTy();
2587 SmallVector<SDValue,8> Ops;
Mon P Wangc7849c22008-11-16 05:06:27 +00002588 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002589 SDValue Arg = Mask.getOperand(i);
2590 if (Arg.getOpcode() == ISD::UNDEF) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002591 Ops.push_back(DAG.getNode(ISD::UNDEF, getCurDebugLoc(), EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002592 } else {
2593 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002594 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2595 if (Idx < SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002596 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002597 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002598 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002599 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002600 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002601 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002602 }
2603 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00002604 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002605 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002606}
2607
2608void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2609 const Value *Op0 = I.getOperand(0);
2610 const Value *Op1 = I.getOperand(1);
2611 const Type *AggTy = I.getType();
2612 const Type *ValTy = Op1->getType();
2613 bool IntoUndef = isa<UndefValue>(Op0);
2614 bool FromUndef = isa<UndefValue>(Op1);
2615
2616 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2617 I.idx_begin(), I.idx_end());
2618
2619 SmallVector<MVT, 4> AggValueVTs;
2620 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2621 SmallVector<MVT, 4> ValValueVTs;
2622 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2623
2624 unsigned NumAggValues = AggValueVTs.size();
2625 unsigned NumValValues = ValValueVTs.size();
2626 SmallVector<SDValue, 4> Values(NumAggValues);
2627
2628 SDValue Agg = getValue(Op0);
2629 SDValue Val = getValue(Op1);
2630 unsigned i = 0;
2631 // Copy the beginning value(s) from the original aggregate.
2632 for (; i != LinearIndex; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002633 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002634 AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002635 SDValue(Agg.getNode(), Agg.getResNo() + i);
2636 // Copy values from the inserted value(s).
2637 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002638 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002639 AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002640 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2641 // Copy remaining value(s) from the original aggregate.
2642 for (; i != NumAggValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002643 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002644 AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002645 SDValue(Agg.getNode(), Agg.getResNo() + i);
2646
Dale Johannesen66978ee2009-01-31 02:22:37 +00002647 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002648 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2649 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002650}
2651
2652void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2653 const Value *Op0 = I.getOperand(0);
2654 const Type *AggTy = Op0->getType();
2655 const Type *ValTy = I.getType();
2656 bool OutOfUndef = isa<UndefValue>(Op0);
2657
2658 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2659 I.idx_begin(), I.idx_end());
2660
2661 SmallVector<MVT, 4> ValValueVTs;
2662 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2663
2664 unsigned NumValValues = ValValueVTs.size();
2665 SmallVector<SDValue, 4> Values(NumValValues);
2666
2667 SDValue Agg = getValue(Op0);
2668 // Copy out the selected value(s).
2669 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2670 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002671 OutOfUndef ?
Dale Johannesen66978ee2009-01-31 02:22:37 +00002672 DAG.getNode(ISD::UNDEF, getCurDebugLoc(),
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002673 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2674 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002675
Dale Johannesen66978ee2009-01-31 02:22:37 +00002676 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002677 DAG.getVTList(&ValValueVTs[0], NumValValues),
2678 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002679}
2680
2681
2682void SelectionDAGLowering::visitGetElementPtr(User &I) {
2683 SDValue N = getValue(I.getOperand(0));
2684 const Type *Ty = I.getOperand(0)->getType();
2685
2686 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2687 OI != E; ++OI) {
2688 Value *Idx = *OI;
2689 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2690 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2691 if (Field) {
2692 // N = N + Offset
2693 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002694 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002695 DAG.getIntPtrConstant(Offset));
2696 }
2697 Ty = StTy->getElementType(Field);
2698 } else {
2699 Ty = cast<SequentialType>(Ty)->getElementType();
2700
2701 // If this is a constant subscript, handle it quickly.
2702 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2703 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002704 uint64_t Offs =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002705 TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Dale Johannesen66978ee2009-01-31 02:22:37 +00002706 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002707 DAG.getIntPtrConstant(Offs));
2708 continue;
2709 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002710
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002711 // N = N + Idx * ElementSize;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002712 uint64_t ElementSize = TD->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002713 SDValue IdxN = getValue(Idx);
2714
2715 // If the index is smaller or larger than intptr_t, truncate or extend
2716 // it.
2717 if (IdxN.getValueType().bitsLT(N.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002718 IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002719 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002720 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002721 IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002722 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002723
2724 // If this is a multiply by a power of two, turn it into a shl
2725 // immediately. This is a very common case.
2726 if (ElementSize != 1) {
2727 if (isPowerOf2_64(ElementSize)) {
2728 unsigned Amt = Log2_64(ElementSize);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002729 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002730 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002731 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002732 } else {
2733 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002734 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002735 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002736 }
2737 }
2738
Dale Johannesen66978ee2009-01-31 02:22:37 +00002739 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002740 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002741 }
2742 }
2743 setValue(&I, N);
2744}
2745
2746void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2747 // If this is a fixed sized alloca in the entry block of the function,
2748 // allocate it statically on the stack.
2749 if (FuncInfo.StaticAllocaMap.count(&I))
2750 return; // getValue will auto-populate this.
2751
2752 const Type *Ty = I.getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002753 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002754 unsigned Align =
2755 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2756 I.getAlignment());
2757
2758 SDValue AllocSize = getValue(I.getArraySize());
2759 MVT IntPtr = TLI.getPointerTy();
2760 if (IntPtr.bitsLT(AllocSize.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002761 AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002762 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002763 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002764 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002765 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002766
Dale Johannesen66978ee2009-01-31 02:22:37 +00002767 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr, AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002768 DAG.getIntPtrConstant(TySize));
2769
2770 // Handle alignment. If the requested alignment is less than or equal to
2771 // the stack alignment, ignore it. If the size is greater than or equal to
2772 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2773 unsigned StackAlign =
2774 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2775 if (Align <= StackAlign)
2776 Align = 0;
2777
2778 // Round the size of the allocation up to the stack alignment size
2779 // by add SA-1 to the size.
Dale Johannesen66978ee2009-01-31 02:22:37 +00002780 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002781 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002782 DAG.getIntPtrConstant(StackAlign-1));
2783 // Mask out the low bits for alignment purposes.
Dale Johannesen66978ee2009-01-31 02:22:37 +00002784 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002785 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002786 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2787
2788 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2789 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2790 MVT::Other);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002791 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002792 VTs, 2, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002793 setValue(&I, DSA);
2794 DAG.setRoot(DSA.getValue(1));
2795
2796 // Inform the Frame Information that we have just allocated a variable-sized
2797 // object.
2798 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2799}
2800
2801void SelectionDAGLowering::visitLoad(LoadInst &I) {
2802 const Value *SV = I.getOperand(0);
2803 SDValue Ptr = getValue(SV);
2804
2805 const Type *Ty = I.getType();
2806 bool isVolatile = I.isVolatile();
2807 unsigned Alignment = I.getAlignment();
2808
2809 SmallVector<MVT, 4> ValueVTs;
2810 SmallVector<uint64_t, 4> Offsets;
2811 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2812 unsigned NumValues = ValueVTs.size();
2813 if (NumValues == 0)
2814 return;
2815
2816 SDValue Root;
2817 bool ConstantMemory = false;
2818 if (I.isVolatile())
2819 // Serialize volatile loads with other side effects.
2820 Root = getRoot();
2821 else if (AA->pointsToConstantMemory(SV)) {
2822 // Do not serialize (non-volatile) loads of constant memory with anything.
2823 Root = DAG.getEntryNode();
2824 ConstantMemory = true;
2825 } else {
2826 // Do not serialize non-volatile loads against each other.
2827 Root = DAG.getRoot();
2828 }
2829
2830 SmallVector<SDValue, 4> Values(NumValues);
2831 SmallVector<SDValue, 4> Chains(NumValues);
2832 MVT PtrVT = Ptr.getValueType();
2833 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002834 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2835 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002836 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002837 DAG.getConstant(Offsets[i], PtrVT)),
2838 SV, Offsets[i],
2839 isVolatile, Alignment);
2840 Values[i] = L;
2841 Chains[i] = L.getValue(1);
2842 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002843
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002844 if (!ConstantMemory) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002845 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002846 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002847 &Chains[0], NumValues);
2848 if (isVolatile)
2849 DAG.setRoot(Chain);
2850 else
2851 PendingLoads.push_back(Chain);
2852 }
2853
Dale Johannesen66978ee2009-01-31 02:22:37 +00002854 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002855 DAG.getVTList(&ValueVTs[0], NumValues),
2856 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002857}
2858
2859
2860void SelectionDAGLowering::visitStore(StoreInst &I) {
2861 Value *SrcV = I.getOperand(0);
2862 Value *PtrV = I.getOperand(1);
2863
2864 SmallVector<MVT, 4> ValueVTs;
2865 SmallVector<uint64_t, 4> Offsets;
2866 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2867 unsigned NumValues = ValueVTs.size();
2868 if (NumValues == 0)
2869 return;
2870
2871 // Get the lowered operands. Note that we do this after
2872 // checking if NumResults is zero, because with zero results
2873 // the operands won't have values in the map.
2874 SDValue Src = getValue(SrcV);
2875 SDValue Ptr = getValue(PtrV);
2876
2877 SDValue Root = getRoot();
2878 SmallVector<SDValue, 4> Chains(NumValues);
2879 MVT PtrVT = Ptr.getValueType();
2880 bool isVolatile = I.isVolatile();
2881 unsigned Alignment = I.getAlignment();
2882 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002883 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002884 SDValue(Src.getNode(), Src.getResNo() + i),
Dale Johannesen66978ee2009-01-31 02:22:37 +00002885 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002886 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002887 DAG.getConstant(Offsets[i], PtrVT)),
2888 PtrV, Offsets[i],
2889 isVolatile, Alignment);
2890
Dale Johannesen66978ee2009-01-31 02:22:37 +00002891 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002892 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002893}
2894
2895/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2896/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002897void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002898 unsigned Intrinsic) {
2899 bool HasChain = !I.doesNotAccessMemory();
2900 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2901
2902 // Build the operand list.
2903 SmallVector<SDValue, 8> Ops;
2904 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2905 if (OnlyLoad) {
2906 // We don't need to serialize loads against other loads.
2907 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002908 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002909 Ops.push_back(getRoot());
2910 }
2911 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002912
2913 // Info is set by getTgtMemInstrinsic
2914 TargetLowering::IntrinsicInfo Info;
2915 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2916
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002917 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002918 if (!IsTgtIntrinsic)
2919 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002920
2921 // Add all operands of the call to the operand list.
2922 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2923 SDValue Op = getValue(I.getOperand(i));
2924 assert(TLI.isTypeLegal(Op.getValueType()) &&
2925 "Intrinsic uses a non-legal type?");
2926 Ops.push_back(Op);
2927 }
2928
2929 std::vector<MVT> VTs;
2930 if (I.getType() != Type::VoidTy) {
2931 MVT VT = TLI.getValueType(I.getType());
2932 if (VT.isVector()) {
2933 const VectorType *DestTy = cast<VectorType>(I.getType());
2934 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002935
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002936 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2937 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2938 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002939
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002940 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2941 VTs.push_back(VT);
2942 }
2943 if (HasChain)
2944 VTs.push_back(MVT::Other);
2945
2946 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2947
2948 // Create the node.
2949 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002950 if (IsTgtIntrinsic) {
2951 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002952 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002953 VTList, VTs.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002954 &Ops[0], Ops.size(),
2955 Info.memVT, Info.ptrVal, Info.offset,
2956 Info.align, Info.vol,
2957 Info.readMem, Info.writeMem);
2958 }
2959 else if (!HasChain)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002960 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002961 VTList, VTs.size(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002962 &Ops[0], Ops.size());
2963 else if (I.getType() != Type::VoidTy)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002964 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002965 VTList, VTs.size(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002966 &Ops[0], Ops.size());
2967 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002968 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002969 VTList, VTs.size(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002970 &Ops[0], Ops.size());
2971
2972 if (HasChain) {
2973 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2974 if (OnlyLoad)
2975 PendingLoads.push_back(Chain);
2976 else
2977 DAG.setRoot(Chain);
2978 }
2979 if (I.getType() != Type::VoidTy) {
2980 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2981 MVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002982 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002983 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002984 setValue(&I, Result);
2985 }
2986}
2987
2988/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2989static GlobalVariable *ExtractTypeInfo(Value *V) {
2990 V = V->stripPointerCasts();
2991 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2992 assert ((GV || isa<ConstantPointerNull>(V)) &&
2993 "TypeInfo must be a global variable or NULL");
2994 return GV;
2995}
2996
2997namespace llvm {
2998
2999/// AddCatchInfo - Extract the personality and type infos from an eh.selector
3000/// call, and add them to the specified machine basic block.
3001void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3002 MachineBasicBlock *MBB) {
3003 // Inform the MachineModuleInfo of the personality for this landing pad.
3004 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3005 assert(CE->getOpcode() == Instruction::BitCast &&
3006 isa<Function>(CE->getOperand(0)) &&
3007 "Personality should be a function");
3008 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3009
3010 // Gather all the type infos for this landing pad and pass them along to
3011 // MachineModuleInfo.
3012 std::vector<GlobalVariable *> TyInfo;
3013 unsigned N = I.getNumOperands();
3014
3015 for (unsigned i = N - 1; i > 2; --i) {
3016 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3017 unsigned FilterLength = CI->getZExtValue();
3018 unsigned FirstCatch = i + FilterLength + !FilterLength;
3019 assert (FirstCatch <= N && "Invalid filter length");
3020
3021 if (FirstCatch < N) {
3022 TyInfo.reserve(N - FirstCatch);
3023 for (unsigned j = FirstCatch; j < N; ++j)
3024 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3025 MMI->addCatchTypeInfo(MBB, TyInfo);
3026 TyInfo.clear();
3027 }
3028
3029 if (!FilterLength) {
3030 // Cleanup.
3031 MMI->addCleanup(MBB);
3032 } else {
3033 // Filter.
3034 TyInfo.reserve(FilterLength - 1);
3035 for (unsigned j = i + 1; j < FirstCatch; ++j)
3036 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3037 MMI->addFilterTypeInfo(MBB, TyInfo);
3038 TyInfo.clear();
3039 }
3040
3041 N = i;
3042 }
3043 }
3044
3045 if (N > 3) {
3046 TyInfo.reserve(N - 3);
3047 for (unsigned j = 3; j < N; ++j)
3048 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3049 MMI->addCatchTypeInfo(MBB, TyInfo);
3050 }
3051}
3052
3053}
3054
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003055/// GetSignificand - Get the significand and build it into a floating-point
3056/// number with exponent of 1:
3057///
3058/// Op = (Op & 0x007fffff) | 0x3f800000;
3059///
3060/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003061static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003062GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3063 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003064 DAG.getConstant(0x007fffff, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003065 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003066 DAG.getConstant(0x3f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003067 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003068}
3069
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003070/// GetExponent - Get the exponent:
3071///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003072/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003073///
3074/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003075static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003076GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3077 DebugLoc dl) {
3078 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003079 DAG.getConstant(0x7f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003080 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003081 DAG.getConstant(23, TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003082 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003083 DAG.getConstant(127, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003084 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003085}
3086
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003087/// getF32Constant - Get 32-bit floating point constant.
3088static SDValue
3089getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3090 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3091}
3092
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003093/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003094/// visitIntrinsicCall: I is a call instruction
3095/// Op is the associated NodeType for I
3096const char *
3097SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003098 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003099 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003100 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003101 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003102 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003103 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003104 getValue(I.getOperand(2)),
3105 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003106 setValue(&I, L);
3107 DAG.setRoot(L.getValue(1));
3108 return 0;
3109}
3110
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003111// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003112const char *
3113SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003114 SDValue Op1 = getValue(I.getOperand(1));
3115 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003116
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003117 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
3118 SDValue Ops[] = { Op1, Op2 };
Bill Wendling74c37652008-12-09 22:08:41 +00003119
Dale Johannesen66978ee2009-01-31 02:22:37 +00003120 SDValue Result = DAG.getNode(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003121 DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
Bill Wendling74c37652008-12-09 22:08:41 +00003122
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003123 setValue(&I, Result);
3124 return 0;
3125}
Bill Wendling74c37652008-12-09 22:08:41 +00003126
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003127/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3128/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003129void
3130SelectionDAGLowering::visitExp(CallInst &I) {
3131 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003132 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003133
3134 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3135 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3136 SDValue Op = getValue(I.getOperand(1));
3137
3138 // Put the exponent in the right bit position for later addition to the
3139 // final result:
3140 //
3141 // #define LOG2OFe 1.4426950f
3142 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003143 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003144 getF32Constant(DAG, 0x3fb8aa3b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003145 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003146
3147 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003148 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3149 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003150
3151 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003152 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003153 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003154
3155 if (LimitFloatPrecision <= 6) {
3156 // For floating-point precision of 6:
3157 //
3158 // TwoToFractionalPartOfX =
3159 // 0.997535578f +
3160 // (0.735607626f + 0.252464424f * x) * x;
3161 //
3162 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003163 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003164 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003165 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003166 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003167 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3168 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003169 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003170 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003171
3172 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003173 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003174 TwoToFracPartOfX, IntegerPartOfX);
3175
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003176 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003177 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3178 // For floating-point precision of 12:
3179 //
3180 // TwoToFractionalPartOfX =
3181 // 0.999892986f +
3182 // (0.696457318f +
3183 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3184 //
3185 // 0.000107046256 error, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003186 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003187 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003188 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003189 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003190 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3191 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003192 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003193 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3194 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003195 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003196 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003197
3198 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003199 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003200 TwoToFracPartOfX, IntegerPartOfX);
3201
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003202 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003203 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3204 // For floating-point precision of 18:
3205 //
3206 // TwoToFractionalPartOfX =
3207 // 0.999999982f +
3208 // (0.693148872f +
3209 // (0.240227044f +
3210 // (0.554906021e-1f +
3211 // (0.961591928e-2f +
3212 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3213 //
3214 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003215 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003216 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003217 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003218 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003219 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3220 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003221 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003222 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3223 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003224 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003225 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3226 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003227 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003228 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3229 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003230 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003231 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3232 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003233 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003234 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3235 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003236
3237 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003238 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003239 TwoToFracPartOfX, IntegerPartOfX);
3240
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003241 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003242 }
3243 } else {
3244 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003245 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003246 getValue(I.getOperand(1)).getValueType(),
3247 getValue(I.getOperand(1)));
3248 }
3249
Dale Johannesen59e577f2008-09-05 18:38:42 +00003250 setValue(&I, result);
3251}
3252
Bill Wendling39150252008-09-09 20:39:27 +00003253/// visitLog - Lower a log intrinsic. Handles the special sequences for
3254/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003255void
3256SelectionDAGLowering::visitLog(CallInst &I) {
3257 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003258 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003259
3260 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3261 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3262 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003263 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003264
3265 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003266 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003267 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003268 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003269
3270 // Get the significand and build it into a floating-point number with
3271 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003272 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003273
3274 if (LimitFloatPrecision <= 6) {
3275 // For floating-point precision of 6:
3276 //
3277 // LogofMantissa =
3278 // -1.1609546f +
3279 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003280 //
Bill Wendling39150252008-09-09 20:39:27 +00003281 // error 0.0034276066, which is better than 8 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003282 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003283 getF32Constant(DAG, 0xbe74c456));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003284 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003285 getF32Constant(DAG, 0x3fb3a2b1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003286 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3287 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003288 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003289
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003290 result = DAG.getNode(ISD::FADD, dl,
3291 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003292 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3293 // For floating-point precision of 12:
3294 //
3295 // LogOfMantissa =
3296 // -1.7417939f +
3297 // (2.8212026f +
3298 // (-1.4699568f +
3299 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3300 //
3301 // error 0.000061011436, which is 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003302 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003303 getF32Constant(DAG, 0xbd67b6d6));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003304 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003305 getF32Constant(DAG, 0x3ee4f4b8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003306 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3307 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003308 getF32Constant(DAG, 0x3fbc278b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003309 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3310 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003311 getF32Constant(DAG, 0x40348e95));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003312 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3313 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003314 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003315
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003316 result = DAG.getNode(ISD::FADD, dl,
3317 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003318 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3319 // For floating-point precision of 18:
3320 //
3321 // LogOfMantissa =
3322 // -2.1072184f +
3323 // (4.2372794f +
3324 // (-3.7029485f +
3325 // (2.2781945f +
3326 // (-0.87823314f +
3327 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3328 //
3329 // error 0.0000023660568, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003330 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003331 getF32Constant(DAG, 0xbc91e5ac));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003332 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003333 getF32Constant(DAG, 0x3e4350aa));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003334 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3335 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003336 getF32Constant(DAG, 0x3f60d3e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003337 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3338 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003339 getF32Constant(DAG, 0x4011cdf0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003340 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3341 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003342 getF32Constant(DAG, 0x406cfd1c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003343 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3344 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003345 getF32Constant(DAG, 0x408797cb));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003346 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3347 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003348 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003349
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003350 result = DAG.getNode(ISD::FADD, dl,
3351 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003352 }
3353 } else {
3354 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003355 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003356 getValue(I.getOperand(1)).getValueType(),
3357 getValue(I.getOperand(1)));
3358 }
3359
Dale Johannesen59e577f2008-09-05 18:38:42 +00003360 setValue(&I, result);
3361}
3362
Bill Wendling3eb59402008-09-09 00:28:24 +00003363/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3364/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003365void
3366SelectionDAGLowering::visitLog2(CallInst &I) {
3367 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003368 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003369
Dale Johannesen853244f2008-09-05 23:49:37 +00003370 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003371 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3372 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003373 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003374
Bill Wendling39150252008-09-09 20:39:27 +00003375 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003376 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003377
3378 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003379 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003380 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003381
Bill Wendling3eb59402008-09-09 00:28:24 +00003382 // Different possible minimax approximations of significand in
3383 // floating-point for various degrees of accuracy over [1,2].
3384 if (LimitFloatPrecision <= 6) {
3385 // For floating-point precision of 6:
3386 //
3387 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3388 //
3389 // error 0.0049451742, which is more than 7 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003390 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003391 getF32Constant(DAG, 0xbeb08fe0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003392 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003393 getF32Constant(DAG, 0x40019463));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003394 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3395 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003396 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003397
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003398 result = DAG.getNode(ISD::FADD, dl,
3399 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003400 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3401 // For floating-point precision of 12:
3402 //
3403 // Log2ofMantissa =
3404 // -2.51285454f +
3405 // (4.07009056f +
3406 // (-2.12067489f +
3407 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003408 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003409 // error 0.0000876136000, which is better than 13 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003410 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003411 getF32Constant(DAG, 0xbda7262e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003412 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003413 getF32Constant(DAG, 0x3f25280b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003414 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3415 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003416 getF32Constant(DAG, 0x4007b923));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003417 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3418 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003419 getF32Constant(DAG, 0x40823e2f));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003420 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3421 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003422 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003423
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003424 result = DAG.getNode(ISD::FADD, dl,
3425 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003426 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3427 // For floating-point precision of 18:
3428 //
3429 // Log2ofMantissa =
3430 // -3.0400495f +
3431 // (6.1129976f +
3432 // (-5.3420409f +
3433 // (3.2865683f +
3434 // (-1.2669343f +
3435 // (0.27515199f -
3436 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3437 //
3438 // error 0.0000018516, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003439 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003440 getF32Constant(DAG, 0xbcd2769e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003441 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003442 getF32Constant(DAG, 0x3e8ce0b9));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003443 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3444 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003445 getF32Constant(DAG, 0x3fa22ae7));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003446 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3447 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003448 getF32Constant(DAG, 0x40525723));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003449 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3450 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003451 getF32Constant(DAG, 0x40aaf200));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003452 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3453 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003454 getF32Constant(DAG, 0x40c39dad));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003455 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3456 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003457 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003458
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003459 result = DAG.getNode(ISD::FADD, dl,
3460 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003461 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003462 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003463 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003464 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003465 getValue(I.getOperand(1)).getValueType(),
3466 getValue(I.getOperand(1)));
3467 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003468
Dale Johannesen59e577f2008-09-05 18:38:42 +00003469 setValue(&I, result);
3470}
3471
Bill Wendling3eb59402008-09-09 00:28:24 +00003472/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3473/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003474void
3475SelectionDAGLowering::visitLog10(CallInst &I) {
3476 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003477 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003478
Dale Johannesen852680a2008-09-05 21:27:19 +00003479 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003480 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3481 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003482 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003483
Bill Wendling39150252008-09-09 20:39:27 +00003484 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003485 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003486 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003487 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003488
3489 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003490 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003491 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003492
3493 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003494 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003495 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003496 // Log10ofMantissa =
3497 // -0.50419619f +
3498 // (0.60948995f - 0.10380950f * x) * x;
3499 //
3500 // error 0.0014886165, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003501 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003502 getF32Constant(DAG, 0xbdd49a13));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003503 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003504 getF32Constant(DAG, 0x3f1c0789));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003505 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3506 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003507 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003508
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003509 result = DAG.getNode(ISD::FADD, dl,
3510 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003511 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3512 // For floating-point precision of 12:
3513 //
3514 // Log10ofMantissa =
3515 // -0.64831180f +
3516 // (0.91751397f +
3517 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3518 //
3519 // error 0.00019228036, which is better than 12 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003520 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003521 getF32Constant(DAG, 0x3d431f31));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003522 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003523 getF32Constant(DAG, 0x3ea21fb2));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003524 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3525 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003526 getF32Constant(DAG, 0x3f6ae232));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003527 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3528 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003529 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003530
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003531 result = DAG.getNode(ISD::FADD, dl,
3532 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003533 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003534 // For floating-point precision of 18:
3535 //
3536 // Log10ofMantissa =
3537 // -0.84299375f +
3538 // (1.5327582f +
3539 // (-1.0688956f +
3540 // (0.49102474f +
3541 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3542 //
3543 // error 0.0000037995730, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003544 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003545 getF32Constant(DAG, 0x3c5d51ce));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003546 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003547 getF32Constant(DAG, 0x3e00685a));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003548 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3549 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003550 getF32Constant(DAG, 0x3efb6798));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003551 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3552 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003553 getF32Constant(DAG, 0x3f88d192));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003554 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3555 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003556 getF32Constant(DAG, 0x3fc4316c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003557 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3558 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003559 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003560
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003561 result = DAG.getNode(ISD::FADD, dl,
3562 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003563 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003564 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003565 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003566 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003567 getValue(I.getOperand(1)).getValueType(),
3568 getValue(I.getOperand(1)));
3569 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003570
Dale Johannesen59e577f2008-09-05 18:38:42 +00003571 setValue(&I, result);
3572}
3573
Bill Wendlinge10c8142008-09-09 22:39:21 +00003574/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3575/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003576void
3577SelectionDAGLowering::visitExp2(CallInst &I) {
3578 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003579 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003580
Dale Johannesen601d3c02008-09-05 01:48:15 +00003581 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003582 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3583 SDValue Op = getValue(I.getOperand(1));
3584
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003585 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003586
3587 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003588 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3589 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003590
3591 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003592 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003593 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003594
3595 if (LimitFloatPrecision <= 6) {
3596 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003597 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003598 // TwoToFractionalPartOfX =
3599 // 0.997535578f +
3600 // (0.735607626f + 0.252464424f * x) * x;
3601 //
3602 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003603 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003604 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003605 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003606 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003607 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3608 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003609 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003610 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003611 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003612 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003613
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003614 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3615 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003616 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3617 // For floating-point precision of 12:
3618 //
3619 // TwoToFractionalPartOfX =
3620 // 0.999892986f +
3621 // (0.696457318f +
3622 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3623 //
3624 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003625 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003626 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003627 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003628 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003629 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3630 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003631 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003632 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3633 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003634 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003635 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003636 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003637 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003638
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003639 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3640 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003641 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3642 // For floating-point precision of 18:
3643 //
3644 // TwoToFractionalPartOfX =
3645 // 0.999999982f +
3646 // (0.693148872f +
3647 // (0.240227044f +
3648 // (0.554906021e-1f +
3649 // (0.961591928e-2f +
3650 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3651 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003652 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003653 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003654 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003655 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003656 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3657 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003658 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003659 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3660 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003661 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003662 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3663 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003664 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003665 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3666 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003667 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003668 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3669 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003670 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003671 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003672 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003673 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003674
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003675 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3676 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003677 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003678 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003679 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003680 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003681 getValue(I.getOperand(1)).getValueType(),
3682 getValue(I.getOperand(1)));
3683 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003684
Dale Johannesen601d3c02008-09-05 01:48:15 +00003685 setValue(&I, result);
3686}
3687
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003688/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3689/// limited-precision mode with x == 10.0f.
3690void
3691SelectionDAGLowering::visitPow(CallInst &I) {
3692 SDValue result;
3693 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003694 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003695 bool IsExp10 = false;
3696
3697 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003698 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003699 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3700 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3701 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3702 APFloat Ten(10.0f);
3703 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3704 }
3705 }
3706 }
3707
3708 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3709 SDValue Op = getValue(I.getOperand(2));
3710
3711 // Put the exponent in the right bit position for later addition to the
3712 // final result:
3713 //
3714 // #define LOG2OF10 3.3219281f
3715 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003716 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003717 getF32Constant(DAG, 0x40549a78));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003718 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003719
3720 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003721 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3722 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003723
3724 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003725 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003726 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003727
3728 if (LimitFloatPrecision <= 6) {
3729 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003730 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003731 // twoToFractionalPartOfX =
3732 // 0.997535578f +
3733 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003734 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003735 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003736 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003737 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003738 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003739 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003740 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3741 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003742 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003743 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003744 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003745 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003746
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003747 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3748 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003749 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3750 // For floating-point precision of 12:
3751 //
3752 // TwoToFractionalPartOfX =
3753 // 0.999892986f +
3754 // (0.696457318f +
3755 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3756 //
3757 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003758 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003759 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003760 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003761 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003762 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3763 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003764 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003765 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3766 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003767 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003768 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003769 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003770 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003771
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003772 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3773 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003774 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3775 // For floating-point precision of 18:
3776 //
3777 // TwoToFractionalPartOfX =
3778 // 0.999999982f +
3779 // (0.693148872f +
3780 // (0.240227044f +
3781 // (0.554906021e-1f +
3782 // (0.961591928e-2f +
3783 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3784 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003785 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003786 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003787 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003788 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003789 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3790 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003791 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003792 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3793 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003794 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003795 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3796 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003797 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003798 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3799 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003800 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003801 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3802 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003803 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003804 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003805 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003806 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003807
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003808 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3809 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003810 }
3811 } else {
3812 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003813 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003814 getValue(I.getOperand(1)).getValueType(),
3815 getValue(I.getOperand(1)),
3816 getValue(I.getOperand(2)));
3817 }
3818
3819 setValue(&I, result);
3820}
3821
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003822/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3823/// we want to emit this as a call to a named external function, return the name
3824/// otherwise lower it and return null.
3825const char *
3826SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003827 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003828 switch (Intrinsic) {
3829 default:
3830 // By default, turn this into a target intrinsic node.
3831 visitTargetIntrinsic(I, Intrinsic);
3832 return 0;
3833 case Intrinsic::vastart: visitVAStart(I); return 0;
3834 case Intrinsic::vaend: visitVAEnd(I); return 0;
3835 case Intrinsic::vacopy: visitVACopy(I); return 0;
3836 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003837 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003838 getValue(I.getOperand(1))));
3839 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003840 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003841 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003842 getValue(I.getOperand(1))));
3843 return 0;
3844 case Intrinsic::setjmp:
3845 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3846 break;
3847 case Intrinsic::longjmp:
3848 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3849 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003850 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003851 SDValue Op1 = getValue(I.getOperand(1));
3852 SDValue Op2 = getValue(I.getOperand(2));
3853 SDValue Op3 = getValue(I.getOperand(3));
3854 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003855 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003856 I.getOperand(1), 0, I.getOperand(2), 0));
3857 return 0;
3858 }
Chris Lattner824b9582008-11-21 16:42:48 +00003859 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003860 SDValue Op1 = getValue(I.getOperand(1));
3861 SDValue Op2 = getValue(I.getOperand(2));
3862 SDValue Op3 = getValue(I.getOperand(3));
3863 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003864 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003865 I.getOperand(1), 0));
3866 return 0;
3867 }
Chris Lattner824b9582008-11-21 16:42:48 +00003868 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003869 SDValue Op1 = getValue(I.getOperand(1));
3870 SDValue Op2 = getValue(I.getOperand(2));
3871 SDValue Op3 = getValue(I.getOperand(3));
3872 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3873
3874 // If the source and destination are known to not be aliases, we can
3875 // lower memmove as memcpy.
3876 uint64_t Size = -1ULL;
3877 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003878 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003879 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3880 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003881 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003882 I.getOperand(1), 0, I.getOperand(2), 0));
3883 return 0;
3884 }
3885
Dale Johannesena04b7572009-02-03 23:04:43 +00003886 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003887 I.getOperand(1), 0, I.getOperand(2), 0));
3888 return 0;
3889 }
3890 case Intrinsic::dbg_stoppoint: {
Devang Patel83489bb2009-01-13 00:35:13 +00003891 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003892 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003893 if (DW && DW->ValidDebugInfo(SPI.getContext())) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003894 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3895 SPI.getLine(),
3896 SPI.getColumn(),
Devang Patel83489bb2009-01-13 00:35:13 +00003897 SPI.getContext()));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003898 DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
3899 unsigned SrcFile = DW->RecordSource(CU.getDirectory(), CU.getFilename());
3900 unsigned idx = DAG.getMachineFunction().
3901 getOrCreateDebugLocID(SrcFile,
3902 SPI.getLine(),
3903 SPI.getColumn());
Dale Johannesen66978ee2009-01-31 02:22:37 +00003904 setCurDebugLoc(DebugLoc::get(idx));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003905 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003906 return 0;
3907 }
3908 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003909 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003910 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Devang Patelb79b5352009-01-19 23:21:49 +00003911 if (DW && DW->ValidDebugInfo(RSI.getContext())) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003912 unsigned LabelID =
Devang Patel83489bb2009-01-13 00:35:13 +00003913 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Dale Johannesen8ad9b432009-02-04 01:17:06 +00003914 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3915 getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003916 }
3917
3918 return 0;
3919 }
3920 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003921 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003922 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patelb79b5352009-01-19 23:21:49 +00003923 if (DW && DW->ValidDebugInfo(REI.getContext())) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003924 unsigned LabelID =
Devang Patel83489bb2009-01-13 00:35:13 +00003925 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
Dale Johannesen8ad9b432009-02-04 01:17:06 +00003926 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3927 getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003928 }
3929
3930 return 0;
3931 }
3932 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003933 DwarfWriter *DW = DAG.getDwarfWriter();
3934 if (!DW) return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003935 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3936 Value *SP = FSI.getSubprogram();
Devang Patelcf3a4482009-01-15 23:41:32 +00003937 if (SP && DW->ValidDebugInfo(SP)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003938 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3939 // what (most?) gdb expects.
Devang Patel83489bb2009-01-13 00:35:13 +00003940 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3941 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
3942 unsigned SrcFile = DW->RecordSource(CompileUnit.getDirectory(),
3943 CompileUnit.getFilename());
Bill Wendling9bc96a52009-02-03 00:55:04 +00003944
Devang Patel20dd0462008-11-06 00:30:09 +00003945 // Record the source line but does not create a label for the normal
3946 // function start. It will be emitted at asm emission time. However,
3947 // create a label if this is a beginning of inlined function.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003948 unsigned Line = Subprogram.getLineNumber();
Bill Wendling9bc96a52009-02-03 00:55:04 +00003949 unsigned LabelID = DW->RecordSourceLine(Line, 0, SrcFile);
3950
Devang Patel83489bb2009-01-13 00:35:13 +00003951 if (DW->getRecordSourceLineCount() != 1)
Dale Johannesen8ad9b432009-02-04 01:17:06 +00003952 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3953 getRoot(), LabelID));
Bill Wendling9bc96a52009-02-03 00:55:04 +00003954
Dale Johannesen66978ee2009-01-31 02:22:37 +00003955 setCurDebugLoc(DebugLoc::get(DAG.getMachineFunction().
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003956 getOrCreateDebugLocID(SrcFile, Line, 0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003957 }
3958
3959 return 0;
3960 }
3961 case Intrinsic::dbg_declare: {
Devang Patel83489bb2009-01-13 00:35:13 +00003962 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003963 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3964 Value *Variable = DI.getVariable();
Devang Patelb79b5352009-01-19 23:21:49 +00003965 if (DW && DW->ValidDebugInfo(Variable))
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003966 DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003967 getValue(DI.getAddress()), getValue(Variable)));
3968 return 0;
3969 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003970
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003971 case Intrinsic::eh_exception: {
3972 if (!CurMBB->isLandingPad()) {
3973 // FIXME: Mark exception register as live in. Hack for PR1508.
3974 unsigned Reg = TLI.getExceptionAddressRegister();
3975 if (Reg) CurMBB->addLiveIn(Reg);
3976 }
3977 // Insert the EXCEPTIONADDR instruction.
3978 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3979 SDValue Ops[1];
3980 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003981 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003982 setValue(&I, Op);
3983 DAG.setRoot(Op.getValue(1));
3984 return 0;
3985 }
3986
3987 case Intrinsic::eh_selector_i32:
3988 case Intrinsic::eh_selector_i64: {
3989 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3990 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3991 MVT::i32 : MVT::i64);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003992
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003993 if (MMI) {
3994 if (CurMBB->isLandingPad())
3995 AddCatchInfo(I, MMI, CurMBB);
3996 else {
3997#ifndef NDEBUG
3998 FuncInfo.CatchInfoLost.insert(&I);
3999#endif
4000 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4001 unsigned Reg = TLI.getExceptionSelectorRegister();
4002 if (Reg) CurMBB->addLiveIn(Reg);
4003 }
4004
4005 // Insert the EHSELECTION instruction.
4006 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4007 SDValue Ops[2];
4008 Ops[0] = getValue(I.getOperand(1));
4009 Ops[1] = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004010 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004011 setValue(&I, Op);
4012 DAG.setRoot(Op.getValue(1));
4013 } else {
4014 setValue(&I, DAG.getConstant(0, VT));
4015 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004016
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004017 return 0;
4018 }
4019
4020 case Intrinsic::eh_typeid_for_i32:
4021 case Intrinsic::eh_typeid_for_i64: {
4022 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4023 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4024 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004025
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004026 if (MMI) {
4027 // Find the type id for the given typeinfo.
4028 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4029
4030 unsigned TypeID = MMI->getTypeIDFor(GV);
4031 setValue(&I, DAG.getConstant(TypeID, VT));
4032 } else {
4033 // Return something different to eh_selector.
4034 setValue(&I, DAG.getConstant(1, VT));
4035 }
4036
4037 return 0;
4038 }
4039
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004040 case Intrinsic::eh_return_i32:
4041 case Intrinsic::eh_return_i64:
4042 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004043 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004044 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004045 MVT::Other,
4046 getControlRoot(),
4047 getValue(I.getOperand(1)),
4048 getValue(I.getOperand(2))));
4049 } else {
4050 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4051 }
4052
4053 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004054 case Intrinsic::eh_unwind_init:
4055 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4056 MMI->setCallsUnwindInit(true);
4057 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004058
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004059 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004060
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004061 case Intrinsic::eh_dwarf_cfa: {
4062 MVT VT = getValue(I.getOperand(1)).getValueType();
4063 SDValue CfaArg;
4064 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004065 CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004066 TLI.getPointerTy(), getValue(I.getOperand(1)));
4067 else
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004068 CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004069 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004070
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004071 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004072 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004073 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004074 TLI.getPointerTy()),
4075 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004076 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004077 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004078 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004079 TLI.getPointerTy(),
4080 DAG.getConstant(0,
4081 TLI.getPointerTy())),
4082 Offset));
4083 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004084 }
4085
Mon P Wang77cdf302008-11-10 20:54:11 +00004086 case Intrinsic::convertff:
4087 case Intrinsic::convertfsi:
4088 case Intrinsic::convertfui:
4089 case Intrinsic::convertsif:
4090 case Intrinsic::convertuif:
4091 case Intrinsic::convertss:
4092 case Intrinsic::convertsu:
4093 case Intrinsic::convertus:
4094 case Intrinsic::convertuu: {
4095 ISD::CvtCode Code = ISD::CVT_INVALID;
4096 switch (Intrinsic) {
4097 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4098 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4099 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4100 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4101 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4102 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4103 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4104 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4105 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4106 }
4107 MVT DestVT = TLI.getValueType(I.getType());
4108 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004109 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004110 DAG.getValueType(DestVT),
4111 DAG.getValueType(getValue(Op1).getValueType()),
4112 getValue(I.getOperand(2)),
4113 getValue(I.getOperand(3)),
4114 Code));
4115 return 0;
4116 }
4117
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004118 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004119 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004120 getValue(I.getOperand(1)).getValueType(),
4121 getValue(I.getOperand(1))));
4122 return 0;
4123 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004124 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004125 getValue(I.getOperand(1)).getValueType(),
4126 getValue(I.getOperand(1)),
4127 getValue(I.getOperand(2))));
4128 return 0;
4129 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004130 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004131 getValue(I.getOperand(1)).getValueType(),
4132 getValue(I.getOperand(1))));
4133 return 0;
4134 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004135 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004136 getValue(I.getOperand(1)).getValueType(),
4137 getValue(I.getOperand(1))));
4138 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004139 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004140 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004141 return 0;
4142 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004143 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004144 return 0;
4145 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004146 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004147 return 0;
4148 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004149 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004150 return 0;
4151 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004152 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004153 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004154 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004155 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004156 return 0;
4157 case Intrinsic::pcmarker: {
4158 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004159 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004160 return 0;
4161 }
4162 case Intrinsic::readcyclecounter: {
4163 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004164 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004165 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4166 &Op, 1);
4167 setValue(&I, Tmp);
4168 DAG.setRoot(Tmp.getValue(1));
4169 return 0;
4170 }
4171 case Intrinsic::part_select: {
4172 // Currently not implemented: just abort
4173 assert(0 && "part_select intrinsic not implemented");
4174 abort();
4175 }
4176 case Intrinsic::part_set: {
4177 // Currently not implemented: just abort
4178 assert(0 && "part_set intrinsic not implemented");
4179 abort();
4180 }
4181 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004182 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004183 getValue(I.getOperand(1)).getValueType(),
4184 getValue(I.getOperand(1))));
4185 return 0;
4186 case Intrinsic::cttz: {
4187 SDValue Arg = getValue(I.getOperand(1));
4188 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004189 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004190 setValue(&I, result);
4191 return 0;
4192 }
4193 case Intrinsic::ctlz: {
4194 SDValue Arg = getValue(I.getOperand(1));
4195 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004196 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004197 setValue(&I, result);
4198 return 0;
4199 }
4200 case Intrinsic::ctpop: {
4201 SDValue Arg = getValue(I.getOperand(1));
4202 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004203 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004204 setValue(&I, result);
4205 return 0;
4206 }
4207 case Intrinsic::stacksave: {
4208 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004209 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004210 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4211 setValue(&I, Tmp);
4212 DAG.setRoot(Tmp.getValue(1));
4213 return 0;
4214 }
4215 case Intrinsic::stackrestore: {
4216 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004217 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004218 return 0;
4219 }
Bill Wendling57344502008-11-18 11:01:33 +00004220 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004221 // Emit code into the DAG to store the stack guard onto the stack.
4222 MachineFunction &MF = DAG.getMachineFunction();
4223 MachineFrameInfo *MFI = MF.getFrameInfo();
4224 MVT PtrTy = TLI.getPointerTy();
4225
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004226 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4227 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004228
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004229 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004230 MFI->setStackProtectorIndex(FI);
4231
4232 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4233
4234 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004235 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Bill Wendlingb2a42982008-11-06 02:29:10 +00004236 PseudoSourceValue::getFixedStack(FI),
4237 0, true);
4238 setValue(&I, Result);
4239 DAG.setRoot(Result);
4240 return 0;
4241 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004242 case Intrinsic::var_annotation:
4243 // Discard annotate attributes
4244 return 0;
4245
4246 case Intrinsic::init_trampoline: {
4247 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4248
4249 SDValue Ops[6];
4250 Ops[0] = getRoot();
4251 Ops[1] = getValue(I.getOperand(1));
4252 Ops[2] = getValue(I.getOperand(2));
4253 Ops[3] = getValue(I.getOperand(3));
4254 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4255 Ops[5] = DAG.getSrcValue(F);
4256
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004257 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004258 DAG.getNodeValueTypes(TLI.getPointerTy(),
4259 MVT::Other), 2,
4260 Ops, 6);
4261
4262 setValue(&I, Tmp);
4263 DAG.setRoot(Tmp.getValue(1));
4264 return 0;
4265 }
4266
4267 case Intrinsic::gcroot:
4268 if (GFI) {
4269 Value *Alloca = I.getOperand(1);
4270 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004271
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004272 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4273 GFI->addStackRoot(FI->getIndex(), TypeMap);
4274 }
4275 return 0;
4276
4277 case Intrinsic::gcread:
4278 case Intrinsic::gcwrite:
4279 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4280 return 0;
4281
4282 case Intrinsic::flt_rounds: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004283 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004284 return 0;
4285 }
4286
4287 case Intrinsic::trap: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004288 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004289 return 0;
4290 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004291
Bill Wendlingef375462008-11-21 02:38:44 +00004292 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004293 return implVisitAluOverflow(I, ISD::UADDO);
4294 case Intrinsic::sadd_with_overflow:
4295 return implVisitAluOverflow(I, ISD::SADDO);
4296 case Intrinsic::usub_with_overflow:
4297 return implVisitAluOverflow(I, ISD::USUBO);
4298 case Intrinsic::ssub_with_overflow:
4299 return implVisitAluOverflow(I, ISD::SSUBO);
4300 case Intrinsic::umul_with_overflow:
4301 return implVisitAluOverflow(I, ISD::UMULO);
4302 case Intrinsic::smul_with_overflow:
4303 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004304
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004305 case Intrinsic::prefetch: {
4306 SDValue Ops[4];
4307 Ops[0] = getRoot();
4308 Ops[1] = getValue(I.getOperand(1));
4309 Ops[2] = getValue(I.getOperand(2));
4310 Ops[3] = getValue(I.getOperand(3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004311 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004312 return 0;
4313 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004314
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004315 case Intrinsic::memory_barrier: {
4316 SDValue Ops[6];
4317 Ops[0] = getRoot();
4318 for (int x = 1; x < 6; ++x)
4319 Ops[x] = getValue(I.getOperand(x));
4320
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004321 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004322 return 0;
4323 }
4324 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004325 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004326 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004327 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004328 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4329 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004330 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004331 getValue(I.getOperand(2)),
4332 getValue(I.getOperand(3)),
4333 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004334 setValue(&I, L);
4335 DAG.setRoot(L.getValue(1));
4336 return 0;
4337 }
4338 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004339 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004340 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004341 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004342 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004343 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004344 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004345 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004346 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004347 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004348 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004349 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004350 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004351 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004352 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004353 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004354 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004355 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004356 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004357 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004358 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004359 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004360 }
4361}
4362
4363
4364void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4365 bool IsTailCall,
4366 MachineBasicBlock *LandingPad) {
4367 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4368 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4369 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4370 unsigned BeginLabel = 0, EndLabel = 0;
4371
4372 TargetLowering::ArgListTy Args;
4373 TargetLowering::ArgListEntry Entry;
4374 Args.reserve(CS.arg_size());
4375 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4376 i != e; ++i) {
4377 SDValue ArgNode = getValue(*i);
4378 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4379
4380 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004381 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4382 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4383 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4384 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4385 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4386 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004387 Entry.Alignment = CS.getParamAlignment(attrInd);
4388 Args.push_back(Entry);
4389 }
4390
4391 if (LandingPad && MMI) {
4392 // Insert a label before the invoke call to mark the try range. This can be
4393 // used to detect deletion of the invoke via the MachineModuleInfo.
4394 BeginLabel = MMI->NextLabelID();
4395 // Both PendingLoads and PendingExports must be flushed here;
4396 // this call might not return.
4397 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004398 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4399 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004400 }
4401
4402 std::pair<SDValue,SDValue> Result =
4403 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004404 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004405 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4406 CS.paramHasAttr(0, Attribute::InReg),
4407 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004408 IsTailCall && PerformTailCallOpt,
Dale Johannesen66978ee2009-01-31 02:22:37 +00004409 Callee, Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004410 if (CS.getType() != Type::VoidTy)
4411 setValue(CS.getInstruction(), Result.first);
4412 DAG.setRoot(Result.second);
4413
4414 if (LandingPad && MMI) {
4415 // Insert a label at the end of the invoke call to mark the try range. This
4416 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4417 EndLabel = MMI->NextLabelID();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004418 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4419 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004420
4421 // Inform MachineModuleInfo of range.
4422 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4423 }
4424}
4425
4426
4427void SelectionDAGLowering::visitCall(CallInst &I) {
4428 const char *RenameFn = 0;
4429 if (Function *F = I.getCalledFunction()) {
4430 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004431 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4432 if (II) {
4433 if (unsigned IID = II->getIntrinsicID(F)) {
4434 RenameFn = visitIntrinsicCall(I, IID);
4435 if (!RenameFn)
4436 return;
4437 }
4438 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004439 if (unsigned IID = F->getIntrinsicID()) {
4440 RenameFn = visitIntrinsicCall(I, IID);
4441 if (!RenameFn)
4442 return;
4443 }
4444 }
4445
4446 // Check for well-known libc/libm calls. If the function is internal, it
4447 // can't be a library call.
4448 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004449 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004450 const char *NameStr = F->getNameStart();
4451 if (NameStr[0] == 'c' &&
4452 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4453 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4454 if (I.getNumOperands() == 3 && // Basic sanity checks.
4455 I.getOperand(1)->getType()->isFloatingPoint() &&
4456 I.getType() == I.getOperand(1)->getType() &&
4457 I.getType() == I.getOperand(2)->getType()) {
4458 SDValue LHS = getValue(I.getOperand(1));
4459 SDValue RHS = getValue(I.getOperand(2));
Dale Johannesen66978ee2009-01-31 02:22:37 +00004460 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004461 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004462 return;
4463 }
4464 } else if (NameStr[0] == 'f' &&
4465 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4466 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4467 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4468 if (I.getNumOperands() == 2 && // Basic sanity checks.
4469 I.getOperand(1)->getType()->isFloatingPoint() &&
4470 I.getType() == I.getOperand(1)->getType()) {
4471 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +00004472 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004473 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004474 return;
4475 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004476 } else if (NameStr[0] == 's' &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004477 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4478 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4479 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4480 if (I.getNumOperands() == 2 && // Basic sanity checks.
4481 I.getOperand(1)->getType()->isFloatingPoint() &&
4482 I.getType() == I.getOperand(1)->getType()) {
4483 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +00004484 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004485 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004486 return;
4487 }
4488 } else if (NameStr[0] == 'c' &&
4489 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4490 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4491 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4492 if (I.getNumOperands() == 2 && // Basic sanity checks.
4493 I.getOperand(1)->getType()->isFloatingPoint() &&
4494 I.getType() == I.getOperand(1)->getType()) {
4495 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +00004496 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004497 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004498 return;
4499 }
4500 }
4501 }
4502 } else if (isa<InlineAsm>(I.getOperand(0))) {
4503 visitInlineAsm(&I);
4504 return;
4505 }
4506
4507 SDValue Callee;
4508 if (!RenameFn)
4509 Callee = getValue(I.getOperand(0));
4510 else
Bill Wendling056292f2008-09-16 21:48:12 +00004511 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004512
4513 LowerCallTo(&I, Callee, I.isTailCall());
4514}
4515
4516
4517/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004518/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004519/// Chain/Flag as the input and updates them for the output Chain/Flag.
4520/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004521SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004522 SDValue &Chain,
4523 SDValue *Flag) const {
4524 // Assemble the legal parts into the final values.
4525 SmallVector<SDValue, 4> Values(ValueVTs.size());
4526 SmallVector<SDValue, 8> Parts;
4527 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4528 // Copy the legal parts from the registers.
4529 MVT ValueVT = ValueVTs[Value];
4530 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4531 MVT RegisterVT = RegVTs[Value];
4532
4533 Parts.resize(NumRegs);
4534 for (unsigned i = 0; i != NumRegs; ++i) {
4535 SDValue P;
4536 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004537 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004538 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004539 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004540 *Flag = P.getValue(2);
4541 }
4542 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004543
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004544 // If the source register was virtual and if we know something about it,
4545 // add an assert node.
4546 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4547 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4548 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4549 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4550 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4551 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004552
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004553 unsigned RegSize = RegisterVT.getSizeInBits();
4554 unsigned NumSignBits = LOI.NumSignBits;
4555 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004556
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004557 // FIXME: We capture more information than the dag can represent. For
4558 // now, just use the tightest assertzext/assertsext possible.
4559 bool isSExt = true;
4560 MVT FromVT(MVT::Other);
4561 if (NumSignBits == RegSize)
4562 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4563 else if (NumZeroBits >= RegSize-1)
4564 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4565 else if (NumSignBits > RegSize-8)
4566 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4567 else if (NumZeroBits >= RegSize-9)
4568 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4569 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004570 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004571 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004572 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004573 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004574 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004575 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004576 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004577
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004578 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004579 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004580 RegisterVT, P, DAG.getValueType(FromVT));
4581
4582 }
4583 }
4584 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004585
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004586 Parts[i] = P;
4587 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004588
Dale Johannesen66978ee2009-01-31 02:22:37 +00004589 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4590 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004591 Part += NumRegs;
4592 Parts.clear();
4593 }
4594
Dale Johannesen66978ee2009-01-31 02:22:37 +00004595 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004596 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4597 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004598}
4599
4600/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004601/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004602/// Chain/Flag as the input and updates them for the output Chain/Flag.
4603/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004604void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004605 SDValue &Chain, SDValue *Flag) const {
4606 // Get the list of the values's legal parts.
4607 unsigned NumRegs = Regs.size();
4608 SmallVector<SDValue, 8> Parts(NumRegs);
4609 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4610 MVT ValueVT = ValueVTs[Value];
4611 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4612 MVT RegisterVT = RegVTs[Value];
4613
Dale Johannesen66978ee2009-01-31 02:22:37 +00004614 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004615 &Parts[Part], NumParts, RegisterVT);
4616 Part += NumParts;
4617 }
4618
4619 // Copy the parts into the registers.
4620 SmallVector<SDValue, 8> Chains(NumRegs);
4621 for (unsigned i = 0; i != NumRegs; ++i) {
4622 SDValue Part;
4623 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004624 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004625 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004626 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004627 *Flag = Part.getValue(1);
4628 }
4629 Chains[i] = Part.getValue(0);
4630 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004631
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004632 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004633 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004634 // flagged to it. That is the CopyToReg nodes and the user are considered
4635 // a single scheduling unit. If we create a TokenFactor and return it as
4636 // chain, then the TokenFactor is both a predecessor (operand) of the
4637 // user as well as a successor (the TF operands are flagged to the user).
4638 // c1, f1 = CopyToReg
4639 // c2, f2 = CopyToReg
4640 // c3 = TokenFactor c1, c2
4641 // ...
4642 // = op c3, ..., f2
4643 Chain = Chains[NumRegs-1];
4644 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00004645 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004646}
4647
4648/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004649/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004650/// values added into it.
4651void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4652 std::vector<SDValue> &Ops) const {
4653 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4654 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4655 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4656 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4657 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004658 for (unsigned i = 0; i != NumRegs; ++i) {
4659 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004660 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004661 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004662 }
4663}
4664
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004665/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004666/// i.e. it isn't a stack pointer or some other special register, return the
4667/// register class for the register. Otherwise, return null.
4668static const TargetRegisterClass *
4669isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4670 const TargetLowering &TLI,
4671 const TargetRegisterInfo *TRI) {
4672 MVT FoundVT = MVT::Other;
4673 const TargetRegisterClass *FoundRC = 0;
4674 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4675 E = TRI->regclass_end(); RCI != E; ++RCI) {
4676 MVT ThisVT = MVT::Other;
4677
4678 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004679 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004680 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4681 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4682 I != E; ++I) {
4683 if (TLI.isTypeLegal(*I)) {
4684 // If we have already found this register in a different register class,
4685 // choose the one with the largest VT specified. For example, on
4686 // PowerPC, we favor f64 register classes over f32.
4687 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4688 ThisVT = *I;
4689 break;
4690 }
4691 }
4692 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004693
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004694 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004695
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004696 // NOTE: This isn't ideal. In particular, this might allocate the
4697 // frame pointer in functions that need it (due to them not being taken
4698 // out of allocation, because a variable sized allocation hasn't been seen
4699 // yet). This is a slight code pessimization, but should still work.
4700 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4701 E = RC->allocation_order_end(MF); I != E; ++I)
4702 if (*I == Reg) {
4703 // We found a matching register class. Keep looking at others in case
4704 // we find one with larger registers that this physreg is also in.
4705 FoundRC = RC;
4706 FoundVT = ThisVT;
4707 break;
4708 }
4709 }
4710 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004711}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004712
4713
4714namespace llvm {
4715/// AsmOperandInfo - This contains information for each constraint that we are
4716/// lowering.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004717struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004718 public TargetLowering::AsmOperandInfo {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004719 /// CallOperand - If this is the result output operand or a clobber
4720 /// this is null, otherwise it is the incoming operand to the CallInst.
4721 /// This gets modified as the asm is processed.
4722 SDValue CallOperand;
4723
4724 /// AssignedRegs - If this is a register or register class operand, this
4725 /// contains the set of register corresponding to the operand.
4726 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004727
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004728 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4729 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4730 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004731
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004732 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4733 /// busy in OutputRegs/InputRegs.
4734 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004735 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004736 std::set<unsigned> &InputRegs,
4737 const TargetRegisterInfo &TRI) const {
4738 if (isOutReg) {
4739 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4740 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4741 }
4742 if (isInReg) {
4743 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4744 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4745 }
4746 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004747
Chris Lattner81249c92008-10-17 17:05:25 +00004748 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4749 /// corresponds to. If there is no Value* for this operand, it returns
4750 /// MVT::Other.
4751 MVT getCallOperandValMVT(const TargetLowering &TLI,
4752 const TargetData *TD) const {
4753 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004754
Chris Lattner81249c92008-10-17 17:05:25 +00004755 if (isa<BasicBlock>(CallOperandVal))
4756 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004757
Chris Lattner81249c92008-10-17 17:05:25 +00004758 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004759
Chris Lattner81249c92008-10-17 17:05:25 +00004760 // If this is an indirect operand, the operand is a pointer to the
4761 // accessed type.
4762 if (isIndirect)
4763 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004764
Chris Lattner81249c92008-10-17 17:05:25 +00004765 // If OpTy is not a single value, it may be a struct/union that we
4766 // can tile with integers.
4767 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4768 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4769 switch (BitSize) {
4770 default: break;
4771 case 1:
4772 case 8:
4773 case 16:
4774 case 32:
4775 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004776 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004777 OpTy = IntegerType::get(BitSize);
4778 break;
4779 }
4780 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004781
Chris Lattner81249c92008-10-17 17:05:25 +00004782 return TLI.getValueType(OpTy, true);
4783 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004784
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004785private:
4786 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4787 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004788 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004789 const TargetRegisterInfo &TRI) {
4790 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4791 Regs.insert(Reg);
4792 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4793 for (; *Aliases; ++Aliases)
4794 Regs.insert(*Aliases);
4795 }
4796};
4797} // end llvm namespace.
4798
4799
4800/// GetRegistersForValue - Assign registers (virtual or physical) for the
4801/// specified operand. We prefer to assign virtual registers, to allow the
4802/// register allocator handle the assignment process. However, if the asm uses
4803/// features that we can't model on machineinstrs, we have SDISel do the
4804/// allocation. This produces generally horrible, but correct, code.
4805///
4806/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004807/// Input and OutputRegs are the set of already allocated physical registers.
4808///
4809void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004810GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004811 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004812 std::set<unsigned> &InputRegs) {
4813 // Compute whether this value requires an input register, an output register,
4814 // or both.
4815 bool isOutReg = false;
4816 bool isInReg = false;
4817 switch (OpInfo.Type) {
4818 case InlineAsm::isOutput:
4819 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004820
4821 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004822 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004823 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004824 break;
4825 case InlineAsm::isInput:
4826 isInReg = true;
4827 isOutReg = false;
4828 break;
4829 case InlineAsm::isClobber:
4830 isOutReg = true;
4831 isInReg = true;
4832 break;
4833 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004834
4835
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004836 MachineFunction &MF = DAG.getMachineFunction();
4837 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004838
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004839 // If this is a constraint for a single physreg, or a constraint for a
4840 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004841 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004842 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4843 OpInfo.ConstraintVT);
4844
4845 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004846 if (OpInfo.ConstraintVT != MVT::Other) {
4847 // If this is a FP input in an integer register (or visa versa) insert a bit
4848 // cast of the input value. More generally, handle any case where the input
4849 // value disagrees with the register class we plan to stick this in.
4850 if (OpInfo.Type == InlineAsm::isInput &&
4851 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4852 // Try to convert to the first MVT that the reg class contains. If the
4853 // types are identical size, use a bitcast to convert (e.g. two differing
4854 // vector types).
4855 MVT RegVT = *PhysReg.second->vt_begin();
4856 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004857 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004858 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004859 OpInfo.ConstraintVT = RegVT;
4860 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4861 // If the input is a FP value and we want it in FP registers, do a
4862 // bitcast to the corresponding integer type. This turns an f64 value
4863 // into i64, which can be passed with two i32 values on a 32-bit
4864 // machine.
4865 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00004866 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004867 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004868 OpInfo.ConstraintVT = RegVT;
4869 }
4870 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004871
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004872 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004873 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004874
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004875 MVT RegVT;
4876 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004877
4878 // If this is a constraint for a specific physical register, like {r17},
4879 // assign it now.
4880 if (PhysReg.first) {
4881 if (OpInfo.ConstraintVT == MVT::Other)
4882 ValueVT = *PhysReg.second->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004883
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004884 // Get the actual register value type. This is important, because the user
4885 // may have asked for (e.g.) the AX register in i32 type. We need to
4886 // remember that AX is actually i16 to get the right extension.
4887 RegVT = *PhysReg.second->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004888
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004889 // This is a explicit reference to a physical register.
4890 Regs.push_back(PhysReg.first);
4891
4892 // If this is an expanded reference, add the rest of the regs to Regs.
4893 if (NumRegs != 1) {
4894 TargetRegisterClass::iterator I = PhysReg.second->begin();
4895 for (; *I != PhysReg.first; ++I)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004896 assert(I != PhysReg.second->end() && "Didn't find reg!");
4897
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004898 // Already added the first reg.
4899 --NumRegs; ++I;
4900 for (; NumRegs; --NumRegs, ++I) {
4901 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4902 Regs.push_back(*I);
4903 }
4904 }
4905 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4906 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4907 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4908 return;
4909 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004910
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004911 // Otherwise, if this was a reference to an LLVM register class, create vregs
4912 // for this reference.
4913 std::vector<unsigned> RegClassRegs;
4914 const TargetRegisterClass *RC = PhysReg.second;
4915 if (RC) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004916 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner58f15c42008-10-17 16:21:11 +00004917 // the constraint, so we have to pick a register to pin the input/output to.
4918 // If it isn't a matched constraint, go ahead and create vreg and let the
4919 // regalloc do its thing.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004920 if (!OpInfo.hasMatchingInput()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004921 RegVT = *PhysReg.second->vt_begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004922 if (OpInfo.ConstraintVT == MVT::Other)
4923 ValueVT = RegVT;
4924
4925 // Create the appropriate number of virtual registers.
4926 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4927 for (; NumRegs; --NumRegs)
4928 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004929
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004930 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4931 return;
4932 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004933
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004934 // Otherwise, we can't allocate it. Let the code below figure out how to
4935 // maintain these constraints.
4936 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004937
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004938 } else {
4939 // This is a reference to a register class that doesn't directly correspond
4940 // to an LLVM register class. Allocate NumRegs consecutive, available,
4941 // registers from the class.
4942 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4943 OpInfo.ConstraintVT);
4944 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004945
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004946 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4947 unsigned NumAllocated = 0;
4948 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4949 unsigned Reg = RegClassRegs[i];
4950 // See if this register is available.
4951 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4952 (isInReg && InputRegs.count(Reg))) { // Already used.
4953 // Make sure we find consecutive registers.
4954 NumAllocated = 0;
4955 continue;
4956 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004957
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004958 // Check to see if this register is allocatable (i.e. don't give out the
4959 // stack pointer).
4960 if (RC == 0) {
4961 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4962 if (!RC) { // Couldn't allocate this register.
4963 // Reset NumAllocated to make sure we return consecutive registers.
4964 NumAllocated = 0;
4965 continue;
4966 }
4967 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004968
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004969 // Okay, this register is good, we can use it.
4970 ++NumAllocated;
4971
4972 // If we allocated enough consecutive registers, succeed.
4973 if (NumAllocated == NumRegs) {
4974 unsigned RegStart = (i-NumAllocated)+1;
4975 unsigned RegEnd = i+1;
4976 // Mark all of the allocated registers used.
4977 for (unsigned i = RegStart; i != RegEnd; ++i)
4978 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004979
4980 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004981 OpInfo.ConstraintVT);
4982 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4983 return;
4984 }
4985 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004986
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004987 // Otherwise, we couldn't allocate enough registers for this.
4988}
4989
Evan Chengda43bcf2008-09-24 00:05:32 +00004990/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4991/// processed uses a memory 'm' constraint.
4992static bool
4993hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00004994 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00004995 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4996 InlineAsm::ConstraintInfo &CI = CInfos[i];
4997 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4998 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4999 if (CType == TargetLowering::C_Memory)
5000 return true;
5001 }
5002 }
5003
5004 return false;
5005}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005006
5007/// visitInlineAsm - Handle a call to an InlineAsm object.
5008///
5009void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5010 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5011
5012 /// ConstraintOperands - Information about all of the constraints.
5013 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005014
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005015 SDValue Chain = getRoot();
5016 SDValue Flag;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005017
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005018 std::set<unsigned> OutputRegs, InputRegs;
5019
5020 // Do a prepass over the constraints, canonicalizing them, and building up the
5021 // ConstraintOperands list.
5022 std::vector<InlineAsm::ConstraintInfo>
5023 ConstraintInfos = IA->ParseConstraints();
5024
Evan Chengda43bcf2008-09-24 00:05:32 +00005025 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005026
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005027 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5028 unsigned ResNo = 0; // ResNo - The result number of the next output.
5029 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5030 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5031 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005032
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005033 MVT OpVT = MVT::Other;
5034
5035 // Compute the value type for each operand.
5036 switch (OpInfo.Type) {
5037 case InlineAsm::isOutput:
5038 // Indirect outputs just consume an argument.
5039 if (OpInfo.isIndirect) {
5040 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5041 break;
5042 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005043
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005044 // The return value of the call is this value. As such, there is no
5045 // corresponding argument.
5046 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5047 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5048 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5049 } else {
5050 assert(ResNo == 0 && "Asm only has one result!");
5051 OpVT = TLI.getValueType(CS.getType());
5052 }
5053 ++ResNo;
5054 break;
5055 case InlineAsm::isInput:
5056 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5057 break;
5058 case InlineAsm::isClobber:
5059 // Nothing to do.
5060 break;
5061 }
5062
5063 // If this is an input or an indirect output, process the call argument.
5064 // BasicBlocks are labels, currently appearing only in asm's.
5065 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00005066 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005067 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005068 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005069 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005070 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005071
Chris Lattner81249c92008-10-17 17:05:25 +00005072 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005073 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005074
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005075 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005076 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005077
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005078 // Second pass over the constraints: compute which constraint option to use
5079 // and assign registers to constraints that want a specific physreg.
5080 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5081 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005082
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005083 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005084 // matching input. If their types mismatch, e.g. one is an integer, the
5085 // other is floating point, or their sizes are different, flag it as an
5086 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005087 if (OpInfo.hasMatchingInput()) {
5088 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5089 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005090 if ((OpInfo.ConstraintVT.isInteger() !=
5091 Input.ConstraintVT.isInteger()) ||
5092 (OpInfo.ConstraintVT.getSizeInBits() !=
5093 Input.ConstraintVT.getSizeInBits())) {
5094 cerr << "Unsupported asm: input constraint with a matching output "
5095 << "constraint of incompatible type!\n";
5096 exit(1);
5097 }
5098 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005099 }
5100 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005101
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005102 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005103 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005104
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005105 // If this is a memory input, and if the operand is not indirect, do what we
5106 // need to to provide an address for the memory input.
5107 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5108 !OpInfo.isIndirect) {
5109 assert(OpInfo.Type == InlineAsm::isInput &&
5110 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005111
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005112 // Memory operands really want the address of the value. If we don't have
5113 // an indirect input, put it in the constpool if we can, otherwise spill
5114 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005115
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005116 // If the operand is a float, integer, or vector constant, spill to a
5117 // constant pool entry to get its address.
5118 Value *OpVal = OpInfo.CallOperandVal;
5119 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5120 isa<ConstantVector>(OpVal)) {
5121 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5122 TLI.getPointerTy());
5123 } else {
5124 // Otherwise, create a stack slot and emit a store to it before the
5125 // asm.
5126 const Type *Ty = OpVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005127 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005128 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5129 MachineFunction &MF = DAG.getMachineFunction();
5130 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5131 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005132 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005133 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005134 OpInfo.CallOperand = StackSlot;
5135 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005136
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005137 // There is no longer a Value* corresponding to this operand.
5138 OpInfo.CallOperandVal = 0;
5139 // It is now an indirect operand.
5140 OpInfo.isIndirect = true;
5141 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005142
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005143 // If this constraint is for a specific register, allocate it before
5144 // anything else.
5145 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005146 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005147 }
5148 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005149
5150
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005151 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005152 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005153 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5154 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005155
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005156 // C_Register operands have already been allocated, Other/Memory don't need
5157 // to be.
5158 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005159 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005160 }
5161
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005162 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5163 std::vector<SDValue> AsmNodeOperands;
5164 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5165 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00005166 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005167
5168
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005169 // Loop over all of the inputs, copying the operand values into the
5170 // appropriate registers and processing the output regs.
5171 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005172
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005173 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5174 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005175
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005176 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5177 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5178
5179 switch (OpInfo.Type) {
5180 case InlineAsm::isOutput: {
5181 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5182 OpInfo.ConstraintType != TargetLowering::C_Register) {
5183 // Memory output, or 'other' output (e.g. 'X' constraint).
5184 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5185
5186 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005187 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5188 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005189 TLI.getPointerTy()));
5190 AsmNodeOperands.push_back(OpInfo.CallOperand);
5191 break;
5192 }
5193
5194 // Otherwise, this is a register or register class output.
5195
5196 // Copy the output from the appropriate register. Find a register that
5197 // we can use.
5198 if (OpInfo.AssignedRegs.Regs.empty()) {
5199 cerr << "Couldn't allocate output reg for constraint '"
5200 << OpInfo.ConstraintCode << "'!\n";
5201 exit(1);
5202 }
5203
5204 // If this is an indirect operand, store through the pointer after the
5205 // asm.
5206 if (OpInfo.isIndirect) {
5207 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5208 OpInfo.CallOperandVal));
5209 } else {
5210 // This is the result value of the call.
5211 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5212 // Concatenate this output onto the outputs list.
5213 RetValRegs.append(OpInfo.AssignedRegs);
5214 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005215
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005216 // Add information to the INLINEASM node to know that this register is
5217 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005218 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5219 6 /* EARLYCLOBBER REGDEF */ :
5220 2 /* REGDEF */ ,
5221 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005222 break;
5223 }
5224 case InlineAsm::isInput: {
5225 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005226
Chris Lattner6bdcda32008-10-17 16:47:46 +00005227 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005228 // If this is required to match an output register we have already set,
5229 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005230 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005231
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005232 // Scan until we find the definition we already emitted of this operand.
5233 // When we find it, create a RegsForValue operand.
5234 unsigned CurOp = 2; // The first operand.
5235 for (; OperandNo; --OperandNo) {
5236 // Advance to the next operand.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005237 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005238 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005239 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen913d3df2008-09-12 17:49:03 +00005240 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen86b49f82008-09-24 01:07:17 +00005241 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005242 "Skipped past definitions?");
5243 CurOp += (NumOps>>3)+1;
5244 }
5245
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005246 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005247 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005248 if ((NumOps & 7) == 2 /*REGDEF*/
Dale Johannesen913d3df2008-09-12 17:49:03 +00005249 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005250 // Add NumOps>>3 registers to MatchedRegs.
5251 RegsForValue MatchedRegs;
5252 MatchedRegs.TLI = &TLI;
5253 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5254 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5255 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5256 unsigned Reg =
5257 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5258 MatchedRegs.Regs.push_back(Reg);
5259 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005260
5261 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005262 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5263 Chain, &Flag);
Dale Johannesen86b49f82008-09-24 01:07:17 +00005264 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005265 break;
5266 } else {
Dale Johannesen86b49f82008-09-24 01:07:17 +00005267 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005268 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005269 // Add information to the INLINEASM node to know about this input.
Dale Johannesen91aac102008-09-17 21:13:11 +00005270 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005271 TLI.getPointerTy()));
5272 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5273 break;
5274 }
5275 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005276
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005277 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005278 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005279 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005280
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005281 std::vector<SDValue> Ops;
5282 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005283 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005284 if (Ops.empty()) {
5285 cerr << "Invalid operand for inline asm constraint '"
5286 << OpInfo.ConstraintCode << "'!\n";
5287 exit(1);
5288 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005289
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005290 // Add information to the INLINEASM node to know about this input.
5291 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005292 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005293 TLI.getPointerTy()));
5294 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5295 break;
5296 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5297 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5298 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5299 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005300
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005301 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005302 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5303 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005304 TLI.getPointerTy()));
5305 AsmNodeOperands.push_back(InOperandVal);
5306 break;
5307 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005308
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005309 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5310 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5311 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005312 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005313 "Don't know how to handle indirect register inputs yet!");
5314
5315 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005316 if (OpInfo.AssignedRegs.Regs.empty()) {
5317 cerr << "Couldn't allocate output reg for constraint '"
5318 << OpInfo.ConstraintCode << "'!\n";
5319 exit(1);
5320 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005321
Dale Johannesen66978ee2009-01-31 02:22:37 +00005322 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5323 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005324
Dale Johannesen86b49f82008-09-24 01:07:17 +00005325 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5326 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005327 break;
5328 }
5329 case InlineAsm::isClobber: {
5330 // Add the clobbered value to the operand list, so that the register
5331 // allocator is aware that the physreg got clobbered.
5332 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005333 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5334 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005335 break;
5336 }
5337 }
5338 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005339
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005340 // Finish up input operands.
5341 AsmNodeOperands[0] = Chain;
5342 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005343
Dale Johannesen66978ee2009-01-31 02:22:37 +00005344 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005345 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5346 &AsmNodeOperands[0], AsmNodeOperands.size());
5347 Flag = Chain.getValue(1);
5348
5349 // If this asm returns a register value, copy the result from that register
5350 // and set it as the value of the call.
5351 if (!RetValRegs.Regs.empty()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005352 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5353 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005354
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005355 // FIXME: Why don't we do this for inline asms with MRVs?
5356 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5357 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005358
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005359 // If any of the results of the inline asm is a vector, it may have the
5360 // wrong width/num elts. This can happen for register classes that can
5361 // contain multiple different value types. The preg or vreg allocated may
5362 // not have the same VT as was expected. Convert it to the right type
5363 // with bit_convert.
5364 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005365 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005366 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005367
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005368 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005369 ResultType.isInteger() && Val.getValueType().isInteger()) {
5370 // If a result value was tied to an input value, the computed result may
5371 // have a wider width than the expected result. Extract the relevant
5372 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005373 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005374 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005375
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005376 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005377 }
Dan Gohman95915732008-10-18 01:03:45 +00005378
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005379 setValue(CS.getInstruction(), Val);
5380 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005381
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005382 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005383
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005384 // Process indirect outputs, first output all of the flagged copies out of
5385 // physregs.
5386 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5387 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5388 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005389 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5390 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005391 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5392 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005393
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005394 // Emit the non-flagged stores from the physregs.
5395 SmallVector<SDValue, 8> OutChains;
5396 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005397 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005398 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005399 getValue(StoresToEmit[i].second),
5400 StoresToEmit[i].second, 0));
5401 if (!OutChains.empty())
Dale Johannesen66978ee2009-01-31 02:22:37 +00005402 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005403 &OutChains[0], OutChains.size());
5404 DAG.setRoot(Chain);
5405}
5406
5407
5408void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5409 SDValue Src = getValue(I.getOperand(0));
5410
5411 MVT IntPtr = TLI.getPointerTy();
5412
5413 if (IntPtr.bitsLT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005414 Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005415 else if (IntPtr.bitsGT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005416 Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005417
5418 // Scale the source by the type size.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005419 uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005420 Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005421 Src, DAG.getIntPtrConstant(ElementSize));
5422
5423 TargetLowering::ArgListTy Args;
5424 TargetLowering::ArgListEntry Entry;
5425 Entry.Node = Src;
5426 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5427 Args.push_back(Entry);
5428
5429 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005430 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005431 CallingConv::C, PerformTailCallOpt,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005432 DAG.getExternalSymbol("malloc", IntPtr),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005433 Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005434 setValue(&I, Result.first); // Pointers always fit in registers
5435 DAG.setRoot(Result.second);
5436}
5437
5438void SelectionDAGLowering::visitFree(FreeInst &I) {
5439 TargetLowering::ArgListTy Args;
5440 TargetLowering::ArgListEntry Entry;
5441 Entry.Node = getValue(I.getOperand(0));
5442 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5443 Args.push_back(Entry);
5444 MVT IntPtr = TLI.getPointerTy();
5445 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005446 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005447 CallingConv::C, PerformTailCallOpt,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005448 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
Dale Johannesen66978ee2009-01-31 02:22:37 +00005449 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005450 DAG.setRoot(Result.second);
5451}
5452
5453void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005454 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005455 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005456 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005457 DAG.getSrcValue(I.getOperand(1))));
5458}
5459
5460void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005461 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5462 getRoot(), getValue(I.getOperand(0)),
5463 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005464 setValue(&I, V);
5465 DAG.setRoot(V.getValue(1));
5466}
5467
5468void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005469 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005470 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005471 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005472 DAG.getSrcValue(I.getOperand(1))));
5473}
5474
5475void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005476 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005477 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005478 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005479 getValue(I.getOperand(2)),
5480 DAG.getSrcValue(I.getOperand(1)),
5481 DAG.getSrcValue(I.getOperand(2))));
5482}
5483
5484/// TargetLowering::LowerArguments - This is the default LowerArguments
5485/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005486/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005487/// integrated into SDISel.
5488void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005489 SmallVectorImpl<SDValue> &ArgValues,
5490 DebugLoc dl) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005491 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5492 SmallVector<SDValue, 3+16> Ops;
5493 Ops.push_back(DAG.getRoot());
5494 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5495 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5496
5497 // Add one result value for each formal argument.
5498 SmallVector<MVT, 16> RetVals;
5499 unsigned j = 1;
5500 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5501 I != E; ++I, ++j) {
5502 SmallVector<MVT, 4> ValueVTs;
5503 ComputeValueVTs(*this, I->getType(), ValueVTs);
5504 for (unsigned Value = 0, NumValues = ValueVTs.size();
5505 Value != NumValues; ++Value) {
5506 MVT VT = ValueVTs[Value];
5507 const Type *ArgTy = VT.getTypeForMVT();
5508 ISD::ArgFlagsTy Flags;
5509 unsigned OriginalAlignment =
5510 getTargetData()->getABITypeAlignment(ArgTy);
5511
Devang Patel05988662008-09-25 21:00:45 +00005512 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005513 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005514 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005515 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005516 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005517 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005518 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005519 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005520 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005521 Flags.setByVal();
5522 const PointerType *Ty = cast<PointerType>(I->getType());
5523 const Type *ElementTy = Ty->getElementType();
5524 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005525 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005526 // For ByVal, alignment should be passed from FE. BE will guess if
5527 // this info is not there but there are cases it cannot get right.
5528 if (F.getParamAlignment(j))
5529 FrameAlign = F.getParamAlignment(j);
5530 Flags.setByValAlign(FrameAlign);
5531 Flags.setByValSize(FrameSize);
5532 }
Devang Patel05988662008-09-25 21:00:45 +00005533 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005534 Flags.setNest();
5535 Flags.setOrigAlign(OriginalAlignment);
5536
5537 MVT RegisterVT = getRegisterType(VT);
5538 unsigned NumRegs = getNumRegisters(VT);
5539 for (unsigned i = 0; i != NumRegs; ++i) {
5540 RetVals.push_back(RegisterVT);
5541 ISD::ArgFlagsTy MyFlags = Flags;
5542 if (NumRegs > 1 && i == 0)
5543 MyFlags.setSplit();
5544 // if it isn't first piece, alignment must be 1
5545 else if (i > 0)
5546 MyFlags.setOrigAlign(1);
5547 Ops.push_back(DAG.getArgFlags(MyFlags));
5548 }
5549 }
5550 }
5551
5552 RetVals.push_back(MVT::Other);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005553
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005554 // Create the node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005555 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005556 DAG.getVTList(&RetVals[0], RetVals.size()),
5557 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005558
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005559 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5560 // allows exposing the loads that may be part of the argument access to the
5561 // first DAGCombiner pass.
5562 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005563
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005564 // The number of results should match up, except that the lowered one may have
5565 // an extra flag result.
5566 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5567 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5568 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5569 && "Lowering produced unexpected number of results!");
5570
5571 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5572 if (Result != TmpRes.getNode() && Result->use_empty()) {
5573 HandleSDNode Dummy(DAG.getRoot());
5574 DAG.RemoveDeadNode(Result);
5575 }
5576
5577 Result = TmpRes.getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005578
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005579 unsigned NumArgRegs = Result->getNumValues() - 1;
5580 DAG.setRoot(SDValue(Result, NumArgRegs));
5581
5582 // Set up the return result vector.
5583 unsigned i = 0;
5584 unsigned Idx = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005585 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005586 ++I, ++Idx) {
5587 SmallVector<MVT, 4> ValueVTs;
5588 ComputeValueVTs(*this, I->getType(), ValueVTs);
5589 for (unsigned Value = 0, NumValues = ValueVTs.size();
5590 Value != NumValues; ++Value) {
5591 MVT VT = ValueVTs[Value];
5592 MVT PartVT = getRegisterType(VT);
5593
5594 unsigned NumParts = getNumRegisters(VT);
5595 SmallVector<SDValue, 4> Parts(NumParts);
5596 for (unsigned j = 0; j != NumParts; ++j)
5597 Parts[j] = SDValue(Result, i++);
5598
5599 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005600 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005601 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005602 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005603 AssertOp = ISD::AssertZext;
5604
Dale Johannesen66978ee2009-01-31 02:22:37 +00005605 ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5606 PartVT, VT, AssertOp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005607 }
5608 }
5609 assert(i == NumArgRegs && "Argument register count mismatch!");
5610}
5611
5612
5613/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5614/// implementation, which just inserts an ISD::CALL node, which is later custom
5615/// lowered by the target to something concrete. FIXME: When all targets are
5616/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5617std::pair<SDValue, SDValue>
5618TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5619 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005620 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005621 unsigned CallingConv, bool isTailCall,
5622 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005623 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005624 assert((!isTailCall || PerformTailCallOpt) &&
5625 "isTailCall set when tail-call optimizations are disabled!");
5626
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005627 SmallVector<SDValue, 32> Ops;
5628 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005629 Ops.push_back(Callee);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005630
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005631 // Handle all of the outgoing arguments.
5632 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5633 SmallVector<MVT, 4> ValueVTs;
5634 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5635 for (unsigned Value = 0, NumValues = ValueVTs.size();
5636 Value != NumValues; ++Value) {
5637 MVT VT = ValueVTs[Value];
5638 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005639 SDValue Op = SDValue(Args[i].Node.getNode(),
5640 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005641 ISD::ArgFlagsTy Flags;
5642 unsigned OriginalAlignment =
5643 getTargetData()->getABITypeAlignment(ArgTy);
5644
5645 if (Args[i].isZExt)
5646 Flags.setZExt();
5647 if (Args[i].isSExt)
5648 Flags.setSExt();
5649 if (Args[i].isInReg)
5650 Flags.setInReg();
5651 if (Args[i].isSRet)
5652 Flags.setSRet();
5653 if (Args[i].isByVal) {
5654 Flags.setByVal();
5655 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5656 const Type *ElementTy = Ty->getElementType();
5657 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005658 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005659 // For ByVal, alignment should come from FE. BE will guess if this
5660 // info is not there but there are cases it cannot get right.
5661 if (Args[i].Alignment)
5662 FrameAlign = Args[i].Alignment;
5663 Flags.setByValAlign(FrameAlign);
5664 Flags.setByValSize(FrameSize);
5665 }
5666 if (Args[i].isNest)
5667 Flags.setNest();
5668 Flags.setOrigAlign(OriginalAlignment);
5669
5670 MVT PartVT = getRegisterType(VT);
5671 unsigned NumParts = getNumRegisters(VT);
5672 SmallVector<SDValue, 4> Parts(NumParts);
5673 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5674
5675 if (Args[i].isSExt)
5676 ExtendKind = ISD::SIGN_EXTEND;
5677 else if (Args[i].isZExt)
5678 ExtendKind = ISD::ZERO_EXTEND;
5679
Dale Johannesen66978ee2009-01-31 02:22:37 +00005680 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005681
5682 for (unsigned i = 0; i != NumParts; ++i) {
5683 // if it isn't first piece, alignment must be 1
5684 ISD::ArgFlagsTy MyFlags = Flags;
5685 if (NumParts > 1 && i == 0)
5686 MyFlags.setSplit();
5687 else if (i != 0)
5688 MyFlags.setOrigAlign(1);
5689
5690 Ops.push_back(Parts[i]);
5691 Ops.push_back(DAG.getArgFlags(MyFlags));
5692 }
5693 }
5694 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005695
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005696 // Figure out the result value types. We start by making a list of
5697 // the potentially illegal return value types.
5698 SmallVector<MVT, 4> LoweredRetTys;
5699 SmallVector<MVT, 4> RetTys;
5700 ComputeValueVTs(*this, RetTy, RetTys);
5701
5702 // Then we translate that to a list of legal types.
5703 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5704 MVT VT = RetTys[I];
5705 MVT RegisterVT = getRegisterType(VT);
5706 unsigned NumRegs = getNumRegisters(VT);
5707 for (unsigned i = 0; i != NumRegs; ++i)
5708 LoweredRetTys.push_back(RegisterVT);
5709 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005710
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005711 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005712
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005713 // Create the CALL node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005714 SDValue Res = DAG.getCall(CallingConv, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005715 isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005716 DAG.getVTList(&LoweredRetTys[0],
5717 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005718 &Ops[0], Ops.size()
5719 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005720 Chain = Res.getValue(LoweredRetTys.size() - 1);
5721
5722 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005723 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005724 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5725
5726 if (RetSExt)
5727 AssertOp = ISD::AssertSext;
5728 else if (RetZExt)
5729 AssertOp = ISD::AssertZext;
5730
5731 SmallVector<SDValue, 4> ReturnValues;
5732 unsigned RegNo = 0;
5733 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5734 MVT VT = RetTys[I];
5735 MVT RegisterVT = getRegisterType(VT);
5736 unsigned NumRegs = getNumRegisters(VT);
5737 unsigned RegNoEnd = NumRegs + RegNo;
5738 SmallVector<SDValue, 4> Results;
5739 for (; RegNo != RegNoEnd; ++RegNo)
5740 Results.push_back(Res.getValue(RegNo));
5741 SDValue ReturnValue =
Dale Johannesen66978ee2009-01-31 02:22:37 +00005742 getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005743 AssertOp);
5744 ReturnValues.push_back(ReturnValue);
5745 }
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005746 Res = DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00005747 DAG.getVTList(&RetTys[0], RetTys.size()),
5748 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005749 }
5750
5751 return std::make_pair(Res, Chain);
5752}
5753
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005754void TargetLowering::LowerOperationWrapper(SDNode *N,
5755 SmallVectorImpl<SDValue> &Results,
5756 SelectionDAG &DAG) {
5757 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005758 if (Res.getNode())
5759 Results.push_back(Res);
5760}
5761
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005762SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5763 assert(0 && "LowerOperation not implemented for this target!");
5764 abort();
5765 return SDValue();
5766}
5767
5768
5769void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5770 SDValue Op = getValue(V);
5771 assert((Op.getOpcode() != ISD::CopyFromReg ||
5772 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5773 "Copy from a reg to the same reg!");
5774 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5775
5776 RegsForValue RFV(TLI, Reg, V->getType());
5777 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005778 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005779 PendingExports.push_back(Chain);
5780}
5781
5782#include "llvm/CodeGen/SelectionDAGISel.h"
5783
5784void SelectionDAGISel::
5785LowerArguments(BasicBlock *LLVMBB) {
5786 // If this is the entry block, emit arguments.
5787 Function &F = *LLVMBB->getParent();
5788 SDValue OldRoot = SDL->DAG.getRoot();
5789 SmallVector<SDValue, 16> Args;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005790 TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005791
5792 unsigned a = 0;
5793 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5794 AI != E; ++AI) {
5795 SmallVector<MVT, 4> ValueVTs;
5796 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5797 unsigned NumValues = ValueVTs.size();
5798 if (!AI->use_empty()) {
Dale Johannesen4be0bdf2009-02-05 00:20:09 +00005799 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
5800 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005801 // If this argument is live outside of the entry block, insert a copy from
5802 // whereever we got it to the vreg that other BB's will reference it as.
5803 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5804 if (VMI != FuncInfo->ValueMap.end()) {
5805 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5806 }
5807 }
5808 a += NumValues;
5809 }
5810
5811 // Finally, if the target has anything special to do, allow it to do so.
5812 // FIXME: this should insert code into the DAG!
5813 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5814}
5815
5816/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5817/// ensure constants are generated when needed. Remember the virtual registers
5818/// that need to be added to the Machine PHI nodes as input. We cannot just
5819/// directly add them, because expansion might result in multiple MBB's for one
5820/// BB. As such, the start of the BB might correspond to a different MBB than
5821/// the end.
5822///
5823void
5824SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5825 TerminatorInst *TI = LLVMBB->getTerminator();
5826
5827 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5828
5829 // Check successor nodes' PHI nodes that expect a constant to be available
5830 // from this block.
5831 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5832 BasicBlock *SuccBB = TI->getSuccessor(succ);
5833 if (!isa<PHINode>(SuccBB->begin())) continue;
5834 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005835
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005836 // If this terminator has multiple identical successors (common for
5837 // switches), only handle each succ once.
5838 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005839
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005840 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5841 PHINode *PN;
5842
5843 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5844 // nodes and Machine PHI nodes, but the incoming operands have not been
5845 // emitted yet.
5846 for (BasicBlock::iterator I = SuccBB->begin();
5847 (PN = dyn_cast<PHINode>(I)); ++I) {
5848 // Ignore dead phi's.
5849 if (PN->use_empty()) continue;
5850
5851 unsigned Reg;
5852 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5853
5854 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5855 unsigned &RegOut = SDL->ConstantsOut[C];
5856 if (RegOut == 0) {
5857 RegOut = FuncInfo->CreateRegForValue(C);
5858 SDL->CopyValueToVirtualRegister(C, RegOut);
5859 }
5860 Reg = RegOut;
5861 } else {
5862 Reg = FuncInfo->ValueMap[PHIOp];
5863 if (Reg == 0) {
5864 assert(isa<AllocaInst>(PHIOp) &&
5865 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5866 "Didn't codegen value into a register!??");
5867 Reg = FuncInfo->CreateRegForValue(PHIOp);
5868 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5869 }
5870 }
5871
5872 // Remember that this register needs to added to the machine PHI node as
5873 // the input for this MBB.
5874 SmallVector<MVT, 4> ValueVTs;
5875 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5876 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5877 MVT VT = ValueVTs[vti];
5878 unsigned NumRegisters = TLI.getNumRegisters(VT);
5879 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5880 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5881 Reg += NumRegisters;
5882 }
5883 }
5884 }
5885 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005886}
5887
Dan Gohman3df24e62008-09-03 23:12:08 +00005888/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5889/// supports legal types, and it emits MachineInstrs directly instead of
5890/// creating SelectionDAG nodes.
5891///
5892bool
5893SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5894 FastISel *F) {
5895 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005896
Dan Gohman3df24e62008-09-03 23:12:08 +00005897 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5898 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5899
5900 // Check successor nodes' PHI nodes that expect a constant to be available
5901 // from this block.
5902 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5903 BasicBlock *SuccBB = TI->getSuccessor(succ);
5904 if (!isa<PHINode>(SuccBB->begin())) continue;
5905 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005906
Dan Gohman3df24e62008-09-03 23:12:08 +00005907 // If this terminator has multiple identical successors (common for
5908 // switches), only handle each succ once.
5909 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005910
Dan Gohman3df24e62008-09-03 23:12:08 +00005911 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5912 PHINode *PN;
5913
5914 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5915 // nodes and Machine PHI nodes, but the incoming operands have not been
5916 // emitted yet.
5917 for (BasicBlock::iterator I = SuccBB->begin();
5918 (PN = dyn_cast<PHINode>(I)); ++I) {
5919 // Ignore dead phi's.
5920 if (PN->use_empty()) continue;
5921
5922 // Only handle legal types. Two interesting things to note here. First,
5923 // by bailing out early, we may leave behind some dead instructions,
5924 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5925 // own moves. Second, this check is necessary becuase FastISel doesn't
5926 // use CreateRegForValue to create registers, so it always creates
5927 // exactly one register for each non-void instruction.
5928 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5929 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005930 // Promote MVT::i1.
5931 if (VT == MVT::i1)
5932 VT = TLI.getTypeToTransformTo(VT);
5933 else {
5934 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5935 return false;
5936 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005937 }
5938
5939 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5940
5941 unsigned Reg = F->getRegForValue(PHIOp);
5942 if (Reg == 0) {
5943 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5944 return false;
5945 }
5946 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5947 }
5948 }
5949
5950 return true;
5951}