blob: 4f17164ce6a7590b703101911a8758aad4d74297 [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');
Devang Patel8a84e442009-01-05 17:31:22 +00002022 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002023
2024 // Get the Value to be switched on and default basic blocks, which will be
2025 // inserted into CaseBlock records, representing basic blocks in the binary
2026 // search tree.
2027 Value *SV = SI.getOperand(0);
2028
2029 // Push the initial CaseRec onto the worklist
2030 CaseRecVector WorkList;
2031 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2032
2033 while (!WorkList.empty()) {
2034 // Grab a record representing a case range to process off the worklist
2035 CaseRec CR = WorkList.back();
2036 WorkList.pop_back();
2037
2038 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2039 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002040
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002041 // If the range has few cases (two or less) emit a series of specific
2042 // tests.
2043 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2044 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002045
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002046 // If the switch has more than 5 blocks, and at least 40% dense, and the
2047 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002048 // lowering the switch to a binary tree of conditional branches.
2049 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2050 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002051
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002052 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2053 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2054 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2055 }
2056}
2057
2058
2059void SelectionDAGLowering::visitSub(User &I) {
2060 // -0.0 - X --> fneg
2061 const Type *Ty = I.getType();
2062 if (isa<VectorType>(Ty)) {
2063 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2064 const VectorType *DestTy = cast<VectorType>(I.getType());
2065 const Type *ElTy = DestTy->getElementType();
2066 if (ElTy->isFloatingPoint()) {
2067 unsigned VL = DestTy->getNumElements();
2068 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2069 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2070 if (CV == CNZ) {
2071 SDValue Op2 = getValue(I.getOperand(1));
2072 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2073 return;
2074 }
2075 }
2076 }
2077 }
2078 if (Ty->isFloatingPoint()) {
2079 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2080 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2081 SDValue Op2 = getValue(I.getOperand(1));
2082 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2083 return;
2084 }
2085 }
2086
2087 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2088}
2089
2090void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2091 SDValue Op1 = getValue(I.getOperand(0));
2092 SDValue Op2 = getValue(I.getOperand(1));
2093
2094 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2095}
2096
2097void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2098 SDValue Op1 = getValue(I.getOperand(0));
2099 SDValue Op2 = getValue(I.getOperand(1));
2100 if (!isa<VectorType>(I.getType())) {
2101 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2102 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2103 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2104 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2105 }
2106
2107 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2108}
2109
2110void SelectionDAGLowering::visitICmp(User &I) {
2111 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2112 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2113 predicate = IC->getPredicate();
2114 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2115 predicate = ICmpInst::Predicate(IC->getPredicate());
2116 SDValue Op1 = getValue(I.getOperand(0));
2117 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002118 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002119 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2120}
2121
2122void SelectionDAGLowering::visitFCmp(User &I) {
2123 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2124 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2125 predicate = FC->getPredicate();
2126 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2127 predicate = FCmpInst::Predicate(FC->getPredicate());
2128 SDValue Op1 = getValue(I.getOperand(0));
2129 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002130 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002131 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2132}
2133
2134void SelectionDAGLowering::visitVICmp(User &I) {
2135 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2136 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2137 predicate = IC->getPredicate();
2138 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2139 predicate = ICmpInst::Predicate(IC->getPredicate());
2140 SDValue Op1 = getValue(I.getOperand(0));
2141 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002142 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002143 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2144}
2145
2146void SelectionDAGLowering::visitVFCmp(User &I) {
2147 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2148 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2149 predicate = FC->getPredicate();
2150 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2151 predicate = FCmpInst::Predicate(FC->getPredicate());
2152 SDValue Op1 = getValue(I.getOperand(0));
2153 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002154 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002155 MVT DestVT = TLI.getValueType(I.getType());
2156
2157 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2158}
2159
2160void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002161 SmallVector<MVT, 4> ValueVTs;
2162 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2163 unsigned NumValues = ValueVTs.size();
2164 if (NumValues != 0) {
2165 SmallVector<SDValue, 4> Values(NumValues);
2166 SDValue Cond = getValue(I.getOperand(0));
2167 SDValue TrueVal = getValue(I.getOperand(1));
2168 SDValue FalseVal = getValue(I.getOperand(2));
2169
2170 for (unsigned i = 0; i != NumValues; ++i)
2171 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2172 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2173 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2174
Duncan Sandsaaffa052008-12-01 11:41:29 +00002175 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2176 DAG.getVTList(&ValueVTs[0], NumValues),
2177 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002178 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002179}
2180
2181
2182void SelectionDAGLowering::visitTrunc(User &I) {
2183 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2184 SDValue N = getValue(I.getOperand(0));
2185 MVT DestVT = TLI.getValueType(I.getType());
2186 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2187}
2188
2189void SelectionDAGLowering::visitZExt(User &I) {
2190 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2191 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2192 SDValue N = getValue(I.getOperand(0));
2193 MVT DestVT = TLI.getValueType(I.getType());
2194 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2195}
2196
2197void SelectionDAGLowering::visitSExt(User &I) {
2198 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2199 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2200 SDValue N = getValue(I.getOperand(0));
2201 MVT DestVT = TLI.getValueType(I.getType());
2202 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2203}
2204
2205void SelectionDAGLowering::visitFPTrunc(User &I) {
2206 // FPTrunc is never a no-op cast, no need to check
2207 SDValue N = getValue(I.getOperand(0));
2208 MVT DestVT = TLI.getValueType(I.getType());
2209 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2210}
2211
2212void SelectionDAGLowering::visitFPExt(User &I){
2213 // FPTrunc is never a no-op cast, no need to check
2214 SDValue N = getValue(I.getOperand(0));
2215 MVT DestVT = TLI.getValueType(I.getType());
2216 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2217}
2218
2219void SelectionDAGLowering::visitFPToUI(User &I) {
2220 // FPToUI is never a no-op cast, no need to check
2221 SDValue N = getValue(I.getOperand(0));
2222 MVT DestVT = TLI.getValueType(I.getType());
2223 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2224}
2225
2226void SelectionDAGLowering::visitFPToSI(User &I) {
2227 // FPToSI is never a no-op cast, no need to check
2228 SDValue N = getValue(I.getOperand(0));
2229 MVT DestVT = TLI.getValueType(I.getType());
2230 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2231}
2232
2233void SelectionDAGLowering::visitUIToFP(User &I) {
2234 // UIToFP is never a no-op cast, no need to check
2235 SDValue N = getValue(I.getOperand(0));
2236 MVT DestVT = TLI.getValueType(I.getType());
2237 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2238}
2239
2240void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002241 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002242 SDValue N = getValue(I.getOperand(0));
2243 MVT DestVT = TLI.getValueType(I.getType());
2244 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2245}
2246
2247void SelectionDAGLowering::visitPtrToInt(User &I) {
2248 // What to do depends on the size of the integer and the size of the pointer.
2249 // We can either truncate, zero extend, or no-op, accordingly.
2250 SDValue N = getValue(I.getOperand(0));
2251 MVT SrcVT = N.getValueType();
2252 MVT DestVT = TLI.getValueType(I.getType());
2253 SDValue Result;
2254 if (DestVT.bitsLT(SrcVT))
2255 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2256 else
2257 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2258 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2259 setValue(&I, Result);
2260}
2261
2262void SelectionDAGLowering::visitIntToPtr(User &I) {
2263 // What to do depends on the size of the integer and the size of the pointer.
2264 // We can either truncate, zero extend, or no-op, accordingly.
2265 SDValue N = getValue(I.getOperand(0));
2266 MVT SrcVT = N.getValueType();
2267 MVT DestVT = TLI.getValueType(I.getType());
2268 if (DestVT.bitsLT(SrcVT))
2269 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2270 else
2271 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2272 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2273}
2274
2275void SelectionDAGLowering::visitBitCast(User &I) {
2276 SDValue N = getValue(I.getOperand(0));
2277 MVT DestVT = TLI.getValueType(I.getType());
2278
2279 // BitCast assures us that source and destination are the same size so this
2280 // is either a BIT_CONVERT or a no-op.
2281 if (DestVT != N.getValueType())
2282 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2283 else
2284 setValue(&I, N); // noop cast.
2285}
2286
2287void SelectionDAGLowering::visitInsertElement(User &I) {
2288 SDValue InVec = getValue(I.getOperand(0));
2289 SDValue InVal = getValue(I.getOperand(1));
2290 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2291 getValue(I.getOperand(2)));
2292
2293 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2294 TLI.getValueType(I.getType()),
2295 InVec, InVal, InIdx));
2296}
2297
2298void SelectionDAGLowering::visitExtractElement(User &I) {
2299 SDValue InVec = getValue(I.getOperand(0));
2300 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2301 getValue(I.getOperand(1)));
2302 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2303 TLI.getValueType(I.getType()), InVec, InIdx));
2304}
2305
Mon P Wangaeb06d22008-11-10 04:46:22 +00002306
2307// Utility for visitShuffleVector - Returns true if the mask is mask starting
2308// from SIndx and increasing to the element length (undefs are allowed).
2309static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002310 unsigned MaskNumElts = Mask.getNumOperands();
2311 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002312 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2313 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2314 if (Idx != i + SIndx)
2315 return false;
2316 }
2317 }
2318 return true;
2319}
2320
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002321void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002322 SDValue Src1 = getValue(I.getOperand(0));
2323 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002324 SDValue Mask = getValue(I.getOperand(2));
2325
Mon P Wangaeb06d22008-11-10 04:46:22 +00002326 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002327 MVT SrcVT = Src1.getValueType();
Mon P Wangc7849c22008-11-16 05:06:27 +00002328 int MaskNumElts = Mask.getNumOperands();
2329 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002330
Mon P Wangc7849c22008-11-16 05:06:27 +00002331 if (SrcNumElts == MaskNumElts) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002332 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002333 return;
2334 }
2335
2336 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002337 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2338
2339 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2340 // Mask is longer than the source vectors and is a multiple of the source
2341 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002342 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002343 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2344 // The shuffle is concatenating two vectors together.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002345 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002346 return;
2347 }
2348
Mon P Wangc7849c22008-11-16 05:06:27 +00002349 // Pad both vectors with undefs to make them the same length as the mask.
2350 unsigned NumConcat = MaskNumElts / SrcNumElts;
2351 SDValue UndefVal = DAG.getNode(ISD::UNDEF, SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002352
Mon P Wang230e4fa2008-11-21 04:25:21 +00002353 SDValue* MOps1 = new SDValue[NumConcat];
2354 SDValue* MOps2 = new SDValue[NumConcat];
2355 MOps1[0] = Src1;
2356 MOps2[0] = Src2;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002357 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002358 MOps1[i] = UndefVal;
2359 MOps2[i] = UndefVal;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002360 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002361 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps1, NumConcat);
2362 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps2, NumConcat);
2363
2364 delete [] MOps1;
2365 delete [] MOps2;
2366
Mon P Wangaeb06d22008-11-10 04:46:22 +00002367 // Readjust mask for new input vector length.
2368 SmallVector<SDValue, 8> MappedOps;
Mon P Wangc7849c22008-11-16 05:06:27 +00002369 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002370 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2371 MappedOps.push_back(Mask.getOperand(i));
2372 } else {
Mon P Wangc7849c22008-11-16 05:06:27 +00002373 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2374 if (Idx < SrcNumElts)
2375 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2376 else
2377 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2378 MaskEltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002379 }
2380 }
2381 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2382 &MappedOps[0], MappedOps.size());
2383
Mon P Wang230e4fa2008-11-21 04:25:21 +00002384 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002385 return;
2386 }
2387
Mon P Wangc7849c22008-11-16 05:06:27 +00002388 if (SrcNumElts > MaskNumElts) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002389 // Resulting vector is shorter than the incoming vector.
Mon P Wangc7849c22008-11-16 05:06:27 +00002390 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002391 // Shuffle extracts 1st vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002392 setValue(&I, Src1);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002393 return;
2394 }
2395
Mon P Wangc7849c22008-11-16 05:06:27 +00002396 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002397 // Shuffle extracts 2nd vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002398 setValue(&I, Src2);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002399 return;
2400 }
2401
Mon P Wangc7849c22008-11-16 05:06:27 +00002402 // Analyze the access pattern of the vector to see if we can extract
2403 // two subvectors and do the shuffle. The analysis is done by calculating
2404 // the range of elements the mask access on both vectors.
2405 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2406 int MaxRange[2] = {-1, -1};
2407
2408 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002409 SDValue Arg = Mask.getOperand(i);
2410 if (Arg.getOpcode() != ISD::UNDEF) {
2411 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002412 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2413 int Input = 0;
2414 if (Idx >= SrcNumElts) {
2415 Input = 1;
2416 Idx -= SrcNumElts;
2417 }
2418 if (Idx > MaxRange[Input])
2419 MaxRange[Input] = Idx;
2420 if (Idx < MinRange[Input])
2421 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002422 }
2423 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002424
Mon P Wangc7849c22008-11-16 05:06:27 +00002425 // Check if the access is smaller than the vector size and can we find
2426 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002427 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002428 int StartIdx[2]; // StartIdx to extract from
2429 for (int Input=0; Input < 2; ++Input) {
2430 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2431 RangeUse[Input] = 0; // Unused
2432 StartIdx[Input] = 0;
2433 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2434 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002435 // start index that is a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002436 if (MaxRange[Input] < MaskNumElts) {
2437 RangeUse[Input] = 1; // Extract from beginning of the vector
2438 StartIdx[Input] = 0;
2439 } else {
2440 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang6cce3da2008-11-23 04:35:05 +00002441 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
2442 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002443 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002444 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002445 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002446 }
2447
2448 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2449 setValue(&I, DAG.getNode(ISD::UNDEF, VT)); // Vectors are not used.
2450 return;
2451 }
2452 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2453 // Extract appropriate subvector and generate a vector shuffle
2454 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002455 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002456 if (RangeUse[Input] == 0) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002457 Src = DAG.getNode(ISD::UNDEF, VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002458 } else {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002459 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, VT, Src,
2460 DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002461 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002462 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002463 // Calculate new mask.
2464 SmallVector<SDValue, 8> MappedOps;
2465 for (int i = 0; i != MaskNumElts; ++i) {
2466 SDValue Arg = Mask.getOperand(i);
2467 if (Arg.getOpcode() == ISD::UNDEF) {
2468 MappedOps.push_back(Arg);
2469 } else {
2470 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2471 if (Idx < SrcNumElts)
2472 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2473 else {
2474 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2475 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2476 }
2477 }
2478 }
2479 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2480 &MappedOps[0], MappedOps.size());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002481 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangc7849c22008-11-16 05:06:27 +00002482 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002483 }
2484 }
2485
Mon P Wangc7849c22008-11-16 05:06:27 +00002486 // We can't use either concat vectors or extract subvectors so fall back to
2487 // replacing the shuffle with extract and build vector.
2488 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002489 MVT EltVT = VT.getVectorElementType();
2490 MVT PtrVT = TLI.getPointerTy();
2491 SmallVector<SDValue,8> Ops;
Mon P Wangc7849c22008-11-16 05:06:27 +00002492 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002493 SDValue Arg = Mask.getOperand(i);
2494 if (Arg.getOpcode() == ISD::UNDEF) {
2495 Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2496 } else {
2497 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002498 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2499 if (Idx < SrcNumElts)
Mon P Wang230e4fa2008-11-21 04:25:21 +00002500 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src1,
Mon P Wangaeb06d22008-11-10 04:46:22 +00002501 DAG.getConstant(Idx, PtrVT)));
2502 else
Mon P Wang230e4fa2008-11-21 04:25:21 +00002503 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002504 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002505 }
2506 }
2507 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002508}
2509
2510void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2511 const Value *Op0 = I.getOperand(0);
2512 const Value *Op1 = I.getOperand(1);
2513 const Type *AggTy = I.getType();
2514 const Type *ValTy = Op1->getType();
2515 bool IntoUndef = isa<UndefValue>(Op0);
2516 bool FromUndef = isa<UndefValue>(Op1);
2517
2518 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2519 I.idx_begin(), I.idx_end());
2520
2521 SmallVector<MVT, 4> AggValueVTs;
2522 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2523 SmallVector<MVT, 4> ValValueVTs;
2524 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2525
2526 unsigned NumAggValues = AggValueVTs.size();
2527 unsigned NumValValues = ValValueVTs.size();
2528 SmallVector<SDValue, 4> Values(NumAggValues);
2529
2530 SDValue Agg = getValue(Op0);
2531 SDValue Val = getValue(Op1);
2532 unsigned i = 0;
2533 // Copy the beginning value(s) from the original aggregate.
2534 for (; i != LinearIndex; ++i)
2535 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2536 SDValue(Agg.getNode(), Agg.getResNo() + i);
2537 // Copy values from the inserted value(s).
2538 for (; i != LinearIndex + NumValValues; ++i)
2539 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2540 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2541 // Copy remaining value(s) from the original aggregate.
2542 for (; i != NumAggValues; ++i)
2543 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2544 SDValue(Agg.getNode(), Agg.getResNo() + i);
2545
Duncan Sandsaaffa052008-12-01 11:41:29 +00002546 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2547 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2548 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002549}
2550
2551void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2552 const Value *Op0 = I.getOperand(0);
2553 const Type *AggTy = Op0->getType();
2554 const Type *ValTy = I.getType();
2555 bool OutOfUndef = isa<UndefValue>(Op0);
2556
2557 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2558 I.idx_begin(), I.idx_end());
2559
2560 SmallVector<MVT, 4> ValValueVTs;
2561 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2562
2563 unsigned NumValValues = ValValueVTs.size();
2564 SmallVector<SDValue, 4> Values(NumValValues);
2565
2566 SDValue Agg = getValue(Op0);
2567 // Copy out the selected value(s).
2568 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2569 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002570 OutOfUndef ?
2571 DAG.getNode(ISD::UNDEF,
2572 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2573 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002574
Duncan Sandsaaffa052008-12-01 11:41:29 +00002575 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2576 DAG.getVTList(&ValValueVTs[0], NumValValues),
2577 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002578}
2579
2580
2581void SelectionDAGLowering::visitGetElementPtr(User &I) {
2582 SDValue N = getValue(I.getOperand(0));
2583 const Type *Ty = I.getOperand(0)->getType();
2584
2585 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2586 OI != E; ++OI) {
2587 Value *Idx = *OI;
2588 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2589 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2590 if (Field) {
2591 // N = N + Offset
2592 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2593 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2594 DAG.getIntPtrConstant(Offset));
2595 }
2596 Ty = StTy->getElementType(Field);
2597 } else {
2598 Ty = cast<SequentialType>(Ty)->getElementType();
2599
2600 // If this is a constant subscript, handle it quickly.
2601 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2602 if (CI->getZExtValue() == 0) continue;
2603 uint64_t Offs =
2604 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2605 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2606 DAG.getIntPtrConstant(Offs));
2607 continue;
2608 }
2609
2610 // N = N + Idx * ElementSize;
2611 uint64_t ElementSize = TD->getABITypeSize(Ty);
2612 SDValue IdxN = getValue(Idx);
2613
2614 // If the index is smaller or larger than intptr_t, truncate or extend
2615 // it.
2616 if (IdxN.getValueType().bitsLT(N.getValueType()))
2617 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2618 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2619 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2620
2621 // If this is a multiply by a power of two, turn it into a shl
2622 // immediately. This is a very common case.
2623 if (ElementSize != 1) {
2624 if (isPowerOf2_64(ElementSize)) {
2625 unsigned Amt = Log2_64(ElementSize);
2626 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2627 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2628 } else {
2629 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2630 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2631 }
2632 }
2633
2634 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2635 }
2636 }
2637 setValue(&I, N);
2638}
2639
2640void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2641 // If this is a fixed sized alloca in the entry block of the function,
2642 // allocate it statically on the stack.
2643 if (FuncInfo.StaticAllocaMap.count(&I))
2644 return; // getValue will auto-populate this.
2645
2646 const Type *Ty = I.getAllocatedType();
2647 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2648 unsigned Align =
2649 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2650 I.getAlignment());
2651
2652 SDValue AllocSize = getValue(I.getArraySize());
2653 MVT IntPtr = TLI.getPointerTy();
2654 if (IntPtr.bitsLT(AllocSize.getValueType()))
2655 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2656 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2657 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2658
2659 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2660 DAG.getIntPtrConstant(TySize));
2661
2662 // Handle alignment. If the requested alignment is less than or equal to
2663 // the stack alignment, ignore it. If the size is greater than or equal to
2664 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2665 unsigned StackAlign =
2666 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2667 if (Align <= StackAlign)
2668 Align = 0;
2669
2670 // Round the size of the allocation up to the stack alignment size
2671 // by add SA-1 to the size.
2672 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2673 DAG.getIntPtrConstant(StackAlign-1));
2674 // Mask out the low bits for alignment purposes.
2675 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2676 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2677
2678 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2679 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2680 MVT::Other);
2681 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2682 setValue(&I, DSA);
2683 DAG.setRoot(DSA.getValue(1));
2684
2685 // Inform the Frame Information that we have just allocated a variable-sized
2686 // object.
2687 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2688}
2689
2690void SelectionDAGLowering::visitLoad(LoadInst &I) {
2691 const Value *SV = I.getOperand(0);
2692 SDValue Ptr = getValue(SV);
2693
2694 const Type *Ty = I.getType();
2695 bool isVolatile = I.isVolatile();
2696 unsigned Alignment = I.getAlignment();
2697
2698 SmallVector<MVT, 4> ValueVTs;
2699 SmallVector<uint64_t, 4> Offsets;
2700 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2701 unsigned NumValues = ValueVTs.size();
2702 if (NumValues == 0)
2703 return;
2704
2705 SDValue Root;
2706 bool ConstantMemory = false;
2707 if (I.isVolatile())
2708 // Serialize volatile loads with other side effects.
2709 Root = getRoot();
2710 else if (AA->pointsToConstantMemory(SV)) {
2711 // Do not serialize (non-volatile) loads of constant memory with anything.
2712 Root = DAG.getEntryNode();
2713 ConstantMemory = true;
2714 } else {
2715 // Do not serialize non-volatile loads against each other.
2716 Root = DAG.getRoot();
2717 }
2718
2719 SmallVector<SDValue, 4> Values(NumValues);
2720 SmallVector<SDValue, 4> Chains(NumValues);
2721 MVT PtrVT = Ptr.getValueType();
2722 for (unsigned i = 0; i != NumValues; ++i) {
2723 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2724 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2725 DAG.getConstant(Offsets[i], PtrVT)),
2726 SV, Offsets[i],
2727 isVolatile, Alignment);
2728 Values[i] = L;
2729 Chains[i] = L.getValue(1);
2730 }
2731
2732 if (!ConstantMemory) {
2733 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2734 &Chains[0], NumValues);
2735 if (isVolatile)
2736 DAG.setRoot(Chain);
2737 else
2738 PendingLoads.push_back(Chain);
2739 }
2740
Duncan Sandsaaffa052008-12-01 11:41:29 +00002741 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2742 DAG.getVTList(&ValueVTs[0], NumValues),
2743 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002744}
2745
2746
2747void SelectionDAGLowering::visitStore(StoreInst &I) {
2748 Value *SrcV = I.getOperand(0);
2749 Value *PtrV = I.getOperand(1);
2750
2751 SmallVector<MVT, 4> ValueVTs;
2752 SmallVector<uint64_t, 4> Offsets;
2753 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2754 unsigned NumValues = ValueVTs.size();
2755 if (NumValues == 0)
2756 return;
2757
2758 // Get the lowered operands. Note that we do this after
2759 // checking if NumResults is zero, because with zero results
2760 // the operands won't have values in the map.
2761 SDValue Src = getValue(SrcV);
2762 SDValue Ptr = getValue(PtrV);
2763
2764 SDValue Root = getRoot();
2765 SmallVector<SDValue, 4> Chains(NumValues);
2766 MVT PtrVT = Ptr.getValueType();
2767 bool isVolatile = I.isVolatile();
2768 unsigned Alignment = I.getAlignment();
2769 for (unsigned i = 0; i != NumValues; ++i)
2770 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2771 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2772 DAG.getConstant(Offsets[i], PtrVT)),
2773 PtrV, Offsets[i],
2774 isVolatile, Alignment);
2775
2776 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2777}
2778
2779/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2780/// node.
2781void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2782 unsigned Intrinsic) {
2783 bool HasChain = !I.doesNotAccessMemory();
2784 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2785
2786 // Build the operand list.
2787 SmallVector<SDValue, 8> Ops;
2788 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2789 if (OnlyLoad) {
2790 // We don't need to serialize loads against other loads.
2791 Ops.push_back(DAG.getRoot());
2792 } else {
2793 Ops.push_back(getRoot());
2794 }
2795 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002796
2797 // Info is set by getTgtMemInstrinsic
2798 TargetLowering::IntrinsicInfo Info;
2799 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2800
2801 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2802 if (!IsTgtIntrinsic)
2803 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002804
2805 // Add all operands of the call to the operand list.
2806 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2807 SDValue Op = getValue(I.getOperand(i));
2808 assert(TLI.isTypeLegal(Op.getValueType()) &&
2809 "Intrinsic uses a non-legal type?");
2810 Ops.push_back(Op);
2811 }
2812
2813 std::vector<MVT> VTs;
2814 if (I.getType() != Type::VoidTy) {
2815 MVT VT = TLI.getValueType(I.getType());
2816 if (VT.isVector()) {
2817 const VectorType *DestTy = cast<VectorType>(I.getType());
2818 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2819
2820 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2821 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2822 }
2823
2824 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2825 VTs.push_back(VT);
2826 }
2827 if (HasChain)
2828 VTs.push_back(MVT::Other);
2829
2830 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2831
2832 // Create the node.
2833 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002834 if (IsTgtIntrinsic) {
2835 // This is target intrinsic that touches memory
2836 Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2837 &Ops[0], Ops.size(),
2838 Info.memVT, Info.ptrVal, Info.offset,
2839 Info.align, Info.vol,
2840 Info.readMem, Info.writeMem);
2841 }
2842 else if (!HasChain)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002843 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2844 &Ops[0], Ops.size());
2845 else if (I.getType() != Type::VoidTy)
2846 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2847 &Ops[0], Ops.size());
2848 else
2849 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2850 &Ops[0], Ops.size());
2851
2852 if (HasChain) {
2853 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2854 if (OnlyLoad)
2855 PendingLoads.push_back(Chain);
2856 else
2857 DAG.setRoot(Chain);
2858 }
2859 if (I.getType() != Type::VoidTy) {
2860 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2861 MVT VT = TLI.getValueType(PTy);
2862 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2863 }
2864 setValue(&I, Result);
2865 }
2866}
2867
2868/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2869static GlobalVariable *ExtractTypeInfo(Value *V) {
2870 V = V->stripPointerCasts();
2871 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2872 assert ((GV || isa<ConstantPointerNull>(V)) &&
2873 "TypeInfo must be a global variable or NULL");
2874 return GV;
2875}
2876
2877namespace llvm {
2878
2879/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2880/// call, and add them to the specified machine basic block.
2881void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2882 MachineBasicBlock *MBB) {
2883 // Inform the MachineModuleInfo of the personality for this landing pad.
2884 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2885 assert(CE->getOpcode() == Instruction::BitCast &&
2886 isa<Function>(CE->getOperand(0)) &&
2887 "Personality should be a function");
2888 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2889
2890 // Gather all the type infos for this landing pad and pass them along to
2891 // MachineModuleInfo.
2892 std::vector<GlobalVariable *> TyInfo;
2893 unsigned N = I.getNumOperands();
2894
2895 for (unsigned i = N - 1; i > 2; --i) {
2896 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2897 unsigned FilterLength = CI->getZExtValue();
2898 unsigned FirstCatch = i + FilterLength + !FilterLength;
2899 assert (FirstCatch <= N && "Invalid filter length");
2900
2901 if (FirstCatch < N) {
2902 TyInfo.reserve(N - FirstCatch);
2903 for (unsigned j = FirstCatch; j < N; ++j)
2904 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2905 MMI->addCatchTypeInfo(MBB, TyInfo);
2906 TyInfo.clear();
2907 }
2908
2909 if (!FilterLength) {
2910 // Cleanup.
2911 MMI->addCleanup(MBB);
2912 } else {
2913 // Filter.
2914 TyInfo.reserve(FilterLength - 1);
2915 for (unsigned j = i + 1; j < FirstCatch; ++j)
2916 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2917 MMI->addFilterTypeInfo(MBB, TyInfo);
2918 TyInfo.clear();
2919 }
2920
2921 N = i;
2922 }
2923 }
2924
2925 if (N > 3) {
2926 TyInfo.reserve(N - 3);
2927 for (unsigned j = 3; j < N; ++j)
2928 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2929 MMI->addCatchTypeInfo(MBB, TyInfo);
2930 }
2931}
2932
2933}
2934
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002935/// GetSignificand - Get the significand and build it into a floating-point
2936/// number with exponent of 1:
2937///
2938/// Op = (Op & 0x007fffff) | 0x3f800000;
2939///
2940/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002941static SDValue
2942GetSignificand(SelectionDAG &DAG, SDValue Op) {
2943 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2944 DAG.getConstant(0x007fffff, MVT::i32));
2945 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2946 DAG.getConstant(0x3f800000, MVT::i32));
2947 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2948}
2949
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002950/// GetExponent - Get the exponent:
2951///
2952/// (float)((Op1 >> 23) - 127);
2953///
2954/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002955static SDValue
2956GetExponent(SelectionDAG &DAG, SDValue Op) {
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002957 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
Bill Wendling39150252008-09-09 20:39:27 +00002958 DAG.getConstant(23, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002959 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
Bill Wendling39150252008-09-09 20:39:27 +00002960 DAG.getConstant(127, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002961 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002962}
2963
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002964/// getF32Constant - Get 32-bit floating point constant.
2965static SDValue
2966getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2967 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2968}
2969
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002970/// Inlined utility function to implement binary input atomic intrinsics for
2971/// visitIntrinsicCall: I is a call instruction
2972/// Op is the associated NodeType for I
2973const char *
2974SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2975 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002976 SDValue L =
2977 DAG.getAtomic(Op, getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2978 Root,
2979 getValue(I.getOperand(1)),
2980 getValue(I.getOperand(2)),
2981 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002982 setValue(&I, L);
2983 DAG.setRoot(L.getValue(1));
2984 return 0;
2985}
2986
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002987// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00002988const char *
2989SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002990 SDValue Op1 = getValue(I.getOperand(1));
2991 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00002992
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002993 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
2994 SDValue Ops[] = { Op1, Op2 };
Bill Wendling74c37652008-12-09 22:08:41 +00002995
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002996 SDValue Result = DAG.getNode(Op, DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
Bill Wendling74c37652008-12-09 22:08:41 +00002997
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002998 setValue(&I, Result);
2999 return 0;
3000}
Bill Wendling74c37652008-12-09 22:08:41 +00003001
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003002/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3003/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003004void
3005SelectionDAGLowering::visitExp(CallInst &I) {
3006 SDValue result;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003007
3008 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3009 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3010 SDValue Op = getValue(I.getOperand(1));
3011
3012 // Put the exponent in the right bit position for later addition to the
3013 // final result:
3014 //
3015 // #define LOG2OFe 1.4426950f
3016 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3017 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003018 getF32Constant(DAG, 0x3fb8aa3b));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003019 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3020
3021 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3022 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3023 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3024
3025 // IntegerPartOfX <<= 23;
3026 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3027 DAG.getConstant(23, MVT::i32));
3028
3029 if (LimitFloatPrecision <= 6) {
3030 // For floating-point precision of 6:
3031 //
3032 // TwoToFractionalPartOfX =
3033 // 0.997535578f +
3034 // (0.735607626f + 0.252464424f * x) * x;
3035 //
3036 // error 0.0144103317, which is 6 bits
3037 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003038 getF32Constant(DAG, 0x3e814304));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003039 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003040 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003041 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3042 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003043 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003044 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3045
3046 // Add the exponent into the result in integer domain.
3047 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
3048 TwoToFracPartOfX, IntegerPartOfX);
3049
3050 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
3051 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3052 // For floating-point precision of 12:
3053 //
3054 // TwoToFractionalPartOfX =
3055 // 0.999892986f +
3056 // (0.696457318f +
3057 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3058 //
3059 // 0.000107046256 error, which is 13 to 14 bits
3060 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003061 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003062 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003063 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003064 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3065 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003066 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003067 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3068 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003069 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003070 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3071
3072 // Add the exponent into the result in integer domain.
3073 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
3074 TwoToFracPartOfX, IntegerPartOfX);
3075
3076 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
3077 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3078 // For floating-point precision of 18:
3079 //
3080 // TwoToFractionalPartOfX =
3081 // 0.999999982f +
3082 // (0.693148872f +
3083 // (0.240227044f +
3084 // (0.554906021e-1f +
3085 // (0.961591928e-2f +
3086 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3087 //
3088 // error 2.47208000*10^(-7), which is better than 18 bits
3089 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003090 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003091 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003092 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003093 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3094 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003095 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003096 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3097 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003098 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003099 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3100 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003101 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003102 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3103 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003104 getF32Constant(DAG, 0x3f317234));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003105 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3106 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003107 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003108 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3109
3110 // Add the exponent into the result in integer domain.
3111 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
3112 TwoToFracPartOfX, IntegerPartOfX);
3113
3114 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
3115 }
3116 } else {
3117 // No special expansion.
3118 result = DAG.getNode(ISD::FEXP,
3119 getValue(I.getOperand(1)).getValueType(),
3120 getValue(I.getOperand(1)));
3121 }
3122
Dale Johannesen59e577f2008-09-05 18:38:42 +00003123 setValue(&I, result);
3124}
3125
Bill Wendling39150252008-09-09 20:39:27 +00003126/// visitLog - Lower a log intrinsic. Handles the special sequences for
3127/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003128void
3129SelectionDAGLowering::visitLog(CallInst &I) {
3130 SDValue result;
Bill Wendling39150252008-09-09 20:39:27 +00003131
3132 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3133 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3134 SDValue Op = getValue(I.getOperand(1));
3135 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3136
3137 // Scale the exponent by log(2) [0.69314718f].
3138 SDValue Exp = GetExponent(DAG, Op1);
3139 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003140 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003141
3142 // Get the significand and build it into a floating-point number with
3143 // exponent of 1.
3144 SDValue X = GetSignificand(DAG, Op1);
3145
3146 if (LimitFloatPrecision <= 6) {
3147 // For floating-point precision of 6:
3148 //
3149 // LogofMantissa =
3150 // -1.1609546f +
3151 // (1.4034025f - 0.23903021f * x) * x;
3152 //
3153 // error 0.0034276066, which is better than 8 bits
3154 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003155 getF32Constant(DAG, 0xbe74c456));
Bill Wendling39150252008-09-09 20:39:27 +00003156 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003157 getF32Constant(DAG, 0x3fb3a2b1));
Bill Wendling39150252008-09-09 20:39:27 +00003158 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3159 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003160 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003161
3162 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3163 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3164 // For floating-point precision of 12:
3165 //
3166 // LogOfMantissa =
3167 // -1.7417939f +
3168 // (2.8212026f +
3169 // (-1.4699568f +
3170 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3171 //
3172 // error 0.000061011436, which is 14 bits
3173 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003174 getF32Constant(DAG, 0xbd67b6d6));
Bill Wendling39150252008-09-09 20:39:27 +00003175 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003176 getF32Constant(DAG, 0x3ee4f4b8));
Bill Wendling39150252008-09-09 20:39:27 +00003177 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3178 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003179 getF32Constant(DAG, 0x3fbc278b));
Bill Wendling39150252008-09-09 20:39:27 +00003180 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3181 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003182 getF32Constant(DAG, 0x40348e95));
Bill Wendling39150252008-09-09 20:39:27 +00003183 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3184 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003185 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003186
3187 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3188 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3189 // For floating-point precision of 18:
3190 //
3191 // LogOfMantissa =
3192 // -2.1072184f +
3193 // (4.2372794f +
3194 // (-3.7029485f +
3195 // (2.2781945f +
3196 // (-0.87823314f +
3197 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3198 //
3199 // error 0.0000023660568, which is better than 18 bits
3200 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003201 getF32Constant(DAG, 0xbc91e5ac));
Bill Wendling39150252008-09-09 20:39:27 +00003202 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003203 getF32Constant(DAG, 0x3e4350aa));
Bill Wendling39150252008-09-09 20:39:27 +00003204 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3205 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003206 getF32Constant(DAG, 0x3f60d3e3));
Bill Wendling39150252008-09-09 20:39:27 +00003207 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3208 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003209 getF32Constant(DAG, 0x4011cdf0));
Bill Wendling39150252008-09-09 20:39:27 +00003210 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3211 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003212 getF32Constant(DAG, 0x406cfd1c));
Bill Wendling39150252008-09-09 20:39:27 +00003213 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3214 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003215 getF32Constant(DAG, 0x408797cb));
Bill Wendling39150252008-09-09 20:39:27 +00003216 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3217 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003218 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003219
3220 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3221 }
3222 } else {
3223 // No special expansion.
3224 result = DAG.getNode(ISD::FLOG,
3225 getValue(I.getOperand(1)).getValueType(),
3226 getValue(I.getOperand(1)));
3227 }
3228
Dale Johannesen59e577f2008-09-05 18:38:42 +00003229 setValue(&I, result);
3230}
3231
Bill Wendling3eb59402008-09-09 00:28:24 +00003232/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3233/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003234void
3235SelectionDAGLowering::visitLog2(CallInst &I) {
3236 SDValue result;
Bill Wendling3eb59402008-09-09 00:28:24 +00003237
Dale Johannesen853244f2008-09-05 23:49:37 +00003238 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003239 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3240 SDValue Op = getValue(I.getOperand(1));
3241 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3242
Bill Wendling39150252008-09-09 20:39:27 +00003243 // Get the exponent.
3244 SDValue LogOfExponent = GetExponent(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003245
3246 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003247 // exponent of 1.
3248 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003249
3250 // Different possible minimax approximations of significand in
3251 // floating-point for various degrees of accuracy over [1,2].
3252 if (LimitFloatPrecision <= 6) {
3253 // For floating-point precision of 6:
3254 //
3255 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3256 //
3257 // error 0.0049451742, which is more than 7 bits
Bill Wendling39150252008-09-09 20:39:27 +00003258 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003259 getF32Constant(DAG, 0xbeb08fe0));
Bill Wendling39150252008-09-09 20:39:27 +00003260 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003261 getF32Constant(DAG, 0x40019463));
Bill Wendling39150252008-09-09 20:39:27 +00003262 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3263 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003264 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003265
3266 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3267 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3268 // For floating-point precision of 12:
3269 //
3270 // Log2ofMantissa =
3271 // -2.51285454f +
3272 // (4.07009056f +
3273 // (-2.12067489f +
3274 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3275 //
3276 // error 0.0000876136000, which is better than 13 bits
Bill Wendling39150252008-09-09 20:39:27 +00003277 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003278 getF32Constant(DAG, 0xbda7262e));
Bill Wendling39150252008-09-09 20:39:27 +00003279 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003280 getF32Constant(DAG, 0x3f25280b));
Bill Wendling39150252008-09-09 20:39:27 +00003281 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3282 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003283 getF32Constant(DAG, 0x4007b923));
Bill Wendling39150252008-09-09 20:39:27 +00003284 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3285 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003286 getF32Constant(DAG, 0x40823e2f));
Bill Wendling39150252008-09-09 20:39:27 +00003287 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3288 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003289 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003290
3291 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3292 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3293 // For floating-point precision of 18:
3294 //
3295 // Log2ofMantissa =
3296 // -3.0400495f +
3297 // (6.1129976f +
3298 // (-5.3420409f +
3299 // (3.2865683f +
3300 // (-1.2669343f +
3301 // (0.27515199f -
3302 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3303 //
3304 // error 0.0000018516, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003305 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003306 getF32Constant(DAG, 0xbcd2769e));
Bill Wendling39150252008-09-09 20:39:27 +00003307 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003308 getF32Constant(DAG, 0x3e8ce0b9));
Bill Wendling39150252008-09-09 20:39:27 +00003309 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3310 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003311 getF32Constant(DAG, 0x3fa22ae7));
Bill Wendling39150252008-09-09 20:39:27 +00003312 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3313 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003314 getF32Constant(DAG, 0x40525723));
Bill Wendling39150252008-09-09 20:39:27 +00003315 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3316 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003317 getF32Constant(DAG, 0x40aaf200));
Bill Wendling39150252008-09-09 20:39:27 +00003318 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3319 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003320 getF32Constant(DAG, 0x40c39dad));
Bill Wendling3eb59402008-09-09 00:28:24 +00003321 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
Bill Wendling39150252008-09-09 20:39:27 +00003322 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003323 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003324
3325 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3326 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003327 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003328 // No special expansion.
Dale Johannesen853244f2008-09-05 23:49:37 +00003329 result = DAG.getNode(ISD::FLOG2,
3330 getValue(I.getOperand(1)).getValueType(),
3331 getValue(I.getOperand(1)));
3332 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003333
Dale Johannesen59e577f2008-09-05 18:38:42 +00003334 setValue(&I, result);
3335}
3336
Bill Wendling3eb59402008-09-09 00:28:24 +00003337/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3338/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003339void
3340SelectionDAGLowering::visitLog10(CallInst &I) {
3341 SDValue result;
Bill Wendling181b6272008-10-19 20:34:04 +00003342
Dale Johannesen852680a2008-09-05 21:27:19 +00003343 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003344 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3345 SDValue Op = getValue(I.getOperand(1));
3346 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3347
Bill Wendling39150252008-09-09 20:39:27 +00003348 // Scale the exponent by log10(2) [0.30102999f].
3349 SDValue Exp = GetExponent(DAG, Op1);
3350 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003351 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003352
3353 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003354 // exponent of 1.
3355 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003356
3357 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003358 // For floating-point precision of 6:
3359 //
3360 // Log10ofMantissa =
3361 // -0.50419619f +
3362 // (0.60948995f - 0.10380950f * x) * x;
3363 //
3364 // error 0.0014886165, which is 6 bits
Bill Wendling39150252008-09-09 20:39:27 +00003365 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003366 getF32Constant(DAG, 0xbdd49a13));
Bill Wendling39150252008-09-09 20:39:27 +00003367 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003368 getF32Constant(DAG, 0x3f1c0789));
Bill Wendling39150252008-09-09 20:39:27 +00003369 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3370 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003371 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003372
3373 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003374 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3375 // For floating-point precision of 12:
3376 //
3377 // Log10ofMantissa =
3378 // -0.64831180f +
3379 // (0.91751397f +
3380 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3381 //
3382 // error 0.00019228036, which is better than 12 bits
Bill Wendling39150252008-09-09 20:39:27 +00003383 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003384 getF32Constant(DAG, 0x3d431f31));
Bill Wendling39150252008-09-09 20:39:27 +00003385 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003386 getF32Constant(DAG, 0x3ea21fb2));
Bill Wendling39150252008-09-09 20:39:27 +00003387 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3388 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003389 getF32Constant(DAG, 0x3f6ae232));
Bill Wendling39150252008-09-09 20:39:27 +00003390 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3391 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003392 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003393
3394 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3395 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003396 // For floating-point precision of 18:
3397 //
3398 // Log10ofMantissa =
3399 // -0.84299375f +
3400 // (1.5327582f +
3401 // (-1.0688956f +
3402 // (0.49102474f +
3403 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3404 //
3405 // error 0.0000037995730, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003406 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003407 getF32Constant(DAG, 0x3c5d51ce));
Bill Wendling39150252008-09-09 20:39:27 +00003408 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003409 getF32Constant(DAG, 0x3e00685a));
Bill Wendling39150252008-09-09 20:39:27 +00003410 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3411 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003412 getF32Constant(DAG, 0x3efb6798));
Bill Wendling39150252008-09-09 20:39:27 +00003413 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3414 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003415 getF32Constant(DAG, 0x3f88d192));
Bill Wendling39150252008-09-09 20:39:27 +00003416 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3417 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003418 getF32Constant(DAG, 0x3fc4316c));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003419 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
Bill Wendling39150252008-09-09 20:39:27 +00003420 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003421 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003422
3423 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003424 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003425 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003426 // No special expansion.
Dale Johannesen852680a2008-09-05 21:27:19 +00003427 result = DAG.getNode(ISD::FLOG10,
3428 getValue(I.getOperand(1)).getValueType(),
3429 getValue(I.getOperand(1)));
3430 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003431
Dale Johannesen59e577f2008-09-05 18:38:42 +00003432 setValue(&I, result);
3433}
3434
Bill Wendlinge10c8142008-09-09 22:39:21 +00003435/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3436/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003437void
3438SelectionDAGLowering::visitExp2(CallInst &I) {
3439 SDValue result;
Bill Wendlinge10c8142008-09-09 22:39:21 +00003440
Dale Johannesen601d3c02008-09-05 01:48:15 +00003441 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003442 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3443 SDValue Op = getValue(I.getOperand(1));
3444
3445 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3446
3447 // FractionalPartOfX = x - (float)IntegerPartOfX;
3448 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3449 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3450
3451 // IntegerPartOfX <<= 23;
3452 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3453 DAG.getConstant(23, MVT::i32));
3454
3455 if (LimitFloatPrecision <= 6) {
3456 // For floating-point precision of 6:
3457 //
3458 // TwoToFractionalPartOfX =
3459 // 0.997535578f +
3460 // (0.735607626f + 0.252464424f * x) * x;
3461 //
3462 // error 0.0144103317, which is 6 bits
3463 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003464 getF32Constant(DAG, 0x3e814304));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003465 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003466 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003467 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3468 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003469 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003470 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3471 SDValue TwoToFractionalPartOfX =
3472 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3473
3474 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3475 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3476 // For floating-point precision of 12:
3477 //
3478 // TwoToFractionalPartOfX =
3479 // 0.999892986f +
3480 // (0.696457318f +
3481 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3482 //
3483 // error 0.000107046256, which is 13 to 14 bits
3484 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003485 getF32Constant(DAG, 0x3da235e3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003486 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003487 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003488 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3489 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003490 getF32Constant(DAG, 0x3f324b07));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003491 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3492 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003493 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003494 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3495 SDValue TwoToFractionalPartOfX =
3496 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3497
3498 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3499 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3500 // For floating-point precision of 18:
3501 //
3502 // TwoToFractionalPartOfX =
3503 // 0.999999982f +
3504 // (0.693148872f +
3505 // (0.240227044f +
3506 // (0.554906021e-1f +
3507 // (0.961591928e-2f +
3508 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3509 // error 2.47208000*10^(-7), which is better than 18 bits
3510 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003511 getF32Constant(DAG, 0x3924b03e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003512 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003513 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003514 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3515 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003516 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003517 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3518 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003519 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003520 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3521 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003522 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003523 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3524 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003525 getF32Constant(DAG, 0x3f317234));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003526 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3527 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003528 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003529 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3530 SDValue TwoToFractionalPartOfX =
3531 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3532
3533 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3534 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003535 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003536 // No special expansion.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003537 result = DAG.getNode(ISD::FEXP2,
3538 getValue(I.getOperand(1)).getValueType(),
3539 getValue(I.getOperand(1)));
3540 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003541
Dale Johannesen601d3c02008-09-05 01:48:15 +00003542 setValue(&I, result);
3543}
3544
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003545/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3546/// limited-precision mode with x == 10.0f.
3547void
3548SelectionDAGLowering::visitPow(CallInst &I) {
3549 SDValue result;
3550 Value *Val = I.getOperand(1);
3551 bool IsExp10 = false;
3552
3553 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003554 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003555 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3556 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3557 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3558 APFloat Ten(10.0f);
3559 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3560 }
3561 }
3562 }
3563
3564 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3565 SDValue Op = getValue(I.getOperand(2));
3566
3567 // Put the exponent in the right bit position for later addition to the
3568 // final result:
3569 //
3570 // #define LOG2OF10 3.3219281f
3571 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3572 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003573 getF32Constant(DAG, 0x40549a78));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003574 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3575
3576 // FractionalPartOfX = x - (float)IntegerPartOfX;
3577 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3578 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3579
3580 // IntegerPartOfX <<= 23;
3581 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3582 DAG.getConstant(23, MVT::i32));
3583
3584 if (LimitFloatPrecision <= 6) {
3585 // For floating-point precision of 6:
3586 //
3587 // twoToFractionalPartOfX =
3588 // 0.997535578f +
3589 // (0.735607626f + 0.252464424f * x) * x;
3590 //
3591 // error 0.0144103317, which is 6 bits
3592 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003593 getF32Constant(DAG, 0x3e814304));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003594 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003595 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003596 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3597 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003598 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003599 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3600 SDValue TwoToFractionalPartOfX =
3601 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3602
3603 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3604 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3605 // For floating-point precision of 12:
3606 //
3607 // TwoToFractionalPartOfX =
3608 // 0.999892986f +
3609 // (0.696457318f +
3610 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3611 //
3612 // error 0.000107046256, which is 13 to 14 bits
3613 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003614 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003615 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003616 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003617 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3618 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003619 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003620 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3621 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003622 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003623 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3624 SDValue TwoToFractionalPartOfX =
3625 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3626
3627 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3628 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3629 // For floating-point precision of 18:
3630 //
3631 // TwoToFractionalPartOfX =
3632 // 0.999999982f +
3633 // (0.693148872f +
3634 // (0.240227044f +
3635 // (0.554906021e-1f +
3636 // (0.961591928e-2f +
3637 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3638 // error 2.47208000*10^(-7), which is better than 18 bits
3639 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003640 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003641 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003642 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003643 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3644 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003645 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003646 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3647 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003648 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003649 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3650 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003651 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003652 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3653 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003654 getF32Constant(DAG, 0x3f317234));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003655 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3656 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003657 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003658 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3659 SDValue TwoToFractionalPartOfX =
3660 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3661
3662 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3663 }
3664 } else {
3665 // No special expansion.
3666 result = DAG.getNode(ISD::FPOW,
3667 getValue(I.getOperand(1)).getValueType(),
3668 getValue(I.getOperand(1)),
3669 getValue(I.getOperand(2)));
3670 }
3671
3672 setValue(&I, result);
3673}
3674
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003675/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3676/// we want to emit this as a call to a named external function, return the name
3677/// otherwise lower it and return null.
3678const char *
3679SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3680 switch (Intrinsic) {
3681 default:
3682 // By default, turn this into a target intrinsic node.
3683 visitTargetIntrinsic(I, Intrinsic);
3684 return 0;
3685 case Intrinsic::vastart: visitVAStart(I); return 0;
3686 case Intrinsic::vaend: visitVAEnd(I); return 0;
3687 case Intrinsic::vacopy: visitVACopy(I); return 0;
3688 case Intrinsic::returnaddress:
3689 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3690 getValue(I.getOperand(1))));
3691 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003692 case Intrinsic::frameaddress:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003693 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3694 getValue(I.getOperand(1))));
3695 return 0;
3696 case Intrinsic::setjmp:
3697 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3698 break;
3699 case Intrinsic::longjmp:
3700 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3701 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003702 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003703 SDValue Op1 = getValue(I.getOperand(1));
3704 SDValue Op2 = getValue(I.getOperand(2));
3705 SDValue Op3 = getValue(I.getOperand(3));
3706 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3707 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3708 I.getOperand(1), 0, I.getOperand(2), 0));
3709 return 0;
3710 }
Chris Lattner824b9582008-11-21 16:42:48 +00003711 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003712 SDValue Op1 = getValue(I.getOperand(1));
3713 SDValue Op2 = getValue(I.getOperand(2));
3714 SDValue Op3 = getValue(I.getOperand(3));
3715 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3716 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3717 I.getOperand(1), 0));
3718 return 0;
3719 }
Chris Lattner824b9582008-11-21 16:42:48 +00003720 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003721 SDValue Op1 = getValue(I.getOperand(1));
3722 SDValue Op2 = getValue(I.getOperand(2));
3723 SDValue Op3 = getValue(I.getOperand(3));
3724 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3725
3726 // If the source and destination are known to not be aliases, we can
3727 // lower memmove as memcpy.
3728 uint64_t Size = -1ULL;
3729 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003730 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003731 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3732 AliasAnalysis::NoAlias) {
3733 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3734 I.getOperand(1), 0, I.getOperand(2), 0));
3735 return 0;
3736 }
3737
3738 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3739 I.getOperand(1), 0, I.getOperand(2), 0));
3740 return 0;
3741 }
3742 case Intrinsic::dbg_stoppoint: {
3743 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3744 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3745 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3746 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3747 assert(DD && "Not a debug information descriptor");
3748 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3749 SPI.getLine(),
3750 SPI.getColumn(),
3751 cast<CompileUnitDesc>(DD)));
3752 }
3753
3754 return 0;
3755 }
3756 case Intrinsic::dbg_region_start: {
3757 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3758 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3759 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3760 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3761 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3762 }
3763
3764 return 0;
3765 }
3766 case Intrinsic::dbg_region_end: {
3767 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3768 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3769 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3770 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3771 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3772 }
3773
3774 return 0;
3775 }
3776 case Intrinsic::dbg_func_start: {
3777 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3778 if (!MMI) return 0;
3779 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3780 Value *SP = FSI.getSubprogram();
3781 if (SP && MMI->Verify(SP)) {
3782 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3783 // what (most?) gdb expects.
3784 DebugInfoDesc *DD = MMI->getDescFor(SP);
3785 assert(DD && "Not a debug information descriptor");
3786 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3787 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3788 unsigned SrcFile = MMI->RecordSource(CompileUnit);
Devang Patel20dd0462008-11-06 00:30:09 +00003789 // Record the source line but does not create a label for the normal
3790 // function start. It will be emitted at asm emission time. However,
3791 // create a label if this is a beginning of inlined function.
3792 unsigned LabelID = MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3793 if (MMI->getSourceLines().size() != 1)
3794 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003795 }
3796
3797 return 0;
3798 }
3799 case Intrinsic::dbg_declare: {
3800 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3801 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3802 Value *Variable = DI.getVariable();
3803 if (MMI && Variable && MMI->Verify(Variable))
3804 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3805 getValue(DI.getAddress()), getValue(Variable)));
3806 return 0;
3807 }
3808
3809 case Intrinsic::eh_exception: {
3810 if (!CurMBB->isLandingPad()) {
3811 // FIXME: Mark exception register as live in. Hack for PR1508.
3812 unsigned Reg = TLI.getExceptionAddressRegister();
3813 if (Reg) CurMBB->addLiveIn(Reg);
3814 }
3815 // Insert the EXCEPTIONADDR instruction.
3816 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3817 SDValue Ops[1];
3818 Ops[0] = DAG.getRoot();
3819 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3820 setValue(&I, Op);
3821 DAG.setRoot(Op.getValue(1));
3822 return 0;
3823 }
3824
3825 case Intrinsic::eh_selector_i32:
3826 case Intrinsic::eh_selector_i64: {
3827 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3828 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3829 MVT::i32 : MVT::i64);
3830
3831 if (MMI) {
3832 if (CurMBB->isLandingPad())
3833 AddCatchInfo(I, MMI, CurMBB);
3834 else {
3835#ifndef NDEBUG
3836 FuncInfo.CatchInfoLost.insert(&I);
3837#endif
3838 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3839 unsigned Reg = TLI.getExceptionSelectorRegister();
3840 if (Reg) CurMBB->addLiveIn(Reg);
3841 }
3842
3843 // Insert the EHSELECTION instruction.
3844 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3845 SDValue Ops[2];
3846 Ops[0] = getValue(I.getOperand(1));
3847 Ops[1] = getRoot();
3848 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3849 setValue(&I, Op);
3850 DAG.setRoot(Op.getValue(1));
3851 } else {
3852 setValue(&I, DAG.getConstant(0, VT));
3853 }
3854
3855 return 0;
3856 }
3857
3858 case Intrinsic::eh_typeid_for_i32:
3859 case Intrinsic::eh_typeid_for_i64: {
3860 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3861 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3862 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003863
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003864 if (MMI) {
3865 // Find the type id for the given typeinfo.
3866 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3867
3868 unsigned TypeID = MMI->getTypeIDFor(GV);
3869 setValue(&I, DAG.getConstant(TypeID, VT));
3870 } else {
3871 // Return something different to eh_selector.
3872 setValue(&I, DAG.getConstant(1, VT));
3873 }
3874
3875 return 0;
3876 }
3877
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003878 case Intrinsic::eh_return_i32:
3879 case Intrinsic::eh_return_i64:
3880 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003881 MMI->setCallsEHReturn(true);
3882 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3883 MVT::Other,
3884 getControlRoot(),
3885 getValue(I.getOperand(1)),
3886 getValue(I.getOperand(2))));
3887 } else {
3888 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3889 }
3890
3891 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003892 case Intrinsic::eh_unwind_init:
3893 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3894 MMI->setCallsUnwindInit(true);
3895 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003896
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003897 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003898
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003899 case Intrinsic::eh_dwarf_cfa: {
3900 MVT VT = getValue(I.getOperand(1)).getValueType();
3901 SDValue CfaArg;
3902 if (VT.bitsGT(TLI.getPointerTy()))
3903 CfaArg = DAG.getNode(ISD::TRUNCATE,
3904 TLI.getPointerTy(), getValue(I.getOperand(1)));
3905 else
3906 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3907 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003908
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003909 SDValue Offset = DAG.getNode(ISD::ADD,
3910 TLI.getPointerTy(),
3911 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3912 TLI.getPointerTy()),
3913 CfaArg);
3914 setValue(&I, DAG.getNode(ISD::ADD,
3915 TLI.getPointerTy(),
3916 DAG.getNode(ISD::FRAMEADDR,
3917 TLI.getPointerTy(),
3918 DAG.getConstant(0,
3919 TLI.getPointerTy())),
3920 Offset));
3921 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003922 }
3923
Mon P Wang77cdf302008-11-10 20:54:11 +00003924 case Intrinsic::convertff:
3925 case Intrinsic::convertfsi:
3926 case Intrinsic::convertfui:
3927 case Intrinsic::convertsif:
3928 case Intrinsic::convertuif:
3929 case Intrinsic::convertss:
3930 case Intrinsic::convertsu:
3931 case Intrinsic::convertus:
3932 case Intrinsic::convertuu: {
3933 ISD::CvtCode Code = ISD::CVT_INVALID;
3934 switch (Intrinsic) {
3935 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3936 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3937 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3938 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3939 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3940 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3941 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3942 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3943 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3944 }
3945 MVT DestVT = TLI.getValueType(I.getType());
3946 Value* Op1 = I.getOperand(1);
3947 setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
3948 DAG.getValueType(DestVT),
3949 DAG.getValueType(getValue(Op1).getValueType()),
3950 getValue(I.getOperand(2)),
3951 getValue(I.getOperand(3)),
3952 Code));
3953 return 0;
3954 }
3955
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003956 case Intrinsic::sqrt:
3957 setValue(&I, DAG.getNode(ISD::FSQRT,
3958 getValue(I.getOperand(1)).getValueType(),
3959 getValue(I.getOperand(1))));
3960 return 0;
3961 case Intrinsic::powi:
3962 setValue(&I, DAG.getNode(ISD::FPOWI,
3963 getValue(I.getOperand(1)).getValueType(),
3964 getValue(I.getOperand(1)),
3965 getValue(I.getOperand(2))));
3966 return 0;
3967 case Intrinsic::sin:
3968 setValue(&I, DAG.getNode(ISD::FSIN,
3969 getValue(I.getOperand(1)).getValueType(),
3970 getValue(I.getOperand(1))));
3971 return 0;
3972 case Intrinsic::cos:
3973 setValue(&I, DAG.getNode(ISD::FCOS,
3974 getValue(I.getOperand(1)).getValueType(),
3975 getValue(I.getOperand(1))));
3976 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003977 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003978 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003979 return 0;
3980 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003981 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003982 return 0;
3983 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003984 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003985 return 0;
3986 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003987 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003988 return 0;
3989 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003990 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003991 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003992 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003993 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003994 return 0;
3995 case Intrinsic::pcmarker: {
3996 SDValue Tmp = getValue(I.getOperand(1));
3997 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3998 return 0;
3999 }
4000 case Intrinsic::readcyclecounter: {
4001 SDValue Op = getRoot();
4002 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
4003 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4004 &Op, 1);
4005 setValue(&I, Tmp);
4006 DAG.setRoot(Tmp.getValue(1));
4007 return 0;
4008 }
4009 case Intrinsic::part_select: {
4010 // Currently not implemented: just abort
4011 assert(0 && "part_select intrinsic not implemented");
4012 abort();
4013 }
4014 case Intrinsic::part_set: {
4015 // Currently not implemented: just abort
4016 assert(0 && "part_set intrinsic not implemented");
4017 abort();
4018 }
4019 case Intrinsic::bswap:
4020 setValue(&I, DAG.getNode(ISD::BSWAP,
4021 getValue(I.getOperand(1)).getValueType(),
4022 getValue(I.getOperand(1))));
4023 return 0;
4024 case Intrinsic::cttz: {
4025 SDValue Arg = getValue(I.getOperand(1));
4026 MVT Ty = Arg.getValueType();
4027 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
4028 setValue(&I, result);
4029 return 0;
4030 }
4031 case Intrinsic::ctlz: {
4032 SDValue Arg = getValue(I.getOperand(1));
4033 MVT Ty = Arg.getValueType();
4034 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
4035 setValue(&I, result);
4036 return 0;
4037 }
4038 case Intrinsic::ctpop: {
4039 SDValue Arg = getValue(I.getOperand(1));
4040 MVT Ty = Arg.getValueType();
4041 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
4042 setValue(&I, result);
4043 return 0;
4044 }
4045 case Intrinsic::stacksave: {
4046 SDValue Op = getRoot();
4047 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
4048 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4049 setValue(&I, Tmp);
4050 DAG.setRoot(Tmp.getValue(1));
4051 return 0;
4052 }
4053 case Intrinsic::stackrestore: {
4054 SDValue Tmp = getValue(I.getOperand(1));
4055 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
4056 return 0;
4057 }
Bill Wendling57344502008-11-18 11:01:33 +00004058 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004059 // Emit code into the DAG to store the stack guard onto the stack.
4060 MachineFunction &MF = DAG.getMachineFunction();
4061 MachineFrameInfo *MFI = MF.getFrameInfo();
4062 MVT PtrTy = TLI.getPointerTy();
4063
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004064 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4065 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004066
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004067 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004068 MFI->setStackProtectorIndex(FI);
4069
4070 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4071
4072 // Store the stack protector onto the stack.
4073 SDValue Result = DAG.getStore(getRoot(), Src, FIN,
4074 PseudoSourceValue::getFixedStack(FI),
4075 0, true);
4076 setValue(&I, Result);
4077 DAG.setRoot(Result);
4078 return 0;
4079 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004080 case Intrinsic::var_annotation:
4081 // Discard annotate attributes
4082 return 0;
4083
4084 case Intrinsic::init_trampoline: {
4085 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4086
4087 SDValue Ops[6];
4088 Ops[0] = getRoot();
4089 Ops[1] = getValue(I.getOperand(1));
4090 Ops[2] = getValue(I.getOperand(2));
4091 Ops[3] = getValue(I.getOperand(3));
4092 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4093 Ops[5] = DAG.getSrcValue(F);
4094
4095 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
4096 DAG.getNodeValueTypes(TLI.getPointerTy(),
4097 MVT::Other), 2,
4098 Ops, 6);
4099
4100 setValue(&I, Tmp);
4101 DAG.setRoot(Tmp.getValue(1));
4102 return 0;
4103 }
4104
4105 case Intrinsic::gcroot:
4106 if (GFI) {
4107 Value *Alloca = I.getOperand(1);
4108 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4109
4110 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4111 GFI->addStackRoot(FI->getIndex(), TypeMap);
4112 }
4113 return 0;
4114
4115 case Intrinsic::gcread:
4116 case Intrinsic::gcwrite:
4117 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4118 return 0;
4119
4120 case Intrinsic::flt_rounds: {
4121 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
4122 return 0;
4123 }
4124
4125 case Intrinsic::trap: {
4126 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
4127 return 0;
4128 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004129
Bill Wendlingef375462008-11-21 02:38:44 +00004130 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004131 return implVisitAluOverflow(I, ISD::UADDO);
4132 case Intrinsic::sadd_with_overflow:
4133 return implVisitAluOverflow(I, ISD::SADDO);
4134 case Intrinsic::usub_with_overflow:
4135 return implVisitAluOverflow(I, ISD::USUBO);
4136 case Intrinsic::ssub_with_overflow:
4137 return implVisitAluOverflow(I, ISD::SSUBO);
4138 case Intrinsic::umul_with_overflow:
4139 return implVisitAluOverflow(I, ISD::UMULO);
4140 case Intrinsic::smul_with_overflow:
4141 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004142
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004143 case Intrinsic::prefetch: {
4144 SDValue Ops[4];
4145 Ops[0] = getRoot();
4146 Ops[1] = getValue(I.getOperand(1));
4147 Ops[2] = getValue(I.getOperand(2));
4148 Ops[3] = getValue(I.getOperand(3));
4149 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
4150 return 0;
4151 }
4152
4153 case Intrinsic::memory_barrier: {
4154 SDValue Ops[6];
4155 Ops[0] = getRoot();
4156 for (int x = 1; x < 6; ++x)
4157 Ops[x] = getValue(I.getOperand(x));
4158
4159 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
4160 return 0;
4161 }
4162 case Intrinsic::atomic_cmp_swap: {
4163 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004164 SDValue L =
4165 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP,
4166 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4167 Root,
4168 getValue(I.getOperand(1)),
4169 getValue(I.getOperand(2)),
4170 getValue(I.getOperand(3)),
4171 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004172 setValue(&I, L);
4173 DAG.setRoot(L.getValue(1));
4174 return 0;
4175 }
4176 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004177 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004178 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004179 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004180 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004181 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004182 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004183 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004184 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004185 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004186 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004187 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004188 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004189 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004190 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004191 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004192 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004193 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004194 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004195 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004196 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004197 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004198 }
4199}
4200
4201
4202void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4203 bool IsTailCall,
4204 MachineBasicBlock *LandingPad) {
4205 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4206 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4207 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4208 unsigned BeginLabel = 0, EndLabel = 0;
4209
4210 TargetLowering::ArgListTy Args;
4211 TargetLowering::ArgListEntry Entry;
4212 Args.reserve(CS.arg_size());
4213 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4214 i != e; ++i) {
4215 SDValue ArgNode = getValue(*i);
4216 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4217
4218 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004219 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4220 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4221 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4222 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4223 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4224 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004225 Entry.Alignment = CS.getParamAlignment(attrInd);
4226 Args.push_back(Entry);
4227 }
4228
4229 if (LandingPad && MMI) {
4230 // Insert a label before the invoke call to mark the try range. This can be
4231 // used to detect deletion of the invoke via the MachineModuleInfo.
4232 BeginLabel = MMI->NextLabelID();
4233 // Both PendingLoads and PendingExports must be flushed here;
4234 // this call might not return.
4235 (void)getRoot();
4236 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4237 }
4238
4239 std::pair<SDValue,SDValue> Result =
4240 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004241 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004242 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4243 CS.paramHasAttr(0, Attribute::InReg),
4244 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004245 IsTailCall && PerformTailCallOpt,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004246 Callee, Args, DAG);
4247 if (CS.getType() != Type::VoidTy)
4248 setValue(CS.getInstruction(), Result.first);
4249 DAG.setRoot(Result.second);
4250
4251 if (LandingPad && MMI) {
4252 // Insert a label at the end of the invoke call to mark the try range. This
4253 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4254 EndLabel = MMI->NextLabelID();
4255 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4256
4257 // Inform MachineModuleInfo of range.
4258 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4259 }
4260}
4261
4262
4263void SelectionDAGLowering::visitCall(CallInst &I) {
4264 const char *RenameFn = 0;
4265 if (Function *F = I.getCalledFunction()) {
4266 if (F->isDeclaration()) {
4267 if (unsigned IID = F->getIntrinsicID()) {
4268 RenameFn = visitIntrinsicCall(I, IID);
4269 if (!RenameFn)
4270 return;
4271 }
4272 }
4273
4274 // Check for well-known libc/libm calls. If the function is internal, it
4275 // can't be a library call.
4276 unsigned NameLen = F->getNameLen();
4277 if (!F->hasInternalLinkage() && NameLen) {
4278 const char *NameStr = F->getNameStart();
4279 if (NameStr[0] == 'c' &&
4280 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4281 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4282 if (I.getNumOperands() == 3 && // Basic sanity checks.
4283 I.getOperand(1)->getType()->isFloatingPoint() &&
4284 I.getType() == I.getOperand(1)->getType() &&
4285 I.getType() == I.getOperand(2)->getType()) {
4286 SDValue LHS = getValue(I.getOperand(1));
4287 SDValue RHS = getValue(I.getOperand(2));
4288 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4289 LHS, RHS));
4290 return;
4291 }
4292 } else if (NameStr[0] == 'f' &&
4293 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4294 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4295 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4296 if (I.getNumOperands() == 2 && // Basic sanity checks.
4297 I.getOperand(1)->getType()->isFloatingPoint() &&
4298 I.getType() == I.getOperand(1)->getType()) {
4299 SDValue Tmp = getValue(I.getOperand(1));
4300 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4301 return;
4302 }
4303 } else if (NameStr[0] == 's' &&
4304 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4305 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4306 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4307 if (I.getNumOperands() == 2 && // Basic sanity checks.
4308 I.getOperand(1)->getType()->isFloatingPoint() &&
4309 I.getType() == I.getOperand(1)->getType()) {
4310 SDValue Tmp = getValue(I.getOperand(1));
4311 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4312 return;
4313 }
4314 } else if (NameStr[0] == 'c' &&
4315 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4316 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4317 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4318 if (I.getNumOperands() == 2 && // Basic sanity checks.
4319 I.getOperand(1)->getType()->isFloatingPoint() &&
4320 I.getType() == I.getOperand(1)->getType()) {
4321 SDValue Tmp = getValue(I.getOperand(1));
4322 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4323 return;
4324 }
4325 }
4326 }
4327 } else if (isa<InlineAsm>(I.getOperand(0))) {
4328 visitInlineAsm(&I);
4329 return;
4330 }
4331
4332 SDValue Callee;
4333 if (!RenameFn)
4334 Callee = getValue(I.getOperand(0));
4335 else
Bill Wendling056292f2008-09-16 21:48:12 +00004336 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004337
4338 LowerCallTo(&I, Callee, I.isTailCall());
4339}
4340
4341
4342/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4343/// this value and returns the result as a ValueVT value. This uses
4344/// Chain/Flag as the input and updates them for the output Chain/Flag.
4345/// If the Flag pointer is NULL, no flag is used.
4346SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4347 SDValue &Chain,
4348 SDValue *Flag) const {
4349 // Assemble the legal parts into the final values.
4350 SmallVector<SDValue, 4> Values(ValueVTs.size());
4351 SmallVector<SDValue, 8> Parts;
4352 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4353 // Copy the legal parts from the registers.
4354 MVT ValueVT = ValueVTs[Value];
4355 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4356 MVT RegisterVT = RegVTs[Value];
4357
4358 Parts.resize(NumRegs);
4359 for (unsigned i = 0; i != NumRegs; ++i) {
4360 SDValue P;
4361 if (Flag == 0)
4362 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4363 else {
4364 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4365 *Flag = P.getValue(2);
4366 }
4367 Chain = P.getValue(1);
4368
4369 // If the source register was virtual and if we know something about it,
4370 // add an assert node.
4371 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4372 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4373 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4374 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4375 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4376 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4377
4378 unsigned RegSize = RegisterVT.getSizeInBits();
4379 unsigned NumSignBits = LOI.NumSignBits;
4380 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4381
4382 // FIXME: We capture more information than the dag can represent. For
4383 // now, just use the tightest assertzext/assertsext possible.
4384 bool isSExt = true;
4385 MVT FromVT(MVT::Other);
4386 if (NumSignBits == RegSize)
4387 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4388 else if (NumZeroBits >= RegSize-1)
4389 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4390 else if (NumSignBits > RegSize-8)
4391 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4392 else if (NumZeroBits >= RegSize-9)
4393 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4394 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004395 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004396 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004397 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004398 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004399 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004400 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004401 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004402
4403 if (FromVT != MVT::Other) {
4404 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4405 RegisterVT, P, DAG.getValueType(FromVT));
4406
4407 }
4408 }
4409 }
4410
4411 Parts[i] = P;
4412 }
4413
4414 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4415 ValueVT);
4416 Part += NumRegs;
4417 Parts.clear();
4418 }
4419
Duncan Sandsaaffa052008-12-01 11:41:29 +00004420 return DAG.getNode(ISD::MERGE_VALUES,
4421 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4422 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004423}
4424
4425/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4426/// specified value into the registers specified by this object. This uses
4427/// Chain/Flag as the input and updates them for the output Chain/Flag.
4428/// If the Flag pointer is NULL, no flag is used.
4429void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4430 SDValue &Chain, SDValue *Flag) const {
4431 // Get the list of the values's legal parts.
4432 unsigned NumRegs = Regs.size();
4433 SmallVector<SDValue, 8> Parts(NumRegs);
4434 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4435 MVT ValueVT = ValueVTs[Value];
4436 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4437 MVT RegisterVT = RegVTs[Value];
4438
4439 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4440 &Parts[Part], NumParts, RegisterVT);
4441 Part += NumParts;
4442 }
4443
4444 // Copy the parts into the registers.
4445 SmallVector<SDValue, 8> Chains(NumRegs);
4446 for (unsigned i = 0; i != NumRegs; ++i) {
4447 SDValue Part;
4448 if (Flag == 0)
4449 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4450 else {
4451 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4452 *Flag = Part.getValue(1);
4453 }
4454 Chains[i] = Part.getValue(0);
4455 }
4456
4457 if (NumRegs == 1 || Flag)
4458 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4459 // flagged to it. That is the CopyToReg nodes and the user are considered
4460 // a single scheduling unit. If we create a TokenFactor and return it as
4461 // chain, then the TokenFactor is both a predecessor (operand) of the
4462 // user as well as a successor (the TF operands are flagged to the user).
4463 // c1, f1 = CopyToReg
4464 // c2, f2 = CopyToReg
4465 // c3 = TokenFactor c1, c2
4466 // ...
4467 // = op c3, ..., f2
4468 Chain = Chains[NumRegs-1];
4469 else
4470 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4471}
4472
4473/// AddInlineAsmOperands - Add this value to the specified inlineasm node
4474/// operand list. This adds the code marker and includes the number of
4475/// values added into it.
4476void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4477 std::vector<SDValue> &Ops) const {
4478 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4479 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4480 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4481 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4482 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004483 for (unsigned i = 0; i != NumRegs; ++i) {
4484 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004485 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004486 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004487 }
4488}
4489
4490/// isAllocatableRegister - If the specified register is safe to allocate,
4491/// i.e. it isn't a stack pointer or some other special register, return the
4492/// register class for the register. Otherwise, return null.
4493static const TargetRegisterClass *
4494isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4495 const TargetLowering &TLI,
4496 const TargetRegisterInfo *TRI) {
4497 MVT FoundVT = MVT::Other;
4498 const TargetRegisterClass *FoundRC = 0;
4499 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4500 E = TRI->regclass_end(); RCI != E; ++RCI) {
4501 MVT ThisVT = MVT::Other;
4502
4503 const TargetRegisterClass *RC = *RCI;
4504 // If none of the the value types for this register class are valid, we
4505 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4506 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4507 I != E; ++I) {
4508 if (TLI.isTypeLegal(*I)) {
4509 // If we have already found this register in a different register class,
4510 // choose the one with the largest VT specified. For example, on
4511 // PowerPC, we favor f64 register classes over f32.
4512 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4513 ThisVT = *I;
4514 break;
4515 }
4516 }
4517 }
4518
4519 if (ThisVT == MVT::Other) continue;
4520
4521 // NOTE: This isn't ideal. In particular, this might allocate the
4522 // frame pointer in functions that need it (due to them not being taken
4523 // out of allocation, because a variable sized allocation hasn't been seen
4524 // yet). This is a slight code pessimization, but should still work.
4525 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4526 E = RC->allocation_order_end(MF); I != E; ++I)
4527 if (*I == Reg) {
4528 // We found a matching register class. Keep looking at others in case
4529 // we find one with larger registers that this physreg is also in.
4530 FoundRC = RC;
4531 FoundVT = ThisVT;
4532 break;
4533 }
4534 }
4535 return FoundRC;
4536}
4537
4538
4539namespace llvm {
4540/// AsmOperandInfo - This contains information for each constraint that we are
4541/// lowering.
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004542struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4543 public TargetLowering::AsmOperandInfo {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004544 /// CallOperand - If this is the result output operand or a clobber
4545 /// this is null, otherwise it is the incoming operand to the CallInst.
4546 /// This gets modified as the asm is processed.
4547 SDValue CallOperand;
4548
4549 /// AssignedRegs - If this is a register or register class operand, this
4550 /// contains the set of register corresponding to the operand.
4551 RegsForValue AssignedRegs;
4552
4553 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4554 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4555 }
4556
4557 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4558 /// busy in OutputRegs/InputRegs.
4559 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4560 std::set<unsigned> &OutputRegs,
4561 std::set<unsigned> &InputRegs,
4562 const TargetRegisterInfo &TRI) const {
4563 if (isOutReg) {
4564 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4565 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4566 }
4567 if (isInReg) {
4568 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4569 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4570 }
4571 }
Chris Lattner81249c92008-10-17 17:05:25 +00004572
4573 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4574 /// corresponds to. If there is no Value* for this operand, it returns
4575 /// MVT::Other.
4576 MVT getCallOperandValMVT(const TargetLowering &TLI,
4577 const TargetData *TD) const {
4578 if (CallOperandVal == 0) return MVT::Other;
4579
4580 if (isa<BasicBlock>(CallOperandVal))
4581 return TLI.getPointerTy();
4582
4583 const llvm::Type *OpTy = CallOperandVal->getType();
4584
4585 // If this is an indirect operand, the operand is a pointer to the
4586 // accessed type.
4587 if (isIndirect)
4588 OpTy = cast<PointerType>(OpTy)->getElementType();
4589
4590 // If OpTy is not a single value, it may be a struct/union that we
4591 // can tile with integers.
4592 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4593 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4594 switch (BitSize) {
4595 default: break;
4596 case 1:
4597 case 8:
4598 case 16:
4599 case 32:
4600 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004601 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004602 OpTy = IntegerType::get(BitSize);
4603 break;
4604 }
4605 }
4606
4607 return TLI.getValueType(OpTy, true);
4608 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004609
4610private:
4611 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4612 /// specified set.
4613 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4614 const TargetRegisterInfo &TRI) {
4615 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4616 Regs.insert(Reg);
4617 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4618 for (; *Aliases; ++Aliases)
4619 Regs.insert(*Aliases);
4620 }
4621};
4622} // end llvm namespace.
4623
4624
4625/// GetRegistersForValue - Assign registers (virtual or physical) for the
4626/// specified operand. We prefer to assign virtual registers, to allow the
4627/// register allocator handle the assignment process. However, if the asm uses
4628/// features that we can't model on machineinstrs, we have SDISel do the
4629/// allocation. This produces generally horrible, but correct, code.
4630///
4631/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004632/// Input and OutputRegs are the set of already allocated physical registers.
4633///
4634void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004635GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004636 std::set<unsigned> &OutputRegs,
4637 std::set<unsigned> &InputRegs) {
4638 // Compute whether this value requires an input register, an output register,
4639 // or both.
4640 bool isOutReg = false;
4641 bool isInReg = false;
4642 switch (OpInfo.Type) {
4643 case InlineAsm::isOutput:
4644 isOutReg = true;
4645
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004646 // If there is an input constraint that matches this, we need to reserve
4647 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004648 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004649 break;
4650 case InlineAsm::isInput:
4651 isInReg = true;
4652 isOutReg = false;
4653 break;
4654 case InlineAsm::isClobber:
4655 isOutReg = true;
4656 isInReg = true;
4657 break;
4658 }
4659
4660
4661 MachineFunction &MF = DAG.getMachineFunction();
4662 SmallVector<unsigned, 4> Regs;
4663
4664 // If this is a constraint for a single physreg, or a constraint for a
4665 // register class, find it.
4666 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4667 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4668 OpInfo.ConstraintVT);
4669
4670 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004671 if (OpInfo.ConstraintVT != MVT::Other) {
4672 // If this is a FP input in an integer register (or visa versa) insert a bit
4673 // cast of the input value. More generally, handle any case where the input
4674 // value disagrees with the register class we plan to stick this in.
4675 if (OpInfo.Type == InlineAsm::isInput &&
4676 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4677 // Try to convert to the first MVT that the reg class contains. If the
4678 // types are identical size, use a bitcast to convert (e.g. two differing
4679 // vector types).
4680 MVT RegVT = *PhysReg.second->vt_begin();
4681 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4682 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4683 OpInfo.CallOperand);
4684 OpInfo.ConstraintVT = RegVT;
4685 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4686 // If the input is a FP value and we want it in FP registers, do a
4687 // bitcast to the corresponding integer type. This turns an f64 value
4688 // into i64, which can be passed with two i32 values on a 32-bit
4689 // machine.
4690 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4691 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4692 OpInfo.CallOperand);
4693 OpInfo.ConstraintVT = RegVT;
4694 }
4695 }
4696
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004697 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004698 }
4699
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004700 MVT RegVT;
4701 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004702
4703 // If this is a constraint for a specific physical register, like {r17},
4704 // assign it now.
4705 if (PhysReg.first) {
4706 if (OpInfo.ConstraintVT == MVT::Other)
4707 ValueVT = *PhysReg.second->vt_begin();
4708
4709 // Get the actual register value type. This is important, because the user
4710 // may have asked for (e.g.) the AX register in i32 type. We need to
4711 // remember that AX is actually i16 to get the right extension.
4712 RegVT = *PhysReg.second->vt_begin();
4713
4714 // This is a explicit reference to a physical register.
4715 Regs.push_back(PhysReg.first);
4716
4717 // If this is an expanded reference, add the rest of the regs to Regs.
4718 if (NumRegs != 1) {
4719 TargetRegisterClass::iterator I = PhysReg.second->begin();
4720 for (; *I != PhysReg.first; ++I)
4721 assert(I != PhysReg.second->end() && "Didn't find reg!");
4722
4723 // Already added the first reg.
4724 --NumRegs; ++I;
4725 for (; NumRegs; --NumRegs, ++I) {
4726 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4727 Regs.push_back(*I);
4728 }
4729 }
4730 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4731 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4732 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4733 return;
4734 }
4735
4736 // Otherwise, if this was a reference to an LLVM register class, create vregs
4737 // for this reference.
4738 std::vector<unsigned> RegClassRegs;
4739 const TargetRegisterClass *RC = PhysReg.second;
4740 if (RC) {
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004741 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner58f15c42008-10-17 16:21:11 +00004742 // the constraint, so we have to pick a register to pin the input/output to.
4743 // If it isn't a matched constraint, go ahead and create vreg and let the
4744 // regalloc do its thing.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004745 if (!OpInfo.hasMatchingInput()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004746 RegVT = *PhysReg.second->vt_begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004747 if (OpInfo.ConstraintVT == MVT::Other)
4748 ValueVT = RegVT;
4749
4750 // Create the appropriate number of virtual registers.
4751 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4752 for (; NumRegs; --NumRegs)
4753 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4754
4755 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4756 return;
4757 }
4758
4759 // Otherwise, we can't allocate it. Let the code below figure out how to
4760 // maintain these constraints.
4761 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4762
4763 } else {
4764 // This is a reference to a register class that doesn't directly correspond
4765 // to an LLVM register class. Allocate NumRegs consecutive, available,
4766 // registers from the class.
4767 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4768 OpInfo.ConstraintVT);
4769 }
4770
4771 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4772 unsigned NumAllocated = 0;
4773 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4774 unsigned Reg = RegClassRegs[i];
4775 // See if this register is available.
4776 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4777 (isInReg && InputRegs.count(Reg))) { // Already used.
4778 // Make sure we find consecutive registers.
4779 NumAllocated = 0;
4780 continue;
4781 }
4782
4783 // Check to see if this register is allocatable (i.e. don't give out the
4784 // stack pointer).
4785 if (RC == 0) {
4786 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4787 if (!RC) { // Couldn't allocate this register.
4788 // Reset NumAllocated to make sure we return consecutive registers.
4789 NumAllocated = 0;
4790 continue;
4791 }
4792 }
4793
4794 // Okay, this register is good, we can use it.
4795 ++NumAllocated;
4796
4797 // If we allocated enough consecutive registers, succeed.
4798 if (NumAllocated == NumRegs) {
4799 unsigned RegStart = (i-NumAllocated)+1;
4800 unsigned RegEnd = i+1;
4801 // Mark all of the allocated registers used.
4802 for (unsigned i = RegStart; i != RegEnd; ++i)
4803 Regs.push_back(RegClassRegs[i]);
4804
4805 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4806 OpInfo.ConstraintVT);
4807 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4808 return;
4809 }
4810 }
4811
4812 // Otherwise, we couldn't allocate enough registers for this.
4813}
4814
Evan Chengda43bcf2008-09-24 00:05:32 +00004815/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4816/// processed uses a memory 'm' constraint.
4817static bool
4818hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4819 TargetLowering &TLI) {
4820 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4821 InlineAsm::ConstraintInfo &CI = CInfos[i];
4822 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4823 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4824 if (CType == TargetLowering::C_Memory)
4825 return true;
4826 }
4827 }
4828
4829 return false;
4830}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004831
4832/// visitInlineAsm - Handle a call to an InlineAsm object.
4833///
4834void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4835 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4836
4837 /// ConstraintOperands - Information about all of the constraints.
4838 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4839
4840 SDValue Chain = getRoot();
4841 SDValue Flag;
4842
4843 std::set<unsigned> OutputRegs, InputRegs;
4844
4845 // Do a prepass over the constraints, canonicalizing them, and building up the
4846 // ConstraintOperands list.
4847 std::vector<InlineAsm::ConstraintInfo>
4848 ConstraintInfos = IA->ParseConstraints();
4849
Evan Chengda43bcf2008-09-24 00:05:32 +00004850 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004851
4852 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4853 unsigned ResNo = 0; // ResNo - The result number of the next output.
4854 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4855 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4856 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4857
4858 MVT OpVT = MVT::Other;
4859
4860 // Compute the value type for each operand.
4861 switch (OpInfo.Type) {
4862 case InlineAsm::isOutput:
4863 // Indirect outputs just consume an argument.
4864 if (OpInfo.isIndirect) {
4865 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4866 break;
4867 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004868
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004869 // The return value of the call is this value. As such, there is no
4870 // corresponding argument.
4871 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4872 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4873 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4874 } else {
4875 assert(ResNo == 0 && "Asm only has one result!");
4876 OpVT = TLI.getValueType(CS.getType());
4877 }
4878 ++ResNo;
4879 break;
4880 case InlineAsm::isInput:
4881 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4882 break;
4883 case InlineAsm::isClobber:
4884 // Nothing to do.
4885 break;
4886 }
4887
4888 // If this is an input or an indirect output, process the call argument.
4889 // BasicBlocks are labels, currently appearing only in asm's.
4890 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00004891 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004892 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00004893 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004894 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004895 }
Chris Lattner81249c92008-10-17 17:05:25 +00004896
4897 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004898 }
4899
4900 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004901 }
4902
4903 // Second pass over the constraints: compute which constraint option to use
4904 // and assign registers to constraints that want a specific physreg.
4905 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4906 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4907
4908 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00004909 // matching input. If their types mismatch, e.g. one is an integer, the
4910 // other is floating point, or their sizes are different, flag it as an
4911 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004912 if (OpInfo.hasMatchingInput()) {
4913 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4914 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00004915 if ((OpInfo.ConstraintVT.isInteger() !=
4916 Input.ConstraintVT.isInteger()) ||
4917 (OpInfo.ConstraintVT.getSizeInBits() !=
4918 Input.ConstraintVT.getSizeInBits())) {
4919 cerr << "Unsupported asm: input constraint with a matching output "
4920 << "constraint of incompatible type!\n";
4921 exit(1);
4922 }
4923 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004924 }
4925 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004926
4927 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00004928 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004929
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004930 // If this is a memory input, and if the operand is not indirect, do what we
4931 // need to to provide an address for the memory input.
4932 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4933 !OpInfo.isIndirect) {
4934 assert(OpInfo.Type == InlineAsm::isInput &&
4935 "Can only indirectify direct input operands!");
4936
4937 // Memory operands really want the address of the value. If we don't have
4938 // an indirect input, put it in the constpool if we can, otherwise spill
4939 // it to a stack slot.
4940
4941 // If the operand is a float, integer, or vector constant, spill to a
4942 // constant pool entry to get its address.
4943 Value *OpVal = OpInfo.CallOperandVal;
4944 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4945 isa<ConstantVector>(OpVal)) {
4946 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4947 TLI.getPointerTy());
4948 } else {
4949 // Otherwise, create a stack slot and emit a store to it before the
4950 // asm.
4951 const Type *Ty = OpVal->getType();
4952 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4953 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4954 MachineFunction &MF = DAG.getMachineFunction();
4955 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4956 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4957 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4958 OpInfo.CallOperand = StackSlot;
4959 }
4960
4961 // There is no longer a Value* corresponding to this operand.
4962 OpInfo.CallOperandVal = 0;
4963 // It is now an indirect operand.
4964 OpInfo.isIndirect = true;
4965 }
4966
4967 // If this constraint is for a specific register, allocate it before
4968 // anything else.
4969 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004970 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004971 }
4972 ConstraintInfos.clear();
4973
4974
4975 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00004976 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004977 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4978 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4979
4980 // C_Register operands have already been allocated, Other/Memory don't need
4981 // to be.
4982 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004983 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004984 }
4985
4986 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4987 std::vector<SDValue> AsmNodeOperands;
4988 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4989 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00004990 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004991
4992
4993 // Loop over all of the inputs, copying the operand values into the
4994 // appropriate registers and processing the output regs.
4995 RegsForValue RetValRegs;
4996
4997 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4998 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4999
5000 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5001 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5002
5003 switch (OpInfo.Type) {
5004 case InlineAsm::isOutput: {
5005 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5006 OpInfo.ConstraintType != TargetLowering::C_Register) {
5007 // Memory output, or 'other' output (e.g. 'X' constraint).
5008 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5009
5010 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005011 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5012 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005013 TLI.getPointerTy()));
5014 AsmNodeOperands.push_back(OpInfo.CallOperand);
5015 break;
5016 }
5017
5018 // Otherwise, this is a register or register class output.
5019
5020 // Copy the output from the appropriate register. Find a register that
5021 // we can use.
5022 if (OpInfo.AssignedRegs.Regs.empty()) {
5023 cerr << "Couldn't allocate output reg for constraint '"
5024 << OpInfo.ConstraintCode << "'!\n";
5025 exit(1);
5026 }
5027
5028 // If this is an indirect operand, store through the pointer after the
5029 // asm.
5030 if (OpInfo.isIndirect) {
5031 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5032 OpInfo.CallOperandVal));
5033 } else {
5034 // This is the result value of the call.
5035 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5036 // Concatenate this output onto the outputs list.
5037 RetValRegs.append(OpInfo.AssignedRegs);
5038 }
5039
5040 // Add information to the INLINEASM node to know that this register is
5041 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005042 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5043 6 /* EARLYCLOBBER REGDEF */ :
5044 2 /* REGDEF */ ,
5045 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005046 break;
5047 }
5048 case InlineAsm::isInput: {
5049 SDValue InOperandVal = OpInfo.CallOperand;
5050
Chris Lattner6bdcda32008-10-17 16:47:46 +00005051 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005052 // If this is required to match an output register we have already set,
5053 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005054 unsigned OperandNo = OpInfo.getMatchedOperand();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005055
5056 // Scan until we find the definition we already emitted of this operand.
5057 // When we find it, create a RegsForValue operand.
5058 unsigned CurOp = 2; // The first operand.
5059 for (; OperandNo; --OperandNo) {
5060 // Advance to the next operand.
5061 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005062 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005063 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen913d3df2008-09-12 17:49:03 +00005064 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen86b49f82008-09-24 01:07:17 +00005065 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005066 "Skipped past definitions?");
5067 CurOp += (NumOps>>3)+1;
5068 }
5069
5070 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005071 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dale Johannesen913d3df2008-09-12 17:49:03 +00005072 if ((NumOps & 7) == 2 /*REGDEF*/
5073 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005074 // Add NumOps>>3 registers to MatchedRegs.
5075 RegsForValue MatchedRegs;
5076 MatchedRegs.TLI = &TLI;
5077 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5078 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5079 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5080 unsigned Reg =
5081 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5082 MatchedRegs.Regs.push_back(Reg);
5083 }
5084
5085 // Use the produced MatchedRegs object to
5086 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Dale Johannesen86b49f82008-09-24 01:07:17 +00005087 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005088 break;
5089 } else {
Dale Johannesen86b49f82008-09-24 01:07:17 +00005090 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005091 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
5092 // Add information to the INLINEASM node to know about this input.
Dale Johannesen91aac102008-09-17 21:13:11 +00005093 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005094 TLI.getPointerTy()));
5095 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5096 break;
5097 }
5098 }
5099
5100 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5101 assert(!OpInfo.isIndirect &&
5102 "Don't know how to handle indirect other inputs yet!");
5103
5104 std::vector<SDValue> Ops;
5105 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005106 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005107 if (Ops.empty()) {
5108 cerr << "Invalid operand for inline asm constraint '"
5109 << OpInfo.ConstraintCode << "'!\n";
5110 exit(1);
5111 }
5112
5113 // Add information to the INLINEASM node to know about this input.
5114 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5115 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5116 TLI.getPointerTy()));
5117 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5118 break;
5119 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5120 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5121 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5122 "Memory operands expect pointer values");
5123
5124 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005125 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5126 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005127 TLI.getPointerTy()));
5128 AsmNodeOperands.push_back(InOperandVal);
5129 break;
5130 }
5131
5132 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5133 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5134 "Unknown constraint type!");
5135 assert(!OpInfo.isIndirect &&
5136 "Don't know how to handle indirect register inputs yet!");
5137
5138 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005139 if (OpInfo.AssignedRegs.Regs.empty()) {
5140 cerr << "Couldn't allocate output reg for constraint '"
5141 << OpInfo.ConstraintCode << "'!\n";
5142 exit(1);
5143 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005144
5145 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5146
Dale Johannesen86b49f82008-09-24 01:07:17 +00005147 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5148 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005149 break;
5150 }
5151 case InlineAsm::isClobber: {
5152 // Add the clobbered value to the operand list, so that the register
5153 // allocator is aware that the physreg got clobbered.
5154 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005155 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5156 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005157 break;
5158 }
5159 }
5160 }
5161
5162 // Finish up input operands.
5163 AsmNodeOperands[0] = Chain;
5164 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5165
5166 Chain = DAG.getNode(ISD::INLINEASM,
5167 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5168 &AsmNodeOperands[0], AsmNodeOperands.size());
5169 Flag = Chain.getValue(1);
5170
5171 // If this asm returns a register value, copy the result from that register
5172 // and set it as the value of the call.
5173 if (!RetValRegs.Regs.empty()) {
5174 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005175
5176 // FIXME: Why don't we do this for inline asms with MRVs?
5177 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5178 MVT ResultType = TLI.getValueType(CS.getType());
5179
5180 // If any of the results of the inline asm is a vector, it may have the
5181 // wrong width/num elts. This can happen for register classes that can
5182 // contain multiple different value types. The preg or vreg allocated may
5183 // not have the same VT as was expected. Convert it to the right type
5184 // with bit_convert.
5185 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5186 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005187
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005188 } else if (ResultType != Val.getValueType() &&
5189 ResultType.isInteger() && Val.getValueType().isInteger()) {
5190 // If a result value was tied to an input value, the computed result may
5191 // have a wider width than the expected result. Extract the relevant
5192 // portion.
5193 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005194 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005195
5196 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005197 }
Dan Gohman95915732008-10-18 01:03:45 +00005198
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005199 setValue(CS.getInstruction(), Val);
5200 }
5201
5202 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5203
5204 // Process indirect outputs, first output all of the flagged copies out of
5205 // physregs.
5206 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5207 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5208 Value *Ptr = IndirectStoresToEmit[i].second;
5209 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5210 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5211 }
5212
5213 // Emit the non-flagged stores from the physregs.
5214 SmallVector<SDValue, 8> OutChains;
5215 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5216 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5217 getValue(StoresToEmit[i].second),
5218 StoresToEmit[i].second, 0));
5219 if (!OutChains.empty())
5220 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5221 &OutChains[0], OutChains.size());
5222 DAG.setRoot(Chain);
5223}
5224
5225
5226void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5227 SDValue Src = getValue(I.getOperand(0));
5228
5229 MVT IntPtr = TLI.getPointerTy();
5230
5231 if (IntPtr.bitsLT(Src.getValueType()))
5232 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5233 else if (IntPtr.bitsGT(Src.getValueType()))
5234 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5235
5236 // Scale the source by the type size.
5237 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5238 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5239 Src, DAG.getIntPtrConstant(ElementSize));
5240
5241 TargetLowering::ArgListTy Args;
5242 TargetLowering::ArgListEntry Entry;
5243 Entry.Node = Src;
5244 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5245 Args.push_back(Entry);
5246
5247 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005248 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5249 CallingConv::C, PerformTailCallOpt,
5250 DAG.getExternalSymbol("malloc", IntPtr),
Dan Gohman1937e2f2008-09-16 01:42:28 +00005251 Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005252 setValue(&I, Result.first); // Pointers always fit in registers
5253 DAG.setRoot(Result.second);
5254}
5255
5256void SelectionDAGLowering::visitFree(FreeInst &I) {
5257 TargetLowering::ArgListTy Args;
5258 TargetLowering::ArgListEntry Entry;
5259 Entry.Node = getValue(I.getOperand(0));
5260 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5261 Args.push_back(Entry);
5262 MVT IntPtr = TLI.getPointerTy();
5263 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005264 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005265 CallingConv::C, PerformTailCallOpt,
Bill Wendling056292f2008-09-16 21:48:12 +00005266 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005267 DAG.setRoot(Result.second);
5268}
5269
5270void SelectionDAGLowering::visitVAStart(CallInst &I) {
5271 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5272 getValue(I.getOperand(1)),
5273 DAG.getSrcValue(I.getOperand(1))));
5274}
5275
5276void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5277 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5278 getValue(I.getOperand(0)),
5279 DAG.getSrcValue(I.getOperand(0)));
5280 setValue(&I, V);
5281 DAG.setRoot(V.getValue(1));
5282}
5283
5284void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5285 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5286 getValue(I.getOperand(1)),
5287 DAG.getSrcValue(I.getOperand(1))));
5288}
5289
5290void SelectionDAGLowering::visitVACopy(CallInst &I) {
5291 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5292 getValue(I.getOperand(1)),
5293 getValue(I.getOperand(2)),
5294 DAG.getSrcValue(I.getOperand(1)),
5295 DAG.getSrcValue(I.getOperand(2))));
5296}
5297
5298/// TargetLowering::LowerArguments - This is the default LowerArguments
5299/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5300/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5301/// integrated into SDISel.
5302void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5303 SmallVectorImpl<SDValue> &ArgValues) {
5304 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5305 SmallVector<SDValue, 3+16> Ops;
5306 Ops.push_back(DAG.getRoot());
5307 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5308 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5309
5310 // Add one result value for each formal argument.
5311 SmallVector<MVT, 16> RetVals;
5312 unsigned j = 1;
5313 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5314 I != E; ++I, ++j) {
5315 SmallVector<MVT, 4> ValueVTs;
5316 ComputeValueVTs(*this, I->getType(), ValueVTs);
5317 for (unsigned Value = 0, NumValues = ValueVTs.size();
5318 Value != NumValues; ++Value) {
5319 MVT VT = ValueVTs[Value];
5320 const Type *ArgTy = VT.getTypeForMVT();
5321 ISD::ArgFlagsTy Flags;
5322 unsigned OriginalAlignment =
5323 getTargetData()->getABITypeAlignment(ArgTy);
5324
Devang Patel05988662008-09-25 21:00:45 +00005325 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005326 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005327 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005328 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005329 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005330 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005331 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005332 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005333 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005334 Flags.setByVal();
5335 const PointerType *Ty = cast<PointerType>(I->getType());
5336 const Type *ElementTy = Ty->getElementType();
5337 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5338 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5339 // For ByVal, alignment should be passed from FE. BE will guess if
5340 // this info is not there but there are cases it cannot get right.
5341 if (F.getParamAlignment(j))
5342 FrameAlign = F.getParamAlignment(j);
5343 Flags.setByValAlign(FrameAlign);
5344 Flags.setByValSize(FrameSize);
5345 }
Devang Patel05988662008-09-25 21:00:45 +00005346 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005347 Flags.setNest();
5348 Flags.setOrigAlign(OriginalAlignment);
5349
5350 MVT RegisterVT = getRegisterType(VT);
5351 unsigned NumRegs = getNumRegisters(VT);
5352 for (unsigned i = 0; i != NumRegs; ++i) {
5353 RetVals.push_back(RegisterVT);
5354 ISD::ArgFlagsTy MyFlags = Flags;
5355 if (NumRegs > 1 && i == 0)
5356 MyFlags.setSplit();
5357 // if it isn't first piece, alignment must be 1
5358 else if (i > 0)
5359 MyFlags.setOrigAlign(1);
5360 Ops.push_back(DAG.getArgFlags(MyFlags));
5361 }
5362 }
5363 }
5364
5365 RetVals.push_back(MVT::Other);
5366
5367 // Create the node.
5368 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5369 DAG.getVTList(&RetVals[0], RetVals.size()),
5370 &Ops[0], Ops.size()).getNode();
5371
5372 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5373 // allows exposing the loads that may be part of the argument access to the
5374 // first DAGCombiner pass.
5375 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5376
5377 // The number of results should match up, except that the lowered one may have
5378 // an extra flag result.
5379 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5380 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5381 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5382 && "Lowering produced unexpected number of results!");
5383
5384 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5385 if (Result != TmpRes.getNode() && Result->use_empty()) {
5386 HandleSDNode Dummy(DAG.getRoot());
5387 DAG.RemoveDeadNode(Result);
5388 }
5389
5390 Result = TmpRes.getNode();
5391
5392 unsigned NumArgRegs = Result->getNumValues() - 1;
5393 DAG.setRoot(SDValue(Result, NumArgRegs));
5394
5395 // Set up the return result vector.
5396 unsigned i = 0;
5397 unsigned Idx = 1;
5398 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5399 ++I, ++Idx) {
5400 SmallVector<MVT, 4> ValueVTs;
5401 ComputeValueVTs(*this, I->getType(), ValueVTs);
5402 for (unsigned Value = 0, NumValues = ValueVTs.size();
5403 Value != NumValues; ++Value) {
5404 MVT VT = ValueVTs[Value];
5405 MVT PartVT = getRegisterType(VT);
5406
5407 unsigned NumParts = getNumRegisters(VT);
5408 SmallVector<SDValue, 4> Parts(NumParts);
5409 for (unsigned j = 0; j != NumParts; ++j)
5410 Parts[j] = SDValue(Result, i++);
5411
5412 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005413 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005414 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005415 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005416 AssertOp = ISD::AssertZext;
5417
5418 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5419 AssertOp));
5420 }
5421 }
5422 assert(i == NumArgRegs && "Argument register count mismatch!");
5423}
5424
5425
5426/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5427/// implementation, which just inserts an ISD::CALL node, which is later custom
5428/// lowered by the target to something concrete. FIXME: When all targets are
5429/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5430std::pair<SDValue, SDValue>
5431TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5432 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005433 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005434 unsigned CallingConv, bool isTailCall,
5435 SDValue Callee,
5436 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005437 assert((!isTailCall || PerformTailCallOpt) &&
5438 "isTailCall set when tail-call optimizations are disabled!");
5439
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005440 SmallVector<SDValue, 32> Ops;
5441 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005442 Ops.push_back(Callee);
5443
5444 // Handle all of the outgoing arguments.
5445 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5446 SmallVector<MVT, 4> ValueVTs;
5447 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5448 for (unsigned Value = 0, NumValues = ValueVTs.size();
5449 Value != NumValues; ++Value) {
5450 MVT VT = ValueVTs[Value];
5451 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005452 SDValue Op = SDValue(Args[i].Node.getNode(),
5453 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005454 ISD::ArgFlagsTy Flags;
5455 unsigned OriginalAlignment =
5456 getTargetData()->getABITypeAlignment(ArgTy);
5457
5458 if (Args[i].isZExt)
5459 Flags.setZExt();
5460 if (Args[i].isSExt)
5461 Flags.setSExt();
5462 if (Args[i].isInReg)
5463 Flags.setInReg();
5464 if (Args[i].isSRet)
5465 Flags.setSRet();
5466 if (Args[i].isByVal) {
5467 Flags.setByVal();
5468 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5469 const Type *ElementTy = Ty->getElementType();
5470 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5471 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5472 // For ByVal, alignment should come from FE. BE will guess if this
5473 // info is not there but there are cases it cannot get right.
5474 if (Args[i].Alignment)
5475 FrameAlign = Args[i].Alignment;
5476 Flags.setByValAlign(FrameAlign);
5477 Flags.setByValSize(FrameSize);
5478 }
5479 if (Args[i].isNest)
5480 Flags.setNest();
5481 Flags.setOrigAlign(OriginalAlignment);
5482
5483 MVT PartVT = getRegisterType(VT);
5484 unsigned NumParts = getNumRegisters(VT);
5485 SmallVector<SDValue, 4> Parts(NumParts);
5486 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5487
5488 if (Args[i].isSExt)
5489 ExtendKind = ISD::SIGN_EXTEND;
5490 else if (Args[i].isZExt)
5491 ExtendKind = ISD::ZERO_EXTEND;
5492
5493 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5494
5495 for (unsigned i = 0; i != NumParts; ++i) {
5496 // if it isn't first piece, alignment must be 1
5497 ISD::ArgFlagsTy MyFlags = Flags;
5498 if (NumParts > 1 && i == 0)
5499 MyFlags.setSplit();
5500 else if (i != 0)
5501 MyFlags.setOrigAlign(1);
5502
5503 Ops.push_back(Parts[i]);
5504 Ops.push_back(DAG.getArgFlags(MyFlags));
5505 }
5506 }
5507 }
5508
5509 // Figure out the result value types. We start by making a list of
5510 // the potentially illegal return value types.
5511 SmallVector<MVT, 4> LoweredRetTys;
5512 SmallVector<MVT, 4> RetTys;
5513 ComputeValueVTs(*this, RetTy, RetTys);
5514
5515 // Then we translate that to a list of legal types.
5516 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5517 MVT VT = RetTys[I];
5518 MVT RegisterVT = getRegisterType(VT);
5519 unsigned NumRegs = getNumRegisters(VT);
5520 for (unsigned i = 0; i != NumRegs; ++i)
5521 LoweredRetTys.push_back(RegisterVT);
5522 }
5523
5524 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5525
5526 // Create the CALL node.
Dale Johannesen86098bd2008-09-26 19:31:26 +00005527 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005528 DAG.getVTList(&LoweredRetTys[0],
5529 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005530 &Ops[0], Ops.size()
5531 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005532 Chain = Res.getValue(LoweredRetTys.size() - 1);
5533
5534 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005535 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005536 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5537
5538 if (RetSExt)
5539 AssertOp = ISD::AssertSext;
5540 else if (RetZExt)
5541 AssertOp = ISD::AssertZext;
5542
5543 SmallVector<SDValue, 4> ReturnValues;
5544 unsigned RegNo = 0;
5545 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5546 MVT VT = RetTys[I];
5547 MVT RegisterVT = getRegisterType(VT);
5548 unsigned NumRegs = getNumRegisters(VT);
5549 unsigned RegNoEnd = NumRegs + RegNo;
5550 SmallVector<SDValue, 4> Results;
5551 for (; RegNo != RegNoEnd; ++RegNo)
5552 Results.push_back(Res.getValue(RegNo));
5553 SDValue ReturnValue =
5554 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5555 AssertOp);
5556 ReturnValues.push_back(ReturnValue);
5557 }
Duncan Sandsaaffa052008-12-01 11:41:29 +00005558 Res = DAG.getNode(ISD::MERGE_VALUES,
5559 DAG.getVTList(&RetTys[0], RetTys.size()),
5560 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005561 }
5562
5563 return std::make_pair(Res, Chain);
5564}
5565
5566SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5567 assert(0 && "LowerOperation not implemented for this target!");
5568 abort();
5569 return SDValue();
5570}
5571
5572
5573void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5574 SDValue Op = getValue(V);
5575 assert((Op.getOpcode() != ISD::CopyFromReg ||
5576 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5577 "Copy from a reg to the same reg!");
5578 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5579
5580 RegsForValue RFV(TLI, Reg, V->getType());
5581 SDValue Chain = DAG.getEntryNode();
5582 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5583 PendingExports.push_back(Chain);
5584}
5585
5586#include "llvm/CodeGen/SelectionDAGISel.h"
5587
5588void SelectionDAGISel::
5589LowerArguments(BasicBlock *LLVMBB) {
5590 // If this is the entry block, emit arguments.
5591 Function &F = *LLVMBB->getParent();
5592 SDValue OldRoot = SDL->DAG.getRoot();
5593 SmallVector<SDValue, 16> Args;
5594 TLI.LowerArguments(F, SDL->DAG, Args);
5595
5596 unsigned a = 0;
5597 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5598 AI != E; ++AI) {
5599 SmallVector<MVT, 4> ValueVTs;
5600 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5601 unsigned NumValues = ValueVTs.size();
5602 if (!AI->use_empty()) {
5603 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5604 // If this argument is live outside of the entry block, insert a copy from
5605 // whereever we got it to the vreg that other BB's will reference it as.
5606 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5607 if (VMI != FuncInfo->ValueMap.end()) {
5608 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5609 }
5610 }
5611 a += NumValues;
5612 }
5613
5614 // Finally, if the target has anything special to do, allow it to do so.
5615 // FIXME: this should insert code into the DAG!
5616 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5617}
5618
5619/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5620/// ensure constants are generated when needed. Remember the virtual registers
5621/// that need to be added to the Machine PHI nodes as input. We cannot just
5622/// directly add them, because expansion might result in multiple MBB's for one
5623/// BB. As such, the start of the BB might correspond to a different MBB than
5624/// the end.
5625///
5626void
5627SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5628 TerminatorInst *TI = LLVMBB->getTerminator();
5629
5630 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5631
5632 // Check successor nodes' PHI nodes that expect a constant to be available
5633 // from this block.
5634 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5635 BasicBlock *SuccBB = TI->getSuccessor(succ);
5636 if (!isa<PHINode>(SuccBB->begin())) continue;
5637 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5638
5639 // If this terminator has multiple identical successors (common for
5640 // switches), only handle each succ once.
5641 if (!SuccsHandled.insert(SuccMBB)) continue;
5642
5643 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5644 PHINode *PN;
5645
5646 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5647 // nodes and Machine PHI nodes, but the incoming operands have not been
5648 // emitted yet.
5649 for (BasicBlock::iterator I = SuccBB->begin();
5650 (PN = dyn_cast<PHINode>(I)); ++I) {
5651 // Ignore dead phi's.
5652 if (PN->use_empty()) continue;
5653
5654 unsigned Reg;
5655 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5656
5657 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5658 unsigned &RegOut = SDL->ConstantsOut[C];
5659 if (RegOut == 0) {
5660 RegOut = FuncInfo->CreateRegForValue(C);
5661 SDL->CopyValueToVirtualRegister(C, RegOut);
5662 }
5663 Reg = RegOut;
5664 } else {
5665 Reg = FuncInfo->ValueMap[PHIOp];
5666 if (Reg == 0) {
5667 assert(isa<AllocaInst>(PHIOp) &&
5668 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5669 "Didn't codegen value into a register!??");
5670 Reg = FuncInfo->CreateRegForValue(PHIOp);
5671 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5672 }
5673 }
5674
5675 // Remember that this register needs to added to the machine PHI node as
5676 // the input for this MBB.
5677 SmallVector<MVT, 4> ValueVTs;
5678 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5679 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5680 MVT VT = ValueVTs[vti];
5681 unsigned NumRegisters = TLI.getNumRegisters(VT);
5682 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5683 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5684 Reg += NumRegisters;
5685 }
5686 }
5687 }
5688 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005689}
5690
Dan Gohman3df24e62008-09-03 23:12:08 +00005691/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5692/// supports legal types, and it emits MachineInstrs directly instead of
5693/// creating SelectionDAG nodes.
5694///
5695bool
5696SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5697 FastISel *F) {
5698 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005699
Dan Gohman3df24e62008-09-03 23:12:08 +00005700 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5701 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5702
5703 // Check successor nodes' PHI nodes that expect a constant to be available
5704 // from this block.
5705 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5706 BasicBlock *SuccBB = TI->getSuccessor(succ);
5707 if (!isa<PHINode>(SuccBB->begin())) continue;
5708 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5709
5710 // If this terminator has multiple identical successors (common for
5711 // switches), only handle each succ once.
5712 if (!SuccsHandled.insert(SuccMBB)) continue;
5713
5714 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5715 PHINode *PN;
5716
5717 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5718 // nodes and Machine PHI nodes, but the incoming operands have not been
5719 // emitted yet.
5720 for (BasicBlock::iterator I = SuccBB->begin();
5721 (PN = dyn_cast<PHINode>(I)); ++I) {
5722 // Ignore dead phi's.
5723 if (PN->use_empty()) continue;
5724
5725 // Only handle legal types. Two interesting things to note here. First,
5726 // by bailing out early, we may leave behind some dead instructions,
5727 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5728 // own moves. Second, this check is necessary becuase FastISel doesn't
5729 // use CreateRegForValue to create registers, so it always creates
5730 // exactly one register for each non-void instruction.
5731 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5732 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005733 // Promote MVT::i1.
5734 if (VT == MVT::i1)
5735 VT = TLI.getTypeToTransformTo(VT);
5736 else {
5737 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5738 return false;
5739 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005740 }
5741
5742 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5743
5744 unsigned Reg = F->getRegForValue(PHIOp);
5745 if (Reg == 0) {
5746 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5747 return false;
5748 }
5749 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5750 }
5751 }
5752
5753 return true;
5754}