blob: 3daa79ed71d68e520ce0a84f2b858586cd2518b4 [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"
40#include "llvm/Target/TargetRegisterInfo.h"
41#include "llvm/Target/TargetData.h"
42#include "llvm/Target/TargetFrameInfo.h"
43#include "llvm/Target/TargetInstrInfo.h"
44#include "llvm/Target/TargetLowering.h"
45#include "llvm/Target/TargetMachine.h"
46#include "llvm/Target/TargetOptions.h"
47#include "llvm/Support/Compiler.h"
48#include "llvm/Support/Debug.h"
49#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000050#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000051#include <algorithm>
52using namespace llvm;
53
Dale Johannesen601d3c02008-09-05 01:48:15 +000054/// LimitFloatPrecision - Generate low-precision inline sequences for
55/// some float libcalls (6, 8 or 12 bits).
56static unsigned LimitFloatPrecision;
57
58static cl::opt<unsigned, true>
59LimitFPPrecision("limit-float-precision",
60 cl::desc("Generate low-precision inline sequences "
61 "for some float libcalls"),
62 cl::location(LimitFloatPrecision),
63 cl::init(0));
64
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000065/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
66/// insertvalue or extractvalue indices that identify a member, return
67/// the linearized index of the start of the member.
68///
69static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
70 const unsigned *Indices,
71 const unsigned *IndicesEnd,
72 unsigned CurIndex = 0) {
73 // Base case: We're done.
74 if (Indices && Indices == IndicesEnd)
75 return CurIndex;
76
77 // Given a struct type, recursively traverse the elements.
78 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
79 for (StructType::element_iterator EB = STy->element_begin(),
80 EI = EB,
81 EE = STy->element_end();
82 EI != EE; ++EI) {
83 if (Indices && *Indices == unsigned(EI - EB))
84 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
85 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
86 }
87 }
88 // Given an array type, recursively traverse the elements.
89 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
90 const Type *EltTy = ATy->getElementType();
91 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
92 if (Indices && *Indices == i)
93 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
94 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
95 }
96 }
97 // We haven't found the type we're looking for, so keep searching.
98 return CurIndex + 1;
99}
100
101/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
102/// MVTs that represent all the individual underlying
103/// non-aggregate types that comprise it.
104///
105/// If Offsets is non-null, it points to a vector to be filled in
106/// with the in-memory offsets of each of the individual values.
107///
108static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
109 SmallVectorImpl<MVT> &ValueVTs,
110 SmallVectorImpl<uint64_t> *Offsets = 0,
111 uint64_t StartingOffset = 0) {
112 // Given a struct type, recursively traverse the elements.
113 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
114 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
115 for (StructType::element_iterator EB = STy->element_begin(),
116 EI = EB,
117 EE = STy->element_end();
118 EI != EE; ++EI)
119 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
120 StartingOffset + SL->getElementOffset(EI - EB));
121 return;
122 }
123 // Given an array type, recursively traverse the elements.
124 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
125 const Type *EltTy = ATy->getElementType();
126 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
127 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
128 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
129 StartingOffset + i * EltSize);
130 return;
131 }
132 // Base case: we can get an MVT for this LLVM IR type.
133 ValueVTs.push_back(TLI.getValueType(Ty));
134 if (Offsets)
135 Offsets->push_back(StartingOffset);
136}
137
Dan Gohman2a7c6712008-09-03 23:18:39 +0000138namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000139 /// RegsForValue - This struct represents the registers (physical or virtual)
140 /// that a particular set of values is assigned, and the type information about
141 /// the value. The most common situation is to represent one value at a time,
142 /// but struct or array values are handled element-wise as multiple values.
143 /// The splitting of aggregates is performed recursively, so that we never
144 /// have aggregate-typed registers. The values at this point do not necessarily
145 /// have legal types, so each value may require one or more registers of some
146 /// legal type.
147 ///
148 struct VISIBILITY_HIDDEN RegsForValue {
149 /// TLI - The TargetLowering object.
150 ///
151 const TargetLowering *TLI;
152
153 /// ValueVTs - The value types of the values, which may not be legal, and
154 /// may need be promoted or synthesized from one or more registers.
155 ///
156 SmallVector<MVT, 4> ValueVTs;
157
158 /// RegVTs - The value types of the registers. This is the same size as
159 /// ValueVTs and it records, for each value, what the type of the assigned
160 /// register or registers are. (Individual values are never synthesized
161 /// from more than one type of register.)
162 ///
163 /// With virtual registers, the contents of RegVTs is redundant with TLI's
164 /// getRegisterType member function, however when with physical registers
165 /// it is necessary to have a separate record of the types.
166 ///
167 SmallVector<MVT, 4> RegVTs;
168
169 /// Regs - This list holds the registers assigned to the values.
170 /// Each legal or promoted value requires one register, and each
171 /// expanded value requires multiple registers.
172 ///
173 SmallVector<unsigned, 4> Regs;
174
175 RegsForValue() : TLI(0) {}
176
177 RegsForValue(const TargetLowering &tli,
178 const SmallVector<unsigned, 4> &regs,
179 MVT regvt, MVT valuevt)
180 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
181 RegsForValue(const TargetLowering &tli,
182 const SmallVector<unsigned, 4> &regs,
183 const SmallVector<MVT, 4> &regvts,
184 const SmallVector<MVT, 4> &valuevts)
185 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
186 RegsForValue(const TargetLowering &tli,
187 unsigned Reg, const Type *Ty) : TLI(&tli) {
188 ComputeValueVTs(tli, Ty, ValueVTs);
189
190 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
191 MVT ValueVT = ValueVTs[Value];
192 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
193 MVT RegisterVT = TLI->getRegisterType(ValueVT);
194 for (unsigned i = 0; i != NumRegs; ++i)
195 Regs.push_back(Reg + i);
196 RegVTs.push_back(RegisterVT);
197 Reg += NumRegs;
198 }
199 }
200
201 /// append - Add the specified values to this one.
202 void append(const RegsForValue &RHS) {
203 TLI = RHS.TLI;
204 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
205 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
206 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
207 }
208
209
210 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
211 /// this value and returns the result as a ValueVTs value. This uses
212 /// Chain/Flag as the input and updates them for the output Chain/Flag.
213 /// If the Flag pointer is NULL, no flag is used.
214 SDValue getCopyFromRegs(SelectionDAG &DAG,
215 SDValue &Chain, SDValue *Flag) const;
216
217 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
218 /// specified value into the registers specified by this object. This uses
219 /// Chain/Flag as the input and updates them for the output Chain/Flag.
220 /// If the Flag pointer is NULL, no flag is used.
221 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
222 SDValue &Chain, SDValue *Flag) const;
223
224 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
225 /// operand list. This adds the code marker and includes the number of
226 /// values added into it.
227 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
228 std::vector<SDValue> &Ops) const;
229 };
230}
231
232/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
233/// PHI nodes or outside of the basic block that defines it, or used by a
234/// switch or atomic instruction, which may expand to multiple basic blocks.
235static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
236 if (isa<PHINode>(I)) return true;
237 BasicBlock *BB = I->getParent();
238 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
239 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
240 // FIXME: Remove switchinst special case.
241 isa<SwitchInst>(*UI))
242 return true;
243 return false;
244}
245
246/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
247/// entry block, return true. This includes arguments used by switches, since
248/// the switch may expand into multiple basic blocks.
249static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
250 // With FastISel active, we may be splitting blocks, so force creation
251 // of virtual registers for all non-dead arguments.
Dan Gohman33134c42008-09-25 17:05:24 +0000252 // Don't force virtual registers for byval arguments though, because
253 // fast-isel can't handle those in all cases.
254 if (EnableFastISel && !A->hasByValAttr())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000255 return A->use_empty();
256
257 BasicBlock *Entry = A->getParent()->begin();
258 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
259 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
260 return false; // Use not in entry block.
261 return true;
262}
263
264FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
265 : TLI(tli) {
266}
267
268void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
269 bool EnableFastISel) {
270 Fn = &fn;
271 MF = &mf;
272 RegInfo = &MF->getRegInfo();
273
274 // Create a vreg for each argument register that is not dead and is used
275 // outside of the entry block for the function.
276 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
277 AI != E; ++AI)
278 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
279 InitializeRegForValue(AI);
280
281 // Initialize the mapping of values to registers. This is only set up for
282 // instruction values that are used outside of the block that defines
283 // them.
284 Function::iterator BB = Fn->begin(), EB = Fn->end();
285 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
286 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
287 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
288 const Type *Ty = AI->getAllocatedType();
289 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
290 unsigned Align =
291 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
292 AI->getAlignment());
293
294 TySize *= CUI->getZExtValue(); // Get total allocated size.
295 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
296 StaticAllocaMap[AI] =
297 MF->getFrameInfo()->CreateStackObject(TySize, Align);
298 }
299
300 for (; BB != EB; ++BB)
301 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
302 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
303 if (!isa<AllocaInst>(I) ||
304 !StaticAllocaMap.count(cast<AllocaInst>(I)))
305 InitializeRegForValue(I);
306
307 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
308 // also creates the initial PHI MachineInstrs, though none of the input
309 // operands are populated.
310 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
311 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
312 MBBMap[BB] = MBB;
313 MF->push_back(MBB);
314
315 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
316 // appropriate.
317 PHINode *PN;
318 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
319 if (PN->use_empty()) continue;
320
321 unsigned PHIReg = ValueMap[PN];
322 assert(PHIReg && "PHI node does not have an assigned virtual register!");
323
324 SmallVector<MVT, 4> ValueVTs;
325 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
326 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
327 MVT VT = ValueVTs[vti];
328 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000329 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000330 for (unsigned i = 0; i != NumRegisters; ++i)
331 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
332 PHIReg += NumRegisters;
333 }
334 }
335 }
336}
337
338unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
339 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
340}
341
342/// CreateRegForValue - Allocate the appropriate number of virtual registers of
343/// the correctly promoted or expanded types. Assign these registers
344/// consecutive vreg numbers and return the first assigned number.
345///
346/// In the case that the given value has struct or array type, this function
347/// will assign registers for each member or element.
348///
349unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
350 SmallVector<MVT, 4> ValueVTs;
351 ComputeValueVTs(TLI, V->getType(), ValueVTs);
352
353 unsigned FirstReg = 0;
354 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
355 MVT ValueVT = ValueVTs[Value];
356 MVT RegisterVT = TLI.getRegisterType(ValueVT);
357
358 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
359 for (unsigned i = 0; i != NumRegs; ++i) {
360 unsigned R = MakeReg(RegisterVT);
361 if (!FirstReg) FirstReg = R;
362 }
363 }
364 return FirstReg;
365}
366
367/// getCopyFromParts - Create a value that contains the specified legal parts
368/// combined into the value they represent. If the parts combine to a type
369/// larger then ValueVT then AssertOp can be used to specify whether the extra
370/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
371/// (ISD::AssertSext).
372static SDValue getCopyFromParts(SelectionDAG &DAG,
373 const SDValue *Parts,
374 unsigned NumParts,
375 MVT PartVT,
376 MVT ValueVT,
377 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
378 assert(NumParts > 0 && "No parts to assemble!");
379 TargetLowering &TLI = DAG.getTargetLoweringInfo();
380 SDValue Val = Parts[0];
381
382 if (NumParts > 1) {
383 // Assemble the value from multiple parts.
384 if (!ValueVT.isVector()) {
385 unsigned PartBits = PartVT.getSizeInBits();
386 unsigned ValueBits = ValueVT.getSizeInBits();
387
388 // Assemble the power of 2 part.
389 unsigned RoundParts = NumParts & (NumParts - 1) ?
390 1 << Log2_32(NumParts) : NumParts;
391 unsigned RoundBits = PartBits * RoundParts;
392 MVT RoundVT = RoundBits == ValueBits ?
393 ValueVT : MVT::getIntegerVT(RoundBits);
394 SDValue Lo, Hi;
395
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000396 MVT HalfVT = ValueVT.isInteger() ?
397 MVT::getIntegerVT(RoundBits/2) :
398 MVT::getFloatingPointVT(RoundBits/2);
399
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000400 if (RoundParts > 2) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000401 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
402 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
403 PartVT, HalfVT);
404 } else {
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000405 Lo = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[0]);
406 Hi = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000407 }
408 if (TLI.isBigEndian())
409 std::swap(Lo, Hi);
410 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
411
412 if (RoundParts < NumParts) {
413 // Assemble the trailing non-power-of-2 part.
414 unsigned OddParts = NumParts - RoundParts;
415 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
416 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
417
418 // Combine the round and odd parts.
419 Lo = Val;
420 if (TLI.isBigEndian())
421 std::swap(Lo, Hi);
422 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
423 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
424 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
425 DAG.getConstant(Lo.getValueType().getSizeInBits(),
426 TLI.getShiftAmountTy()));
427 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
428 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
429 }
430 } else {
431 // Handle a multi-element vector.
432 MVT IntermediateVT, RegisterVT;
433 unsigned NumIntermediates;
434 unsigned NumRegs =
435 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
436 RegisterVT);
437 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
438 NumParts = NumRegs; // Silence a compiler warning.
439 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
440 assert(RegisterVT == Parts[0].getValueType() &&
441 "Part type doesn't match part!");
442
443 // Assemble the parts into intermediate operands.
444 SmallVector<SDValue, 8> Ops(NumIntermediates);
445 if (NumIntermediates == NumParts) {
446 // If the register was not expanded, truncate or copy the value,
447 // as appropriate.
448 for (unsigned i = 0; i != NumParts; ++i)
449 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
450 PartVT, IntermediateVT);
451 } else if (NumParts > 0) {
452 // If the intermediate type was expanded, build the intermediate operands
453 // from the parts.
454 assert(NumParts % NumIntermediates == 0 &&
455 "Must expand into a divisible number of parts!");
456 unsigned Factor = NumParts / NumIntermediates;
457 for (unsigned i = 0; i != NumIntermediates; ++i)
458 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
459 PartVT, IntermediateVT);
460 }
461
462 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
463 // operands.
464 Val = DAG.getNode(IntermediateVT.isVector() ?
465 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
466 ValueVT, &Ops[0], NumIntermediates);
467 }
468 }
469
470 // There is now one part, held in Val. Correct it to match ValueVT.
471 PartVT = Val.getValueType();
472
473 if (PartVT == ValueVT)
474 return Val;
475
476 if (PartVT.isVector()) {
477 assert(ValueVT.isVector() && "Unknown vector conversion!");
478 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
479 }
480
481 if (ValueVT.isVector()) {
482 assert(ValueVT.getVectorElementType() == PartVT &&
483 ValueVT.getVectorNumElements() == 1 &&
484 "Only trivial scalar-to-vector conversions should get here!");
485 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
486 }
487
488 if (PartVT.isInteger() &&
489 ValueVT.isInteger()) {
490 if (ValueVT.bitsLT(PartVT)) {
491 // For a truncate, see if we have any information to
492 // indicate whether the truncated bits will always be
493 // zero or sign-extension.
494 if (AssertOp != ISD::DELETED_NODE)
495 Val = DAG.getNode(AssertOp, PartVT, Val,
496 DAG.getValueType(ValueVT));
497 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
498 } else {
499 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
500 }
501 }
502
503 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
504 if (ValueVT.bitsLT(Val.getValueType()))
505 // FP_ROUND's are always exact here.
506 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
507 DAG.getIntPtrConstant(1));
508 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
509 }
510
511 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
512 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
513
514 assert(0 && "Unknown mismatch!");
515 return SDValue();
516}
517
518/// getCopyToParts - Create a series of nodes that contain the specified value
519/// split into legal parts. If the parts contain more bits than Val, then, for
520/// integers, ExtendKind can be used to specify how to generate the extra bits.
Chris Lattner01426e12008-10-21 00:45:36 +0000521static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
522 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000523 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
524 TargetLowering &TLI = DAG.getTargetLoweringInfo();
525 MVT PtrVT = TLI.getPointerTy();
526 MVT ValueVT = Val.getValueType();
527 unsigned PartBits = PartVT.getSizeInBits();
528 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
529
530 if (!NumParts)
531 return;
532
533 if (!ValueVT.isVector()) {
534 if (PartVT == ValueVT) {
535 assert(NumParts == 1 && "No-op copy with multiple parts!");
536 Parts[0] = Val;
537 return;
538 }
539
540 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
541 // If the parts cover more bits than the value has, promote the value.
542 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
543 assert(NumParts == 1 && "Do not know what to promote to!");
544 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
545 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
546 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
547 Val = DAG.getNode(ExtendKind, ValueVT, Val);
548 } else {
549 assert(0 && "Unknown mismatch!");
550 }
551 } else if (PartBits == ValueVT.getSizeInBits()) {
552 // Different types of the same size.
553 assert(NumParts == 1 && PartVT != ValueVT);
554 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
555 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
556 // If the parts cover less bits than value has, truncate the value.
557 if (PartVT.isInteger() && ValueVT.isInteger()) {
558 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
559 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
560 } else {
561 assert(0 && "Unknown mismatch!");
562 }
563 }
564
565 // The value may have changed - recompute ValueVT.
566 ValueVT = Val.getValueType();
567 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
568 "Failed to tile the value with PartVT!");
569
570 if (NumParts == 1) {
571 assert(PartVT == ValueVT && "Type conversion failed!");
572 Parts[0] = Val;
573 return;
574 }
575
576 // Expand the value into multiple parts.
577 if (NumParts & (NumParts - 1)) {
578 // The number of parts is not a power of 2. Split off and copy the tail.
579 assert(PartVT.isInteger() && ValueVT.isInteger() &&
580 "Do not know what to expand to!");
581 unsigned RoundParts = 1 << Log2_32(NumParts);
582 unsigned RoundBits = RoundParts * PartBits;
583 unsigned OddParts = NumParts - RoundParts;
584 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
585 DAG.getConstant(RoundBits,
586 TLI.getShiftAmountTy()));
587 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
588 if (TLI.isBigEndian())
589 // The odd parts were reversed by getCopyToParts - unreverse them.
590 std::reverse(Parts + RoundParts, Parts + NumParts);
591 NumParts = RoundParts;
592 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
593 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
594 }
595
596 // The number of parts is a power of 2. Repeatedly bisect the value using
597 // EXTRACT_ELEMENT.
598 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
599 MVT::getIntegerVT(ValueVT.getSizeInBits()),
600 Val);
601 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
602 for (unsigned i = 0; i < NumParts; i += StepSize) {
603 unsigned ThisBits = StepSize * PartBits / 2;
604 MVT ThisVT = MVT::getIntegerVT (ThisBits);
605 SDValue &Part0 = Parts[i];
606 SDValue &Part1 = Parts[i+StepSize/2];
607
608 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
609 DAG.getConstant(1, PtrVT));
610 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
611 DAG.getConstant(0, PtrVT));
612
613 if (ThisBits == PartBits && ThisVT != PartVT) {
614 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
615 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
616 }
617 }
618 }
619
620 if (TLI.isBigEndian())
621 std::reverse(Parts, Parts + NumParts);
622
623 return;
624 }
625
626 // Vector ValueVT.
627 if (NumParts == 1) {
628 if (PartVT != ValueVT) {
629 if (PartVT.isVector()) {
630 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
631 } else {
632 assert(ValueVT.getVectorElementType() == PartVT &&
633 ValueVT.getVectorNumElements() == 1 &&
634 "Only trivial vector-to-scalar conversions should get here!");
635 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
636 DAG.getConstant(0, PtrVT));
637 }
638 }
639
640 Parts[0] = Val;
641 return;
642 }
643
644 // Handle a multi-element vector.
645 MVT IntermediateVT, RegisterVT;
646 unsigned NumIntermediates;
647 unsigned NumRegs =
648 DAG.getTargetLoweringInfo()
649 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
650 RegisterVT);
651 unsigned NumElements = ValueVT.getVectorNumElements();
652
653 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
654 NumParts = NumRegs; // Silence a compiler warning.
655 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
656
657 // Split the vector into intermediate operands.
658 SmallVector<SDValue, 8> Ops(NumIntermediates);
659 for (unsigned i = 0; i != NumIntermediates; ++i)
660 if (IntermediateVT.isVector())
661 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
662 IntermediateVT, Val,
663 DAG.getConstant(i * (NumElements / NumIntermediates),
664 PtrVT));
665 else
666 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
667 IntermediateVT, Val,
668 DAG.getConstant(i, PtrVT));
669
670 // Split the intermediate operands into legal parts.
671 if (NumParts == NumIntermediates) {
672 // If the register was not expanded, promote or copy the value,
673 // as appropriate.
674 for (unsigned i = 0; i != NumParts; ++i)
675 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
676 } else if (NumParts > 0) {
677 // If the intermediate type was expanded, split each the value into
678 // legal parts.
679 assert(NumParts % NumIntermediates == 0 &&
680 "Must expand into a divisible number of parts!");
681 unsigned Factor = NumParts / NumIntermediates;
682 for (unsigned i = 0; i != NumIntermediates; ++i)
683 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
684 }
685}
686
687
688void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
689 AA = &aa;
690 GFI = gfi;
691 TD = DAG.getTarget().getTargetData();
692}
693
694/// clear - Clear out the curret SelectionDAG and the associated
695/// state and prepare this SelectionDAGLowering object to be used
696/// for a new block. This doesn't clear out information about
697/// additional blocks that are needed to complete switch lowering
698/// or PHI node updating; that information is cleared out as it is
699/// consumed.
700void SelectionDAGLowering::clear() {
701 NodeMap.clear();
702 PendingLoads.clear();
703 PendingExports.clear();
704 DAG.clear();
705}
706
707/// getRoot - Return the current virtual root of the Selection DAG,
708/// flushing any PendingLoad items. This must be done before emitting
709/// a store or any other node that may need to be ordered after any
710/// prior load instructions.
711///
712SDValue SelectionDAGLowering::getRoot() {
713 if (PendingLoads.empty())
714 return DAG.getRoot();
715
716 if (PendingLoads.size() == 1) {
717 SDValue Root = PendingLoads[0];
718 DAG.setRoot(Root);
719 PendingLoads.clear();
720 return Root;
721 }
722
723 // Otherwise, we have to make a token factor node.
724 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
725 &PendingLoads[0], PendingLoads.size());
726 PendingLoads.clear();
727 DAG.setRoot(Root);
728 return Root;
729}
730
731/// getControlRoot - Similar to getRoot, but instead of flushing all the
732/// PendingLoad items, flush all the PendingExports items. It is necessary
733/// to do this before emitting a terminator instruction.
734///
735SDValue SelectionDAGLowering::getControlRoot() {
736 SDValue Root = DAG.getRoot();
737
738 if (PendingExports.empty())
739 return Root;
740
741 // Turn all of the CopyToReg chains into one factored node.
742 if (Root.getOpcode() != ISD::EntryToken) {
743 unsigned i = 0, e = PendingExports.size();
744 for (; i != e; ++i) {
745 assert(PendingExports[i].getNode()->getNumOperands() > 1);
746 if (PendingExports[i].getNode()->getOperand(0) == Root)
747 break; // Don't add the root if we already indirectly depend on it.
748 }
749
750 if (i == e)
751 PendingExports.push_back(Root);
752 }
753
754 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
755 &PendingExports[0],
756 PendingExports.size());
757 PendingExports.clear();
758 DAG.setRoot(Root);
759 return Root;
760}
761
762void SelectionDAGLowering::visit(Instruction &I) {
763 visit(I.getOpcode(), I);
764}
765
766void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
767 // Note: this doesn't use InstVisitor, because it has to work with
768 // ConstantExpr's in addition to instructions.
769 switch (Opcode) {
770 default: assert(0 && "Unknown instruction type encountered!");
771 abort();
772 // Build the switch statement using the Instruction.def file.
773#define HANDLE_INST(NUM, OPCODE, CLASS) \
774 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
775#include "llvm/Instruction.def"
776 }
777}
778
779void SelectionDAGLowering::visitAdd(User &I) {
780 if (I.getType()->isFPOrFPVector())
781 visitBinary(I, ISD::FADD);
782 else
783 visitBinary(I, ISD::ADD);
784}
785
786void SelectionDAGLowering::visitMul(User &I) {
787 if (I.getType()->isFPOrFPVector())
788 visitBinary(I, ISD::FMUL);
789 else
790 visitBinary(I, ISD::MUL);
791}
792
793SDValue SelectionDAGLowering::getValue(const Value *V) {
794 SDValue &N = NodeMap[V];
795 if (N.getNode()) return N;
796
797 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
798 MVT VT = TLI.getValueType(V->getType(), true);
799
800 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000801 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000802
803 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
804 return N = DAG.getGlobalAddress(GV, VT);
805
806 if (isa<ConstantPointerNull>(C))
807 return N = DAG.getConstant(0, TLI.getPointerTy());
808
809 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000810 return N = DAG.getConstantFP(*CFP, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000811
812 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
813 !V->getType()->isAggregateType())
814 return N = DAG.getNode(ISD::UNDEF, VT);
815
816 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
817 visit(CE->getOpcode(), *CE);
818 SDValue N1 = NodeMap[V];
819 assert(N1.getNode() && "visit didn't populate the ValueMap!");
820 return N1;
821 }
822
823 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
824 SmallVector<SDValue, 4> Constants;
825 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
826 OI != OE; ++OI) {
827 SDNode *Val = getValue(*OI).getNode();
828 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
829 Constants.push_back(SDValue(Val, i));
830 }
831 return DAG.getMergeValues(&Constants[0], Constants.size());
832 }
833
834 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
835 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
836 "Unknown struct or array constant!");
837
838 SmallVector<MVT, 4> ValueVTs;
839 ComputeValueVTs(TLI, C->getType(), ValueVTs);
840 unsigned NumElts = ValueVTs.size();
841 if (NumElts == 0)
842 return SDValue(); // empty struct
843 SmallVector<SDValue, 4> Constants(NumElts);
844 for (unsigned i = 0; i != NumElts; ++i) {
845 MVT EltVT = ValueVTs[i];
846 if (isa<UndefValue>(C))
847 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
848 else if (EltVT.isFloatingPoint())
849 Constants[i] = DAG.getConstantFP(0, EltVT);
850 else
851 Constants[i] = DAG.getConstant(0, EltVT);
852 }
853 return DAG.getMergeValues(&Constants[0], NumElts);
854 }
855
856 const VectorType *VecTy = cast<VectorType>(V->getType());
857 unsigned NumElements = VecTy->getNumElements();
858
859 // Now that we know the number and type of the elements, get that number of
860 // elements into the Ops array based on what kind of constant it is.
861 SmallVector<SDValue, 16> Ops;
862 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
863 for (unsigned i = 0; i != NumElements; ++i)
864 Ops.push_back(getValue(CP->getOperand(i)));
865 } else {
866 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
867 "Unknown vector constant!");
868 MVT EltVT = TLI.getValueType(VecTy->getElementType());
869
870 SDValue Op;
871 if (isa<UndefValue>(C))
872 Op = DAG.getNode(ISD::UNDEF, EltVT);
873 else if (EltVT.isFloatingPoint())
874 Op = DAG.getConstantFP(0, EltVT);
875 else
876 Op = DAG.getConstant(0, EltVT);
877 Ops.assign(NumElements, Op);
878 }
879
880 // Create a BUILD_VECTOR node.
881 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
882 }
883
884 // If this is a static alloca, generate it as the frameindex instead of
885 // computation.
886 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
887 DenseMap<const AllocaInst*, int>::iterator SI =
888 FuncInfo.StaticAllocaMap.find(AI);
889 if (SI != FuncInfo.StaticAllocaMap.end())
890 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
891 }
892
893 unsigned InReg = FuncInfo.ValueMap[V];
894 assert(InReg && "Value not in map!");
895
896 RegsForValue RFV(TLI, InReg, V->getType());
897 SDValue Chain = DAG.getEntryNode();
898 return RFV.getCopyFromRegs(DAG, Chain, NULL);
899}
900
901
902void SelectionDAGLowering::visitRet(ReturnInst &I) {
903 if (I.getNumOperands() == 0) {
904 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
905 return;
906 }
907
908 SmallVector<SDValue, 8> NewValues;
909 NewValues.push_back(getControlRoot());
910 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000911 SmallVector<MVT, 4> ValueVTs;
912 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000913 unsigned NumValues = ValueVTs.size();
914 if (NumValues == 0) continue;
915
916 SDValue RetOp = getValue(I.getOperand(i));
917 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000918 MVT VT = ValueVTs[j];
919
920 // FIXME: C calling convention requires the return type to be promoted to
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000921 // at least 32-bit. But this is not necessary for non-C calling
922 // conventions.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000923 if (VT.isInteger()) {
924 MVT MinVT = TLI.getRegisterType(MVT::i32);
925 if (VT.bitsLT(MinVT))
926 VT = MinVT;
927 }
928
929 unsigned NumParts = TLI.getNumRegisters(VT);
930 MVT PartVT = TLI.getRegisterType(VT);
931 SmallVector<SDValue, 4> Parts(NumParts);
932 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
933
934 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000935 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000936 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000937 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000938 ExtendKind = ISD::ZERO_EXTEND;
939
940 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
941 &Parts[0], NumParts, PartVT, ExtendKind);
942
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000943 // 'inreg' on function refers to return value
944 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000945 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000946 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000947 for (unsigned i = 0; i < NumParts; ++i) {
948 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000949 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000950 }
951 }
952 }
953 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
954 &NewValues[0], NewValues.size()));
955}
956
957/// ExportFromCurrentBlock - If this condition isn't known to be exported from
958/// the current basic block, add it to ValueMap now so that we'll get a
959/// CopyTo/FromReg.
960void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
961 // No need to export constants.
962 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
963
964 // Already exported?
965 if (FuncInfo.isExportedInst(V)) return;
966
967 unsigned Reg = FuncInfo.InitializeRegForValue(V);
968 CopyValueToVirtualRegister(V, Reg);
969}
970
971bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
972 const BasicBlock *FromBB) {
973 // The operands of the setcc have to be in this block. We don't know
974 // how to export them from some other block.
975 if (Instruction *VI = dyn_cast<Instruction>(V)) {
976 // Can export from current BB.
977 if (VI->getParent() == FromBB)
978 return true;
979
980 // Is already exported, noop.
981 return FuncInfo.isExportedInst(V);
982 }
983
984 // If this is an argument, we can export it if the BB is the entry block or
985 // if it is already exported.
986 if (isa<Argument>(V)) {
987 if (FromBB == &FromBB->getParent()->getEntryBlock())
988 return true;
989
990 // Otherwise, can only export this if it is already exported.
991 return FuncInfo.isExportedInst(V);
992 }
993
994 // Otherwise, constants can always be exported.
995 return true;
996}
997
998static bool InBlock(const Value *V, const BasicBlock *BB) {
999 if (const Instruction *I = dyn_cast<Instruction>(V))
1000 return I->getParent() == BB;
1001 return true;
1002}
1003
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001004/// getFCmpCondCode - Return the ISD condition code corresponding to
1005/// the given LLVM IR floating-point condition code. This includes
1006/// consideration of global floating-point math flags.
1007///
1008static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1009 ISD::CondCode FPC, FOC;
1010 switch (Pred) {
1011 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1012 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1013 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1014 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1015 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1016 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1017 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1018 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1019 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1020 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1021 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1022 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1023 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1024 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1025 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1026 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1027 default:
1028 assert(0 && "Invalid FCmp predicate opcode!");
1029 FOC = FPC = ISD::SETFALSE;
1030 break;
1031 }
1032 if (FiniteOnlyFPMath())
1033 return FOC;
1034 else
1035 return FPC;
1036}
1037
1038/// getICmpCondCode - Return the ISD condition code corresponding to
1039/// the given LLVM IR integer condition code.
1040///
1041static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1042 switch (Pred) {
1043 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1044 case ICmpInst::ICMP_NE: return ISD::SETNE;
1045 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1046 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1047 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1048 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1049 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1050 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1051 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1052 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1053 default:
1054 assert(0 && "Invalid ICmp predicate opcode!");
1055 return ISD::SETNE;
1056 }
1057}
1058
Dan Gohmanc2277342008-10-17 21:16:08 +00001059/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1060/// This function emits a branch and is used at the leaves of an OR or an
1061/// AND operator tree.
1062///
1063void
1064SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1065 MachineBasicBlock *TBB,
1066 MachineBasicBlock *FBB,
1067 MachineBasicBlock *CurBB) {
1068 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001069
Dan Gohmanc2277342008-10-17 21:16:08 +00001070 // If the leaf of the tree is a comparison, merge the condition into
1071 // the caseblock.
1072 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1073 // The operands of the cmp have to be in this block. We don't know
1074 // how to export them from some other block. If this is the first block
1075 // of the sequence, no exporting is needed.
1076 if (CurBB == CurMBB ||
1077 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1078 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001079 ISD::CondCode Condition;
1080 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001081 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001082 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001083 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001084 } else {
1085 Condition = ISD::SETEQ; // silence warning.
1086 assert(0 && "Unknown compare instruction");
1087 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001088
1089 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001090 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1091 SwitchCases.push_back(CB);
1092 return;
1093 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001094 }
1095
1096 // Create a CaseBlock record representing this branch.
1097 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1098 NULL, TBB, FBB, CurBB);
1099 SwitchCases.push_back(CB);
1100}
1101
1102/// FindMergedConditions - If Cond is an expression like
1103void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1104 MachineBasicBlock *TBB,
1105 MachineBasicBlock *FBB,
1106 MachineBasicBlock *CurBB,
1107 unsigned Opc) {
1108 // If this node is not part of the or/and tree, emit it as a branch.
1109 Instruction *BOp = dyn_cast<Instruction>(Cond);
1110 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1111 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1112 BOp->getParent() != CurBB->getBasicBlock() ||
1113 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1114 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1115 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001116 return;
1117 }
1118
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001119 // Create TmpBB after CurBB.
1120 MachineFunction::iterator BBI = CurBB;
1121 MachineFunction &MF = DAG.getMachineFunction();
1122 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1123 CurBB->getParent()->insert(++BBI, TmpBB);
1124
1125 if (Opc == Instruction::Or) {
1126 // Codegen X | Y as:
1127 // jmp_if_X TBB
1128 // jmp TmpBB
1129 // TmpBB:
1130 // jmp_if_Y TBB
1131 // jmp FBB
1132 //
1133
1134 // Emit the LHS condition.
1135 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1136
1137 // Emit the RHS condition into TmpBB.
1138 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1139 } else {
1140 assert(Opc == Instruction::And && "Unknown merge op!");
1141 // Codegen X & Y as:
1142 // jmp_if_X TmpBB
1143 // jmp FBB
1144 // TmpBB:
1145 // jmp_if_Y TBB
1146 // jmp FBB
1147 //
1148 // This requires creation of TmpBB after CurBB.
1149
1150 // Emit the LHS condition.
1151 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1152
1153 // Emit the RHS condition into TmpBB.
1154 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1155 }
1156}
1157
1158/// If the set of cases should be emitted as a series of branches, return true.
1159/// If we should emit this as a bunch of and/or'd together conditions, return
1160/// false.
1161bool
1162SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1163 if (Cases.size() != 2) return true;
1164
1165 // If this is two comparisons of the same values or'd or and'd together, they
1166 // will get folded into a single comparison, so don't emit two blocks.
1167 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1168 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1169 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1170 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1171 return false;
1172 }
1173
1174 return true;
1175}
1176
1177void SelectionDAGLowering::visitBr(BranchInst &I) {
1178 // Update machine-CFG edges.
1179 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1180
1181 // Figure out which block is immediately after the current one.
1182 MachineBasicBlock *NextBlock = 0;
1183 MachineFunction::iterator BBI = CurMBB;
1184 if (++BBI != CurMBB->getParent()->end())
1185 NextBlock = BBI;
1186
1187 if (I.isUnconditional()) {
1188 // Update machine-CFG edges.
1189 CurMBB->addSuccessor(Succ0MBB);
1190
1191 // If this is not a fall-through branch, emit the branch.
1192 if (Succ0MBB != NextBlock)
1193 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1194 DAG.getBasicBlock(Succ0MBB)));
1195 return;
1196 }
1197
1198 // If this condition is one of the special cases we handle, do special stuff
1199 // now.
1200 Value *CondVal = I.getCondition();
1201 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1202
1203 // If this is a series of conditions that are or'd or and'd together, emit
1204 // this as a sequence of branches instead of setcc's with and/or operations.
1205 // For example, instead of something like:
1206 // cmp A, B
1207 // C = seteq
1208 // cmp D, E
1209 // F = setle
1210 // or C, F
1211 // jnz foo
1212 // Emit:
1213 // cmp A, B
1214 // je foo
1215 // cmp D, E
1216 // jle foo
1217 //
1218 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1219 if (BOp->hasOneUse() &&
1220 (BOp->getOpcode() == Instruction::And ||
1221 BOp->getOpcode() == Instruction::Or)) {
1222 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1223 // If the compares in later blocks need to use values not currently
1224 // exported from this block, export them now. This block should always
1225 // be the first entry.
1226 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1227
1228 // Allow some cases to be rejected.
1229 if (ShouldEmitAsBranches(SwitchCases)) {
1230 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1231 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1232 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1233 }
1234
1235 // Emit the branch for this block.
1236 visitSwitchCase(SwitchCases[0]);
1237 SwitchCases.erase(SwitchCases.begin());
1238 return;
1239 }
1240
1241 // Okay, we decided not to do this, remove any inserted MBB's and clear
1242 // SwitchCases.
1243 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1244 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1245
1246 SwitchCases.clear();
1247 }
1248 }
1249
1250 // Create a CaseBlock record representing this branch.
1251 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1252 NULL, Succ0MBB, Succ1MBB, CurMBB);
1253 // Use visitSwitchCase to actually insert the fast branch sequence for this
1254 // cond branch.
1255 visitSwitchCase(CB);
1256}
1257
1258/// visitSwitchCase - Emits the necessary code to represent a single node in
1259/// the binary search tree resulting from lowering a switch instruction.
1260void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1261 SDValue Cond;
1262 SDValue CondLHS = getValue(CB.CmpLHS);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001263
1264 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001265 if (CB.CmpMHS == NULL) {
1266 // Fold "(X == true)" to X and "(X == false)" to !X to
1267 // handle common cases produced by branch lowering.
1268 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1269 Cond = CondLHS;
1270 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1271 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1272 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1273 } else
1274 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1275 } else {
1276 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1277
Anton Korobeynikov23218582008-12-23 22:25:27 +00001278 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1279 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001280
1281 SDValue CmpOp = getValue(CB.CmpMHS);
1282 MVT VT = CmpOp.getValueType();
1283
1284 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1285 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1286 } else {
1287 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1288 Cond = DAG.getSetCC(MVT::i1, SUB,
1289 DAG.getConstant(High-Low, VT), ISD::SETULE);
1290 }
1291 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001292
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001293 // Update successor info
1294 CurMBB->addSuccessor(CB.TrueBB);
1295 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001296
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001297 // Set NextBlock to be the MBB immediately after the current one, if any.
1298 // This is used to avoid emitting unnecessary branches to the next block.
1299 MachineBasicBlock *NextBlock = 0;
1300 MachineFunction::iterator BBI = CurMBB;
1301 if (++BBI != CurMBB->getParent()->end())
1302 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001303
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001304 // If the lhs block is the next block, invert the condition so that we can
1305 // fall through to the lhs instead of the rhs block.
1306 if (CB.TrueBB == NextBlock) {
1307 std::swap(CB.TrueBB, CB.FalseBB);
1308 SDValue True = DAG.getConstant(1, Cond.getValueType());
1309 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1310 }
1311 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1312 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001313
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001314 // If the branch was constant folded, fix up the CFG.
1315 if (BrCond.getOpcode() == ISD::BR) {
1316 CurMBB->removeSuccessor(CB.FalseBB);
1317 DAG.setRoot(BrCond);
1318 } else {
1319 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001320 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001321 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001322
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001323 if (CB.FalseBB == NextBlock)
1324 DAG.setRoot(BrCond);
1325 else
Anton Korobeynikov23218582008-12-23 22:25:27 +00001326 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001327 DAG.getBasicBlock(CB.FalseBB)));
1328 }
1329}
1330
1331/// visitJumpTable - Emit JumpTable node in the current MBB
1332void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1333 // Emit the code for the jump table
1334 assert(JT.Reg != -1U && "Should lower JT Header first!");
1335 MVT PTy = TLI.getPointerTy();
1336 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1337 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1338 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1339 Table, Index));
1340 return;
1341}
1342
1343/// visitJumpTableHeader - This function emits necessary code to produce index
1344/// in the JumpTable from switch case.
1345void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1346 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001347 // Subtract the lowest switch case value from the value being switched on and
1348 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001349 // difference between smallest and largest cases.
1350 SDValue SwitchOp = getValue(JTH.SValue);
1351 MVT VT = SwitchOp.getValueType();
1352 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001353 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001354
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001355 // The SDNode we just created, which holds the value being switched on minus
1356 // the the smallest case value, needs to be copied to a virtual register so it
1357 // can be used as an index into the jump table in a subsequent basic block.
1358 // This value may be smaller or larger than the target's pointer type, and
1359 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001360 if (VT.bitsGT(TLI.getPointerTy()))
1361 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1362 else
1363 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001364
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001365 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1366 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1367 JT.Reg = JumpTableReg;
1368
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001369 // Emit the range check for the jump table, and branch to the default block
1370 // for the switch statement if the value being switched on exceeds the largest
1371 // case in the switch.
Duncan Sands5480c042009-01-01 15:52:00 +00001372 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001373 DAG.getConstant(JTH.Last-JTH.First,VT),
1374 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001375
1376 // Set NextBlock to be the MBB immediately after the current one, if any.
1377 // This is used to avoid emitting unnecessary branches to the next block.
1378 MachineBasicBlock *NextBlock = 0;
1379 MachineFunction::iterator BBI = CurMBB;
1380 if (++BBI != CurMBB->getParent()->end())
1381 NextBlock = BBI;
1382
1383 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001384 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001385
1386 if (JT.MBB == NextBlock)
1387 DAG.setRoot(BrCond);
1388 else
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001389 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001390 DAG.getBasicBlock(JT.MBB)));
1391
1392 return;
1393}
1394
1395/// visitBitTestHeader - This function emits necessary code to produce value
1396/// suitable for "bit tests"
1397void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1398 // Subtract the minimum value
1399 SDValue SwitchOp = getValue(B.SValue);
1400 MVT VT = SwitchOp.getValueType();
1401 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001402 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001403
1404 // Check range
Duncan Sands5480c042009-01-01 15:52:00 +00001405 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001406 DAG.getConstant(B.Range, VT),
1407 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001408
1409 SDValue ShiftOp;
1410 if (VT.bitsGT(TLI.getShiftAmountTy()))
1411 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1412 else
1413 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1414
1415 // Make desired shift
1416 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001417 DAG.getConstant(1, TLI.getPointerTy()),
1418 ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001419
1420 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1421 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1422 B.Reg = SwitchReg;
1423
1424 // Set NextBlock to be the MBB immediately after the current one, if any.
1425 // This is used to avoid emitting unnecessary branches to the next block.
1426 MachineBasicBlock *NextBlock = 0;
1427 MachineFunction::iterator BBI = CurMBB;
1428 if (++BBI != CurMBB->getParent()->end())
1429 NextBlock = BBI;
1430
1431 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1432
1433 CurMBB->addSuccessor(B.Default);
1434 CurMBB->addSuccessor(MBB);
1435
1436 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001437 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001438
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001439 if (MBB == NextBlock)
1440 DAG.setRoot(BrRange);
1441 else
1442 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1443 DAG.getBasicBlock(MBB)));
1444
1445 return;
1446}
1447
1448/// visitBitTestCase - this function produces one "bit test"
1449void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1450 unsigned Reg,
1451 BitTestCase &B) {
1452 // Emit bit tests and jumps
Anton Korobeynikov23218582008-12-23 22:25:27 +00001453 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001454 TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001455
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001456 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001457 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Duncan Sands5480c042009-01-01 15:52:00 +00001458 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp.getValueType()),
1459 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001460 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001461
1462 CurMBB->addSuccessor(B.TargetBB);
1463 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001464
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001465 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001466 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001467
1468 // Set NextBlock to be the MBB immediately after the current one, if any.
1469 // This is used to avoid emitting unnecessary branches to the next block.
1470 MachineBasicBlock *NextBlock = 0;
1471 MachineFunction::iterator BBI = CurMBB;
1472 if (++BBI != CurMBB->getParent()->end())
1473 NextBlock = BBI;
1474
1475 if (NextMBB == NextBlock)
1476 DAG.setRoot(BrAnd);
1477 else
1478 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1479 DAG.getBasicBlock(NextMBB)));
1480
1481 return;
1482}
1483
1484void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1485 // Retrieve successors.
1486 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1487 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1488
1489 if (isa<InlineAsm>(I.getCalledValue()))
1490 visitInlineAsm(&I);
1491 else
1492 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1493
1494 // If the value of the invoke is used outside of its defining block, make it
1495 // available as a virtual register.
1496 if (!I.use_empty()) {
1497 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1498 if (VMI != FuncInfo.ValueMap.end())
1499 CopyValueToVirtualRegister(&I, VMI->second);
1500 }
1501
1502 // Update successor info
1503 CurMBB->addSuccessor(Return);
1504 CurMBB->addSuccessor(LandingPad);
1505
1506 // Drop into normal successor.
1507 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1508 DAG.getBasicBlock(Return)));
1509}
1510
1511void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1512}
1513
1514/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1515/// small case ranges).
1516bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1517 CaseRecVector& WorkList,
1518 Value* SV,
1519 MachineBasicBlock* Default) {
1520 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001521
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001522 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001523 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001524 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001525 return false;
1526
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001527 // Get the MachineFunction which holds the current MBB. This is used when
1528 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001529 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001530
1531 // Figure out which block is immediately after the current one.
1532 MachineBasicBlock *NextBlock = 0;
1533 MachineFunction::iterator BBI = CR.CaseBB;
1534
1535 if (++BBI != CurMBB->getParent()->end())
1536 NextBlock = BBI;
1537
1538 // TODO: If any two of the cases has the same destination, and if one value
1539 // is the same as the other, but has one bit unset that the other has set,
1540 // use bit manipulation to do two compares at once. For example:
1541 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001542
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001543 // Rearrange the case blocks so that the last one falls through if possible.
1544 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1545 // The last case block won't fall through into 'NextBlock' if we emit the
1546 // branches in this order. See if rearranging a case value would help.
1547 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1548 if (I->BB == NextBlock) {
1549 std::swap(*I, BackCase);
1550 break;
1551 }
1552 }
1553 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001554
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001555 // Create a CaseBlock record representing a conditional branch to
1556 // the Case's target mbb if the value being switched on SV is equal
1557 // to C.
1558 MachineBasicBlock *CurBlock = CR.CaseBB;
1559 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1560 MachineBasicBlock *FallThrough;
1561 if (I != E-1) {
1562 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1563 CurMF->insert(BBI, FallThrough);
1564 } else {
1565 // If the last case doesn't match, go to the default block.
1566 FallThrough = Default;
1567 }
1568
1569 Value *RHS, *LHS, *MHS;
1570 ISD::CondCode CC;
1571 if (I->High == I->Low) {
1572 // This is just small small case range :) containing exactly 1 case
1573 CC = ISD::SETEQ;
1574 LHS = SV; RHS = I->High; MHS = NULL;
1575 } else {
1576 CC = ISD::SETLE;
1577 LHS = I->Low; MHS = SV; RHS = I->High;
1578 }
1579 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001580
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001581 // If emitting the first comparison, just call visitSwitchCase to emit the
1582 // code into the current block. Otherwise, push the CaseBlock onto the
1583 // vector to be later processed by SDISel, and insert the node's MBB
1584 // before the next MBB.
1585 if (CurBlock == CurMBB)
1586 visitSwitchCase(CB);
1587 else
1588 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001589
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001590 CurBlock = FallThrough;
1591 }
1592
1593 return true;
1594}
1595
1596static inline bool areJTsAllowed(const TargetLowering &TLI) {
1597 return !DisableJumpTables &&
1598 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1599 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1600}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001601
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001602static APInt ComputeRange(const APInt &First, const APInt &Last) {
1603 APInt LastExt(Last), FirstExt(First);
1604 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1605 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1606 return (LastExt - FirstExt + 1ULL);
1607}
1608
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001609/// handleJTSwitchCase - Emit jumptable for current switch case range
1610bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1611 CaseRecVector& WorkList,
1612 Value* SV,
1613 MachineBasicBlock* Default) {
1614 Case& FrontCase = *CR.Range.first;
1615 Case& BackCase = *(CR.Range.second-1);
1616
Anton Korobeynikov23218582008-12-23 22:25:27 +00001617 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1618 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001619
Anton Korobeynikov23218582008-12-23 22:25:27 +00001620 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001621 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1622 I!=E; ++I)
1623 TSize += I->size();
1624
1625 if (!areJTsAllowed(TLI) || TSize <= 3)
1626 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001627
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001628 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001629 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001630 if (Density < 0.4)
1631 return false;
1632
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001633 DEBUG(errs() << "Lowering jump table\n"
1634 << "First entry: " << First << ". Last entry: " << Last << '\n'
1635 << "Range: " << Range
1636 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001637
1638 // Get the MachineFunction which holds the current MBB. This is used when
1639 // inserting any additional MBBs necessary to represent the switch.
1640 MachineFunction *CurMF = CurMBB->getParent();
1641
1642 // Figure out which block is immediately after the current one.
1643 MachineBasicBlock *NextBlock = 0;
1644 MachineFunction::iterator BBI = CR.CaseBB;
1645
1646 if (++BBI != CurMBB->getParent()->end())
1647 NextBlock = BBI;
1648
1649 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1650
1651 // Create a new basic block to hold the code for loading the address
1652 // of the jump table, and jumping to it. Update successor information;
1653 // we will either branch to the default case for the switch, or the jump
1654 // table.
1655 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1656 CurMF->insert(BBI, JumpTableBB);
1657 CR.CaseBB->addSuccessor(Default);
1658 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001659
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001660 // Build a vector of destination BBs, corresponding to each target
1661 // of the jump table. If the value of the jump table slot corresponds to
1662 // a case statement, push the case's BB onto the vector, otherwise, push
1663 // the default BB.
1664 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001665 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001666 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001667 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1668 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1669
1670 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001671 DestBBs.push_back(I->BB);
1672 if (TEI==High)
1673 ++I;
1674 } else {
1675 DestBBs.push_back(Default);
1676 }
1677 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001678
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001679 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001680 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1681 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001682 E = DestBBs.end(); I != E; ++I) {
1683 if (!SuccsHandled[(*I)->getNumber()]) {
1684 SuccsHandled[(*I)->getNumber()] = true;
1685 JumpTableBB->addSuccessor(*I);
1686 }
1687 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001688
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001689 // Create a jump table index for this jump table, or return an existing
1690 // one.
1691 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001692
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001693 // Set the jump table information so that we can codegen it as a second
1694 // MachineBasicBlock
1695 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1696 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1697 if (CR.CaseBB == CurMBB)
1698 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001699
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001700 JTCases.push_back(JumpTableBlock(JTH, JT));
1701
1702 return true;
1703}
1704
1705/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1706/// 2 subtrees.
1707bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1708 CaseRecVector& WorkList,
1709 Value* SV,
1710 MachineBasicBlock* Default) {
1711 // Get the MachineFunction which holds the current MBB. This is used when
1712 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001713 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001714
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 Case& FrontCase = *CR.Range.first;
1723 Case& BackCase = *(CR.Range.second-1);
1724 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1725
1726 // Size is the number of Cases represented by this range.
1727 unsigned Size = CR.Range.second - CR.Range.first;
1728
Anton Korobeynikov23218582008-12-23 22:25:27 +00001729 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1730 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001731 double FMetric = 0;
1732 CaseItr Pivot = CR.Range.first + Size/2;
1733
1734 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1735 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001736 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001737 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1738 I!=E; ++I)
1739 TSize += I->size();
1740
Anton Korobeynikov23218582008-12-23 22:25:27 +00001741 size_t LSize = FrontCase.size();
1742 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001743 DEBUG(errs() << "Selecting best pivot: \n"
1744 << "First: " << First << ", Last: " << Last <<'\n'
1745 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001746 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1747 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001748 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1749 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001750 APInt Range = ComputeRange(LEnd, RBegin);
1751 assert((Range - 2ULL).isNonNegative() &&
1752 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001753 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1754 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001755 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001756 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001757 DEBUG(errs() <<"=>Step\n"
1758 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1759 << "LDensity: " << LDensity
1760 << ", RDensity: " << RDensity << '\n'
1761 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001762 if (FMetric < Metric) {
1763 Pivot = J;
1764 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001765 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001766 }
1767
1768 LSize += J->size();
1769 RSize -= J->size();
1770 }
1771 if (areJTsAllowed(TLI)) {
1772 // If our case is dense we *really* should handle it earlier!
1773 assert((FMetric > 0) && "Should handle dense range earlier!");
1774 } else {
1775 Pivot = CR.Range.first + Size/2;
1776 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001777
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001778 CaseRange LHSR(CR.Range.first, Pivot);
1779 CaseRange RHSR(Pivot, CR.Range.second);
1780 Constant *C = Pivot->Low;
1781 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001782
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001783 // We know that we branch to the LHS if the Value being switched on is
1784 // less than the Pivot value, C. We use this to optimize our binary
1785 // tree a bit, by recognizing that if SV is greater than or equal to the
1786 // LHS's Case Value, and that Case Value is exactly one less than the
1787 // Pivot's Value, then we can branch directly to the LHS's Target,
1788 // rather than creating a leaf node for it.
1789 if ((LHSR.second - LHSR.first) == 1 &&
1790 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001791 cast<ConstantInt>(C)->getValue() ==
1792 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001793 TrueBB = LHSR.first->BB;
1794 } else {
1795 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1796 CurMF->insert(BBI, TrueBB);
1797 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1798 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001799
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001800 // Similar to the optimization above, if the Value being switched on is
1801 // known to be less than the Constant CR.LT, and the current Case Value
1802 // is CR.LT - 1, then we can branch directly to the target block for
1803 // the current Case Value, rather than emitting a RHS leaf node for it.
1804 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001805 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1806 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001807 FalseBB = RHSR.first->BB;
1808 } else {
1809 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1810 CurMF->insert(BBI, FalseBB);
1811 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1812 }
1813
1814 // Create a CaseBlock record representing a conditional branch to
1815 // the LHS node if the value being switched on SV is less than C.
1816 // Otherwise, branch to LHS.
1817 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1818
1819 if (CR.CaseBB == CurMBB)
1820 visitSwitchCase(CB);
1821 else
1822 SwitchCases.push_back(CB);
1823
1824 return true;
1825}
1826
1827/// handleBitTestsSwitchCase - if current case range has few destination and
1828/// range span less, than machine word bitwidth, encode case range into series
1829/// of masks and emit bit tests with these masks.
1830bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1831 CaseRecVector& WorkList,
1832 Value* SV,
1833 MachineBasicBlock* Default){
1834 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1835
1836 Case& FrontCase = *CR.Range.first;
1837 Case& BackCase = *(CR.Range.second-1);
1838
1839 // Get the MachineFunction which holds the current MBB. This is used when
1840 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001841 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001842
Anton Korobeynikov23218582008-12-23 22:25:27 +00001843 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001844 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1845 I!=E; ++I) {
1846 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001847 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001848 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001849
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001850 // Count unique destinations
1851 SmallSet<MachineBasicBlock*, 4> Dests;
1852 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1853 Dests.insert(I->BB);
1854 if (Dests.size() > 3)
1855 // Don't bother the code below, if there are too much unique destinations
1856 return false;
1857 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001858 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1859 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001860
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001861 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001862 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1863 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001864 APInt cmpRange = maxValue - minValue;
1865
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001866 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1867 << "Low bound: " << minValue << '\n'
1868 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001869
1870 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001871 (!(Dests.size() == 1 && numCmps >= 3) &&
1872 !(Dests.size() == 2 && numCmps >= 5) &&
1873 !(Dests.size() >= 3 && numCmps >= 6)))
1874 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001875
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001876 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001877 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1878
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001879 // Optimize the case where all the case values fit in a
1880 // word without having to subtract minValue. In this case,
1881 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001882 if (minValue.isNonNegative() &&
1883 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1884 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001885 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001886 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001887 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001888
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001889 CaseBitsVector CasesBits;
1890 unsigned i, count = 0;
1891
1892 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1893 MachineBasicBlock* Dest = I->BB;
1894 for (i = 0; i < count; ++i)
1895 if (Dest == CasesBits[i].BB)
1896 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001897
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001898 if (i == count) {
1899 assert((count < 3) && "Too much destinations to test!");
1900 CasesBits.push_back(CaseBits(0, Dest, 0));
1901 count++;
1902 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001903
1904 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1905 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1906
1907 uint64_t lo = (lowValue - lowBound).getZExtValue();
1908 uint64_t hi = (highValue - lowBound).getZExtValue();
1909
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001910 for (uint64_t j = lo; j <= hi; j++) {
1911 CasesBits[i].Mask |= 1ULL << j;
1912 CasesBits[i].Bits++;
1913 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001914
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001915 }
1916 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001917
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001918 BitTestInfo BTC;
1919
1920 // Figure out which block is immediately after the current one.
1921 MachineFunction::iterator BBI = CR.CaseBB;
1922 ++BBI;
1923
1924 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1925
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001926 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001927 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001928 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1929 << ", Bits: " << CasesBits[i].Bits
1930 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001931
1932 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1933 CurMF->insert(BBI, CaseBB);
1934 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1935 CaseBB,
1936 CasesBits[i].BB));
1937 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001938
1939 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001940 -1U, (CR.CaseBB == CurMBB),
1941 CR.CaseBB, Default, BTC);
1942
1943 if (CR.CaseBB == CurMBB)
1944 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001945
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001946 BitTestCases.push_back(BTB);
1947
1948 return true;
1949}
1950
1951
1952/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00001953size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001954 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001955 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001956
1957 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00001958 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001959 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1960 Cases.push_back(Case(SI.getSuccessorValue(i),
1961 SI.getSuccessorValue(i),
1962 SMBB));
1963 }
1964 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1965
1966 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00001967 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001968 // Must recompute end() each iteration because it may be
1969 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00001970 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1971 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1972 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001973 MachineBasicBlock* nextBB = J->BB;
1974 MachineBasicBlock* currentBB = I->BB;
1975
1976 // If the two neighboring cases go to the same destination, merge them
1977 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001978 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001979 I->High = J->High;
1980 J = Cases.erase(J);
1981 } else {
1982 I = J++;
1983 }
1984 }
1985
1986 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1987 if (I->Low != I->High)
1988 // A range counts double, since it requires two compares.
1989 ++numCmps;
1990 }
1991
1992 return numCmps;
1993}
1994
Anton Korobeynikov23218582008-12-23 22:25:27 +00001995void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001996 // Figure out which block is immediately after the current one.
1997 MachineBasicBlock *NextBlock = 0;
1998 MachineFunction::iterator BBI = CurMBB;
1999
2000 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2001
2002 // If there is only the default destination, branch to it if it is not the
2003 // next basic block. Otherwise, just fall through.
2004 if (SI.getNumOperands() == 2) {
2005 // Update machine-CFG edges.
2006
2007 // If this is not a fall-through branch, emit the branch.
2008 CurMBB->addSuccessor(Default);
2009 if (Default != NextBlock)
2010 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2011 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002012 return;
2013 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002014
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002015 // If there are any non-default case statements, create a vector of Cases
2016 // representing each one, and sort the vector so that we can efficiently
2017 // create a binary search tree from them.
2018 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002019 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002020 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2021 << ". Total compares: " << numCmps << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002022
2023 // Get the Value to be switched on and default basic blocks, which will be
2024 // inserted into CaseBlock records, representing basic blocks in the binary
2025 // search tree.
2026 Value *SV = SI.getOperand(0);
2027
2028 // Push the initial CaseRec onto the worklist
2029 CaseRecVector WorkList;
2030 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2031
2032 while (!WorkList.empty()) {
2033 // Grab a record representing a case range to process off the worklist
2034 CaseRec CR = WorkList.back();
2035 WorkList.pop_back();
2036
2037 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2038 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002039
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002040 // If the range has few cases (two or less) emit a series of specific
2041 // tests.
2042 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2043 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002044
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002045 // If the switch has more than 5 blocks, and at least 40% dense, and the
2046 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002047 // lowering the switch to a binary tree of conditional branches.
2048 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2049 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002050
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002051 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2052 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2053 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2054 }
2055}
2056
2057
2058void SelectionDAGLowering::visitSub(User &I) {
2059 // -0.0 - X --> fneg
2060 const Type *Ty = I.getType();
2061 if (isa<VectorType>(Ty)) {
2062 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2063 const VectorType *DestTy = cast<VectorType>(I.getType());
2064 const Type *ElTy = DestTy->getElementType();
2065 if (ElTy->isFloatingPoint()) {
2066 unsigned VL = DestTy->getNumElements();
2067 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2068 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2069 if (CV == CNZ) {
2070 SDValue Op2 = getValue(I.getOperand(1));
2071 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2072 return;
2073 }
2074 }
2075 }
2076 }
2077 if (Ty->isFloatingPoint()) {
2078 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2079 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2080 SDValue Op2 = getValue(I.getOperand(1));
2081 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2082 return;
2083 }
2084 }
2085
2086 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2087}
2088
2089void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2090 SDValue Op1 = getValue(I.getOperand(0));
2091 SDValue Op2 = getValue(I.getOperand(1));
2092
2093 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2094}
2095
2096void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2097 SDValue Op1 = getValue(I.getOperand(0));
2098 SDValue Op2 = getValue(I.getOperand(1));
2099 if (!isa<VectorType>(I.getType())) {
2100 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2101 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2102 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2103 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2104 }
2105
2106 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2107}
2108
2109void SelectionDAGLowering::visitICmp(User &I) {
2110 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2111 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2112 predicate = IC->getPredicate();
2113 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2114 predicate = ICmpInst::Predicate(IC->getPredicate());
2115 SDValue Op1 = getValue(I.getOperand(0));
2116 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002117 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002118 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2119}
2120
2121void SelectionDAGLowering::visitFCmp(User &I) {
2122 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2123 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2124 predicate = FC->getPredicate();
2125 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2126 predicate = FCmpInst::Predicate(FC->getPredicate());
2127 SDValue Op1 = getValue(I.getOperand(0));
2128 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002129 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002130 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2131}
2132
2133void SelectionDAGLowering::visitVICmp(User &I) {
2134 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2135 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2136 predicate = IC->getPredicate();
2137 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2138 predicate = ICmpInst::Predicate(IC->getPredicate());
2139 SDValue Op1 = getValue(I.getOperand(0));
2140 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002141 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002142 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2143}
2144
2145void SelectionDAGLowering::visitVFCmp(User &I) {
2146 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2147 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2148 predicate = FC->getPredicate();
2149 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2150 predicate = FCmpInst::Predicate(FC->getPredicate());
2151 SDValue Op1 = getValue(I.getOperand(0));
2152 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002153 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002154 MVT DestVT = TLI.getValueType(I.getType());
2155
2156 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2157}
2158
2159void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002160 SmallVector<MVT, 4> ValueVTs;
2161 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2162 unsigned NumValues = ValueVTs.size();
2163 if (NumValues != 0) {
2164 SmallVector<SDValue, 4> Values(NumValues);
2165 SDValue Cond = getValue(I.getOperand(0));
2166 SDValue TrueVal = getValue(I.getOperand(1));
2167 SDValue FalseVal = getValue(I.getOperand(2));
2168
2169 for (unsigned i = 0; i != NumValues; ++i)
2170 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2171 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2172 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2173
Duncan Sandsaaffa052008-12-01 11:41:29 +00002174 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2175 DAG.getVTList(&ValueVTs[0], NumValues),
2176 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002177 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002178}
2179
2180
2181void SelectionDAGLowering::visitTrunc(User &I) {
2182 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2183 SDValue N = getValue(I.getOperand(0));
2184 MVT DestVT = TLI.getValueType(I.getType());
2185 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2186}
2187
2188void SelectionDAGLowering::visitZExt(User &I) {
2189 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2190 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2191 SDValue N = getValue(I.getOperand(0));
2192 MVT DestVT = TLI.getValueType(I.getType());
2193 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2194}
2195
2196void SelectionDAGLowering::visitSExt(User &I) {
2197 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2198 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2199 SDValue N = getValue(I.getOperand(0));
2200 MVT DestVT = TLI.getValueType(I.getType());
2201 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2202}
2203
2204void SelectionDAGLowering::visitFPTrunc(User &I) {
2205 // FPTrunc is never a no-op cast, no need to check
2206 SDValue N = getValue(I.getOperand(0));
2207 MVT DestVT = TLI.getValueType(I.getType());
2208 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2209}
2210
2211void SelectionDAGLowering::visitFPExt(User &I){
2212 // FPTrunc is never a no-op cast, no need to check
2213 SDValue N = getValue(I.getOperand(0));
2214 MVT DestVT = TLI.getValueType(I.getType());
2215 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2216}
2217
2218void SelectionDAGLowering::visitFPToUI(User &I) {
2219 // FPToUI is never a no-op cast, no need to check
2220 SDValue N = getValue(I.getOperand(0));
2221 MVT DestVT = TLI.getValueType(I.getType());
2222 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2223}
2224
2225void SelectionDAGLowering::visitFPToSI(User &I) {
2226 // FPToSI is never a no-op cast, no need to check
2227 SDValue N = getValue(I.getOperand(0));
2228 MVT DestVT = TLI.getValueType(I.getType());
2229 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2230}
2231
2232void SelectionDAGLowering::visitUIToFP(User &I) {
2233 // UIToFP is never a no-op cast, no need to check
2234 SDValue N = getValue(I.getOperand(0));
2235 MVT DestVT = TLI.getValueType(I.getType());
2236 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2237}
2238
2239void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002240 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002241 SDValue N = getValue(I.getOperand(0));
2242 MVT DestVT = TLI.getValueType(I.getType());
2243 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2244}
2245
2246void SelectionDAGLowering::visitPtrToInt(User &I) {
2247 // What to do depends on the size of the integer and the size of the pointer.
2248 // We can either truncate, zero extend, or no-op, accordingly.
2249 SDValue N = getValue(I.getOperand(0));
2250 MVT SrcVT = N.getValueType();
2251 MVT DestVT = TLI.getValueType(I.getType());
2252 SDValue Result;
2253 if (DestVT.bitsLT(SrcVT))
2254 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2255 else
2256 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2257 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2258 setValue(&I, Result);
2259}
2260
2261void SelectionDAGLowering::visitIntToPtr(User &I) {
2262 // What to do depends on the size of the integer and the size of the pointer.
2263 // We can either truncate, zero extend, or no-op, accordingly.
2264 SDValue N = getValue(I.getOperand(0));
2265 MVT SrcVT = N.getValueType();
2266 MVT DestVT = TLI.getValueType(I.getType());
2267 if (DestVT.bitsLT(SrcVT))
2268 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2269 else
2270 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2271 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2272}
2273
2274void SelectionDAGLowering::visitBitCast(User &I) {
2275 SDValue N = getValue(I.getOperand(0));
2276 MVT DestVT = TLI.getValueType(I.getType());
2277
2278 // BitCast assures us that source and destination are the same size so this
2279 // is either a BIT_CONVERT or a no-op.
2280 if (DestVT != N.getValueType())
2281 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2282 else
2283 setValue(&I, N); // noop cast.
2284}
2285
2286void SelectionDAGLowering::visitInsertElement(User &I) {
2287 SDValue InVec = getValue(I.getOperand(0));
2288 SDValue InVal = getValue(I.getOperand(1));
2289 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2290 getValue(I.getOperand(2)));
2291
2292 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2293 TLI.getValueType(I.getType()),
2294 InVec, InVal, InIdx));
2295}
2296
2297void SelectionDAGLowering::visitExtractElement(User &I) {
2298 SDValue InVec = getValue(I.getOperand(0));
2299 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2300 getValue(I.getOperand(1)));
2301 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2302 TLI.getValueType(I.getType()), InVec, InIdx));
2303}
2304
Mon P Wangaeb06d22008-11-10 04:46:22 +00002305
2306// Utility for visitShuffleVector - Returns true if the mask is mask starting
2307// from SIndx and increasing to the element length (undefs are allowed).
2308static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002309 unsigned MaskNumElts = Mask.getNumOperands();
2310 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002311 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2312 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2313 if (Idx != i + SIndx)
2314 return false;
2315 }
2316 }
2317 return true;
2318}
2319
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002320void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002321 SDValue Src1 = getValue(I.getOperand(0));
2322 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002323 SDValue Mask = getValue(I.getOperand(2));
2324
Mon P Wangaeb06d22008-11-10 04:46:22 +00002325 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002326 MVT SrcVT = Src1.getValueType();
Mon P Wangc7849c22008-11-16 05:06:27 +00002327 int MaskNumElts = Mask.getNumOperands();
2328 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002329
Mon P Wangc7849c22008-11-16 05:06:27 +00002330 if (SrcNumElts == MaskNumElts) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002331 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002332 return;
2333 }
2334
2335 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002336 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2337
2338 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2339 // Mask is longer than the source vectors and is a multiple of the source
2340 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002341 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002342 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2343 // The shuffle is concatenating two vectors together.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002344 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002345 return;
2346 }
2347
Mon P Wangc7849c22008-11-16 05:06:27 +00002348 // Pad both vectors with undefs to make them the same length as the mask.
2349 unsigned NumConcat = MaskNumElts / SrcNumElts;
2350 SDValue UndefVal = DAG.getNode(ISD::UNDEF, SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002351
Mon P Wang230e4fa2008-11-21 04:25:21 +00002352 SDValue* MOps1 = new SDValue[NumConcat];
2353 SDValue* MOps2 = new SDValue[NumConcat];
2354 MOps1[0] = Src1;
2355 MOps2[0] = Src2;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002356 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002357 MOps1[i] = UndefVal;
2358 MOps2[i] = UndefVal;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002359 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002360 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps1, NumConcat);
2361 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps2, NumConcat);
2362
2363 delete [] MOps1;
2364 delete [] MOps2;
2365
Mon P Wangaeb06d22008-11-10 04:46:22 +00002366 // Readjust mask for new input vector length.
2367 SmallVector<SDValue, 8> MappedOps;
Mon P Wangc7849c22008-11-16 05:06:27 +00002368 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002369 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2370 MappedOps.push_back(Mask.getOperand(i));
2371 } else {
Mon P Wangc7849c22008-11-16 05:06:27 +00002372 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2373 if (Idx < SrcNumElts)
2374 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2375 else
2376 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2377 MaskEltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002378 }
2379 }
2380 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2381 &MappedOps[0], MappedOps.size());
2382
Mon P Wang230e4fa2008-11-21 04:25:21 +00002383 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002384 return;
2385 }
2386
Mon P Wangc7849c22008-11-16 05:06:27 +00002387 if (SrcNumElts > MaskNumElts) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002388 // Resulting vector is shorter than the incoming vector.
Mon P Wangc7849c22008-11-16 05:06:27 +00002389 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002390 // Shuffle extracts 1st vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002391 setValue(&I, Src1);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002392 return;
2393 }
2394
Mon P Wangc7849c22008-11-16 05:06:27 +00002395 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002396 // Shuffle extracts 2nd vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002397 setValue(&I, Src2);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002398 return;
2399 }
2400
Mon P Wangc7849c22008-11-16 05:06:27 +00002401 // Analyze the access pattern of the vector to see if we can extract
2402 // two subvectors and do the shuffle. The analysis is done by calculating
2403 // the range of elements the mask access on both vectors.
2404 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2405 int MaxRange[2] = {-1, -1};
2406
2407 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002408 SDValue Arg = Mask.getOperand(i);
2409 if (Arg.getOpcode() != ISD::UNDEF) {
2410 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002411 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2412 int Input = 0;
2413 if (Idx >= SrcNumElts) {
2414 Input = 1;
2415 Idx -= SrcNumElts;
2416 }
2417 if (Idx > MaxRange[Input])
2418 MaxRange[Input] = Idx;
2419 if (Idx < MinRange[Input])
2420 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002421 }
2422 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002423
Mon P Wangc7849c22008-11-16 05:06:27 +00002424 // Check if the access is smaller than the vector size and can we find
2425 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002426 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002427 int StartIdx[2]; // StartIdx to extract from
2428 for (int Input=0; Input < 2; ++Input) {
2429 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2430 RangeUse[Input] = 0; // Unused
2431 StartIdx[Input] = 0;
2432 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2433 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002434 // start index that is a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002435 if (MaxRange[Input] < MaskNumElts) {
2436 RangeUse[Input] = 1; // Extract from beginning of the vector
2437 StartIdx[Input] = 0;
2438 } else {
2439 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang6cce3da2008-11-23 04:35:05 +00002440 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
2441 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002442 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002443 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002444 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002445 }
2446
2447 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2448 setValue(&I, DAG.getNode(ISD::UNDEF, VT)); // Vectors are not used.
2449 return;
2450 }
2451 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2452 // Extract appropriate subvector and generate a vector shuffle
2453 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002454 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002455 if (RangeUse[Input] == 0) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002456 Src = DAG.getNode(ISD::UNDEF, VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002457 } else {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002458 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, VT, Src,
2459 DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002460 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002461 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002462 // Calculate new mask.
2463 SmallVector<SDValue, 8> MappedOps;
2464 for (int i = 0; i != MaskNumElts; ++i) {
2465 SDValue Arg = Mask.getOperand(i);
2466 if (Arg.getOpcode() == ISD::UNDEF) {
2467 MappedOps.push_back(Arg);
2468 } else {
2469 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2470 if (Idx < SrcNumElts)
2471 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2472 else {
2473 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2474 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2475 }
2476 }
2477 }
2478 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2479 &MappedOps[0], MappedOps.size());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002480 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangc7849c22008-11-16 05:06:27 +00002481 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002482 }
2483 }
2484
Mon P Wangc7849c22008-11-16 05:06:27 +00002485 // We can't use either concat vectors or extract subvectors so fall back to
2486 // replacing the shuffle with extract and build vector.
2487 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002488 MVT EltVT = VT.getVectorElementType();
2489 MVT PtrVT = TLI.getPointerTy();
2490 SmallVector<SDValue,8> Ops;
Mon P Wangc7849c22008-11-16 05:06:27 +00002491 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002492 SDValue Arg = Mask.getOperand(i);
2493 if (Arg.getOpcode() == ISD::UNDEF) {
2494 Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2495 } else {
2496 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002497 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2498 if (Idx < SrcNumElts)
Mon P Wang230e4fa2008-11-21 04:25:21 +00002499 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src1,
Mon P Wangaeb06d22008-11-10 04:46:22 +00002500 DAG.getConstant(Idx, PtrVT)));
2501 else
Mon P Wang230e4fa2008-11-21 04:25:21 +00002502 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002503 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002504 }
2505 }
2506 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002507}
2508
2509void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2510 const Value *Op0 = I.getOperand(0);
2511 const Value *Op1 = I.getOperand(1);
2512 const Type *AggTy = I.getType();
2513 const Type *ValTy = Op1->getType();
2514 bool IntoUndef = isa<UndefValue>(Op0);
2515 bool FromUndef = isa<UndefValue>(Op1);
2516
2517 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2518 I.idx_begin(), I.idx_end());
2519
2520 SmallVector<MVT, 4> AggValueVTs;
2521 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2522 SmallVector<MVT, 4> ValValueVTs;
2523 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2524
2525 unsigned NumAggValues = AggValueVTs.size();
2526 unsigned NumValValues = ValValueVTs.size();
2527 SmallVector<SDValue, 4> Values(NumAggValues);
2528
2529 SDValue Agg = getValue(Op0);
2530 SDValue Val = getValue(Op1);
2531 unsigned i = 0;
2532 // Copy the beginning value(s) from the original aggregate.
2533 for (; i != LinearIndex; ++i)
2534 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2535 SDValue(Agg.getNode(), Agg.getResNo() + i);
2536 // Copy values from the inserted value(s).
2537 for (; i != LinearIndex + NumValValues; ++i)
2538 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2539 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2540 // Copy remaining value(s) from the original aggregate.
2541 for (; i != NumAggValues; ++i)
2542 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2543 SDValue(Agg.getNode(), Agg.getResNo() + i);
2544
Duncan Sandsaaffa052008-12-01 11:41:29 +00002545 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2546 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2547 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002548}
2549
2550void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2551 const Value *Op0 = I.getOperand(0);
2552 const Type *AggTy = Op0->getType();
2553 const Type *ValTy = I.getType();
2554 bool OutOfUndef = isa<UndefValue>(Op0);
2555
2556 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2557 I.idx_begin(), I.idx_end());
2558
2559 SmallVector<MVT, 4> ValValueVTs;
2560 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2561
2562 unsigned NumValValues = ValValueVTs.size();
2563 SmallVector<SDValue, 4> Values(NumValValues);
2564
2565 SDValue Agg = getValue(Op0);
2566 // Copy out the selected value(s).
2567 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2568 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002569 OutOfUndef ?
2570 DAG.getNode(ISD::UNDEF,
2571 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2572 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002573
Duncan Sandsaaffa052008-12-01 11:41:29 +00002574 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2575 DAG.getVTList(&ValValueVTs[0], NumValValues),
2576 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002577}
2578
2579
2580void SelectionDAGLowering::visitGetElementPtr(User &I) {
2581 SDValue N = getValue(I.getOperand(0));
2582 const Type *Ty = I.getOperand(0)->getType();
2583
2584 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2585 OI != E; ++OI) {
2586 Value *Idx = *OI;
2587 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2588 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2589 if (Field) {
2590 // N = N + Offset
2591 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2592 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2593 DAG.getIntPtrConstant(Offset));
2594 }
2595 Ty = StTy->getElementType(Field);
2596 } else {
2597 Ty = cast<SequentialType>(Ty)->getElementType();
2598
2599 // If this is a constant subscript, handle it quickly.
2600 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2601 if (CI->getZExtValue() == 0) continue;
2602 uint64_t Offs =
2603 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2604 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2605 DAG.getIntPtrConstant(Offs));
2606 continue;
2607 }
2608
2609 // N = N + Idx * ElementSize;
2610 uint64_t ElementSize = TD->getABITypeSize(Ty);
2611 SDValue IdxN = getValue(Idx);
2612
2613 // If the index is smaller or larger than intptr_t, truncate or extend
2614 // it.
2615 if (IdxN.getValueType().bitsLT(N.getValueType()))
2616 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2617 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2618 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2619
2620 // If this is a multiply by a power of two, turn it into a shl
2621 // immediately. This is a very common case.
2622 if (ElementSize != 1) {
2623 if (isPowerOf2_64(ElementSize)) {
2624 unsigned Amt = Log2_64(ElementSize);
2625 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2626 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2627 } else {
2628 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2629 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2630 }
2631 }
2632
2633 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2634 }
2635 }
2636 setValue(&I, N);
2637}
2638
2639void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2640 // If this is a fixed sized alloca in the entry block of the function,
2641 // allocate it statically on the stack.
2642 if (FuncInfo.StaticAllocaMap.count(&I))
2643 return; // getValue will auto-populate this.
2644
2645 const Type *Ty = I.getAllocatedType();
2646 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2647 unsigned Align =
2648 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2649 I.getAlignment());
2650
2651 SDValue AllocSize = getValue(I.getArraySize());
2652 MVT IntPtr = TLI.getPointerTy();
2653 if (IntPtr.bitsLT(AllocSize.getValueType()))
2654 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2655 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2656 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2657
2658 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2659 DAG.getIntPtrConstant(TySize));
2660
2661 // Handle alignment. If the requested alignment is less than or equal to
2662 // the stack alignment, ignore it. If the size is greater than or equal to
2663 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2664 unsigned StackAlign =
2665 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2666 if (Align <= StackAlign)
2667 Align = 0;
2668
2669 // Round the size of the allocation up to the stack alignment size
2670 // by add SA-1 to the size.
2671 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2672 DAG.getIntPtrConstant(StackAlign-1));
2673 // Mask out the low bits for alignment purposes.
2674 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2675 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2676
2677 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2678 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2679 MVT::Other);
2680 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2681 setValue(&I, DSA);
2682 DAG.setRoot(DSA.getValue(1));
2683
2684 // Inform the Frame Information that we have just allocated a variable-sized
2685 // object.
2686 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2687}
2688
2689void SelectionDAGLowering::visitLoad(LoadInst &I) {
2690 const Value *SV = I.getOperand(0);
2691 SDValue Ptr = getValue(SV);
2692
2693 const Type *Ty = I.getType();
2694 bool isVolatile = I.isVolatile();
2695 unsigned Alignment = I.getAlignment();
2696
2697 SmallVector<MVT, 4> ValueVTs;
2698 SmallVector<uint64_t, 4> Offsets;
2699 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2700 unsigned NumValues = ValueVTs.size();
2701 if (NumValues == 0)
2702 return;
2703
2704 SDValue Root;
2705 bool ConstantMemory = false;
2706 if (I.isVolatile())
2707 // Serialize volatile loads with other side effects.
2708 Root = getRoot();
2709 else if (AA->pointsToConstantMemory(SV)) {
2710 // Do not serialize (non-volatile) loads of constant memory with anything.
2711 Root = DAG.getEntryNode();
2712 ConstantMemory = true;
2713 } else {
2714 // Do not serialize non-volatile loads against each other.
2715 Root = DAG.getRoot();
2716 }
2717
2718 SmallVector<SDValue, 4> Values(NumValues);
2719 SmallVector<SDValue, 4> Chains(NumValues);
2720 MVT PtrVT = Ptr.getValueType();
2721 for (unsigned i = 0; i != NumValues; ++i) {
2722 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2723 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2724 DAG.getConstant(Offsets[i], PtrVT)),
2725 SV, Offsets[i],
2726 isVolatile, Alignment);
2727 Values[i] = L;
2728 Chains[i] = L.getValue(1);
2729 }
2730
2731 if (!ConstantMemory) {
2732 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2733 &Chains[0], NumValues);
2734 if (isVolatile)
2735 DAG.setRoot(Chain);
2736 else
2737 PendingLoads.push_back(Chain);
2738 }
2739
Duncan Sandsaaffa052008-12-01 11:41:29 +00002740 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2741 DAG.getVTList(&ValueVTs[0], NumValues),
2742 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002743}
2744
2745
2746void SelectionDAGLowering::visitStore(StoreInst &I) {
2747 Value *SrcV = I.getOperand(0);
2748 Value *PtrV = I.getOperand(1);
2749
2750 SmallVector<MVT, 4> ValueVTs;
2751 SmallVector<uint64_t, 4> Offsets;
2752 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2753 unsigned NumValues = ValueVTs.size();
2754 if (NumValues == 0)
2755 return;
2756
2757 // Get the lowered operands. Note that we do this after
2758 // checking if NumResults is zero, because with zero results
2759 // the operands won't have values in the map.
2760 SDValue Src = getValue(SrcV);
2761 SDValue Ptr = getValue(PtrV);
2762
2763 SDValue Root = getRoot();
2764 SmallVector<SDValue, 4> Chains(NumValues);
2765 MVT PtrVT = Ptr.getValueType();
2766 bool isVolatile = I.isVolatile();
2767 unsigned Alignment = I.getAlignment();
2768 for (unsigned i = 0; i != NumValues; ++i)
2769 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2770 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2771 DAG.getConstant(Offsets[i], PtrVT)),
2772 PtrV, Offsets[i],
2773 isVolatile, Alignment);
2774
2775 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2776}
2777
2778/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2779/// node.
2780void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2781 unsigned Intrinsic) {
2782 bool HasChain = !I.doesNotAccessMemory();
2783 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2784
2785 // Build the operand list.
2786 SmallVector<SDValue, 8> Ops;
2787 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2788 if (OnlyLoad) {
2789 // We don't need to serialize loads against other loads.
2790 Ops.push_back(DAG.getRoot());
2791 } else {
2792 Ops.push_back(getRoot());
2793 }
2794 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002795
2796 // Info is set by getTgtMemInstrinsic
2797 TargetLowering::IntrinsicInfo Info;
2798 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2799
2800 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2801 if (!IsTgtIntrinsic)
2802 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002803
2804 // Add all operands of the call to the operand list.
2805 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2806 SDValue Op = getValue(I.getOperand(i));
2807 assert(TLI.isTypeLegal(Op.getValueType()) &&
2808 "Intrinsic uses a non-legal type?");
2809 Ops.push_back(Op);
2810 }
2811
2812 std::vector<MVT> VTs;
2813 if (I.getType() != Type::VoidTy) {
2814 MVT VT = TLI.getValueType(I.getType());
2815 if (VT.isVector()) {
2816 const VectorType *DestTy = cast<VectorType>(I.getType());
2817 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2818
2819 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2820 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2821 }
2822
2823 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2824 VTs.push_back(VT);
2825 }
2826 if (HasChain)
2827 VTs.push_back(MVT::Other);
2828
2829 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2830
2831 // Create the node.
2832 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002833 if (IsTgtIntrinsic) {
2834 // This is target intrinsic that touches memory
2835 Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2836 &Ops[0], Ops.size(),
2837 Info.memVT, Info.ptrVal, Info.offset,
2838 Info.align, Info.vol,
2839 Info.readMem, Info.writeMem);
2840 }
2841 else if (!HasChain)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002842 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2843 &Ops[0], Ops.size());
2844 else if (I.getType() != Type::VoidTy)
2845 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2846 &Ops[0], Ops.size());
2847 else
2848 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2849 &Ops[0], Ops.size());
2850
2851 if (HasChain) {
2852 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2853 if (OnlyLoad)
2854 PendingLoads.push_back(Chain);
2855 else
2856 DAG.setRoot(Chain);
2857 }
2858 if (I.getType() != Type::VoidTy) {
2859 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2860 MVT VT = TLI.getValueType(PTy);
2861 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2862 }
2863 setValue(&I, Result);
2864 }
2865}
2866
2867/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2868static GlobalVariable *ExtractTypeInfo(Value *V) {
2869 V = V->stripPointerCasts();
2870 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2871 assert ((GV || isa<ConstantPointerNull>(V)) &&
2872 "TypeInfo must be a global variable or NULL");
2873 return GV;
2874}
2875
2876namespace llvm {
2877
2878/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2879/// call, and add them to the specified machine basic block.
2880void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2881 MachineBasicBlock *MBB) {
2882 // Inform the MachineModuleInfo of the personality for this landing pad.
2883 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2884 assert(CE->getOpcode() == Instruction::BitCast &&
2885 isa<Function>(CE->getOperand(0)) &&
2886 "Personality should be a function");
2887 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2888
2889 // Gather all the type infos for this landing pad and pass them along to
2890 // MachineModuleInfo.
2891 std::vector<GlobalVariable *> TyInfo;
2892 unsigned N = I.getNumOperands();
2893
2894 for (unsigned i = N - 1; i > 2; --i) {
2895 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2896 unsigned FilterLength = CI->getZExtValue();
2897 unsigned FirstCatch = i + FilterLength + !FilterLength;
2898 assert (FirstCatch <= N && "Invalid filter length");
2899
2900 if (FirstCatch < N) {
2901 TyInfo.reserve(N - FirstCatch);
2902 for (unsigned j = FirstCatch; j < N; ++j)
2903 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2904 MMI->addCatchTypeInfo(MBB, TyInfo);
2905 TyInfo.clear();
2906 }
2907
2908 if (!FilterLength) {
2909 // Cleanup.
2910 MMI->addCleanup(MBB);
2911 } else {
2912 // Filter.
2913 TyInfo.reserve(FilterLength - 1);
2914 for (unsigned j = i + 1; j < FirstCatch; ++j)
2915 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2916 MMI->addFilterTypeInfo(MBB, TyInfo);
2917 TyInfo.clear();
2918 }
2919
2920 N = i;
2921 }
2922 }
2923
2924 if (N > 3) {
2925 TyInfo.reserve(N - 3);
2926 for (unsigned j = 3; j < N; ++j)
2927 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2928 MMI->addCatchTypeInfo(MBB, TyInfo);
2929 }
2930}
2931
2932}
2933
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002934/// GetSignificand - Get the significand and build it into a floating-point
2935/// number with exponent of 1:
2936///
2937/// Op = (Op & 0x007fffff) | 0x3f800000;
2938///
2939/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002940static SDValue
2941GetSignificand(SelectionDAG &DAG, SDValue Op) {
2942 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2943 DAG.getConstant(0x007fffff, MVT::i32));
2944 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2945 DAG.getConstant(0x3f800000, MVT::i32));
2946 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2947}
2948
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002949/// GetExponent - Get the exponent:
2950///
2951/// (float)((Op1 >> 23) - 127);
2952///
2953/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002954static SDValue
2955GetExponent(SelectionDAG &DAG, SDValue Op) {
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002956 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
Bill Wendling39150252008-09-09 20:39:27 +00002957 DAG.getConstant(23, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002958 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
Bill Wendling39150252008-09-09 20:39:27 +00002959 DAG.getConstant(127, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002960 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002961}
2962
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002963/// getF32Constant - Get 32-bit floating point constant.
2964static SDValue
2965getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2966 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2967}
2968
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002969/// Inlined utility function to implement binary input atomic intrinsics for
2970/// visitIntrinsicCall: I is a call instruction
2971/// Op is the associated NodeType for I
2972const char *
2973SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2974 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002975 SDValue L =
2976 DAG.getAtomic(Op, getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2977 Root,
2978 getValue(I.getOperand(1)),
2979 getValue(I.getOperand(2)),
2980 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002981 setValue(&I, L);
2982 DAG.setRoot(L.getValue(1));
2983 return 0;
2984}
2985
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002986// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00002987const char *
2988SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002989 SDValue Op1 = getValue(I.getOperand(1));
2990 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00002991
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002992 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
2993 SDValue Ops[] = { Op1, Op2 };
Bill Wendling74c37652008-12-09 22:08:41 +00002994
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002995 SDValue Result = DAG.getNode(Op, DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
Bill Wendling74c37652008-12-09 22:08:41 +00002996
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002997 setValue(&I, Result);
2998 return 0;
2999}
Bill Wendling74c37652008-12-09 22:08:41 +00003000
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003001/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3002/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003003void
3004SelectionDAGLowering::visitExp(CallInst &I) {
3005 SDValue result;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003006
3007 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3008 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3009 SDValue Op = getValue(I.getOperand(1));
3010
3011 // Put the exponent in the right bit position for later addition to the
3012 // final result:
3013 //
3014 // #define LOG2OFe 1.4426950f
3015 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3016 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003017 getF32Constant(DAG, 0x3fb8aa3b));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003018 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3019
3020 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3021 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3022 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3023
3024 // IntegerPartOfX <<= 23;
3025 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3026 DAG.getConstant(23, MVT::i32));
3027
3028 if (LimitFloatPrecision <= 6) {
3029 // For floating-point precision of 6:
3030 //
3031 // TwoToFractionalPartOfX =
3032 // 0.997535578f +
3033 // (0.735607626f + 0.252464424f * x) * x;
3034 //
3035 // error 0.0144103317, which is 6 bits
3036 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003037 getF32Constant(DAG, 0x3e814304));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003038 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003039 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003040 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3041 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003042 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003043 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3044
3045 // Add the exponent into the result in integer domain.
3046 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
3047 TwoToFracPartOfX, IntegerPartOfX);
3048
3049 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
3050 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3051 // For floating-point precision of 12:
3052 //
3053 // TwoToFractionalPartOfX =
3054 // 0.999892986f +
3055 // (0.696457318f +
3056 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3057 //
3058 // 0.000107046256 error, which is 13 to 14 bits
3059 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003060 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003061 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003062 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003063 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3064 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003065 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003066 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3067 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003068 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003069 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3070
3071 // Add the exponent into the result in integer domain.
3072 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
3073 TwoToFracPartOfX, IntegerPartOfX);
3074
3075 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
3076 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3077 // For floating-point precision of 18:
3078 //
3079 // TwoToFractionalPartOfX =
3080 // 0.999999982f +
3081 // (0.693148872f +
3082 // (0.240227044f +
3083 // (0.554906021e-1f +
3084 // (0.961591928e-2f +
3085 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3086 //
3087 // error 2.47208000*10^(-7), which is better than 18 bits
3088 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003089 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003090 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003091 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003092 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3093 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003094 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003095 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3096 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003097 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003098 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3099 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003100 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003101 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3102 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003103 getF32Constant(DAG, 0x3f317234));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003104 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3105 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003106 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003107 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3108
3109 // Add the exponent into the result in integer domain.
3110 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
3111 TwoToFracPartOfX, IntegerPartOfX);
3112
3113 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
3114 }
3115 } else {
3116 // No special expansion.
3117 result = DAG.getNode(ISD::FEXP,
3118 getValue(I.getOperand(1)).getValueType(),
3119 getValue(I.getOperand(1)));
3120 }
3121
Dale Johannesen59e577f2008-09-05 18:38:42 +00003122 setValue(&I, result);
3123}
3124
Bill Wendling39150252008-09-09 20:39:27 +00003125/// visitLog - Lower a log intrinsic. Handles the special sequences for
3126/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003127void
3128SelectionDAGLowering::visitLog(CallInst &I) {
3129 SDValue result;
Bill Wendling39150252008-09-09 20:39:27 +00003130
3131 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3132 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3133 SDValue Op = getValue(I.getOperand(1));
3134 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3135
3136 // Scale the exponent by log(2) [0.69314718f].
3137 SDValue Exp = GetExponent(DAG, Op1);
3138 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003139 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003140
3141 // Get the significand and build it into a floating-point number with
3142 // exponent of 1.
3143 SDValue X = GetSignificand(DAG, Op1);
3144
3145 if (LimitFloatPrecision <= 6) {
3146 // For floating-point precision of 6:
3147 //
3148 // LogofMantissa =
3149 // -1.1609546f +
3150 // (1.4034025f - 0.23903021f * x) * x;
3151 //
3152 // error 0.0034276066, which is better than 8 bits
3153 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003154 getF32Constant(DAG, 0xbe74c456));
Bill Wendling39150252008-09-09 20:39:27 +00003155 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003156 getF32Constant(DAG, 0x3fb3a2b1));
Bill Wendling39150252008-09-09 20:39:27 +00003157 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3158 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003159 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003160
3161 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3162 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3163 // For floating-point precision of 12:
3164 //
3165 // LogOfMantissa =
3166 // -1.7417939f +
3167 // (2.8212026f +
3168 // (-1.4699568f +
3169 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3170 //
3171 // error 0.000061011436, which is 14 bits
3172 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003173 getF32Constant(DAG, 0xbd67b6d6));
Bill Wendling39150252008-09-09 20:39:27 +00003174 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003175 getF32Constant(DAG, 0x3ee4f4b8));
Bill Wendling39150252008-09-09 20:39:27 +00003176 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3177 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003178 getF32Constant(DAG, 0x3fbc278b));
Bill Wendling39150252008-09-09 20:39:27 +00003179 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3180 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003181 getF32Constant(DAG, 0x40348e95));
Bill Wendling39150252008-09-09 20:39:27 +00003182 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3183 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003184 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003185
3186 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3187 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3188 // For floating-point precision of 18:
3189 //
3190 // LogOfMantissa =
3191 // -2.1072184f +
3192 // (4.2372794f +
3193 // (-3.7029485f +
3194 // (2.2781945f +
3195 // (-0.87823314f +
3196 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3197 //
3198 // error 0.0000023660568, which is better than 18 bits
3199 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003200 getF32Constant(DAG, 0xbc91e5ac));
Bill Wendling39150252008-09-09 20:39:27 +00003201 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003202 getF32Constant(DAG, 0x3e4350aa));
Bill Wendling39150252008-09-09 20:39:27 +00003203 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3204 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003205 getF32Constant(DAG, 0x3f60d3e3));
Bill Wendling39150252008-09-09 20:39:27 +00003206 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3207 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003208 getF32Constant(DAG, 0x4011cdf0));
Bill Wendling39150252008-09-09 20:39:27 +00003209 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3210 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003211 getF32Constant(DAG, 0x406cfd1c));
Bill Wendling39150252008-09-09 20:39:27 +00003212 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3213 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003214 getF32Constant(DAG, 0x408797cb));
Bill Wendling39150252008-09-09 20:39:27 +00003215 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3216 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003217 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003218
3219 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3220 }
3221 } else {
3222 // No special expansion.
3223 result = DAG.getNode(ISD::FLOG,
3224 getValue(I.getOperand(1)).getValueType(),
3225 getValue(I.getOperand(1)));
3226 }
3227
Dale Johannesen59e577f2008-09-05 18:38:42 +00003228 setValue(&I, result);
3229}
3230
Bill Wendling3eb59402008-09-09 00:28:24 +00003231/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3232/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003233void
3234SelectionDAGLowering::visitLog2(CallInst &I) {
3235 SDValue result;
Bill Wendling3eb59402008-09-09 00:28:24 +00003236
Dale Johannesen853244f2008-09-05 23:49:37 +00003237 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003238 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3239 SDValue Op = getValue(I.getOperand(1));
3240 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3241
Bill Wendling39150252008-09-09 20:39:27 +00003242 // Get the exponent.
3243 SDValue LogOfExponent = GetExponent(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003244
3245 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003246 // exponent of 1.
3247 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003248
3249 // Different possible minimax approximations of significand in
3250 // floating-point for various degrees of accuracy over [1,2].
3251 if (LimitFloatPrecision <= 6) {
3252 // For floating-point precision of 6:
3253 //
3254 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3255 //
3256 // error 0.0049451742, which is more than 7 bits
Bill Wendling39150252008-09-09 20:39:27 +00003257 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003258 getF32Constant(DAG, 0xbeb08fe0));
Bill Wendling39150252008-09-09 20:39:27 +00003259 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003260 getF32Constant(DAG, 0x40019463));
Bill Wendling39150252008-09-09 20:39:27 +00003261 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3262 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003263 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003264
3265 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3266 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3267 // For floating-point precision of 12:
3268 //
3269 // Log2ofMantissa =
3270 // -2.51285454f +
3271 // (4.07009056f +
3272 // (-2.12067489f +
3273 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3274 //
3275 // error 0.0000876136000, which is better than 13 bits
Bill Wendling39150252008-09-09 20:39:27 +00003276 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003277 getF32Constant(DAG, 0xbda7262e));
Bill Wendling39150252008-09-09 20:39:27 +00003278 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003279 getF32Constant(DAG, 0x3f25280b));
Bill Wendling39150252008-09-09 20:39:27 +00003280 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3281 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003282 getF32Constant(DAG, 0x4007b923));
Bill Wendling39150252008-09-09 20:39:27 +00003283 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3284 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003285 getF32Constant(DAG, 0x40823e2f));
Bill Wendling39150252008-09-09 20:39:27 +00003286 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3287 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003288 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003289
3290 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3291 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3292 // For floating-point precision of 18:
3293 //
3294 // Log2ofMantissa =
3295 // -3.0400495f +
3296 // (6.1129976f +
3297 // (-5.3420409f +
3298 // (3.2865683f +
3299 // (-1.2669343f +
3300 // (0.27515199f -
3301 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3302 //
3303 // error 0.0000018516, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003304 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003305 getF32Constant(DAG, 0xbcd2769e));
Bill Wendling39150252008-09-09 20:39:27 +00003306 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003307 getF32Constant(DAG, 0x3e8ce0b9));
Bill Wendling39150252008-09-09 20:39:27 +00003308 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3309 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003310 getF32Constant(DAG, 0x3fa22ae7));
Bill Wendling39150252008-09-09 20:39:27 +00003311 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3312 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003313 getF32Constant(DAG, 0x40525723));
Bill Wendling39150252008-09-09 20:39:27 +00003314 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3315 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003316 getF32Constant(DAG, 0x40aaf200));
Bill Wendling39150252008-09-09 20:39:27 +00003317 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3318 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003319 getF32Constant(DAG, 0x40c39dad));
Bill Wendling3eb59402008-09-09 00:28:24 +00003320 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
Bill Wendling39150252008-09-09 20:39:27 +00003321 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003322 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003323
3324 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3325 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003326 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003327 // No special expansion.
Dale Johannesen853244f2008-09-05 23:49:37 +00003328 result = DAG.getNode(ISD::FLOG2,
3329 getValue(I.getOperand(1)).getValueType(),
3330 getValue(I.getOperand(1)));
3331 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003332
Dale Johannesen59e577f2008-09-05 18:38:42 +00003333 setValue(&I, result);
3334}
3335
Bill Wendling3eb59402008-09-09 00:28:24 +00003336/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3337/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003338void
3339SelectionDAGLowering::visitLog10(CallInst &I) {
3340 SDValue result;
Bill Wendling181b6272008-10-19 20:34:04 +00003341
Dale Johannesen852680a2008-09-05 21:27:19 +00003342 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003343 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3344 SDValue Op = getValue(I.getOperand(1));
3345 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3346
Bill Wendling39150252008-09-09 20:39:27 +00003347 // Scale the exponent by log10(2) [0.30102999f].
3348 SDValue Exp = GetExponent(DAG, Op1);
3349 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003350 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003351
3352 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003353 // exponent of 1.
3354 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003355
3356 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003357 // For floating-point precision of 6:
3358 //
3359 // Log10ofMantissa =
3360 // -0.50419619f +
3361 // (0.60948995f - 0.10380950f * x) * x;
3362 //
3363 // error 0.0014886165, which is 6 bits
Bill Wendling39150252008-09-09 20:39:27 +00003364 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003365 getF32Constant(DAG, 0xbdd49a13));
Bill Wendling39150252008-09-09 20:39:27 +00003366 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003367 getF32Constant(DAG, 0x3f1c0789));
Bill Wendling39150252008-09-09 20:39:27 +00003368 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3369 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003370 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003371
3372 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003373 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3374 // For floating-point precision of 12:
3375 //
3376 // Log10ofMantissa =
3377 // -0.64831180f +
3378 // (0.91751397f +
3379 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3380 //
3381 // error 0.00019228036, which is better than 12 bits
Bill Wendling39150252008-09-09 20:39:27 +00003382 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003383 getF32Constant(DAG, 0x3d431f31));
Bill Wendling39150252008-09-09 20:39:27 +00003384 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003385 getF32Constant(DAG, 0x3ea21fb2));
Bill Wendling39150252008-09-09 20:39:27 +00003386 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3387 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003388 getF32Constant(DAG, 0x3f6ae232));
Bill Wendling39150252008-09-09 20:39:27 +00003389 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3390 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003391 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003392
3393 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3394 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003395 // For floating-point precision of 18:
3396 //
3397 // Log10ofMantissa =
3398 // -0.84299375f +
3399 // (1.5327582f +
3400 // (-1.0688956f +
3401 // (0.49102474f +
3402 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3403 //
3404 // error 0.0000037995730, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003405 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003406 getF32Constant(DAG, 0x3c5d51ce));
Bill Wendling39150252008-09-09 20:39:27 +00003407 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003408 getF32Constant(DAG, 0x3e00685a));
Bill Wendling39150252008-09-09 20:39:27 +00003409 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3410 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003411 getF32Constant(DAG, 0x3efb6798));
Bill Wendling39150252008-09-09 20:39:27 +00003412 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3413 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003414 getF32Constant(DAG, 0x3f88d192));
Bill Wendling39150252008-09-09 20:39:27 +00003415 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3416 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003417 getF32Constant(DAG, 0x3fc4316c));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003418 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
Bill Wendling39150252008-09-09 20:39:27 +00003419 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003420 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003421
3422 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003423 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003424 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003425 // No special expansion.
Dale Johannesen852680a2008-09-05 21:27:19 +00003426 result = DAG.getNode(ISD::FLOG10,
3427 getValue(I.getOperand(1)).getValueType(),
3428 getValue(I.getOperand(1)));
3429 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003430
Dale Johannesen59e577f2008-09-05 18:38:42 +00003431 setValue(&I, result);
3432}
3433
Bill Wendlinge10c8142008-09-09 22:39:21 +00003434/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3435/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003436void
3437SelectionDAGLowering::visitExp2(CallInst &I) {
3438 SDValue result;
Bill Wendlinge10c8142008-09-09 22:39:21 +00003439
Dale Johannesen601d3c02008-09-05 01:48:15 +00003440 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003441 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3442 SDValue Op = getValue(I.getOperand(1));
3443
3444 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3445
3446 // FractionalPartOfX = x - (float)IntegerPartOfX;
3447 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3448 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3449
3450 // IntegerPartOfX <<= 23;
3451 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3452 DAG.getConstant(23, MVT::i32));
3453
3454 if (LimitFloatPrecision <= 6) {
3455 // For floating-point precision of 6:
3456 //
3457 // TwoToFractionalPartOfX =
3458 // 0.997535578f +
3459 // (0.735607626f + 0.252464424f * x) * x;
3460 //
3461 // error 0.0144103317, which is 6 bits
3462 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003463 getF32Constant(DAG, 0x3e814304));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003464 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003465 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003466 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3467 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003468 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003469 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3470 SDValue TwoToFractionalPartOfX =
3471 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3472
3473 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3474 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3475 // For floating-point precision of 12:
3476 //
3477 // TwoToFractionalPartOfX =
3478 // 0.999892986f +
3479 // (0.696457318f +
3480 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3481 //
3482 // error 0.000107046256, which is 13 to 14 bits
3483 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003484 getF32Constant(DAG, 0x3da235e3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003485 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003486 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003487 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3488 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003489 getF32Constant(DAG, 0x3f324b07));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003490 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3491 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003492 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003493 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3494 SDValue TwoToFractionalPartOfX =
3495 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3496
3497 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3498 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3499 // For floating-point precision of 18:
3500 //
3501 // TwoToFractionalPartOfX =
3502 // 0.999999982f +
3503 // (0.693148872f +
3504 // (0.240227044f +
3505 // (0.554906021e-1f +
3506 // (0.961591928e-2f +
3507 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3508 // error 2.47208000*10^(-7), which is better than 18 bits
3509 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003510 getF32Constant(DAG, 0x3924b03e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003511 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003512 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003513 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3514 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003515 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003516 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3517 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003518 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003519 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3520 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003521 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003522 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3523 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003524 getF32Constant(DAG, 0x3f317234));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003525 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3526 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003527 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003528 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3529 SDValue TwoToFractionalPartOfX =
3530 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3531
3532 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3533 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003534 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003535 // No special expansion.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003536 result = DAG.getNode(ISD::FEXP2,
3537 getValue(I.getOperand(1)).getValueType(),
3538 getValue(I.getOperand(1)));
3539 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003540
Dale Johannesen601d3c02008-09-05 01:48:15 +00003541 setValue(&I, result);
3542}
3543
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003544/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3545/// limited-precision mode with x == 10.0f.
3546void
3547SelectionDAGLowering::visitPow(CallInst &I) {
3548 SDValue result;
3549 Value *Val = I.getOperand(1);
3550 bool IsExp10 = false;
3551
3552 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003553 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003554 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3555 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3556 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3557 APFloat Ten(10.0f);
3558 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3559 }
3560 }
3561 }
3562
3563 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3564 SDValue Op = getValue(I.getOperand(2));
3565
3566 // Put the exponent in the right bit position for later addition to the
3567 // final result:
3568 //
3569 // #define LOG2OF10 3.3219281f
3570 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3571 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003572 getF32Constant(DAG, 0x40549a78));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003573 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3574
3575 // FractionalPartOfX = x - (float)IntegerPartOfX;
3576 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3577 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3578
3579 // IntegerPartOfX <<= 23;
3580 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3581 DAG.getConstant(23, MVT::i32));
3582
3583 if (LimitFloatPrecision <= 6) {
3584 // For floating-point precision of 6:
3585 //
3586 // twoToFractionalPartOfX =
3587 // 0.997535578f +
3588 // (0.735607626f + 0.252464424f * x) * x;
3589 //
3590 // error 0.0144103317, which is 6 bits
3591 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003592 getF32Constant(DAG, 0x3e814304));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003593 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003594 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003595 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3596 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003597 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003598 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3599 SDValue TwoToFractionalPartOfX =
3600 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3601
3602 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3603 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3604 // For floating-point precision of 12:
3605 //
3606 // TwoToFractionalPartOfX =
3607 // 0.999892986f +
3608 // (0.696457318f +
3609 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3610 //
3611 // error 0.000107046256, which is 13 to 14 bits
3612 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003613 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003614 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003615 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003616 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3617 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003618 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003619 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3620 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003621 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003622 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3623 SDValue TwoToFractionalPartOfX =
3624 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3625
3626 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3627 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3628 // For floating-point precision of 18:
3629 //
3630 // TwoToFractionalPartOfX =
3631 // 0.999999982f +
3632 // (0.693148872f +
3633 // (0.240227044f +
3634 // (0.554906021e-1f +
3635 // (0.961591928e-2f +
3636 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3637 // error 2.47208000*10^(-7), which is better than 18 bits
3638 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003639 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003640 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003641 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003642 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3643 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003644 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003645 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3646 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003647 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003648 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3649 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003650 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003651 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3652 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003653 getF32Constant(DAG, 0x3f317234));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003654 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3655 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003656 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003657 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3658 SDValue TwoToFractionalPartOfX =
3659 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3660
3661 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3662 }
3663 } else {
3664 // No special expansion.
3665 result = DAG.getNode(ISD::FPOW,
3666 getValue(I.getOperand(1)).getValueType(),
3667 getValue(I.getOperand(1)),
3668 getValue(I.getOperand(2)));
3669 }
3670
3671 setValue(&I, result);
3672}
3673
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003674/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3675/// we want to emit this as a call to a named external function, return the name
3676/// otherwise lower it and return null.
3677const char *
3678SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3679 switch (Intrinsic) {
3680 default:
3681 // By default, turn this into a target intrinsic node.
3682 visitTargetIntrinsic(I, Intrinsic);
3683 return 0;
3684 case Intrinsic::vastart: visitVAStart(I); return 0;
3685 case Intrinsic::vaend: visitVAEnd(I); return 0;
3686 case Intrinsic::vacopy: visitVACopy(I); return 0;
3687 case Intrinsic::returnaddress:
3688 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3689 getValue(I.getOperand(1))));
3690 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003691 case Intrinsic::frameaddress:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003692 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3693 getValue(I.getOperand(1))));
3694 return 0;
3695 case Intrinsic::setjmp:
3696 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3697 break;
3698 case Intrinsic::longjmp:
3699 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3700 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003701 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003702 SDValue Op1 = getValue(I.getOperand(1));
3703 SDValue Op2 = getValue(I.getOperand(2));
3704 SDValue Op3 = getValue(I.getOperand(3));
3705 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3706 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3707 I.getOperand(1), 0, I.getOperand(2), 0));
3708 return 0;
3709 }
Chris Lattner824b9582008-11-21 16:42:48 +00003710 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003711 SDValue Op1 = getValue(I.getOperand(1));
3712 SDValue Op2 = getValue(I.getOperand(2));
3713 SDValue Op3 = getValue(I.getOperand(3));
3714 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3715 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3716 I.getOperand(1), 0));
3717 return 0;
3718 }
Chris Lattner824b9582008-11-21 16:42:48 +00003719 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003720 SDValue Op1 = getValue(I.getOperand(1));
3721 SDValue Op2 = getValue(I.getOperand(2));
3722 SDValue Op3 = getValue(I.getOperand(3));
3723 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3724
3725 // If the source and destination are known to not be aliases, we can
3726 // lower memmove as memcpy.
3727 uint64_t Size = -1ULL;
3728 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003729 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003730 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3731 AliasAnalysis::NoAlias) {
3732 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3733 I.getOperand(1), 0, I.getOperand(2), 0));
3734 return 0;
3735 }
3736
3737 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3738 I.getOperand(1), 0, I.getOperand(2), 0));
3739 return 0;
3740 }
3741 case Intrinsic::dbg_stoppoint: {
3742 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3743 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3744 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3745 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3746 assert(DD && "Not a debug information descriptor");
3747 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3748 SPI.getLine(),
3749 SPI.getColumn(),
3750 cast<CompileUnitDesc>(DD)));
3751 }
3752
3753 return 0;
3754 }
3755 case Intrinsic::dbg_region_start: {
3756 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3757 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3758 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3759 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3760 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3761 }
3762
3763 return 0;
3764 }
3765 case Intrinsic::dbg_region_end: {
3766 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3767 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3768 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3769 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3770 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3771 }
3772
3773 return 0;
3774 }
3775 case Intrinsic::dbg_func_start: {
3776 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3777 if (!MMI) return 0;
3778 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3779 Value *SP = FSI.getSubprogram();
3780 if (SP && MMI->Verify(SP)) {
3781 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3782 // what (most?) gdb expects.
3783 DebugInfoDesc *DD = MMI->getDescFor(SP);
3784 assert(DD && "Not a debug information descriptor");
3785 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3786 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3787 unsigned SrcFile = MMI->RecordSource(CompileUnit);
Devang Patel20dd0462008-11-06 00:30:09 +00003788 // Record the source line but does not create a label for the normal
3789 // function start. It will be emitted at asm emission time. However,
3790 // create a label if this is a beginning of inlined function.
3791 unsigned LabelID = MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3792 if (MMI->getSourceLines().size() != 1)
3793 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003794 }
3795
3796 return 0;
3797 }
3798 case Intrinsic::dbg_declare: {
3799 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3800 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3801 Value *Variable = DI.getVariable();
3802 if (MMI && Variable && MMI->Verify(Variable))
3803 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3804 getValue(DI.getAddress()), getValue(Variable)));
3805 return 0;
3806 }
3807
3808 case Intrinsic::eh_exception: {
3809 if (!CurMBB->isLandingPad()) {
3810 // FIXME: Mark exception register as live in. Hack for PR1508.
3811 unsigned Reg = TLI.getExceptionAddressRegister();
3812 if (Reg) CurMBB->addLiveIn(Reg);
3813 }
3814 // Insert the EXCEPTIONADDR instruction.
3815 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3816 SDValue Ops[1];
3817 Ops[0] = DAG.getRoot();
3818 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3819 setValue(&I, Op);
3820 DAG.setRoot(Op.getValue(1));
3821 return 0;
3822 }
3823
3824 case Intrinsic::eh_selector_i32:
3825 case Intrinsic::eh_selector_i64: {
3826 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3827 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3828 MVT::i32 : MVT::i64);
3829
3830 if (MMI) {
3831 if (CurMBB->isLandingPad())
3832 AddCatchInfo(I, MMI, CurMBB);
3833 else {
3834#ifndef NDEBUG
3835 FuncInfo.CatchInfoLost.insert(&I);
3836#endif
3837 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3838 unsigned Reg = TLI.getExceptionSelectorRegister();
3839 if (Reg) CurMBB->addLiveIn(Reg);
3840 }
3841
3842 // Insert the EHSELECTION instruction.
3843 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3844 SDValue Ops[2];
3845 Ops[0] = getValue(I.getOperand(1));
3846 Ops[1] = getRoot();
3847 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3848 setValue(&I, Op);
3849 DAG.setRoot(Op.getValue(1));
3850 } else {
3851 setValue(&I, DAG.getConstant(0, VT));
3852 }
3853
3854 return 0;
3855 }
3856
3857 case Intrinsic::eh_typeid_for_i32:
3858 case Intrinsic::eh_typeid_for_i64: {
3859 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3860 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3861 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003862
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003863 if (MMI) {
3864 // Find the type id for the given typeinfo.
3865 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3866
3867 unsigned TypeID = MMI->getTypeIDFor(GV);
3868 setValue(&I, DAG.getConstant(TypeID, VT));
3869 } else {
3870 // Return something different to eh_selector.
3871 setValue(&I, DAG.getConstant(1, VT));
3872 }
3873
3874 return 0;
3875 }
3876
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003877 case Intrinsic::eh_return_i32:
3878 case Intrinsic::eh_return_i64:
3879 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003880 MMI->setCallsEHReturn(true);
3881 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3882 MVT::Other,
3883 getControlRoot(),
3884 getValue(I.getOperand(1)),
3885 getValue(I.getOperand(2))));
3886 } else {
3887 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3888 }
3889
3890 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003891 case Intrinsic::eh_unwind_init:
3892 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3893 MMI->setCallsUnwindInit(true);
3894 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003895
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003896 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003897
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003898 case Intrinsic::eh_dwarf_cfa: {
3899 MVT VT = getValue(I.getOperand(1)).getValueType();
3900 SDValue CfaArg;
3901 if (VT.bitsGT(TLI.getPointerTy()))
3902 CfaArg = DAG.getNode(ISD::TRUNCATE,
3903 TLI.getPointerTy(), getValue(I.getOperand(1)));
3904 else
3905 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3906 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003907
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003908 SDValue Offset = DAG.getNode(ISD::ADD,
3909 TLI.getPointerTy(),
3910 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3911 TLI.getPointerTy()),
3912 CfaArg);
3913 setValue(&I, DAG.getNode(ISD::ADD,
3914 TLI.getPointerTy(),
3915 DAG.getNode(ISD::FRAMEADDR,
3916 TLI.getPointerTy(),
3917 DAG.getConstant(0,
3918 TLI.getPointerTy())),
3919 Offset));
3920 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003921 }
3922
Mon P Wang77cdf302008-11-10 20:54:11 +00003923 case Intrinsic::convertff:
3924 case Intrinsic::convertfsi:
3925 case Intrinsic::convertfui:
3926 case Intrinsic::convertsif:
3927 case Intrinsic::convertuif:
3928 case Intrinsic::convertss:
3929 case Intrinsic::convertsu:
3930 case Intrinsic::convertus:
3931 case Intrinsic::convertuu: {
3932 ISD::CvtCode Code = ISD::CVT_INVALID;
3933 switch (Intrinsic) {
3934 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3935 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3936 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3937 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3938 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3939 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3940 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3941 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3942 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3943 }
3944 MVT DestVT = TLI.getValueType(I.getType());
3945 Value* Op1 = I.getOperand(1);
3946 setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
3947 DAG.getValueType(DestVT),
3948 DAG.getValueType(getValue(Op1).getValueType()),
3949 getValue(I.getOperand(2)),
3950 getValue(I.getOperand(3)),
3951 Code));
3952 return 0;
3953 }
3954
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003955 case Intrinsic::sqrt:
3956 setValue(&I, DAG.getNode(ISD::FSQRT,
3957 getValue(I.getOperand(1)).getValueType(),
3958 getValue(I.getOperand(1))));
3959 return 0;
3960 case Intrinsic::powi:
3961 setValue(&I, DAG.getNode(ISD::FPOWI,
3962 getValue(I.getOperand(1)).getValueType(),
3963 getValue(I.getOperand(1)),
3964 getValue(I.getOperand(2))));
3965 return 0;
3966 case Intrinsic::sin:
3967 setValue(&I, DAG.getNode(ISD::FSIN,
3968 getValue(I.getOperand(1)).getValueType(),
3969 getValue(I.getOperand(1))));
3970 return 0;
3971 case Intrinsic::cos:
3972 setValue(&I, DAG.getNode(ISD::FCOS,
3973 getValue(I.getOperand(1)).getValueType(),
3974 getValue(I.getOperand(1))));
3975 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003976 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003977 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003978 return 0;
3979 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003980 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003981 return 0;
3982 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003983 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003984 return 0;
3985 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003986 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003987 return 0;
3988 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003989 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003990 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003991 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003992 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003993 return 0;
3994 case Intrinsic::pcmarker: {
3995 SDValue Tmp = getValue(I.getOperand(1));
3996 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3997 return 0;
3998 }
3999 case Intrinsic::readcyclecounter: {
4000 SDValue Op = getRoot();
4001 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
4002 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4003 &Op, 1);
4004 setValue(&I, Tmp);
4005 DAG.setRoot(Tmp.getValue(1));
4006 return 0;
4007 }
4008 case Intrinsic::part_select: {
4009 // Currently not implemented: just abort
4010 assert(0 && "part_select intrinsic not implemented");
4011 abort();
4012 }
4013 case Intrinsic::part_set: {
4014 // Currently not implemented: just abort
4015 assert(0 && "part_set intrinsic not implemented");
4016 abort();
4017 }
4018 case Intrinsic::bswap:
4019 setValue(&I, DAG.getNode(ISD::BSWAP,
4020 getValue(I.getOperand(1)).getValueType(),
4021 getValue(I.getOperand(1))));
4022 return 0;
4023 case Intrinsic::cttz: {
4024 SDValue Arg = getValue(I.getOperand(1));
4025 MVT Ty = Arg.getValueType();
4026 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
4027 setValue(&I, result);
4028 return 0;
4029 }
4030 case Intrinsic::ctlz: {
4031 SDValue Arg = getValue(I.getOperand(1));
4032 MVT Ty = Arg.getValueType();
4033 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
4034 setValue(&I, result);
4035 return 0;
4036 }
4037 case Intrinsic::ctpop: {
4038 SDValue Arg = getValue(I.getOperand(1));
4039 MVT Ty = Arg.getValueType();
4040 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
4041 setValue(&I, result);
4042 return 0;
4043 }
4044 case Intrinsic::stacksave: {
4045 SDValue Op = getRoot();
4046 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
4047 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4048 setValue(&I, Tmp);
4049 DAG.setRoot(Tmp.getValue(1));
4050 return 0;
4051 }
4052 case Intrinsic::stackrestore: {
4053 SDValue Tmp = getValue(I.getOperand(1));
4054 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
4055 return 0;
4056 }
Bill Wendling57344502008-11-18 11:01:33 +00004057 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004058 // Emit code into the DAG to store the stack guard onto the stack.
4059 MachineFunction &MF = DAG.getMachineFunction();
4060 MachineFrameInfo *MFI = MF.getFrameInfo();
4061 MVT PtrTy = TLI.getPointerTy();
4062
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004063 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4064 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004065
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004066 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004067 MFI->setStackProtectorIndex(FI);
4068
4069 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4070
4071 // Store the stack protector onto the stack.
4072 SDValue Result = DAG.getStore(getRoot(), Src, FIN,
4073 PseudoSourceValue::getFixedStack(FI),
4074 0, true);
4075 setValue(&I, Result);
4076 DAG.setRoot(Result);
4077 return 0;
4078 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004079 case Intrinsic::var_annotation:
4080 // Discard annotate attributes
4081 return 0;
4082
4083 case Intrinsic::init_trampoline: {
4084 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4085
4086 SDValue Ops[6];
4087 Ops[0] = getRoot();
4088 Ops[1] = getValue(I.getOperand(1));
4089 Ops[2] = getValue(I.getOperand(2));
4090 Ops[3] = getValue(I.getOperand(3));
4091 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4092 Ops[5] = DAG.getSrcValue(F);
4093
4094 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
4095 DAG.getNodeValueTypes(TLI.getPointerTy(),
4096 MVT::Other), 2,
4097 Ops, 6);
4098
4099 setValue(&I, Tmp);
4100 DAG.setRoot(Tmp.getValue(1));
4101 return 0;
4102 }
4103
4104 case Intrinsic::gcroot:
4105 if (GFI) {
4106 Value *Alloca = I.getOperand(1);
4107 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4108
4109 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4110 GFI->addStackRoot(FI->getIndex(), TypeMap);
4111 }
4112 return 0;
4113
4114 case Intrinsic::gcread:
4115 case Intrinsic::gcwrite:
4116 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4117 return 0;
4118
4119 case Intrinsic::flt_rounds: {
4120 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
4121 return 0;
4122 }
4123
4124 case Intrinsic::trap: {
4125 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
4126 return 0;
4127 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004128
Bill Wendlingef375462008-11-21 02:38:44 +00004129 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004130 return implVisitAluOverflow(I, ISD::UADDO);
4131 case Intrinsic::sadd_with_overflow:
4132 return implVisitAluOverflow(I, ISD::SADDO);
4133 case Intrinsic::usub_with_overflow:
4134 return implVisitAluOverflow(I, ISD::USUBO);
4135 case Intrinsic::ssub_with_overflow:
4136 return implVisitAluOverflow(I, ISD::SSUBO);
4137 case Intrinsic::umul_with_overflow:
4138 return implVisitAluOverflow(I, ISD::UMULO);
4139 case Intrinsic::smul_with_overflow:
4140 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004141
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004142 case Intrinsic::prefetch: {
4143 SDValue Ops[4];
4144 Ops[0] = getRoot();
4145 Ops[1] = getValue(I.getOperand(1));
4146 Ops[2] = getValue(I.getOperand(2));
4147 Ops[3] = getValue(I.getOperand(3));
4148 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
4149 return 0;
4150 }
4151
4152 case Intrinsic::memory_barrier: {
4153 SDValue Ops[6];
4154 Ops[0] = getRoot();
4155 for (int x = 1; x < 6; ++x)
4156 Ops[x] = getValue(I.getOperand(x));
4157
4158 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
4159 return 0;
4160 }
4161 case Intrinsic::atomic_cmp_swap: {
4162 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004163 SDValue L =
4164 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP,
4165 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4166 Root,
4167 getValue(I.getOperand(1)),
4168 getValue(I.getOperand(2)),
4169 getValue(I.getOperand(3)),
4170 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004171 setValue(&I, L);
4172 DAG.setRoot(L.getValue(1));
4173 return 0;
4174 }
4175 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004176 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004177 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004178 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004179 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004180 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004181 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004182 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004183 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004184 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004185 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004186 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004187 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004188 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004189 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004190 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004191 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004192 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004193 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004194 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004195 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004196 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004197 }
4198}
4199
4200
4201void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4202 bool IsTailCall,
4203 MachineBasicBlock *LandingPad) {
4204 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4205 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4206 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4207 unsigned BeginLabel = 0, EndLabel = 0;
4208
4209 TargetLowering::ArgListTy Args;
4210 TargetLowering::ArgListEntry Entry;
4211 Args.reserve(CS.arg_size());
4212 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4213 i != e; ++i) {
4214 SDValue ArgNode = getValue(*i);
4215 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4216
4217 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004218 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4219 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4220 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4221 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4222 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4223 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004224 Entry.Alignment = CS.getParamAlignment(attrInd);
4225 Args.push_back(Entry);
4226 }
4227
4228 if (LandingPad && MMI) {
4229 // Insert a label before the invoke call to mark the try range. This can be
4230 // used to detect deletion of the invoke via the MachineModuleInfo.
4231 BeginLabel = MMI->NextLabelID();
4232 // Both PendingLoads and PendingExports must be flushed here;
4233 // this call might not return.
4234 (void)getRoot();
4235 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4236 }
4237
4238 std::pair<SDValue,SDValue> Result =
4239 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004240 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004241 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4242 CS.paramHasAttr(0, Attribute::InReg),
4243 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004244 IsTailCall && PerformTailCallOpt,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004245 Callee, Args, DAG);
4246 if (CS.getType() != Type::VoidTy)
4247 setValue(CS.getInstruction(), Result.first);
4248 DAG.setRoot(Result.second);
4249
4250 if (LandingPad && MMI) {
4251 // Insert a label at the end of the invoke call to mark the try range. This
4252 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4253 EndLabel = MMI->NextLabelID();
4254 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4255
4256 // Inform MachineModuleInfo of range.
4257 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4258 }
4259}
4260
4261
4262void SelectionDAGLowering::visitCall(CallInst &I) {
4263 const char *RenameFn = 0;
4264 if (Function *F = I.getCalledFunction()) {
4265 if (F->isDeclaration()) {
4266 if (unsigned IID = F->getIntrinsicID()) {
4267 RenameFn = visitIntrinsicCall(I, IID);
4268 if (!RenameFn)
4269 return;
4270 }
4271 }
4272
4273 // Check for well-known libc/libm calls. If the function is internal, it
4274 // can't be a library call.
4275 unsigned NameLen = F->getNameLen();
4276 if (!F->hasInternalLinkage() && NameLen) {
4277 const char *NameStr = F->getNameStart();
4278 if (NameStr[0] == 'c' &&
4279 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4280 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4281 if (I.getNumOperands() == 3 && // Basic sanity checks.
4282 I.getOperand(1)->getType()->isFloatingPoint() &&
4283 I.getType() == I.getOperand(1)->getType() &&
4284 I.getType() == I.getOperand(2)->getType()) {
4285 SDValue LHS = getValue(I.getOperand(1));
4286 SDValue RHS = getValue(I.getOperand(2));
4287 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4288 LHS, RHS));
4289 return;
4290 }
4291 } else if (NameStr[0] == 'f' &&
4292 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4293 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4294 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4295 if (I.getNumOperands() == 2 && // Basic sanity checks.
4296 I.getOperand(1)->getType()->isFloatingPoint() &&
4297 I.getType() == I.getOperand(1)->getType()) {
4298 SDValue Tmp = getValue(I.getOperand(1));
4299 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4300 return;
4301 }
4302 } else if (NameStr[0] == 's' &&
4303 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4304 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4305 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4306 if (I.getNumOperands() == 2 && // Basic sanity checks.
4307 I.getOperand(1)->getType()->isFloatingPoint() &&
4308 I.getType() == I.getOperand(1)->getType()) {
4309 SDValue Tmp = getValue(I.getOperand(1));
4310 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4311 return;
4312 }
4313 } else if (NameStr[0] == 'c' &&
4314 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4315 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4316 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4317 if (I.getNumOperands() == 2 && // Basic sanity checks.
4318 I.getOperand(1)->getType()->isFloatingPoint() &&
4319 I.getType() == I.getOperand(1)->getType()) {
4320 SDValue Tmp = getValue(I.getOperand(1));
4321 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4322 return;
4323 }
4324 }
4325 }
4326 } else if (isa<InlineAsm>(I.getOperand(0))) {
4327 visitInlineAsm(&I);
4328 return;
4329 }
4330
4331 SDValue Callee;
4332 if (!RenameFn)
4333 Callee = getValue(I.getOperand(0));
4334 else
Bill Wendling056292f2008-09-16 21:48:12 +00004335 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004336
4337 LowerCallTo(&I, Callee, I.isTailCall());
4338}
4339
4340
4341/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4342/// this value and returns the result as a ValueVT value. This uses
4343/// Chain/Flag as the input and updates them for the output Chain/Flag.
4344/// If the Flag pointer is NULL, no flag is used.
4345SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4346 SDValue &Chain,
4347 SDValue *Flag) const {
4348 // Assemble the legal parts into the final values.
4349 SmallVector<SDValue, 4> Values(ValueVTs.size());
4350 SmallVector<SDValue, 8> Parts;
4351 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4352 // Copy the legal parts from the registers.
4353 MVT ValueVT = ValueVTs[Value];
4354 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4355 MVT RegisterVT = RegVTs[Value];
4356
4357 Parts.resize(NumRegs);
4358 for (unsigned i = 0; i != NumRegs; ++i) {
4359 SDValue P;
4360 if (Flag == 0)
4361 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4362 else {
4363 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4364 *Flag = P.getValue(2);
4365 }
4366 Chain = P.getValue(1);
4367
4368 // If the source register was virtual and if we know something about it,
4369 // add an assert node.
4370 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4371 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4372 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4373 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4374 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4375 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4376
4377 unsigned RegSize = RegisterVT.getSizeInBits();
4378 unsigned NumSignBits = LOI.NumSignBits;
4379 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4380
4381 // FIXME: We capture more information than the dag can represent. For
4382 // now, just use the tightest assertzext/assertsext possible.
4383 bool isSExt = true;
4384 MVT FromVT(MVT::Other);
4385 if (NumSignBits == RegSize)
4386 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4387 else if (NumZeroBits >= RegSize-1)
4388 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4389 else if (NumSignBits > RegSize-8)
4390 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4391 else if (NumZeroBits >= RegSize-9)
4392 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4393 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004394 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004395 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004396 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004397 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004398 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004399 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004400 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004401
4402 if (FromVT != MVT::Other) {
4403 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4404 RegisterVT, P, DAG.getValueType(FromVT));
4405
4406 }
4407 }
4408 }
4409
4410 Parts[i] = P;
4411 }
4412
4413 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4414 ValueVT);
4415 Part += NumRegs;
4416 Parts.clear();
4417 }
4418
Duncan Sandsaaffa052008-12-01 11:41:29 +00004419 return DAG.getNode(ISD::MERGE_VALUES,
4420 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4421 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004422}
4423
4424/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4425/// specified value into the registers specified by this object. This uses
4426/// Chain/Flag as the input and updates them for the output Chain/Flag.
4427/// If the Flag pointer is NULL, no flag is used.
4428void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4429 SDValue &Chain, SDValue *Flag) const {
4430 // Get the list of the values's legal parts.
4431 unsigned NumRegs = Regs.size();
4432 SmallVector<SDValue, 8> Parts(NumRegs);
4433 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4434 MVT ValueVT = ValueVTs[Value];
4435 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4436 MVT RegisterVT = RegVTs[Value];
4437
4438 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4439 &Parts[Part], NumParts, RegisterVT);
4440 Part += NumParts;
4441 }
4442
4443 // Copy the parts into the registers.
4444 SmallVector<SDValue, 8> Chains(NumRegs);
4445 for (unsigned i = 0; i != NumRegs; ++i) {
4446 SDValue Part;
4447 if (Flag == 0)
4448 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4449 else {
4450 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4451 *Flag = Part.getValue(1);
4452 }
4453 Chains[i] = Part.getValue(0);
4454 }
4455
4456 if (NumRegs == 1 || Flag)
4457 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4458 // flagged to it. That is the CopyToReg nodes and the user are considered
4459 // a single scheduling unit. If we create a TokenFactor and return it as
4460 // chain, then the TokenFactor is both a predecessor (operand) of the
4461 // user as well as a successor (the TF operands are flagged to the user).
4462 // c1, f1 = CopyToReg
4463 // c2, f2 = CopyToReg
4464 // c3 = TokenFactor c1, c2
4465 // ...
4466 // = op c3, ..., f2
4467 Chain = Chains[NumRegs-1];
4468 else
4469 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4470}
4471
4472/// AddInlineAsmOperands - Add this value to the specified inlineasm node
4473/// operand list. This adds the code marker and includes the number of
4474/// values added into it.
4475void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4476 std::vector<SDValue> &Ops) const {
4477 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4478 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4479 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4480 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4481 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004482 for (unsigned i = 0; i != NumRegs; ++i) {
4483 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004484 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004485 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004486 }
4487}
4488
4489/// isAllocatableRegister - If the specified register is safe to allocate,
4490/// i.e. it isn't a stack pointer or some other special register, return the
4491/// register class for the register. Otherwise, return null.
4492static const TargetRegisterClass *
4493isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4494 const TargetLowering &TLI,
4495 const TargetRegisterInfo *TRI) {
4496 MVT FoundVT = MVT::Other;
4497 const TargetRegisterClass *FoundRC = 0;
4498 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4499 E = TRI->regclass_end(); RCI != E; ++RCI) {
4500 MVT ThisVT = MVT::Other;
4501
4502 const TargetRegisterClass *RC = *RCI;
4503 // If none of the the value types for this register class are valid, we
4504 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4505 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4506 I != E; ++I) {
4507 if (TLI.isTypeLegal(*I)) {
4508 // If we have already found this register in a different register class,
4509 // choose the one with the largest VT specified. For example, on
4510 // PowerPC, we favor f64 register classes over f32.
4511 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4512 ThisVT = *I;
4513 break;
4514 }
4515 }
4516 }
4517
4518 if (ThisVT == MVT::Other) continue;
4519
4520 // NOTE: This isn't ideal. In particular, this might allocate the
4521 // frame pointer in functions that need it (due to them not being taken
4522 // out of allocation, because a variable sized allocation hasn't been seen
4523 // yet). This is a slight code pessimization, but should still work.
4524 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4525 E = RC->allocation_order_end(MF); I != E; ++I)
4526 if (*I == Reg) {
4527 // We found a matching register class. Keep looking at others in case
4528 // we find one with larger registers that this physreg is also in.
4529 FoundRC = RC;
4530 FoundVT = ThisVT;
4531 break;
4532 }
4533 }
4534 return FoundRC;
4535}
4536
4537
4538namespace llvm {
4539/// AsmOperandInfo - This contains information for each constraint that we are
4540/// lowering.
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004541struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4542 public TargetLowering::AsmOperandInfo {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004543 /// CallOperand - If this is the result output operand or a clobber
4544 /// this is null, otherwise it is the incoming operand to the CallInst.
4545 /// This gets modified as the asm is processed.
4546 SDValue CallOperand;
4547
4548 /// AssignedRegs - If this is a register or register class operand, this
4549 /// contains the set of register corresponding to the operand.
4550 RegsForValue AssignedRegs;
4551
4552 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4553 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4554 }
4555
4556 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4557 /// busy in OutputRegs/InputRegs.
4558 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4559 std::set<unsigned> &OutputRegs,
4560 std::set<unsigned> &InputRegs,
4561 const TargetRegisterInfo &TRI) const {
4562 if (isOutReg) {
4563 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4564 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4565 }
4566 if (isInReg) {
4567 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4568 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4569 }
4570 }
Chris Lattner81249c92008-10-17 17:05:25 +00004571
4572 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4573 /// corresponds to. If there is no Value* for this operand, it returns
4574 /// MVT::Other.
4575 MVT getCallOperandValMVT(const TargetLowering &TLI,
4576 const TargetData *TD) const {
4577 if (CallOperandVal == 0) return MVT::Other;
4578
4579 if (isa<BasicBlock>(CallOperandVal))
4580 return TLI.getPointerTy();
4581
4582 const llvm::Type *OpTy = CallOperandVal->getType();
4583
4584 // If this is an indirect operand, the operand is a pointer to the
4585 // accessed type.
4586 if (isIndirect)
4587 OpTy = cast<PointerType>(OpTy)->getElementType();
4588
4589 // If OpTy is not a single value, it may be a struct/union that we
4590 // can tile with integers.
4591 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4592 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4593 switch (BitSize) {
4594 default: break;
4595 case 1:
4596 case 8:
4597 case 16:
4598 case 32:
4599 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004600 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004601 OpTy = IntegerType::get(BitSize);
4602 break;
4603 }
4604 }
4605
4606 return TLI.getValueType(OpTy, true);
4607 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004608
4609private:
4610 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4611 /// specified set.
4612 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4613 const TargetRegisterInfo &TRI) {
4614 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4615 Regs.insert(Reg);
4616 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4617 for (; *Aliases; ++Aliases)
4618 Regs.insert(*Aliases);
4619 }
4620};
4621} // end llvm namespace.
4622
4623
4624/// GetRegistersForValue - Assign registers (virtual or physical) for the
4625/// specified operand. We prefer to assign virtual registers, to allow the
4626/// register allocator handle the assignment process. However, if the asm uses
4627/// features that we can't model on machineinstrs, we have SDISel do the
4628/// allocation. This produces generally horrible, but correct, code.
4629///
4630/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004631/// Input and OutputRegs are the set of already allocated physical registers.
4632///
4633void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004634GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004635 std::set<unsigned> &OutputRegs,
4636 std::set<unsigned> &InputRegs) {
4637 // Compute whether this value requires an input register, an output register,
4638 // or both.
4639 bool isOutReg = false;
4640 bool isInReg = false;
4641 switch (OpInfo.Type) {
4642 case InlineAsm::isOutput:
4643 isOutReg = true;
4644
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004645 // If there is an input constraint that matches this, we need to reserve
4646 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004647 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004648 break;
4649 case InlineAsm::isInput:
4650 isInReg = true;
4651 isOutReg = false;
4652 break;
4653 case InlineAsm::isClobber:
4654 isOutReg = true;
4655 isInReg = true;
4656 break;
4657 }
4658
4659
4660 MachineFunction &MF = DAG.getMachineFunction();
4661 SmallVector<unsigned, 4> Regs;
4662
4663 // If this is a constraint for a single physreg, or a constraint for a
4664 // register class, find it.
4665 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4666 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4667 OpInfo.ConstraintVT);
4668
4669 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004670 if (OpInfo.ConstraintVT != MVT::Other) {
4671 // If this is a FP input in an integer register (or visa versa) insert a bit
4672 // cast of the input value. More generally, handle any case where the input
4673 // value disagrees with the register class we plan to stick this in.
4674 if (OpInfo.Type == InlineAsm::isInput &&
4675 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4676 // Try to convert to the first MVT that the reg class contains. If the
4677 // types are identical size, use a bitcast to convert (e.g. two differing
4678 // vector types).
4679 MVT RegVT = *PhysReg.second->vt_begin();
4680 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4681 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4682 OpInfo.CallOperand);
4683 OpInfo.ConstraintVT = RegVT;
4684 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4685 // If the input is a FP value and we want it in FP registers, do a
4686 // bitcast to the corresponding integer type. This turns an f64 value
4687 // into i64, which can be passed with two i32 values on a 32-bit
4688 // machine.
4689 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4690 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4691 OpInfo.CallOperand);
4692 OpInfo.ConstraintVT = RegVT;
4693 }
4694 }
4695
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004696 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004697 }
4698
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004699 MVT RegVT;
4700 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004701
4702 // If this is a constraint for a specific physical register, like {r17},
4703 // assign it now.
4704 if (PhysReg.first) {
4705 if (OpInfo.ConstraintVT == MVT::Other)
4706 ValueVT = *PhysReg.second->vt_begin();
4707
4708 // Get the actual register value type. This is important, because the user
4709 // may have asked for (e.g.) the AX register in i32 type. We need to
4710 // remember that AX is actually i16 to get the right extension.
4711 RegVT = *PhysReg.second->vt_begin();
4712
4713 // This is a explicit reference to a physical register.
4714 Regs.push_back(PhysReg.first);
4715
4716 // If this is an expanded reference, add the rest of the regs to Regs.
4717 if (NumRegs != 1) {
4718 TargetRegisterClass::iterator I = PhysReg.second->begin();
4719 for (; *I != PhysReg.first; ++I)
4720 assert(I != PhysReg.second->end() && "Didn't find reg!");
4721
4722 // Already added the first reg.
4723 --NumRegs; ++I;
4724 for (; NumRegs; --NumRegs, ++I) {
4725 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4726 Regs.push_back(*I);
4727 }
4728 }
4729 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4730 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4731 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4732 return;
4733 }
4734
4735 // Otherwise, if this was a reference to an LLVM register class, create vregs
4736 // for this reference.
4737 std::vector<unsigned> RegClassRegs;
4738 const TargetRegisterClass *RC = PhysReg.second;
4739 if (RC) {
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004740 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner58f15c42008-10-17 16:21:11 +00004741 // the constraint, so we have to pick a register to pin the input/output to.
4742 // If it isn't a matched constraint, go ahead and create vreg and let the
4743 // regalloc do its thing.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004744 if (!OpInfo.hasMatchingInput()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004745 RegVT = *PhysReg.second->vt_begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004746 if (OpInfo.ConstraintVT == MVT::Other)
4747 ValueVT = RegVT;
4748
4749 // Create the appropriate number of virtual registers.
4750 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4751 for (; NumRegs; --NumRegs)
4752 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4753
4754 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4755 return;
4756 }
4757
4758 // Otherwise, we can't allocate it. Let the code below figure out how to
4759 // maintain these constraints.
4760 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4761
4762 } else {
4763 // This is a reference to a register class that doesn't directly correspond
4764 // to an LLVM register class. Allocate NumRegs consecutive, available,
4765 // registers from the class.
4766 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4767 OpInfo.ConstraintVT);
4768 }
4769
4770 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4771 unsigned NumAllocated = 0;
4772 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4773 unsigned Reg = RegClassRegs[i];
4774 // See if this register is available.
4775 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4776 (isInReg && InputRegs.count(Reg))) { // Already used.
4777 // Make sure we find consecutive registers.
4778 NumAllocated = 0;
4779 continue;
4780 }
4781
4782 // Check to see if this register is allocatable (i.e. don't give out the
4783 // stack pointer).
4784 if (RC == 0) {
4785 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4786 if (!RC) { // Couldn't allocate this register.
4787 // Reset NumAllocated to make sure we return consecutive registers.
4788 NumAllocated = 0;
4789 continue;
4790 }
4791 }
4792
4793 // Okay, this register is good, we can use it.
4794 ++NumAllocated;
4795
4796 // If we allocated enough consecutive registers, succeed.
4797 if (NumAllocated == NumRegs) {
4798 unsigned RegStart = (i-NumAllocated)+1;
4799 unsigned RegEnd = i+1;
4800 // Mark all of the allocated registers used.
4801 for (unsigned i = RegStart; i != RegEnd; ++i)
4802 Regs.push_back(RegClassRegs[i]);
4803
4804 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4805 OpInfo.ConstraintVT);
4806 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4807 return;
4808 }
4809 }
4810
4811 // Otherwise, we couldn't allocate enough registers for this.
4812}
4813
Evan Chengda43bcf2008-09-24 00:05:32 +00004814/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4815/// processed uses a memory 'm' constraint.
4816static bool
4817hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4818 TargetLowering &TLI) {
4819 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4820 InlineAsm::ConstraintInfo &CI = CInfos[i];
4821 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4822 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4823 if (CType == TargetLowering::C_Memory)
4824 return true;
4825 }
4826 }
4827
4828 return false;
4829}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004830
4831/// visitInlineAsm - Handle a call to an InlineAsm object.
4832///
4833void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4834 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4835
4836 /// ConstraintOperands - Information about all of the constraints.
4837 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4838
4839 SDValue Chain = getRoot();
4840 SDValue Flag;
4841
4842 std::set<unsigned> OutputRegs, InputRegs;
4843
4844 // Do a prepass over the constraints, canonicalizing them, and building up the
4845 // ConstraintOperands list.
4846 std::vector<InlineAsm::ConstraintInfo>
4847 ConstraintInfos = IA->ParseConstraints();
4848
Evan Chengda43bcf2008-09-24 00:05:32 +00004849 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004850
4851 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4852 unsigned ResNo = 0; // ResNo - The result number of the next output.
4853 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4854 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4855 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4856
4857 MVT OpVT = MVT::Other;
4858
4859 // Compute the value type for each operand.
4860 switch (OpInfo.Type) {
4861 case InlineAsm::isOutput:
4862 // Indirect outputs just consume an argument.
4863 if (OpInfo.isIndirect) {
4864 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4865 break;
4866 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004867
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004868 // The return value of the call is this value. As such, there is no
4869 // corresponding argument.
4870 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4871 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4872 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4873 } else {
4874 assert(ResNo == 0 && "Asm only has one result!");
4875 OpVT = TLI.getValueType(CS.getType());
4876 }
4877 ++ResNo;
4878 break;
4879 case InlineAsm::isInput:
4880 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4881 break;
4882 case InlineAsm::isClobber:
4883 // Nothing to do.
4884 break;
4885 }
4886
4887 // If this is an input or an indirect output, process the call argument.
4888 // BasicBlocks are labels, currently appearing only in asm's.
4889 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00004890 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004891 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00004892 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004893 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004894 }
Chris Lattner81249c92008-10-17 17:05:25 +00004895
4896 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004897 }
4898
4899 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004900 }
4901
4902 // Second pass over the constraints: compute which constraint option to use
4903 // and assign registers to constraints that want a specific physreg.
4904 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4905 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4906
4907 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00004908 // matching input. If their types mismatch, e.g. one is an integer, the
4909 // other is floating point, or their sizes are different, flag it as an
4910 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004911 if (OpInfo.hasMatchingInput()) {
4912 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4913 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00004914 if ((OpInfo.ConstraintVT.isInteger() !=
4915 Input.ConstraintVT.isInteger()) ||
4916 (OpInfo.ConstraintVT.getSizeInBits() !=
4917 Input.ConstraintVT.getSizeInBits())) {
4918 cerr << "Unsupported asm: input constraint with a matching output "
4919 << "constraint of incompatible type!\n";
4920 exit(1);
4921 }
4922 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004923 }
4924 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004925
4926 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00004927 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004928
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004929 // If this is a memory input, and if the operand is not indirect, do what we
4930 // need to to provide an address for the memory input.
4931 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4932 !OpInfo.isIndirect) {
4933 assert(OpInfo.Type == InlineAsm::isInput &&
4934 "Can only indirectify direct input operands!");
4935
4936 // Memory operands really want the address of the value. If we don't have
4937 // an indirect input, put it in the constpool if we can, otherwise spill
4938 // it to a stack slot.
4939
4940 // If the operand is a float, integer, or vector constant, spill to a
4941 // constant pool entry to get its address.
4942 Value *OpVal = OpInfo.CallOperandVal;
4943 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4944 isa<ConstantVector>(OpVal)) {
4945 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4946 TLI.getPointerTy());
4947 } else {
4948 // Otherwise, create a stack slot and emit a store to it before the
4949 // asm.
4950 const Type *Ty = OpVal->getType();
4951 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4952 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4953 MachineFunction &MF = DAG.getMachineFunction();
4954 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4955 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4956 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4957 OpInfo.CallOperand = StackSlot;
4958 }
4959
4960 // There is no longer a Value* corresponding to this operand.
4961 OpInfo.CallOperandVal = 0;
4962 // It is now an indirect operand.
4963 OpInfo.isIndirect = true;
4964 }
4965
4966 // If this constraint is for a specific register, allocate it before
4967 // anything else.
4968 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004969 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004970 }
4971 ConstraintInfos.clear();
4972
4973
4974 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00004975 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004976 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4977 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4978
4979 // C_Register operands have already been allocated, Other/Memory don't need
4980 // to be.
4981 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004982 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004983 }
4984
4985 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4986 std::vector<SDValue> AsmNodeOperands;
4987 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4988 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00004989 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004990
4991
4992 // Loop over all of the inputs, copying the operand values into the
4993 // appropriate registers and processing the output regs.
4994 RegsForValue RetValRegs;
4995
4996 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4997 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4998
4999 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5000 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5001
5002 switch (OpInfo.Type) {
5003 case InlineAsm::isOutput: {
5004 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5005 OpInfo.ConstraintType != TargetLowering::C_Register) {
5006 // Memory output, or 'other' output (e.g. 'X' constraint).
5007 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5008
5009 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005010 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5011 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005012 TLI.getPointerTy()));
5013 AsmNodeOperands.push_back(OpInfo.CallOperand);
5014 break;
5015 }
5016
5017 // Otherwise, this is a register or register class output.
5018
5019 // Copy the output from the appropriate register. Find a register that
5020 // we can use.
5021 if (OpInfo.AssignedRegs.Regs.empty()) {
5022 cerr << "Couldn't allocate output reg for constraint '"
5023 << OpInfo.ConstraintCode << "'!\n";
5024 exit(1);
5025 }
5026
5027 // If this is an indirect operand, store through the pointer after the
5028 // asm.
5029 if (OpInfo.isIndirect) {
5030 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5031 OpInfo.CallOperandVal));
5032 } else {
5033 // This is the result value of the call.
5034 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5035 // Concatenate this output onto the outputs list.
5036 RetValRegs.append(OpInfo.AssignedRegs);
5037 }
5038
5039 // Add information to the INLINEASM node to know that this register is
5040 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005041 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5042 6 /* EARLYCLOBBER REGDEF */ :
5043 2 /* REGDEF */ ,
5044 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005045 break;
5046 }
5047 case InlineAsm::isInput: {
5048 SDValue InOperandVal = OpInfo.CallOperand;
5049
Chris Lattner6bdcda32008-10-17 16:47:46 +00005050 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005051 // If this is required to match an output register we have already set,
5052 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005053 unsigned OperandNo = OpInfo.getMatchedOperand();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005054
5055 // Scan until we find the definition we already emitted of this operand.
5056 // When we find it, create a RegsForValue operand.
5057 unsigned CurOp = 2; // The first operand.
5058 for (; OperandNo; --OperandNo) {
5059 // Advance to the next operand.
5060 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005061 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005062 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen913d3df2008-09-12 17:49:03 +00005063 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen86b49f82008-09-24 01:07:17 +00005064 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005065 "Skipped past definitions?");
5066 CurOp += (NumOps>>3)+1;
5067 }
5068
5069 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005070 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dale Johannesen913d3df2008-09-12 17:49:03 +00005071 if ((NumOps & 7) == 2 /*REGDEF*/
5072 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005073 // Add NumOps>>3 registers to MatchedRegs.
5074 RegsForValue MatchedRegs;
5075 MatchedRegs.TLI = &TLI;
5076 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5077 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5078 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5079 unsigned Reg =
5080 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5081 MatchedRegs.Regs.push_back(Reg);
5082 }
5083
5084 // Use the produced MatchedRegs object to
5085 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Dale Johannesen86b49f82008-09-24 01:07:17 +00005086 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005087 break;
5088 } else {
Dale Johannesen86b49f82008-09-24 01:07:17 +00005089 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005090 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
5091 // Add information to the INLINEASM node to know about this input.
Dale Johannesen91aac102008-09-17 21:13:11 +00005092 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005093 TLI.getPointerTy()));
5094 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5095 break;
5096 }
5097 }
5098
5099 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5100 assert(!OpInfo.isIndirect &&
5101 "Don't know how to handle indirect other inputs yet!");
5102
5103 std::vector<SDValue> Ops;
5104 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005105 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005106 if (Ops.empty()) {
5107 cerr << "Invalid operand for inline asm constraint '"
5108 << OpInfo.ConstraintCode << "'!\n";
5109 exit(1);
5110 }
5111
5112 // Add information to the INLINEASM node to know about this input.
5113 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5114 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5115 TLI.getPointerTy()));
5116 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5117 break;
5118 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5119 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5120 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5121 "Memory operands expect pointer values");
5122
5123 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005124 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5125 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005126 TLI.getPointerTy()));
5127 AsmNodeOperands.push_back(InOperandVal);
5128 break;
5129 }
5130
5131 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5132 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5133 "Unknown constraint type!");
5134 assert(!OpInfo.isIndirect &&
5135 "Don't know how to handle indirect register inputs yet!");
5136
5137 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005138 if (OpInfo.AssignedRegs.Regs.empty()) {
5139 cerr << "Couldn't allocate output reg for constraint '"
5140 << OpInfo.ConstraintCode << "'!\n";
5141 exit(1);
5142 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005143
5144 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5145
Dale Johannesen86b49f82008-09-24 01:07:17 +00005146 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5147 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005148 break;
5149 }
5150 case InlineAsm::isClobber: {
5151 // Add the clobbered value to the operand list, so that the register
5152 // allocator is aware that the physreg got clobbered.
5153 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005154 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5155 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005156 break;
5157 }
5158 }
5159 }
5160
5161 // Finish up input operands.
5162 AsmNodeOperands[0] = Chain;
5163 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5164
5165 Chain = DAG.getNode(ISD::INLINEASM,
5166 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5167 &AsmNodeOperands[0], AsmNodeOperands.size());
5168 Flag = Chain.getValue(1);
5169
5170 // If this asm returns a register value, copy the result from that register
5171 // and set it as the value of the call.
5172 if (!RetValRegs.Regs.empty()) {
5173 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005174
5175 // FIXME: Why don't we do this for inline asms with MRVs?
5176 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5177 MVT ResultType = TLI.getValueType(CS.getType());
5178
5179 // If any of the results of the inline asm is a vector, it may have the
5180 // wrong width/num elts. This can happen for register classes that can
5181 // contain multiple different value types. The preg or vreg allocated may
5182 // not have the same VT as was expected. Convert it to the right type
5183 // with bit_convert.
5184 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5185 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005186
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005187 } else if (ResultType != Val.getValueType() &&
5188 ResultType.isInteger() && Val.getValueType().isInteger()) {
5189 // If a result value was tied to an input value, the computed result may
5190 // have a wider width than the expected result. Extract the relevant
5191 // portion.
5192 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005193 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005194
5195 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005196 }
Dan Gohman95915732008-10-18 01:03:45 +00005197
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005198 setValue(CS.getInstruction(), Val);
5199 }
5200
5201 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5202
5203 // Process indirect outputs, first output all of the flagged copies out of
5204 // physregs.
5205 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5206 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5207 Value *Ptr = IndirectStoresToEmit[i].second;
5208 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5209 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5210 }
5211
5212 // Emit the non-flagged stores from the physregs.
5213 SmallVector<SDValue, 8> OutChains;
5214 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5215 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5216 getValue(StoresToEmit[i].second),
5217 StoresToEmit[i].second, 0));
5218 if (!OutChains.empty())
5219 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5220 &OutChains[0], OutChains.size());
5221 DAG.setRoot(Chain);
5222}
5223
5224
5225void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5226 SDValue Src = getValue(I.getOperand(0));
5227
5228 MVT IntPtr = TLI.getPointerTy();
5229
5230 if (IntPtr.bitsLT(Src.getValueType()))
5231 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5232 else if (IntPtr.bitsGT(Src.getValueType()))
5233 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5234
5235 // Scale the source by the type size.
5236 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5237 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5238 Src, DAG.getIntPtrConstant(ElementSize));
5239
5240 TargetLowering::ArgListTy Args;
5241 TargetLowering::ArgListEntry Entry;
5242 Entry.Node = Src;
5243 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5244 Args.push_back(Entry);
5245
5246 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005247 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5248 CallingConv::C, PerformTailCallOpt,
5249 DAG.getExternalSymbol("malloc", IntPtr),
Dan Gohman1937e2f2008-09-16 01:42:28 +00005250 Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005251 setValue(&I, Result.first); // Pointers always fit in registers
5252 DAG.setRoot(Result.second);
5253}
5254
5255void SelectionDAGLowering::visitFree(FreeInst &I) {
5256 TargetLowering::ArgListTy Args;
5257 TargetLowering::ArgListEntry Entry;
5258 Entry.Node = getValue(I.getOperand(0));
5259 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5260 Args.push_back(Entry);
5261 MVT IntPtr = TLI.getPointerTy();
5262 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005263 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005264 CallingConv::C, PerformTailCallOpt,
Bill Wendling056292f2008-09-16 21:48:12 +00005265 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005266 DAG.setRoot(Result.second);
5267}
5268
5269void SelectionDAGLowering::visitVAStart(CallInst &I) {
5270 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5271 getValue(I.getOperand(1)),
5272 DAG.getSrcValue(I.getOperand(1))));
5273}
5274
5275void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5276 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5277 getValue(I.getOperand(0)),
5278 DAG.getSrcValue(I.getOperand(0)));
5279 setValue(&I, V);
5280 DAG.setRoot(V.getValue(1));
5281}
5282
5283void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5284 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5285 getValue(I.getOperand(1)),
5286 DAG.getSrcValue(I.getOperand(1))));
5287}
5288
5289void SelectionDAGLowering::visitVACopy(CallInst &I) {
5290 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5291 getValue(I.getOperand(1)),
5292 getValue(I.getOperand(2)),
5293 DAG.getSrcValue(I.getOperand(1)),
5294 DAG.getSrcValue(I.getOperand(2))));
5295}
5296
5297/// TargetLowering::LowerArguments - This is the default LowerArguments
5298/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5299/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5300/// integrated into SDISel.
5301void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5302 SmallVectorImpl<SDValue> &ArgValues) {
5303 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5304 SmallVector<SDValue, 3+16> Ops;
5305 Ops.push_back(DAG.getRoot());
5306 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5307 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5308
5309 // Add one result value for each formal argument.
5310 SmallVector<MVT, 16> RetVals;
5311 unsigned j = 1;
5312 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5313 I != E; ++I, ++j) {
5314 SmallVector<MVT, 4> ValueVTs;
5315 ComputeValueVTs(*this, I->getType(), ValueVTs);
5316 for (unsigned Value = 0, NumValues = ValueVTs.size();
5317 Value != NumValues; ++Value) {
5318 MVT VT = ValueVTs[Value];
5319 const Type *ArgTy = VT.getTypeForMVT();
5320 ISD::ArgFlagsTy Flags;
5321 unsigned OriginalAlignment =
5322 getTargetData()->getABITypeAlignment(ArgTy);
5323
Devang Patel05988662008-09-25 21:00:45 +00005324 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005325 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005326 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005327 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005328 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005329 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005330 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005331 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005332 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005333 Flags.setByVal();
5334 const PointerType *Ty = cast<PointerType>(I->getType());
5335 const Type *ElementTy = Ty->getElementType();
5336 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5337 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5338 // For ByVal, alignment should be passed from FE. BE will guess if
5339 // this info is not there but there are cases it cannot get right.
5340 if (F.getParamAlignment(j))
5341 FrameAlign = F.getParamAlignment(j);
5342 Flags.setByValAlign(FrameAlign);
5343 Flags.setByValSize(FrameSize);
5344 }
Devang Patel05988662008-09-25 21:00:45 +00005345 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005346 Flags.setNest();
5347 Flags.setOrigAlign(OriginalAlignment);
5348
5349 MVT RegisterVT = getRegisterType(VT);
5350 unsigned NumRegs = getNumRegisters(VT);
5351 for (unsigned i = 0; i != NumRegs; ++i) {
5352 RetVals.push_back(RegisterVT);
5353 ISD::ArgFlagsTy MyFlags = Flags;
5354 if (NumRegs > 1 && i == 0)
5355 MyFlags.setSplit();
5356 // if it isn't first piece, alignment must be 1
5357 else if (i > 0)
5358 MyFlags.setOrigAlign(1);
5359 Ops.push_back(DAG.getArgFlags(MyFlags));
5360 }
5361 }
5362 }
5363
5364 RetVals.push_back(MVT::Other);
5365
5366 // Create the node.
5367 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5368 DAG.getVTList(&RetVals[0], RetVals.size()),
5369 &Ops[0], Ops.size()).getNode();
5370
5371 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5372 // allows exposing the loads that may be part of the argument access to the
5373 // first DAGCombiner pass.
5374 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5375
5376 // The number of results should match up, except that the lowered one may have
5377 // an extra flag result.
5378 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5379 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5380 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5381 && "Lowering produced unexpected number of results!");
5382
5383 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5384 if (Result != TmpRes.getNode() && Result->use_empty()) {
5385 HandleSDNode Dummy(DAG.getRoot());
5386 DAG.RemoveDeadNode(Result);
5387 }
5388
5389 Result = TmpRes.getNode();
5390
5391 unsigned NumArgRegs = Result->getNumValues() - 1;
5392 DAG.setRoot(SDValue(Result, NumArgRegs));
5393
5394 // Set up the return result vector.
5395 unsigned i = 0;
5396 unsigned Idx = 1;
5397 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5398 ++I, ++Idx) {
5399 SmallVector<MVT, 4> ValueVTs;
5400 ComputeValueVTs(*this, I->getType(), ValueVTs);
5401 for (unsigned Value = 0, NumValues = ValueVTs.size();
5402 Value != NumValues; ++Value) {
5403 MVT VT = ValueVTs[Value];
5404 MVT PartVT = getRegisterType(VT);
5405
5406 unsigned NumParts = getNumRegisters(VT);
5407 SmallVector<SDValue, 4> Parts(NumParts);
5408 for (unsigned j = 0; j != NumParts; ++j)
5409 Parts[j] = SDValue(Result, i++);
5410
5411 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005412 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005413 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005414 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005415 AssertOp = ISD::AssertZext;
5416
5417 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5418 AssertOp));
5419 }
5420 }
5421 assert(i == NumArgRegs && "Argument register count mismatch!");
5422}
5423
5424
5425/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5426/// implementation, which just inserts an ISD::CALL node, which is later custom
5427/// lowered by the target to something concrete. FIXME: When all targets are
5428/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5429std::pair<SDValue, SDValue>
5430TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5431 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005432 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005433 unsigned CallingConv, bool isTailCall,
5434 SDValue Callee,
5435 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005436 assert((!isTailCall || PerformTailCallOpt) &&
5437 "isTailCall set when tail-call optimizations are disabled!");
5438
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005439 SmallVector<SDValue, 32> Ops;
5440 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005441 Ops.push_back(Callee);
5442
5443 // Handle all of the outgoing arguments.
5444 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5445 SmallVector<MVT, 4> ValueVTs;
5446 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5447 for (unsigned Value = 0, NumValues = ValueVTs.size();
5448 Value != NumValues; ++Value) {
5449 MVT VT = ValueVTs[Value];
5450 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005451 SDValue Op = SDValue(Args[i].Node.getNode(),
5452 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005453 ISD::ArgFlagsTy Flags;
5454 unsigned OriginalAlignment =
5455 getTargetData()->getABITypeAlignment(ArgTy);
5456
5457 if (Args[i].isZExt)
5458 Flags.setZExt();
5459 if (Args[i].isSExt)
5460 Flags.setSExt();
5461 if (Args[i].isInReg)
5462 Flags.setInReg();
5463 if (Args[i].isSRet)
5464 Flags.setSRet();
5465 if (Args[i].isByVal) {
5466 Flags.setByVal();
5467 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5468 const Type *ElementTy = Ty->getElementType();
5469 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5470 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5471 // For ByVal, alignment should come from FE. BE will guess if this
5472 // info is not there but there are cases it cannot get right.
5473 if (Args[i].Alignment)
5474 FrameAlign = Args[i].Alignment;
5475 Flags.setByValAlign(FrameAlign);
5476 Flags.setByValSize(FrameSize);
5477 }
5478 if (Args[i].isNest)
5479 Flags.setNest();
5480 Flags.setOrigAlign(OriginalAlignment);
5481
5482 MVT PartVT = getRegisterType(VT);
5483 unsigned NumParts = getNumRegisters(VT);
5484 SmallVector<SDValue, 4> Parts(NumParts);
5485 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5486
5487 if (Args[i].isSExt)
5488 ExtendKind = ISD::SIGN_EXTEND;
5489 else if (Args[i].isZExt)
5490 ExtendKind = ISD::ZERO_EXTEND;
5491
5492 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5493
5494 for (unsigned i = 0; i != NumParts; ++i) {
5495 // if it isn't first piece, alignment must be 1
5496 ISD::ArgFlagsTy MyFlags = Flags;
5497 if (NumParts > 1 && i == 0)
5498 MyFlags.setSplit();
5499 else if (i != 0)
5500 MyFlags.setOrigAlign(1);
5501
5502 Ops.push_back(Parts[i]);
5503 Ops.push_back(DAG.getArgFlags(MyFlags));
5504 }
5505 }
5506 }
5507
5508 // Figure out the result value types. We start by making a list of
5509 // the potentially illegal return value types.
5510 SmallVector<MVT, 4> LoweredRetTys;
5511 SmallVector<MVT, 4> RetTys;
5512 ComputeValueVTs(*this, RetTy, RetTys);
5513
5514 // Then we translate that to a list of legal types.
5515 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5516 MVT VT = RetTys[I];
5517 MVT RegisterVT = getRegisterType(VT);
5518 unsigned NumRegs = getNumRegisters(VT);
5519 for (unsigned i = 0; i != NumRegs; ++i)
5520 LoweredRetTys.push_back(RegisterVT);
5521 }
5522
5523 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5524
5525 // Create the CALL node.
Dale Johannesen86098bd2008-09-26 19:31:26 +00005526 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005527 DAG.getVTList(&LoweredRetTys[0],
5528 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005529 &Ops[0], Ops.size()
5530 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005531 Chain = Res.getValue(LoweredRetTys.size() - 1);
5532
5533 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005534 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005535 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5536
5537 if (RetSExt)
5538 AssertOp = ISD::AssertSext;
5539 else if (RetZExt)
5540 AssertOp = ISD::AssertZext;
5541
5542 SmallVector<SDValue, 4> ReturnValues;
5543 unsigned RegNo = 0;
5544 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5545 MVT VT = RetTys[I];
5546 MVT RegisterVT = getRegisterType(VT);
5547 unsigned NumRegs = getNumRegisters(VT);
5548 unsigned RegNoEnd = NumRegs + RegNo;
5549 SmallVector<SDValue, 4> Results;
5550 for (; RegNo != RegNoEnd; ++RegNo)
5551 Results.push_back(Res.getValue(RegNo));
5552 SDValue ReturnValue =
5553 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5554 AssertOp);
5555 ReturnValues.push_back(ReturnValue);
5556 }
Duncan Sandsaaffa052008-12-01 11:41:29 +00005557 Res = DAG.getNode(ISD::MERGE_VALUES,
5558 DAG.getVTList(&RetTys[0], RetTys.size()),
5559 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005560 }
5561
5562 return std::make_pair(Res, Chain);
5563}
5564
5565SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5566 assert(0 && "LowerOperation not implemented for this target!");
5567 abort();
5568 return SDValue();
5569}
5570
5571
5572void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5573 SDValue Op = getValue(V);
5574 assert((Op.getOpcode() != ISD::CopyFromReg ||
5575 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5576 "Copy from a reg to the same reg!");
5577 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5578
5579 RegsForValue RFV(TLI, Reg, V->getType());
5580 SDValue Chain = DAG.getEntryNode();
5581 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5582 PendingExports.push_back(Chain);
5583}
5584
5585#include "llvm/CodeGen/SelectionDAGISel.h"
5586
5587void SelectionDAGISel::
5588LowerArguments(BasicBlock *LLVMBB) {
5589 // If this is the entry block, emit arguments.
5590 Function &F = *LLVMBB->getParent();
5591 SDValue OldRoot = SDL->DAG.getRoot();
5592 SmallVector<SDValue, 16> Args;
5593 TLI.LowerArguments(F, SDL->DAG, Args);
5594
5595 unsigned a = 0;
5596 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5597 AI != E; ++AI) {
5598 SmallVector<MVT, 4> ValueVTs;
5599 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5600 unsigned NumValues = ValueVTs.size();
5601 if (!AI->use_empty()) {
5602 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5603 // If this argument is live outside of the entry block, insert a copy from
5604 // whereever we got it to the vreg that other BB's will reference it as.
5605 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5606 if (VMI != FuncInfo->ValueMap.end()) {
5607 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5608 }
5609 }
5610 a += NumValues;
5611 }
5612
5613 // Finally, if the target has anything special to do, allow it to do so.
5614 // FIXME: this should insert code into the DAG!
5615 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5616}
5617
5618/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5619/// ensure constants are generated when needed. Remember the virtual registers
5620/// that need to be added to the Machine PHI nodes as input. We cannot just
5621/// directly add them, because expansion might result in multiple MBB's for one
5622/// BB. As such, the start of the BB might correspond to a different MBB than
5623/// the end.
5624///
5625void
5626SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5627 TerminatorInst *TI = LLVMBB->getTerminator();
5628
5629 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5630
5631 // Check successor nodes' PHI nodes that expect a constant to be available
5632 // from this block.
5633 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5634 BasicBlock *SuccBB = TI->getSuccessor(succ);
5635 if (!isa<PHINode>(SuccBB->begin())) continue;
5636 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5637
5638 // If this terminator has multiple identical successors (common for
5639 // switches), only handle each succ once.
5640 if (!SuccsHandled.insert(SuccMBB)) continue;
5641
5642 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5643 PHINode *PN;
5644
5645 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5646 // nodes and Machine PHI nodes, but the incoming operands have not been
5647 // emitted yet.
5648 for (BasicBlock::iterator I = SuccBB->begin();
5649 (PN = dyn_cast<PHINode>(I)); ++I) {
5650 // Ignore dead phi's.
5651 if (PN->use_empty()) continue;
5652
5653 unsigned Reg;
5654 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5655
5656 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5657 unsigned &RegOut = SDL->ConstantsOut[C];
5658 if (RegOut == 0) {
5659 RegOut = FuncInfo->CreateRegForValue(C);
5660 SDL->CopyValueToVirtualRegister(C, RegOut);
5661 }
5662 Reg = RegOut;
5663 } else {
5664 Reg = FuncInfo->ValueMap[PHIOp];
5665 if (Reg == 0) {
5666 assert(isa<AllocaInst>(PHIOp) &&
5667 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5668 "Didn't codegen value into a register!??");
5669 Reg = FuncInfo->CreateRegForValue(PHIOp);
5670 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5671 }
5672 }
5673
5674 // Remember that this register needs to added to the machine PHI node as
5675 // the input for this MBB.
5676 SmallVector<MVT, 4> ValueVTs;
5677 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5678 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5679 MVT VT = ValueVTs[vti];
5680 unsigned NumRegisters = TLI.getNumRegisters(VT);
5681 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5682 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5683 Reg += NumRegisters;
5684 }
5685 }
5686 }
5687 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005688}
5689
Dan Gohman3df24e62008-09-03 23:12:08 +00005690/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5691/// supports legal types, and it emits MachineInstrs directly instead of
5692/// creating SelectionDAG nodes.
5693///
5694bool
5695SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5696 FastISel *F) {
5697 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005698
Dan Gohman3df24e62008-09-03 23:12:08 +00005699 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5700 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5701
5702 // Check successor nodes' PHI nodes that expect a constant to be available
5703 // from this block.
5704 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5705 BasicBlock *SuccBB = TI->getSuccessor(succ);
5706 if (!isa<PHINode>(SuccBB->begin())) continue;
5707 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5708
5709 // If this terminator has multiple identical successors (common for
5710 // switches), only handle each succ once.
5711 if (!SuccsHandled.insert(SuccMBB)) continue;
5712
5713 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5714 PHINode *PN;
5715
5716 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5717 // nodes and Machine PHI nodes, but the incoming operands have not been
5718 // emitted yet.
5719 for (BasicBlock::iterator I = SuccBB->begin();
5720 (PN = dyn_cast<PHINode>(I)); ++I) {
5721 // Ignore dead phi's.
5722 if (PN->use_empty()) continue;
5723
5724 // Only handle legal types. Two interesting things to note here. First,
5725 // by bailing out early, we may leave behind some dead instructions,
5726 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5727 // own moves. Second, this check is necessary becuase FastISel doesn't
5728 // use CreateRegForValue to create registers, so it always creates
5729 // exactly one register for each non-void instruction.
5730 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5731 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005732 // Promote MVT::i1.
5733 if (VT == MVT::i1)
5734 VT = TLI.getTypeToTransformTo(VT);
5735 else {
5736 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5737 return false;
5738 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005739 }
5740
5741 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5742
5743 unsigned Reg = F->getRegForValue(PHIOp);
5744 if (Reg == 0) {
5745 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5746 return false;
5747 }
5748 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5749 }
5750 }
5751
5752 return true;
5753}