1 //===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuild.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #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"
28 #include "llvm/CodeGen/FastISel.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/GCMetadata.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetFrameInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/MathExtras.h"
51 /// LimitFloatPrecision - Generate low-precision inline sequences for
52 /// some float libcalls (6, 8 or 12 bits).
53 static unsigned LimitFloatPrecision;
55 static cl::opt<unsigned, true>
56 LimitFPPrecision("limit-float-precision",
57 cl::desc("Generate low-precision inline sequences "
58 "for some float libcalls"),
59 cl::location(LimitFloatPrecision),
62 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
63 /// insertvalue or extractvalue indices that identify a member, return
64 /// the linearized index of the start of the member.
66 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
67 const unsigned *Indices,
68 const unsigned *IndicesEnd,
69 unsigned CurIndex = 0) {
70 // Base case: We're done.
71 if (Indices && Indices == IndicesEnd)
74 // Given a struct type, recursively traverse the elements.
75 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
76 for (StructType::element_iterator EB = STy->element_begin(),
78 EE = STy->element_end();
80 if (Indices && *Indices == unsigned(EI - EB))
81 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
82 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
85 // Given an array type, recursively traverse the elements.
86 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
87 const Type *EltTy = ATy->getElementType();
88 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
89 if (Indices && *Indices == i)
90 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
91 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
94 // We haven't found the type we're looking for, so keep searching.
98 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
99 /// MVTs that represent all the individual underlying
100 /// non-aggregate types that comprise it.
102 /// If Offsets is non-null, it points to a vector to be filled in
103 /// with the in-memory offsets of each of the individual values.
105 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
106 SmallVectorImpl<MVT> &ValueVTs,
107 SmallVectorImpl<uint64_t> *Offsets = 0,
108 uint64_t StartingOffset = 0) {
109 // Given a struct type, recursively traverse the elements.
110 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
111 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
112 for (StructType::element_iterator EB = STy->element_begin(),
114 EE = STy->element_end();
116 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
117 StartingOffset + SL->getElementOffset(EI - EB));
120 // Given an array type, recursively traverse the elements.
121 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
122 const Type *EltTy = ATy->getElementType();
123 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
124 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
125 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
126 StartingOffset + i * EltSize);
129 // Base case: we can get an MVT for this LLVM IR type.
130 ValueVTs.push_back(TLI.getValueType(Ty));
132 Offsets->push_back(StartingOffset);
136 /// RegsForValue - This struct represents the registers (physical or virtual)
137 /// that a particular set of values is assigned, and the type information about
138 /// the value. The most common situation is to represent one value at a time,
139 /// but struct or array values are handled element-wise as multiple values.
140 /// The splitting of aggregates is performed recursively, so that we never
141 /// have aggregate-typed registers. The values at this point do not necessarily
142 /// have legal types, so each value may require one or more registers of some
145 struct VISIBILITY_HIDDEN RegsForValue {
146 /// TLI - The TargetLowering object.
148 const TargetLowering *TLI;
150 /// ValueVTs - The value types of the values, which may not be legal, and
151 /// may need be promoted or synthesized from one or more registers.
153 SmallVector<MVT, 4> ValueVTs;
155 /// RegVTs - The value types of the registers. This is the same size as
156 /// ValueVTs and it records, for each value, what the type of the assigned
157 /// register or registers are. (Individual values are never synthesized
158 /// from more than one type of register.)
160 /// With virtual registers, the contents of RegVTs is redundant with TLI's
161 /// getRegisterType member function, however when with physical registers
162 /// it is necessary to have a separate record of the types.
164 SmallVector<MVT, 4> RegVTs;
166 /// Regs - This list holds the registers assigned to the values.
167 /// Each legal or promoted value requires one register, and each
168 /// expanded value requires multiple registers.
170 SmallVector<unsigned, 4> Regs;
172 RegsForValue() : TLI(0) {}
174 RegsForValue(const TargetLowering &tli,
175 const SmallVector<unsigned, 4> ®s,
176 MVT regvt, MVT valuevt)
177 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
178 RegsForValue(const TargetLowering &tli,
179 const SmallVector<unsigned, 4> ®s,
180 const SmallVector<MVT, 4> ®vts,
181 const SmallVector<MVT, 4> &valuevts)
182 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
183 RegsForValue(const TargetLowering &tli,
184 unsigned Reg, const Type *Ty) : TLI(&tli) {
185 ComputeValueVTs(tli, Ty, ValueVTs);
187 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
188 MVT ValueVT = ValueVTs[Value];
189 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
190 MVT RegisterVT = TLI->getRegisterType(ValueVT);
191 for (unsigned i = 0; i != NumRegs; ++i)
192 Regs.push_back(Reg + i);
193 RegVTs.push_back(RegisterVT);
198 /// append - Add the specified values to this one.
199 void append(const RegsForValue &RHS) {
201 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
202 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
203 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
207 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
208 /// this value and returns the result as a ValueVTs value. This uses
209 /// Chain/Flag as the input and updates them for the output Chain/Flag.
210 /// If the Flag pointer is NULL, no flag is used.
211 SDValue getCopyFromRegs(SelectionDAG &DAG,
212 SDValue &Chain, SDValue *Flag) const;
214 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
215 /// specified value into the registers specified by this object. This uses
216 /// Chain/Flag as the input and updates them for the output Chain/Flag.
217 /// If the Flag pointer is NULL, no flag is used.
218 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
219 SDValue &Chain, SDValue *Flag) const;
221 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
222 /// operand list. This adds the code marker and includes the number of
223 /// values added into it.
224 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
225 std::vector<SDValue> &Ops) const;
229 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
230 /// PHI nodes or outside of the basic block that defines it, or used by a
231 /// switch or atomic instruction, which may expand to multiple basic blocks.
232 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
233 if (isa<PHINode>(I)) return true;
234 BasicBlock *BB = I->getParent();
235 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
236 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
237 // FIXME: Remove switchinst special case.
238 isa<SwitchInst>(*UI))
243 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
244 /// entry block, return true. This includes arguments used by switches, since
245 /// the switch may expand into multiple basic blocks.
246 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
247 // With FastISel active, we may be splitting blocks, so force creation
248 // of virtual registers for all non-dead arguments.
249 // Don't force virtual registers for byval arguments though, because
250 // fast-isel can't handle those in all cases.
251 if (EnableFastISel && !A->hasByValAttr())
252 return A->use_empty();
254 BasicBlock *Entry = A->getParent()->begin();
255 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
256 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
257 return false; // Use not in entry block.
261 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
265 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
266 bool EnableFastISel) {
269 RegInfo = &MF->getRegInfo();
271 // Create a vreg for each argument register that is not dead and is used
272 // outside of the entry block for the function.
273 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
275 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
276 InitializeRegForValue(AI);
278 // Initialize the mapping of values to registers. This is only set up for
279 // instruction values that are used outside of the block that defines
281 Function::iterator BB = Fn->begin(), EB = Fn->end();
282 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
283 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
284 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
285 const Type *Ty = AI->getAllocatedType();
286 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
288 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
291 TySize *= CUI->getZExtValue(); // Get total allocated size.
292 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
293 StaticAllocaMap[AI] =
294 MF->getFrameInfo()->CreateStackObject(TySize, Align);
297 for (; BB != EB; ++BB)
298 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
299 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
300 if (!isa<AllocaInst>(I) ||
301 !StaticAllocaMap.count(cast<AllocaInst>(I)))
302 InitializeRegForValue(I);
304 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
305 // also creates the initial PHI MachineInstrs, though none of the input
306 // operands are populated.
307 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
308 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
312 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
315 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
316 if (PN->use_empty()) continue;
318 unsigned PHIReg = ValueMap[PN];
319 assert(PHIReg && "PHI node does not have an assigned virtual register!");
321 SmallVector<MVT, 4> ValueVTs;
322 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
323 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
324 MVT VT = ValueVTs[vti];
325 unsigned NumRegisters = TLI.getNumRegisters(VT);
326 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
327 for (unsigned i = 0; i != NumRegisters; ++i)
328 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
329 PHIReg += NumRegisters;
335 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
336 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
339 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
340 /// the correctly promoted or expanded types. Assign these registers
341 /// consecutive vreg numbers and return the first assigned number.
343 /// In the case that the given value has struct or array type, this function
344 /// will assign registers for each member or element.
346 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
347 SmallVector<MVT, 4> ValueVTs;
348 ComputeValueVTs(TLI, V->getType(), ValueVTs);
350 unsigned FirstReg = 0;
351 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
352 MVT ValueVT = ValueVTs[Value];
353 MVT RegisterVT = TLI.getRegisterType(ValueVT);
355 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
356 for (unsigned i = 0; i != NumRegs; ++i) {
357 unsigned R = MakeReg(RegisterVT);
358 if (!FirstReg) FirstReg = R;
364 /// getCopyFromParts - Create a value that contains the specified legal parts
365 /// combined into the value they represent. If the parts combine to a type
366 /// larger then ValueVT then AssertOp can be used to specify whether the extra
367 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
368 /// (ISD::AssertSext).
369 static SDValue getCopyFromParts(SelectionDAG &DAG,
370 const SDValue *Parts,
374 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
375 assert(NumParts > 0 && "No parts to assemble!");
376 TargetLowering &TLI = DAG.getTargetLoweringInfo();
377 SDValue Val = Parts[0];
380 // Assemble the value from multiple parts.
381 if (!ValueVT.isVector()) {
382 unsigned PartBits = PartVT.getSizeInBits();
383 unsigned ValueBits = ValueVT.getSizeInBits();
385 // Assemble the power of 2 part.
386 unsigned RoundParts = NumParts & (NumParts - 1) ?
387 1 << Log2_32(NumParts) : NumParts;
388 unsigned RoundBits = PartBits * RoundParts;
389 MVT RoundVT = RoundBits == ValueBits ?
390 ValueVT : MVT::getIntegerVT(RoundBits);
393 if (RoundParts > 2) {
394 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
395 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
396 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
402 if (TLI.isBigEndian())
404 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
406 if (RoundParts < NumParts) {
407 // Assemble the trailing non-power-of-2 part.
408 unsigned OddParts = NumParts - RoundParts;
409 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
410 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
412 // Combine the round and odd parts.
414 if (TLI.isBigEndian())
416 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
417 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
418 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
419 DAG.getConstant(Lo.getValueType().getSizeInBits(),
420 TLI.getShiftAmountTy()));
421 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
422 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
425 // Handle a multi-element vector.
426 MVT IntermediateVT, RegisterVT;
427 unsigned NumIntermediates;
429 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
431 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
432 NumParts = NumRegs; // Silence a compiler warning.
433 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
434 assert(RegisterVT == Parts[0].getValueType() &&
435 "Part type doesn't match part!");
437 // Assemble the parts into intermediate operands.
438 SmallVector<SDValue, 8> Ops(NumIntermediates);
439 if (NumIntermediates == NumParts) {
440 // If the register was not expanded, truncate or copy the value,
442 for (unsigned i = 0; i != NumParts; ++i)
443 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
444 PartVT, IntermediateVT);
445 } else if (NumParts > 0) {
446 // If the intermediate type was expanded, build the intermediate operands
448 assert(NumParts % NumIntermediates == 0 &&
449 "Must expand into a divisible number of parts!");
450 unsigned Factor = NumParts / NumIntermediates;
451 for (unsigned i = 0; i != NumIntermediates; ++i)
452 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
453 PartVT, IntermediateVT);
456 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
458 Val = DAG.getNode(IntermediateVT.isVector() ?
459 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
460 ValueVT, &Ops[0], NumIntermediates);
464 // There is now one part, held in Val. Correct it to match ValueVT.
465 PartVT = Val.getValueType();
467 if (PartVT == ValueVT)
470 if (PartVT.isVector()) {
471 assert(ValueVT.isVector() && "Unknown vector conversion!");
472 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
475 if (ValueVT.isVector()) {
476 assert(ValueVT.getVectorElementType() == PartVT &&
477 ValueVT.getVectorNumElements() == 1 &&
478 "Only trivial scalar-to-vector conversions should get here!");
479 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
482 if (PartVT.isInteger() &&
483 ValueVT.isInteger()) {
484 if (ValueVT.bitsLT(PartVT)) {
485 // For a truncate, see if we have any information to
486 // indicate whether the truncated bits will always be
487 // zero or sign-extension.
488 if (AssertOp != ISD::DELETED_NODE)
489 Val = DAG.getNode(AssertOp, PartVT, Val,
490 DAG.getValueType(ValueVT));
491 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
493 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
497 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
498 if (ValueVT.bitsLT(Val.getValueType()))
499 // FP_ROUND's are always exact here.
500 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
501 DAG.getIntPtrConstant(1));
502 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
505 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
506 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
508 assert(0 && "Unknown mismatch!");
512 /// getCopyToParts - Create a series of nodes that contain the specified value
513 /// split into legal parts. If the parts contain more bits than Val, then, for
514 /// integers, ExtendKind can be used to specify how to generate the extra bits.
515 static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
516 SDValue *Parts, unsigned NumParts, MVT PartVT,
517 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
518 TargetLowering &TLI = DAG.getTargetLoweringInfo();
519 MVT PtrVT = TLI.getPointerTy();
520 MVT ValueVT = Val.getValueType();
521 unsigned PartBits = PartVT.getSizeInBits();
522 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
527 if (!ValueVT.isVector()) {
528 if (PartVT == ValueVT) {
529 assert(NumParts == 1 && "No-op copy with multiple parts!");
534 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
535 // If the parts cover more bits than the value has, promote the value.
536 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
537 assert(NumParts == 1 && "Do not know what to promote to!");
538 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
539 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
540 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
541 Val = DAG.getNode(ExtendKind, ValueVT, Val);
543 assert(0 && "Unknown mismatch!");
545 } else if (PartBits == ValueVT.getSizeInBits()) {
546 // Different types of the same size.
547 assert(NumParts == 1 && PartVT != ValueVT);
548 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
549 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
550 // If the parts cover less bits than value has, truncate the value.
551 if (PartVT.isInteger() && ValueVT.isInteger()) {
552 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
553 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
555 assert(0 && "Unknown mismatch!");
559 // The value may have changed - recompute ValueVT.
560 ValueVT = Val.getValueType();
561 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
562 "Failed to tile the value with PartVT!");
565 assert(PartVT == ValueVT && "Type conversion failed!");
570 // Expand the value into multiple parts.
571 if (NumParts & (NumParts - 1)) {
572 // The number of parts is not a power of 2. Split off and copy the tail.
573 assert(PartVT.isInteger() && ValueVT.isInteger() &&
574 "Do not know what to expand to!");
575 unsigned RoundParts = 1 << Log2_32(NumParts);
576 unsigned RoundBits = RoundParts * PartBits;
577 unsigned OddParts = NumParts - RoundParts;
578 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
579 DAG.getConstant(RoundBits,
580 TLI.getShiftAmountTy()));
581 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
582 if (TLI.isBigEndian())
583 // The odd parts were reversed by getCopyToParts - unreverse them.
584 std::reverse(Parts + RoundParts, Parts + NumParts);
585 NumParts = RoundParts;
586 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
587 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
590 // The number of parts is a power of 2. Repeatedly bisect the value using
592 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
593 MVT::getIntegerVT(ValueVT.getSizeInBits()),
595 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
596 for (unsigned i = 0; i < NumParts; i += StepSize) {
597 unsigned ThisBits = StepSize * PartBits / 2;
598 MVT ThisVT = MVT::getIntegerVT (ThisBits);
599 SDValue &Part0 = Parts[i];
600 SDValue &Part1 = Parts[i+StepSize/2];
602 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
603 DAG.getConstant(1, PtrVT));
604 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
605 DAG.getConstant(0, PtrVT));
607 if (ThisBits == PartBits && ThisVT != PartVT) {
608 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
609 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
614 if (TLI.isBigEndian())
615 std::reverse(Parts, Parts + NumParts);
622 if (PartVT != ValueVT) {
623 if (PartVT.isVector()) {
624 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
626 assert(ValueVT.getVectorElementType() == PartVT &&
627 ValueVT.getVectorNumElements() == 1 &&
628 "Only trivial vector-to-scalar conversions should get here!");
629 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
630 DAG.getConstant(0, PtrVT));
638 // Handle a multi-element vector.
639 MVT IntermediateVT, RegisterVT;
640 unsigned NumIntermediates;
642 DAG.getTargetLoweringInfo()
643 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
645 unsigned NumElements = ValueVT.getVectorNumElements();
647 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
648 NumParts = NumRegs; // Silence a compiler warning.
649 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
651 // Split the vector into intermediate operands.
652 SmallVector<SDValue, 8> Ops(NumIntermediates);
653 for (unsigned i = 0; i != NumIntermediates; ++i)
654 if (IntermediateVT.isVector())
655 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
657 DAG.getConstant(i * (NumElements / NumIntermediates),
660 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
662 DAG.getConstant(i, PtrVT));
664 // Split the intermediate operands into legal parts.
665 if (NumParts == NumIntermediates) {
666 // If the register was not expanded, promote or copy the value,
668 for (unsigned i = 0; i != NumParts; ++i)
669 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
670 } else if (NumParts > 0) {
671 // If the intermediate type was expanded, split each the value into
673 assert(NumParts % NumIntermediates == 0 &&
674 "Must expand into a divisible number of parts!");
675 unsigned Factor = NumParts / NumIntermediates;
676 for (unsigned i = 0; i != NumIntermediates; ++i)
677 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
682 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
685 TD = DAG.getTarget().getTargetData();
688 /// clear - Clear out the curret SelectionDAG and the associated
689 /// state and prepare this SelectionDAGLowering object to be used
690 /// for a new block. This doesn't clear out information about
691 /// additional blocks that are needed to complete switch lowering
692 /// or PHI node updating; that information is cleared out as it is
694 void SelectionDAGLowering::clear() {
696 PendingLoads.clear();
697 PendingExports.clear();
701 /// getRoot - Return the current virtual root of the Selection DAG,
702 /// flushing any PendingLoad items. This must be done before emitting
703 /// a store or any other node that may need to be ordered after any
704 /// prior load instructions.
706 SDValue SelectionDAGLowering::getRoot() {
707 if (PendingLoads.empty())
708 return DAG.getRoot();
710 if (PendingLoads.size() == 1) {
711 SDValue Root = PendingLoads[0];
713 PendingLoads.clear();
717 // Otherwise, we have to make a token factor node.
718 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
719 &PendingLoads[0], PendingLoads.size());
720 PendingLoads.clear();
725 /// getControlRoot - Similar to getRoot, but instead of flushing all the
726 /// PendingLoad items, flush all the PendingExports items. It is necessary
727 /// to do this before emitting a terminator instruction.
729 SDValue SelectionDAGLowering::getControlRoot() {
730 SDValue Root = DAG.getRoot();
732 if (PendingExports.empty())
735 // Turn all of the CopyToReg chains into one factored node.
736 if (Root.getOpcode() != ISD::EntryToken) {
737 unsigned i = 0, e = PendingExports.size();
738 for (; i != e; ++i) {
739 assert(PendingExports[i].getNode()->getNumOperands() > 1);
740 if (PendingExports[i].getNode()->getOperand(0) == Root)
741 break; // Don't add the root if we already indirectly depend on it.
745 PendingExports.push_back(Root);
748 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
750 PendingExports.size());
751 PendingExports.clear();
756 void SelectionDAGLowering::visit(Instruction &I) {
757 visit(I.getOpcode(), I);
760 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
761 // Note: this doesn't use InstVisitor, because it has to work with
762 // ConstantExpr's in addition to instructions.
764 default: assert(0 && "Unknown instruction type encountered!");
766 // Build the switch statement using the Instruction.def file.
767 #define HANDLE_INST(NUM, OPCODE, CLASS) \
768 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
769 #include "llvm/Instruction.def"
773 void SelectionDAGLowering::visitAdd(User &I) {
774 if (I.getType()->isFPOrFPVector())
775 visitBinary(I, ISD::FADD);
777 visitBinary(I, ISD::ADD);
780 void SelectionDAGLowering::visitMul(User &I) {
781 if (I.getType()->isFPOrFPVector())
782 visitBinary(I, ISD::FMUL);
784 visitBinary(I, ISD::MUL);
787 SDValue SelectionDAGLowering::getValue(const Value *V) {
788 SDValue &N = NodeMap[V];
789 if (N.getNode()) return N;
791 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
792 MVT VT = TLI.getValueType(V->getType(), true);
794 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
795 return N = DAG.getConstant(*CI, VT);
797 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
798 return N = DAG.getGlobalAddress(GV, VT);
800 if (isa<ConstantPointerNull>(C))
801 return N = DAG.getConstant(0, TLI.getPointerTy());
803 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
804 return N = DAG.getConstantFP(*CFP, VT);
806 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
807 !V->getType()->isAggregateType())
808 return N = DAG.getNode(ISD::UNDEF, VT);
810 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
811 visit(CE->getOpcode(), *CE);
812 SDValue N1 = NodeMap[V];
813 assert(N1.getNode() && "visit didn't populate the ValueMap!");
817 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
818 SmallVector<SDValue, 4> Constants;
819 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
821 SDNode *Val = getValue(*OI).getNode();
822 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
823 Constants.push_back(SDValue(Val, i));
825 return DAG.getMergeValues(&Constants[0], Constants.size());
828 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
829 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
830 "Unknown struct or array constant!");
832 SmallVector<MVT, 4> ValueVTs;
833 ComputeValueVTs(TLI, C->getType(), ValueVTs);
834 unsigned NumElts = ValueVTs.size();
836 return SDValue(); // empty struct
837 SmallVector<SDValue, 4> Constants(NumElts);
838 for (unsigned i = 0; i != NumElts; ++i) {
839 MVT EltVT = ValueVTs[i];
840 if (isa<UndefValue>(C))
841 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
842 else if (EltVT.isFloatingPoint())
843 Constants[i] = DAG.getConstantFP(0, EltVT);
845 Constants[i] = DAG.getConstant(0, EltVT);
847 return DAG.getMergeValues(&Constants[0], NumElts);
850 const VectorType *VecTy = cast<VectorType>(V->getType());
851 unsigned NumElements = VecTy->getNumElements();
853 // Now that we know the number and type of the elements, get that number of
854 // elements into the Ops array based on what kind of constant it is.
855 SmallVector<SDValue, 16> Ops;
856 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
857 for (unsigned i = 0; i != NumElements; ++i)
858 Ops.push_back(getValue(CP->getOperand(i)));
860 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
861 "Unknown vector constant!");
862 MVT EltVT = TLI.getValueType(VecTy->getElementType());
865 if (isa<UndefValue>(C))
866 Op = DAG.getNode(ISD::UNDEF, EltVT);
867 else if (EltVT.isFloatingPoint())
868 Op = DAG.getConstantFP(0, EltVT);
870 Op = DAG.getConstant(0, EltVT);
871 Ops.assign(NumElements, Op);
874 // Create a BUILD_VECTOR node.
875 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
878 // If this is a static alloca, generate it as the frameindex instead of
880 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
881 DenseMap<const AllocaInst*, int>::iterator SI =
882 FuncInfo.StaticAllocaMap.find(AI);
883 if (SI != FuncInfo.StaticAllocaMap.end())
884 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
887 unsigned InReg = FuncInfo.ValueMap[V];
888 assert(InReg && "Value not in map!");
890 RegsForValue RFV(TLI, InReg, V->getType());
891 SDValue Chain = DAG.getEntryNode();
892 return RFV.getCopyFromRegs(DAG, Chain, NULL);
896 void SelectionDAGLowering::visitRet(ReturnInst &I) {
897 if (I.getNumOperands() == 0) {
898 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
902 SmallVector<SDValue, 8> NewValues;
903 NewValues.push_back(getControlRoot());
904 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
905 SDValue RetOp = getValue(I.getOperand(i));
907 SmallVector<MVT, 4> ValueVTs;
908 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
909 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
910 MVT VT = ValueVTs[j];
912 // FIXME: C calling convention requires the return type to be promoted to
913 // at least 32-bit. But this is not necessary for non-C calling
915 if (VT.isInteger()) {
916 MVT MinVT = TLI.getRegisterType(MVT::i32);
917 if (VT.bitsLT(MinVT))
921 unsigned NumParts = TLI.getNumRegisters(VT);
922 MVT PartVT = TLI.getRegisterType(VT);
923 SmallVector<SDValue, 4> Parts(NumParts);
924 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
926 const Function *F = I.getParent()->getParent();
927 if (F->paramHasAttr(0, Attribute::SExt))
928 ExtendKind = ISD::SIGN_EXTEND;
929 else if (F->paramHasAttr(0, Attribute::ZExt))
930 ExtendKind = ISD::ZERO_EXTEND;
932 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
933 &Parts[0], NumParts, PartVT, ExtendKind);
935 // 'inreg' on function refers to return value
936 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
937 if (F->paramHasAttr(0, Attribute::InReg))
939 for (unsigned i = 0; i < NumParts; ++i) {
940 NewValues.push_back(Parts[i]);
941 NewValues.push_back(DAG.getArgFlags(Flags));
945 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
946 &NewValues[0], NewValues.size()));
949 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
950 /// the current basic block, add it to ValueMap now so that we'll get a
952 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
953 // No need to export constants.
954 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
957 if (FuncInfo.isExportedInst(V)) return;
959 unsigned Reg = FuncInfo.InitializeRegForValue(V);
960 CopyValueToVirtualRegister(V, Reg);
963 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
964 const BasicBlock *FromBB) {
965 // The operands of the setcc have to be in this block. We don't know
966 // how to export them from some other block.
967 if (Instruction *VI = dyn_cast<Instruction>(V)) {
968 // Can export from current BB.
969 if (VI->getParent() == FromBB)
972 // Is already exported, noop.
973 return FuncInfo.isExportedInst(V);
976 // If this is an argument, we can export it if the BB is the entry block or
977 // if it is already exported.
978 if (isa<Argument>(V)) {
979 if (FromBB == &FromBB->getParent()->getEntryBlock())
982 // Otherwise, can only export this if it is already exported.
983 return FuncInfo.isExportedInst(V);
986 // Otherwise, constants can always be exported.
990 static bool InBlock(const Value *V, const BasicBlock *BB) {
991 if (const Instruction *I = dyn_cast<Instruction>(V))
992 return I->getParent() == BB;
996 /// getFCmpCondCode - Return the ISD condition code corresponding to
997 /// the given LLVM IR floating-point condition code. This includes
998 /// consideration of global floating-point math flags.
1000 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1001 ISD::CondCode FPC, FOC;
1003 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1004 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1005 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1006 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1007 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1008 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1009 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1010 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1011 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1012 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1013 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1014 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1015 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1016 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1017 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1018 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1020 assert(0 && "Invalid FCmp predicate opcode!");
1021 FOC = FPC = ISD::SETFALSE;
1024 if (FiniteOnlyFPMath())
1030 /// getICmpCondCode - Return the ISD condition code corresponding to
1031 /// the given LLVM IR integer condition code.
1033 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1035 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1036 case ICmpInst::ICMP_NE: return ISD::SETNE;
1037 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1038 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1039 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1040 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1041 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1042 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1043 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1044 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1046 assert(0 && "Invalid ICmp predicate opcode!");
1051 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1052 /// This function emits a branch and is used at the leaves of an OR or an
1053 /// AND operator tree.
1056 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1057 MachineBasicBlock *TBB,
1058 MachineBasicBlock *FBB,
1059 MachineBasicBlock *CurBB) {
1060 const BasicBlock *BB = CurBB->getBasicBlock();
1062 // If the leaf of the tree is a comparison, merge the condition into
1064 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1065 // The operands of the cmp have to be in this block. We don't know
1066 // how to export them from some other block. If this is the first block
1067 // of the sequence, no exporting is needed.
1068 if (CurBB == CurMBB ||
1069 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1070 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1071 ISD::CondCode Condition;
1072 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1073 Condition = getICmpCondCode(IC->getPredicate());
1074 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1075 Condition = getFCmpCondCode(FC->getPredicate());
1077 Condition = ISD::SETEQ; // silence warning.
1078 assert(0 && "Unknown compare instruction");
1081 CaseBlock CB(Condition, BOp->getOperand(0),
1082 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1083 SwitchCases.push_back(CB);
1088 // Create a CaseBlock record representing this branch.
1089 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1090 NULL, TBB, FBB, CurBB);
1091 SwitchCases.push_back(CB);
1094 /// FindMergedConditions - If Cond is an expression like
1095 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1096 MachineBasicBlock *TBB,
1097 MachineBasicBlock *FBB,
1098 MachineBasicBlock *CurBB,
1100 // If this node is not part of the or/and tree, emit it as a branch.
1101 Instruction *BOp = dyn_cast<Instruction>(Cond);
1102 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1103 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1104 BOp->getParent() != CurBB->getBasicBlock() ||
1105 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1106 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1107 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1111 // Create TmpBB after CurBB.
1112 MachineFunction::iterator BBI = CurBB;
1113 MachineFunction &MF = DAG.getMachineFunction();
1114 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1115 CurBB->getParent()->insert(++BBI, TmpBB);
1117 if (Opc == Instruction::Or) {
1118 // Codegen X | Y as:
1126 // Emit the LHS condition.
1127 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1129 // Emit the RHS condition into TmpBB.
1130 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1132 assert(Opc == Instruction::And && "Unknown merge op!");
1133 // Codegen X & Y as:
1140 // This requires creation of TmpBB after CurBB.
1142 // Emit the LHS condition.
1143 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1145 // Emit the RHS condition into TmpBB.
1146 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1150 /// If the set of cases should be emitted as a series of branches, return true.
1151 /// If we should emit this as a bunch of and/or'd together conditions, return
1154 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1155 if (Cases.size() != 2) return true;
1157 // If this is two comparisons of the same values or'd or and'd together, they
1158 // will get folded into a single comparison, so don't emit two blocks.
1159 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1160 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1161 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1162 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1169 void SelectionDAGLowering::visitBr(BranchInst &I) {
1170 // Update machine-CFG edges.
1171 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1173 // Figure out which block is immediately after the current one.
1174 MachineBasicBlock *NextBlock = 0;
1175 MachineFunction::iterator BBI = CurMBB;
1176 if (++BBI != CurMBB->getParent()->end())
1179 if (I.isUnconditional()) {
1180 // Update machine-CFG edges.
1181 CurMBB->addSuccessor(Succ0MBB);
1183 // If this is not a fall-through branch, emit the branch.
1184 if (Succ0MBB != NextBlock)
1185 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1186 DAG.getBasicBlock(Succ0MBB)));
1190 // If this condition is one of the special cases we handle, do special stuff
1192 Value *CondVal = I.getCondition();
1193 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1195 // If this is a series of conditions that are or'd or and'd together, emit
1196 // this as a sequence of branches instead of setcc's with and/or operations.
1197 // For example, instead of something like:
1210 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1211 if (BOp->hasOneUse() &&
1212 (BOp->getOpcode() == Instruction::And ||
1213 BOp->getOpcode() == Instruction::Or)) {
1214 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1215 // If the compares in later blocks need to use values not currently
1216 // exported from this block, export them now. This block should always
1217 // be the first entry.
1218 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1220 // Allow some cases to be rejected.
1221 if (ShouldEmitAsBranches(SwitchCases)) {
1222 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1223 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1224 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1227 // Emit the branch for this block.
1228 visitSwitchCase(SwitchCases[0]);
1229 SwitchCases.erase(SwitchCases.begin());
1233 // Okay, we decided not to do this, remove any inserted MBB's and clear
1235 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1236 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1238 SwitchCases.clear();
1242 // Create a CaseBlock record representing this branch.
1243 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1244 NULL, Succ0MBB, Succ1MBB, CurMBB);
1245 // Use visitSwitchCase to actually insert the fast branch sequence for this
1247 visitSwitchCase(CB);
1250 /// visitSwitchCase - Emits the necessary code to represent a single node in
1251 /// the binary search tree resulting from lowering a switch instruction.
1252 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1254 SDValue CondLHS = getValue(CB.CmpLHS);
1256 // Build the setcc now.
1257 if (CB.CmpMHS == NULL) {
1258 // Fold "(X == true)" to X and "(X == false)" to !X to
1259 // handle common cases produced by branch lowering.
1260 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1262 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1263 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1264 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1266 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1268 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1270 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1271 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1273 SDValue CmpOp = getValue(CB.CmpMHS);
1274 MVT VT = CmpOp.getValueType();
1276 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1277 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1279 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1280 Cond = DAG.getSetCC(MVT::i1, SUB,
1281 DAG.getConstant(High-Low, VT), ISD::SETULE);
1285 // Update successor info
1286 CurMBB->addSuccessor(CB.TrueBB);
1287 CurMBB->addSuccessor(CB.FalseBB);
1289 // Set NextBlock to be the MBB immediately after the current one, if any.
1290 // This is used to avoid emitting unnecessary branches to the next block.
1291 MachineBasicBlock *NextBlock = 0;
1292 MachineFunction::iterator BBI = CurMBB;
1293 if (++BBI != CurMBB->getParent()->end())
1296 // If the lhs block is the next block, invert the condition so that we can
1297 // fall through to the lhs instead of the rhs block.
1298 if (CB.TrueBB == NextBlock) {
1299 std::swap(CB.TrueBB, CB.FalseBB);
1300 SDValue True = DAG.getConstant(1, Cond.getValueType());
1301 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1303 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1304 DAG.getBasicBlock(CB.TrueBB));
1306 // If the branch was constant folded, fix up the CFG.
1307 if (BrCond.getOpcode() == ISD::BR) {
1308 CurMBB->removeSuccessor(CB.FalseBB);
1309 DAG.setRoot(BrCond);
1311 // Otherwise, go ahead and insert the false branch.
1312 if (BrCond == getControlRoot())
1313 CurMBB->removeSuccessor(CB.TrueBB);
1315 if (CB.FalseBB == NextBlock)
1316 DAG.setRoot(BrCond);
1318 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1319 DAG.getBasicBlock(CB.FalseBB)));
1323 /// visitJumpTable - Emit JumpTable node in the current MBB
1324 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1325 // Emit the code for the jump table
1326 assert(JT.Reg != -1U && "Should lower JT Header first!");
1327 MVT PTy = TLI.getPointerTy();
1328 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1329 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1330 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1335 /// visitJumpTableHeader - This function emits necessary code to produce index
1336 /// in the JumpTable from switch case.
1337 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1338 JumpTableHeader &JTH) {
1339 // Subtract the lowest switch case value from the value being switched on
1340 // and conditional branch to default mbb if the result is greater than the
1341 // difference between smallest and largest cases.
1342 SDValue SwitchOp = getValue(JTH.SValue);
1343 MVT VT = SwitchOp.getValueType();
1344 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1345 DAG.getConstant(JTH.First, VT));
1347 // The SDNode we just created, which holds the value being switched on
1348 // minus the the smallest case value, needs to be copied to a virtual
1349 // register so it can be used as an index into the jump table in a
1350 // subsequent basic block. This value may be smaller or larger than the
1351 // target's pointer type, and therefore require extension or truncating.
1352 if (VT.bitsGT(TLI.getPointerTy()))
1353 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1355 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1357 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1358 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1359 JT.Reg = JumpTableReg;
1361 // Emit the range check for the jump table, and branch to the default
1362 // block for the switch statement if the value being switched on exceeds
1363 // the largest case in the switch.
1364 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1365 DAG.getConstant(JTH.Last-JTH.First,VT),
1368 // Set NextBlock to be the MBB immediately after the current one, if any.
1369 // This is used to avoid emitting unnecessary branches to the next block.
1370 MachineBasicBlock *NextBlock = 0;
1371 MachineFunction::iterator BBI = CurMBB;
1372 if (++BBI != CurMBB->getParent()->end())
1375 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1376 DAG.getBasicBlock(JT.Default));
1378 if (JT.MBB == NextBlock)
1379 DAG.setRoot(BrCond);
1381 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1382 DAG.getBasicBlock(JT.MBB)));
1387 /// visitBitTestHeader - This function emits necessary code to produce value
1388 /// suitable for "bit tests"
1389 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1390 // Subtract the minimum value
1391 SDValue SwitchOp = getValue(B.SValue);
1392 MVT VT = SwitchOp.getValueType();
1393 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1394 DAG.getConstant(B.First, VT));
1397 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1398 DAG.getConstant(B.Range, VT),
1402 if (VT.bitsGT(TLI.getShiftAmountTy()))
1403 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1405 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1407 // Make desired shift
1408 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1409 DAG.getConstant(1, TLI.getPointerTy()),
1412 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1413 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1416 // Set NextBlock to be the MBB immediately after the current one, if any.
1417 // This is used to avoid emitting unnecessary branches to the next block.
1418 MachineBasicBlock *NextBlock = 0;
1419 MachineFunction::iterator BBI = CurMBB;
1420 if (++BBI != CurMBB->getParent()->end())
1423 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1425 CurMBB->addSuccessor(B.Default);
1426 CurMBB->addSuccessor(MBB);
1428 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1429 DAG.getBasicBlock(B.Default));
1431 if (MBB == NextBlock)
1432 DAG.setRoot(BrRange);
1434 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1435 DAG.getBasicBlock(MBB)));
1440 /// visitBitTestCase - this function produces one "bit test"
1441 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1444 // Emit bit tests and jumps
1445 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1446 TLI.getPointerTy());
1448 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1449 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1450 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1451 DAG.getConstant(0, TLI.getPointerTy()),
1454 CurMBB->addSuccessor(B.TargetBB);
1455 CurMBB->addSuccessor(NextMBB);
1457 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1458 AndCmp, DAG.getBasicBlock(B.TargetBB));
1460 // Set NextBlock to be the MBB immediately after the current one, if any.
1461 // This is used to avoid emitting unnecessary branches to the next block.
1462 MachineBasicBlock *NextBlock = 0;
1463 MachineFunction::iterator BBI = CurMBB;
1464 if (++BBI != CurMBB->getParent()->end())
1467 if (NextMBB == NextBlock)
1470 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1471 DAG.getBasicBlock(NextMBB)));
1476 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1477 // Retrieve successors.
1478 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1479 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1481 if (isa<InlineAsm>(I.getCalledValue()))
1484 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1486 // If the value of the invoke is used outside of its defining block, make it
1487 // available as a virtual register.
1488 if (!I.use_empty()) {
1489 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1490 if (VMI != FuncInfo.ValueMap.end())
1491 CopyValueToVirtualRegister(&I, VMI->second);
1494 // Update successor info
1495 CurMBB->addSuccessor(Return);
1496 CurMBB->addSuccessor(LandingPad);
1498 // Drop into normal successor.
1499 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1500 DAG.getBasicBlock(Return)));
1503 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1506 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1507 /// small case ranges).
1508 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1509 CaseRecVector& WorkList,
1511 MachineBasicBlock* Default) {
1512 Case& BackCase = *(CR.Range.second-1);
1514 // Size is the number of Cases represented by this range.
1515 unsigned Size = CR.Range.second - CR.Range.first;
1519 // Get the MachineFunction which holds the current MBB. This is used when
1520 // inserting any additional MBBs necessary to represent the switch.
1521 MachineFunction *CurMF = CurMBB->getParent();
1523 // Figure out which block is immediately after the current one.
1524 MachineBasicBlock *NextBlock = 0;
1525 MachineFunction::iterator BBI = CR.CaseBB;
1527 if (++BBI != CurMBB->getParent()->end())
1530 // TODO: If any two of the cases has the same destination, and if one value
1531 // is the same as the other, but has one bit unset that the other has set,
1532 // use bit manipulation to do two compares at once. For example:
1533 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1535 // Rearrange the case blocks so that the last one falls through if possible.
1536 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1537 // The last case block won't fall through into 'NextBlock' if we emit the
1538 // branches in this order. See if rearranging a case value would help.
1539 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1540 if (I->BB == NextBlock) {
1541 std::swap(*I, BackCase);
1547 // Create a CaseBlock record representing a conditional branch to
1548 // the Case's target mbb if the value being switched on SV is equal
1550 MachineBasicBlock *CurBlock = CR.CaseBB;
1551 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1552 MachineBasicBlock *FallThrough;
1554 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1555 CurMF->insert(BBI, FallThrough);
1557 // If the last case doesn't match, go to the default block.
1558 FallThrough = Default;
1561 Value *RHS, *LHS, *MHS;
1563 if (I->High == I->Low) {
1564 // This is just small small case range :) containing exactly 1 case
1566 LHS = SV; RHS = I->High; MHS = NULL;
1569 LHS = I->Low; MHS = SV; RHS = I->High;
1571 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1573 // If emitting the first comparison, just call visitSwitchCase to emit the
1574 // code into the current block. Otherwise, push the CaseBlock onto the
1575 // vector to be later processed by SDISel, and insert the node's MBB
1576 // before the next MBB.
1577 if (CurBlock == CurMBB)
1578 visitSwitchCase(CB);
1580 SwitchCases.push_back(CB);
1582 CurBlock = FallThrough;
1588 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1589 return !DisableJumpTables &&
1590 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1591 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1594 /// handleJTSwitchCase - Emit jumptable for current switch case range
1595 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1596 CaseRecVector& WorkList,
1598 MachineBasicBlock* Default) {
1599 Case& FrontCase = *CR.Range.first;
1600 Case& BackCase = *(CR.Range.second-1);
1602 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1603 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1606 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1610 if (!areJTsAllowed(TLI) || TSize <= 3)
1613 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1617 DOUT << "Lowering jump table\n"
1618 << "First entry: " << First << ". Last entry: " << Last << "\n"
1619 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1621 // Get the MachineFunction which holds the current MBB. This is used when
1622 // inserting any additional MBBs necessary to represent the switch.
1623 MachineFunction *CurMF = CurMBB->getParent();
1625 // Figure out which block is immediately after the current one.
1626 MachineBasicBlock *NextBlock = 0;
1627 MachineFunction::iterator BBI = CR.CaseBB;
1629 if (++BBI != CurMBB->getParent()->end())
1632 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1634 // Create a new basic block to hold the code for loading the address
1635 // of the jump table, and jumping to it. Update successor information;
1636 // we will either branch to the default case for the switch, or the jump
1638 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1639 CurMF->insert(BBI, JumpTableBB);
1640 CR.CaseBB->addSuccessor(Default);
1641 CR.CaseBB->addSuccessor(JumpTableBB);
1643 // Build a vector of destination BBs, corresponding to each target
1644 // of the jump table. If the value of the jump table slot corresponds to
1645 // a case statement, push the case's BB onto the vector, otherwise, push
1647 std::vector<MachineBasicBlock*> DestBBs;
1648 int64_t TEI = First;
1649 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1650 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1651 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1653 if ((Low <= TEI) && (TEI <= High)) {
1654 DestBBs.push_back(I->BB);
1658 DestBBs.push_back(Default);
1662 // Update successor info. Add one edge to each unique successor.
1663 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1664 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1665 E = DestBBs.end(); I != E; ++I) {
1666 if (!SuccsHandled[(*I)->getNumber()]) {
1667 SuccsHandled[(*I)->getNumber()] = true;
1668 JumpTableBB->addSuccessor(*I);
1672 // Create a jump table index for this jump table, or return an existing
1674 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1676 // Set the jump table information so that we can codegen it as a second
1677 // MachineBasicBlock
1678 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1679 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1680 if (CR.CaseBB == CurMBB)
1681 visitJumpTableHeader(JT, JTH);
1683 JTCases.push_back(JumpTableBlock(JTH, JT));
1688 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1690 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1691 CaseRecVector& WorkList,
1693 MachineBasicBlock* Default) {
1694 // Get the MachineFunction which holds the current MBB. This is used when
1695 // inserting any additional MBBs necessary to represent the switch.
1696 MachineFunction *CurMF = CurMBB->getParent();
1698 // Figure out which block is immediately after the current one.
1699 MachineBasicBlock *NextBlock = 0;
1700 MachineFunction::iterator BBI = CR.CaseBB;
1702 if (++BBI != CurMBB->getParent()->end())
1705 Case& FrontCase = *CR.Range.first;
1706 Case& BackCase = *(CR.Range.second-1);
1707 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1709 // Size is the number of Cases represented by this range.
1710 unsigned Size = CR.Range.second - CR.Range.first;
1712 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1713 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1715 CaseItr Pivot = CR.Range.first + Size/2;
1717 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1718 // (heuristically) allow us to emit JumpTable's later.
1720 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1724 uint64_t LSize = FrontCase.size();
1725 uint64_t RSize = TSize-LSize;
1726 DOUT << "Selecting best pivot: \n"
1727 << "First: " << First << ", Last: " << Last <<"\n"
1728 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1729 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1731 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1732 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1733 assert((RBegin-LEnd>=1) && "Invalid case distance");
1734 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1735 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1736 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1737 // Should always split in some non-trivial place
1739 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1740 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1741 << "Metric: " << Metric << "\n";
1742 if (FMetric < Metric) {
1745 DOUT << "Current metric set to: " << FMetric << "\n";
1751 if (areJTsAllowed(TLI)) {
1752 // If our case is dense we *really* should handle it earlier!
1753 assert((FMetric > 0) && "Should handle dense range earlier!");
1755 Pivot = CR.Range.first + Size/2;
1758 CaseRange LHSR(CR.Range.first, Pivot);
1759 CaseRange RHSR(Pivot, CR.Range.second);
1760 Constant *C = Pivot->Low;
1761 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1763 // We know that we branch to the LHS if the Value being switched on is
1764 // less than the Pivot value, C. We use this to optimize our binary
1765 // tree a bit, by recognizing that if SV is greater than or equal to the
1766 // LHS's Case Value, and that Case Value is exactly one less than the
1767 // Pivot's Value, then we can branch directly to the LHS's Target,
1768 // rather than creating a leaf node for it.
1769 if ((LHSR.second - LHSR.first) == 1 &&
1770 LHSR.first->High == CR.GE &&
1771 cast<ConstantInt>(C)->getSExtValue() ==
1772 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1773 TrueBB = LHSR.first->BB;
1775 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1776 CurMF->insert(BBI, TrueBB);
1777 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1780 // Similar to the optimization above, if the Value being switched on is
1781 // known to be less than the Constant CR.LT, and the current Case Value
1782 // is CR.LT - 1, then we can branch directly to the target block for
1783 // the current Case Value, rather than emitting a RHS leaf node for it.
1784 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1785 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1786 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1787 FalseBB = RHSR.first->BB;
1789 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1790 CurMF->insert(BBI, FalseBB);
1791 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1794 // Create a CaseBlock record representing a conditional branch to
1795 // the LHS node if the value being switched on SV is less than C.
1796 // Otherwise, branch to LHS.
1797 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1799 if (CR.CaseBB == CurMBB)
1800 visitSwitchCase(CB);
1802 SwitchCases.push_back(CB);
1807 /// handleBitTestsSwitchCase - if current case range has few destination and
1808 /// range span less, than machine word bitwidth, encode case range into series
1809 /// of masks and emit bit tests with these masks.
1810 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1811 CaseRecVector& WorkList,
1813 MachineBasicBlock* Default){
1814 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1816 Case& FrontCase = *CR.Range.first;
1817 Case& BackCase = *(CR.Range.second-1);
1819 // Get the MachineFunction which holds the current MBB. This is used when
1820 // inserting any additional MBBs necessary to represent the switch.
1821 MachineFunction *CurMF = CurMBB->getParent();
1823 unsigned numCmps = 0;
1824 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1826 // Single case counts one, case range - two.
1827 if (I->Low == I->High)
1833 // Count unique destinations
1834 SmallSet<MachineBasicBlock*, 4> Dests;
1835 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1836 Dests.insert(I->BB);
1837 if (Dests.size() > 3)
1838 // Don't bother the code below, if there are too much unique destinations
1841 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1842 << "Total number of comparisons: " << numCmps << "\n";
1844 // Compute span of values.
1845 Constant* minValue = FrontCase.Low;
1846 Constant* maxValue = BackCase.High;
1847 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1848 cast<ConstantInt>(minValue)->getSExtValue();
1849 DOUT << "Compare range: " << range << "\n"
1850 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1851 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1853 if (range>=IntPtrBits ||
1854 (!(Dests.size() == 1 && numCmps >= 3) &&
1855 !(Dests.size() == 2 && numCmps >= 5) &&
1856 !(Dests.size() >= 3 && numCmps >= 6)))
1859 DOUT << "Emitting bit tests\n";
1860 int64_t lowBound = 0;
1862 // Optimize the case where all the case values fit in a
1863 // word without having to subtract minValue. In this case,
1864 // we can optimize away the subtraction.
1865 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1866 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1867 range = cast<ConstantInt>(maxValue)->getSExtValue();
1869 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1872 CaseBitsVector CasesBits;
1873 unsigned i, count = 0;
1875 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1876 MachineBasicBlock* Dest = I->BB;
1877 for (i = 0; i < count; ++i)
1878 if (Dest == CasesBits[i].BB)
1882 assert((count < 3) && "Too much destinations to test!");
1883 CasesBits.push_back(CaseBits(0, Dest, 0));
1887 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1888 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1890 for (uint64_t j = lo; j <= hi; j++) {
1891 CasesBits[i].Mask |= 1ULL << j;
1892 CasesBits[i].Bits++;
1896 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1900 // Figure out which block is immediately after the current one.
1901 MachineFunction::iterator BBI = CR.CaseBB;
1904 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1907 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1908 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1909 << ", BB: " << CasesBits[i].BB << "\n";
1911 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1912 CurMF->insert(BBI, CaseBB);
1913 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1918 BitTestBlock BTB(lowBound, range, SV,
1919 -1U, (CR.CaseBB == CurMBB),
1920 CR.CaseBB, Default, BTC);
1922 if (CR.CaseBB == CurMBB)
1923 visitBitTestHeader(BTB);
1925 BitTestCases.push_back(BTB);
1931 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1932 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1933 const SwitchInst& SI) {
1934 unsigned numCmps = 0;
1936 // Start with "simple" cases
1937 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1938 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1939 Cases.push_back(Case(SI.getSuccessorValue(i),
1940 SI.getSuccessorValue(i),
1943 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1945 // Merge case into clusters
1946 if (Cases.size()>=2)
1947 // Must recompute end() each iteration because it may be
1948 // invalidated by erase if we hold on to it
1949 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1950 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1951 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1952 MachineBasicBlock* nextBB = J->BB;
1953 MachineBasicBlock* currentBB = I->BB;
1955 // If the two neighboring cases go to the same destination, merge them
1956 // into a single case.
1957 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1965 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1966 if (I->Low != I->High)
1967 // A range counts double, since it requires two compares.
1974 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1975 // Figure out which block is immediately after the current one.
1976 MachineBasicBlock *NextBlock = 0;
1977 MachineFunction::iterator BBI = CurMBB;
1979 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1981 // If there is only the default destination, branch to it if it is not the
1982 // next basic block. Otherwise, just fall through.
1983 if (SI.getNumOperands() == 2) {
1984 // Update machine-CFG edges.
1986 // If this is not a fall-through branch, emit the branch.
1987 CurMBB->addSuccessor(Default);
1988 if (Default != NextBlock)
1989 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1990 DAG.getBasicBlock(Default)));
1995 // If there are any non-default case statements, create a vector of Cases
1996 // representing each one, and sort the vector so that we can efficiently
1997 // create a binary search tree from them.
1999 unsigned numCmps = Clusterify(Cases, SI);
2000 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2001 << ". Total compares: " << numCmps << "\n";
2003 // Get the Value to be switched on and default basic blocks, which will be
2004 // inserted into CaseBlock records, representing basic blocks in the binary
2006 Value *SV = SI.getOperand(0);
2008 // Push the initial CaseRec onto the worklist
2009 CaseRecVector WorkList;
2010 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2012 while (!WorkList.empty()) {
2013 // Grab a record representing a case range to process off the worklist
2014 CaseRec CR = WorkList.back();
2015 WorkList.pop_back();
2017 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2020 // If the range has few cases (two or less) emit a series of specific
2022 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2025 // If the switch has more than 5 blocks, and at least 40% dense, and the
2026 // target supports indirect branches, then emit a jump table rather than
2027 // lowering the switch to a binary tree of conditional branches.
2028 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2031 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2032 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2033 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2038 void SelectionDAGLowering::visitSub(User &I) {
2039 // -0.0 - X --> fneg
2040 const Type *Ty = I.getType();
2041 if (isa<VectorType>(Ty)) {
2042 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2043 const VectorType *DestTy = cast<VectorType>(I.getType());
2044 const Type *ElTy = DestTy->getElementType();
2045 if (ElTy->isFloatingPoint()) {
2046 unsigned VL = DestTy->getNumElements();
2047 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2048 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2050 SDValue Op2 = getValue(I.getOperand(1));
2051 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2057 if (Ty->isFloatingPoint()) {
2058 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2059 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2060 SDValue Op2 = getValue(I.getOperand(1));
2061 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2066 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2069 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2070 SDValue Op1 = getValue(I.getOperand(0));
2071 SDValue Op2 = getValue(I.getOperand(1));
2073 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2076 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2077 SDValue Op1 = getValue(I.getOperand(0));
2078 SDValue Op2 = getValue(I.getOperand(1));
2079 if (!isa<VectorType>(I.getType())) {
2080 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2081 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2082 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2083 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2086 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2089 void SelectionDAGLowering::visitICmp(User &I) {
2090 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2091 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2092 predicate = IC->getPredicate();
2093 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2094 predicate = ICmpInst::Predicate(IC->getPredicate());
2095 SDValue Op1 = getValue(I.getOperand(0));
2096 SDValue Op2 = getValue(I.getOperand(1));
2097 ISD::CondCode Opcode = getICmpCondCode(predicate);
2098 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2101 void SelectionDAGLowering::visitFCmp(User &I) {
2102 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2103 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2104 predicate = FC->getPredicate();
2105 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2106 predicate = FCmpInst::Predicate(FC->getPredicate());
2107 SDValue Op1 = getValue(I.getOperand(0));
2108 SDValue Op2 = getValue(I.getOperand(1));
2109 ISD::CondCode Condition = getFCmpCondCode(predicate);
2110 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2113 void SelectionDAGLowering::visitVICmp(User &I) {
2114 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2115 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2116 predicate = IC->getPredicate();
2117 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2118 predicate = ICmpInst::Predicate(IC->getPredicate());
2119 SDValue Op1 = getValue(I.getOperand(0));
2120 SDValue Op2 = getValue(I.getOperand(1));
2121 ISD::CondCode Opcode = getICmpCondCode(predicate);
2122 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2125 void SelectionDAGLowering::visitVFCmp(User &I) {
2126 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2127 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2128 predicate = FC->getPredicate();
2129 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2130 predicate = FCmpInst::Predicate(FC->getPredicate());
2131 SDValue Op1 = getValue(I.getOperand(0));
2132 SDValue Op2 = getValue(I.getOperand(1));
2133 ISD::CondCode Condition = getFCmpCondCode(predicate);
2134 MVT DestVT = TLI.getValueType(I.getType());
2136 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2139 void SelectionDAGLowering::visitSelect(User &I) {
2140 SDValue Cond = getValue(I.getOperand(0));
2141 SDValue TrueVal = getValue(I.getOperand(1));
2142 SDValue FalseVal = getValue(I.getOperand(2));
2143 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2144 TrueVal, FalseVal));
2148 void SelectionDAGLowering::visitTrunc(User &I) {
2149 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2150 SDValue N = getValue(I.getOperand(0));
2151 MVT DestVT = TLI.getValueType(I.getType());
2152 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2155 void SelectionDAGLowering::visitZExt(User &I) {
2156 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2157 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2158 SDValue N = getValue(I.getOperand(0));
2159 MVT DestVT = TLI.getValueType(I.getType());
2160 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2163 void SelectionDAGLowering::visitSExt(User &I) {
2164 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2165 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2166 SDValue N = getValue(I.getOperand(0));
2167 MVT DestVT = TLI.getValueType(I.getType());
2168 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2171 void SelectionDAGLowering::visitFPTrunc(User &I) {
2172 // FPTrunc is never a no-op cast, no need to check
2173 SDValue N = getValue(I.getOperand(0));
2174 MVT DestVT = TLI.getValueType(I.getType());
2175 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2178 void SelectionDAGLowering::visitFPExt(User &I){
2179 // FPTrunc is never a no-op cast, no need to check
2180 SDValue N = getValue(I.getOperand(0));
2181 MVT DestVT = TLI.getValueType(I.getType());
2182 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2185 void SelectionDAGLowering::visitFPToUI(User &I) {
2186 // FPToUI is never a no-op cast, no need to check
2187 SDValue N = getValue(I.getOperand(0));
2188 MVT DestVT = TLI.getValueType(I.getType());
2189 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2192 void SelectionDAGLowering::visitFPToSI(User &I) {
2193 // FPToSI is never a no-op cast, no need to check
2194 SDValue N = getValue(I.getOperand(0));
2195 MVT DestVT = TLI.getValueType(I.getType());
2196 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2199 void SelectionDAGLowering::visitUIToFP(User &I) {
2200 // UIToFP is never a no-op cast, no need to check
2201 SDValue N = getValue(I.getOperand(0));
2202 MVT DestVT = TLI.getValueType(I.getType());
2203 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2206 void SelectionDAGLowering::visitSIToFP(User &I){
2207 // SIToFP is never a no-op cast, no need to check
2208 SDValue N = getValue(I.getOperand(0));
2209 MVT DestVT = TLI.getValueType(I.getType());
2210 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2213 void SelectionDAGLowering::visitPtrToInt(User &I) {
2214 // What to do depends on the size of the integer and the size of the pointer.
2215 // We can either truncate, zero extend, or no-op, accordingly.
2216 SDValue N = getValue(I.getOperand(0));
2217 MVT SrcVT = N.getValueType();
2218 MVT DestVT = TLI.getValueType(I.getType());
2220 if (DestVT.bitsLT(SrcVT))
2221 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2223 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2224 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2225 setValue(&I, Result);
2228 void SelectionDAGLowering::visitIntToPtr(User &I) {
2229 // What to do depends on the size of the integer and the size of the pointer.
2230 // We can either truncate, zero extend, or no-op, accordingly.
2231 SDValue N = getValue(I.getOperand(0));
2232 MVT SrcVT = N.getValueType();
2233 MVT DestVT = TLI.getValueType(I.getType());
2234 if (DestVT.bitsLT(SrcVT))
2235 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2237 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2238 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2241 void SelectionDAGLowering::visitBitCast(User &I) {
2242 SDValue N = getValue(I.getOperand(0));
2243 MVT DestVT = TLI.getValueType(I.getType());
2245 // BitCast assures us that source and destination are the same size so this
2246 // is either a BIT_CONVERT or a no-op.
2247 if (DestVT != N.getValueType())
2248 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2250 setValue(&I, N); // noop cast.
2253 void SelectionDAGLowering::visitInsertElement(User &I) {
2254 SDValue InVec = getValue(I.getOperand(0));
2255 SDValue InVal = getValue(I.getOperand(1));
2256 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2257 getValue(I.getOperand(2)));
2259 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2260 TLI.getValueType(I.getType()),
2261 InVec, InVal, InIdx));
2264 void SelectionDAGLowering::visitExtractElement(User &I) {
2265 SDValue InVec = getValue(I.getOperand(0));
2266 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2267 getValue(I.getOperand(1)));
2268 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2269 TLI.getValueType(I.getType()), InVec, InIdx));
2272 void SelectionDAGLowering::visitShuffleVector(User &I) {
2273 SDValue V1 = getValue(I.getOperand(0));
2274 SDValue V2 = getValue(I.getOperand(1));
2275 SDValue Mask = getValue(I.getOperand(2));
2277 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2278 TLI.getValueType(I.getType()),
2282 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2283 const Value *Op0 = I.getOperand(0);
2284 const Value *Op1 = I.getOperand(1);
2285 const Type *AggTy = I.getType();
2286 const Type *ValTy = Op1->getType();
2287 bool IntoUndef = isa<UndefValue>(Op0);
2288 bool FromUndef = isa<UndefValue>(Op1);
2290 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2291 I.idx_begin(), I.idx_end());
2293 SmallVector<MVT, 4> AggValueVTs;
2294 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2295 SmallVector<MVT, 4> ValValueVTs;
2296 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2298 unsigned NumAggValues = AggValueVTs.size();
2299 unsigned NumValValues = ValValueVTs.size();
2300 SmallVector<SDValue, 4> Values(NumAggValues);
2302 SDValue Agg = getValue(Op0);
2303 SDValue Val = getValue(Op1);
2305 // Copy the beginning value(s) from the original aggregate.
2306 for (; i != LinearIndex; ++i)
2307 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2308 SDValue(Agg.getNode(), Agg.getResNo() + i);
2309 // Copy values from the inserted value(s).
2310 for (; i != LinearIndex + NumValValues; ++i)
2311 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2312 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2313 // Copy remaining value(s) from the original aggregate.
2314 for (; i != NumAggValues; ++i)
2315 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2316 SDValue(Agg.getNode(), Agg.getResNo() + i);
2318 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2319 &Values[0], NumAggValues));
2322 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2323 const Value *Op0 = I.getOperand(0);
2324 const Type *AggTy = Op0->getType();
2325 const Type *ValTy = I.getType();
2326 bool OutOfUndef = isa<UndefValue>(Op0);
2328 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2329 I.idx_begin(), I.idx_end());
2331 SmallVector<MVT, 4> ValValueVTs;
2332 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2334 unsigned NumValValues = ValValueVTs.size();
2335 SmallVector<SDValue, 4> Values(NumValValues);
2337 SDValue Agg = getValue(Op0);
2338 // Copy out the selected value(s).
2339 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2340 Values[i - LinearIndex] =
2341 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2342 SDValue(Agg.getNode(), Agg.getResNo() + i);
2344 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2345 &Values[0], NumValValues));
2349 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2350 SDValue N = getValue(I.getOperand(0));
2351 const Type *Ty = I.getOperand(0)->getType();
2353 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2356 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2357 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2360 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2361 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2362 DAG.getIntPtrConstant(Offset));
2364 Ty = StTy->getElementType(Field);
2366 Ty = cast<SequentialType>(Ty)->getElementType();
2368 // If this is a constant subscript, handle it quickly.
2369 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2370 if (CI->getZExtValue() == 0) continue;
2372 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2373 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2374 DAG.getIntPtrConstant(Offs));
2378 // N = N + Idx * ElementSize;
2379 uint64_t ElementSize = TD->getABITypeSize(Ty);
2380 SDValue IdxN = getValue(Idx);
2382 // If the index is smaller or larger than intptr_t, truncate or extend
2384 if (IdxN.getValueType().bitsLT(N.getValueType()))
2385 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2386 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2387 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2389 // If this is a multiply by a power of two, turn it into a shl
2390 // immediately. This is a very common case.
2391 if (ElementSize != 1) {
2392 if (isPowerOf2_64(ElementSize)) {
2393 unsigned Amt = Log2_64(ElementSize);
2394 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2395 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2397 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2398 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2402 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2408 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2409 // If this is a fixed sized alloca in the entry block of the function,
2410 // allocate it statically on the stack.
2411 if (FuncInfo.StaticAllocaMap.count(&I))
2412 return; // getValue will auto-populate this.
2414 const Type *Ty = I.getAllocatedType();
2415 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2417 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2420 SDValue AllocSize = getValue(I.getArraySize());
2421 MVT IntPtr = TLI.getPointerTy();
2422 if (IntPtr.bitsLT(AllocSize.getValueType()))
2423 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2424 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2425 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2427 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2428 DAG.getIntPtrConstant(TySize));
2430 // Handle alignment. If the requested alignment is less than or equal to
2431 // the stack alignment, ignore it. If the size is greater than or equal to
2432 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2433 unsigned StackAlign =
2434 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2435 if (Align <= StackAlign)
2438 // Round the size of the allocation up to the stack alignment size
2439 // by add SA-1 to the size.
2440 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2441 DAG.getIntPtrConstant(StackAlign-1));
2442 // Mask out the low bits for alignment purposes.
2443 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2444 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2446 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2447 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2449 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2451 DAG.setRoot(DSA.getValue(1));
2453 // Inform the Frame Information that we have just allocated a variable-sized
2455 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2458 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2459 const Value *SV = I.getOperand(0);
2460 SDValue Ptr = getValue(SV);
2462 const Type *Ty = I.getType();
2463 bool isVolatile = I.isVolatile();
2464 unsigned Alignment = I.getAlignment();
2466 SmallVector<MVT, 4> ValueVTs;
2467 SmallVector<uint64_t, 4> Offsets;
2468 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2469 unsigned NumValues = ValueVTs.size();
2474 bool ConstantMemory = false;
2476 // Serialize volatile loads with other side effects.
2478 else if (AA->pointsToConstantMemory(SV)) {
2479 // Do not serialize (non-volatile) loads of constant memory with anything.
2480 Root = DAG.getEntryNode();
2481 ConstantMemory = true;
2483 // Do not serialize non-volatile loads against each other.
2484 Root = DAG.getRoot();
2487 SmallVector<SDValue, 4> Values(NumValues);
2488 SmallVector<SDValue, 4> Chains(NumValues);
2489 MVT PtrVT = Ptr.getValueType();
2490 for (unsigned i = 0; i != NumValues; ++i) {
2491 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2492 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2493 DAG.getConstant(Offsets[i], PtrVT)),
2495 isVolatile, Alignment);
2497 Chains[i] = L.getValue(1);
2500 if (!ConstantMemory) {
2501 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2502 &Chains[0], NumValues);
2506 PendingLoads.push_back(Chain);
2509 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2510 &Values[0], NumValues));
2514 void SelectionDAGLowering::visitStore(StoreInst &I) {
2515 Value *SrcV = I.getOperand(0);
2516 Value *PtrV = I.getOperand(1);
2518 SmallVector<MVT, 4> ValueVTs;
2519 SmallVector<uint64_t, 4> Offsets;
2520 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2521 unsigned NumValues = ValueVTs.size();
2525 // Get the lowered operands. Note that we do this after
2526 // checking if NumResults is zero, because with zero results
2527 // the operands won't have values in the map.
2528 SDValue Src = getValue(SrcV);
2529 SDValue Ptr = getValue(PtrV);
2531 SDValue Root = getRoot();
2532 SmallVector<SDValue, 4> Chains(NumValues);
2533 MVT PtrVT = Ptr.getValueType();
2534 bool isVolatile = I.isVolatile();
2535 unsigned Alignment = I.getAlignment();
2536 for (unsigned i = 0; i != NumValues; ++i)
2537 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2538 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2539 DAG.getConstant(Offsets[i], PtrVT)),
2541 isVolatile, Alignment);
2543 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2546 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2548 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2549 unsigned Intrinsic) {
2550 bool HasChain = !I.doesNotAccessMemory();
2551 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2553 // Build the operand list.
2554 SmallVector<SDValue, 8> Ops;
2555 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2557 // We don't need to serialize loads against other loads.
2558 Ops.push_back(DAG.getRoot());
2560 Ops.push_back(getRoot());
2564 // Add the intrinsic ID as an integer operand.
2565 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2567 // Add all operands of the call to the operand list.
2568 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2569 SDValue Op = getValue(I.getOperand(i));
2570 assert(TLI.isTypeLegal(Op.getValueType()) &&
2571 "Intrinsic uses a non-legal type?");
2575 std::vector<MVT> VTs;
2576 if (I.getType() != Type::VoidTy) {
2577 MVT VT = TLI.getValueType(I.getType());
2578 if (VT.isVector()) {
2579 const VectorType *DestTy = cast<VectorType>(I.getType());
2580 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2582 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2583 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2586 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2590 VTs.push_back(MVT::Other);
2592 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2597 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2598 &Ops[0], Ops.size());
2599 else if (I.getType() != Type::VoidTy)
2600 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2601 &Ops[0], Ops.size());
2603 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2604 &Ops[0], Ops.size());
2607 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2609 PendingLoads.push_back(Chain);
2613 if (I.getType() != Type::VoidTy) {
2614 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2615 MVT VT = TLI.getValueType(PTy);
2616 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2618 setValue(&I, Result);
2622 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2623 static GlobalVariable *ExtractTypeInfo(Value *V) {
2624 V = V->stripPointerCasts();
2625 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2626 assert ((GV || isa<ConstantPointerNull>(V)) &&
2627 "TypeInfo must be a global variable or NULL");
2633 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2634 /// call, and add them to the specified machine basic block.
2635 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2636 MachineBasicBlock *MBB) {
2637 // Inform the MachineModuleInfo of the personality for this landing pad.
2638 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2639 assert(CE->getOpcode() == Instruction::BitCast &&
2640 isa<Function>(CE->getOperand(0)) &&
2641 "Personality should be a function");
2642 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2644 // Gather all the type infos for this landing pad and pass them along to
2645 // MachineModuleInfo.
2646 std::vector<GlobalVariable *> TyInfo;
2647 unsigned N = I.getNumOperands();
2649 for (unsigned i = N - 1; i > 2; --i) {
2650 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2651 unsigned FilterLength = CI->getZExtValue();
2652 unsigned FirstCatch = i + FilterLength + !FilterLength;
2653 assert (FirstCatch <= N && "Invalid filter length");
2655 if (FirstCatch < N) {
2656 TyInfo.reserve(N - FirstCatch);
2657 for (unsigned j = FirstCatch; j < N; ++j)
2658 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2659 MMI->addCatchTypeInfo(MBB, TyInfo);
2663 if (!FilterLength) {
2665 MMI->addCleanup(MBB);
2668 TyInfo.reserve(FilterLength - 1);
2669 for (unsigned j = i + 1; j < FirstCatch; ++j)
2670 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2671 MMI->addFilterTypeInfo(MBB, TyInfo);
2680 TyInfo.reserve(N - 3);
2681 for (unsigned j = 3; j < N; ++j)
2682 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2683 MMI->addCatchTypeInfo(MBB, TyInfo);
2689 /// GetSignificand - Get the significand and build it into a floating-point
2690 /// number with exponent of 1:
2692 /// Op = (Op & 0x007fffff) | 0x3f800000;
2694 /// where Op is the hexidecimal representation of floating point value.
2696 GetSignificand(SelectionDAG &DAG, SDValue Op) {
2697 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2698 DAG.getConstant(0x007fffff, MVT::i32));
2699 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2700 DAG.getConstant(0x3f800000, MVT::i32));
2701 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2704 /// GetExponent - Get the exponent:
2706 /// (float)((Op1 >> 23) - 127);
2708 /// where Op is the hexidecimal representation of floating point value.
2710 GetExponent(SelectionDAG &DAG, SDValue Op) {
2711 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
2712 DAG.getConstant(23, MVT::i32));
2713 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2714 DAG.getConstant(127, MVT::i32));
2715 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
2718 /// getF32Constant - Get 32-bit floating point constant.
2720 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2721 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2724 /// Inlined utility function to implement binary input atomic intrinsics for
2725 /// visitIntrinsicCall: I is a call instruction
2726 /// Op is the associated NodeType for I
2728 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2729 SDValue Root = getRoot();
2730 SDValue L = DAG.getAtomic(Op, Root,
2731 getValue(I.getOperand(1)),
2732 getValue(I.getOperand(2)),
2735 DAG.setRoot(L.getValue(1));
2739 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2740 /// limited-precision mode.
2742 SelectionDAGLowering::visitExp(CallInst &I) {
2745 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2746 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2747 SDValue Op = getValue(I.getOperand(1));
2749 // Put the exponent in the right bit position for later addition to the
2752 // #define LOG2OFe 1.4426950f
2753 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2754 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
2755 getF32Constant(DAG, 0x3fb8aa3b));
2756 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
2758 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2759 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
2760 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
2762 // IntegerPartOfX <<= 23;
2763 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
2764 DAG.getConstant(23, MVT::i32));
2766 if (LimitFloatPrecision <= 6) {
2767 // For floating-point precision of 6:
2769 // TwoToFractionalPartOfX =
2771 // (0.735607626f + 0.252464424f * x) * x;
2773 // error 0.0144103317, which is 6 bits
2774 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2775 getF32Constant(DAG, 0x3e814304));
2776 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2777 getF32Constant(DAG, 0x3f3c50c8));
2778 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2779 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2780 getF32Constant(DAG, 0x3f7f5e7e));
2781 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
2783 // Add the exponent into the result in integer domain.
2784 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
2785 TwoToFracPartOfX, IntegerPartOfX);
2787 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
2788 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2789 // For floating-point precision of 12:
2791 // TwoToFractionalPartOfX =
2794 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
2796 // 0.000107046256 error, which is 13 to 14 bits
2797 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2798 getF32Constant(DAG, 0x3da235e3));
2799 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2800 getF32Constant(DAG, 0x3e65b8f3));
2801 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2802 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2803 getF32Constant(DAG, 0x3f324b07));
2804 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2805 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
2806 getF32Constant(DAG, 0x3f7ff8fd));
2807 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
2809 // Add the exponent into the result in integer domain.
2810 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
2811 TwoToFracPartOfX, IntegerPartOfX);
2813 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
2814 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2815 // For floating-point precision of 18:
2817 // TwoToFractionalPartOfX =
2821 // (0.554906021e-1f +
2822 // (0.961591928e-2f +
2823 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
2825 // error 2.47208000*10^(-7), which is better than 18 bits
2826 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2827 getF32Constant(DAG, 0x3924b03e));
2828 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2829 getF32Constant(DAG, 0x3ab24b87));
2830 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2831 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2832 getF32Constant(DAG, 0x3c1d8c17));
2833 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2834 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
2835 getF32Constant(DAG, 0x3d634a1d));
2836 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2837 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
2838 getF32Constant(DAG, 0x3e75fe14));
2839 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2840 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
2841 getF32Constant(DAG, 0x3f317234));
2842 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
2843 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
2844 getF32Constant(DAG, 0x3f800000));
2845 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
2847 // Add the exponent into the result in integer domain.
2848 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
2849 TwoToFracPartOfX, IntegerPartOfX);
2851 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
2854 // No special expansion.
2855 result = DAG.getNode(ISD::FEXP,
2856 getValue(I.getOperand(1)).getValueType(),
2857 getValue(I.getOperand(1)));
2860 setValue(&I, result);
2863 /// visitLog - Lower a log intrinsic. Handles the special sequences for
2864 /// limited-precision mode.
2866 SelectionDAGLowering::visitLog(CallInst &I) {
2869 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2870 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2871 SDValue Op = getValue(I.getOperand(1));
2872 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2874 // Scale the exponent by log(2) [0.69314718f].
2875 SDValue Exp = GetExponent(DAG, Op1);
2876 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
2877 getF32Constant(DAG, 0x3f317218));
2879 // Get the significand and build it into a floating-point number with
2881 SDValue X = GetSignificand(DAG, Op1);
2883 if (LimitFloatPrecision <= 6) {
2884 // For floating-point precision of 6:
2888 // (1.4034025f - 0.23903021f * x) * x;
2890 // error 0.0034276066, which is better than 8 bits
2891 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2892 getF32Constant(DAG, 0xbe74c456));
2893 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2894 getF32Constant(DAG, 0x3fb3a2b1));
2895 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2896 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2897 getF32Constant(DAG, 0x3f949a29));
2899 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2900 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2901 // For floating-point precision of 12:
2907 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
2909 // error 0.000061011436, which is 14 bits
2910 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2911 getF32Constant(DAG, 0xbd67b6d6));
2912 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2913 getF32Constant(DAG, 0x3ee4f4b8));
2914 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2915 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2916 getF32Constant(DAG, 0x3fbc278b));
2917 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2918 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2919 getF32Constant(DAG, 0x40348e95));
2920 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2921 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
2922 getF32Constant(DAG, 0x3fdef31a));
2924 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2925 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2926 // For floating-point precision of 18:
2934 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
2936 // error 0.0000023660568, which is better than 18 bits
2937 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2938 getF32Constant(DAG, 0xbc91e5ac));
2939 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2940 getF32Constant(DAG, 0x3e4350aa));
2941 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2942 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2943 getF32Constant(DAG, 0x3f60d3e3));
2944 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2945 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2946 getF32Constant(DAG, 0x4011cdf0));
2947 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2948 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
2949 getF32Constant(DAG, 0x406cfd1c));
2950 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2951 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
2952 getF32Constant(DAG, 0x408797cb));
2953 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2954 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
2955 getF32Constant(DAG, 0x4006dcab));
2957 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2960 // No special expansion.
2961 result = DAG.getNode(ISD::FLOG,
2962 getValue(I.getOperand(1)).getValueType(),
2963 getValue(I.getOperand(1)));
2966 setValue(&I, result);
2969 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
2970 /// limited-precision mode.
2972 SelectionDAGLowering::visitLog2(CallInst &I) {
2975 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2976 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2977 SDValue Op = getValue(I.getOperand(1));
2978 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2980 // Get the exponent.
2981 SDValue LogOfExponent = GetExponent(DAG, Op1);
2983 // Get the significand and build it into a floating-point number with
2985 SDValue X = GetSignificand(DAG, Op1);
2987 // Different possible minimax approximations of significand in
2988 // floating-point for various degrees of accuracy over [1,2].
2989 if (LimitFloatPrecision <= 6) {
2990 // For floating-point precision of 6:
2992 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
2994 // error 0.0049451742, which is more than 7 bits
2995 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2996 getF32Constant(DAG, 0xbeb08fe0));
2997 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2998 getF32Constant(DAG, 0x40019463));
2999 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3000 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3001 getF32Constant(DAG, 0x3fd6633d));
3003 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3004 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3005 // For floating-point precision of 12:
3011 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3013 // error 0.0000876136000, which is better than 13 bits
3014 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3015 getF32Constant(DAG, 0xbda7262e));
3016 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3017 getF32Constant(DAG, 0x3f25280b));
3018 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3019 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3020 getF32Constant(DAG, 0x4007b923));
3021 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3022 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3023 getF32Constant(DAG, 0x40823e2f));
3024 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3025 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3026 getF32Constant(DAG, 0x4020d29c));
3028 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3029 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3030 // For floating-point precision of 18:
3039 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3041 // error 0.0000018516, which is better than 18 bits
3042 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3043 getF32Constant(DAG, 0xbcd2769e));
3044 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3045 getF32Constant(DAG, 0x3e8ce0b9));
3046 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3047 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3048 getF32Constant(DAG, 0x3fa22ae7));
3049 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3050 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3051 getF32Constant(DAG, 0x40525723));
3052 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3053 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3054 getF32Constant(DAG, 0x40aaf200));
3055 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3056 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3057 getF32Constant(DAG, 0x40c39dad));
3058 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3059 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3060 getF32Constant(DAG, 0x4042902c));
3062 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3065 // No special expansion.
3066 result = DAG.getNode(ISD::FLOG2,
3067 getValue(I.getOperand(1)).getValueType(),
3068 getValue(I.getOperand(1)));
3071 setValue(&I, result);
3074 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3075 /// limited-precision mode.
3077 SelectionDAGLowering::visitLog10(CallInst &I) {
3080 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3081 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3082 SDValue Op = getValue(I.getOperand(1));
3083 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3085 // Scale the exponent by log10(2) [0.30102999f].
3086 SDValue Exp = GetExponent(DAG, Op1);
3087 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
3088 getF32Constant(DAG, 0x3e9a209a));
3090 // Get the significand and build it into a floating-point number with
3092 SDValue X = GetSignificand(DAG, Op1);
3094 if (LimitFloatPrecision <= 6) {
3095 // For floating-point precision of 6:
3097 // Log10ofMantissa =
3099 // (0.60948995f - 0.10380950f * x) * x;
3101 // error 0.0014886165, which is 6 bits
3102 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3103 getF32Constant(DAG, 0xbdd49a13));
3104 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3105 getF32Constant(DAG, 0x3f1c0789));
3106 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3107 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3108 getF32Constant(DAG, 0x3f011300));
3110 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3111 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3112 // For floating-point precision of 12:
3114 // Log10ofMantissa =
3117 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3119 // error 0.00019228036, which is better than 12 bits
3120 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3121 getF32Constant(DAG, 0x3d431f31));
3122 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3123 getF32Constant(DAG, 0x3ea21fb2));
3124 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3125 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3126 getF32Constant(DAG, 0x3f6ae232));
3127 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3128 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3129 getF32Constant(DAG, 0x3f25f7c3));
3131 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3132 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3133 // For floating-point precision of 18:
3135 // Log10ofMantissa =
3140 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3142 // error 0.0000037995730, which is better than 18 bits
3143 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3144 getF32Constant(DAG, 0x3c5d51ce));
3145 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3146 getF32Constant(DAG, 0x3e00685a));
3147 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3148 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3149 getF32Constant(DAG, 0x3efb6798));
3150 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3151 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3152 getF32Constant(DAG, 0x3f88d192));
3153 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3154 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3155 getF32Constant(DAG, 0x3fc4316c));
3156 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3157 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
3158 getF32Constant(DAG, 0x3f57ce70));
3160 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3163 // No special expansion.
3164 result = DAG.getNode(ISD::FLOG10,
3165 getValue(I.getOperand(1)).getValueType(),
3166 getValue(I.getOperand(1)));
3169 setValue(&I, result);
3172 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3173 /// limited-precision mode.
3175 SelectionDAGLowering::visitExp2(CallInst &I) {
3178 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3179 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3180 SDValue Op = getValue(I.getOperand(1));
3182 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3184 // FractionalPartOfX = x - (float)IntegerPartOfX;
3185 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3186 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3188 // IntegerPartOfX <<= 23;
3189 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3190 DAG.getConstant(23, MVT::i32));
3192 if (LimitFloatPrecision <= 6) {
3193 // For floating-point precision of 6:
3195 // TwoToFractionalPartOfX =
3197 // (0.735607626f + 0.252464424f * x) * x;
3199 // error 0.0144103317, which is 6 bits
3200 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3201 getF32Constant(DAG, 0x3e814304));
3202 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3203 getF32Constant(DAG, 0x3f3c50c8));
3204 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3205 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3206 getF32Constant(DAG, 0x3f7f5e7e));
3207 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3208 SDValue TwoToFractionalPartOfX =
3209 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3211 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3212 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3213 // For floating-point precision of 12:
3215 // TwoToFractionalPartOfX =
3218 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3220 // error 0.000107046256, which is 13 to 14 bits
3221 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3222 getF32Constant(DAG, 0x3da235e3));
3223 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3224 getF32Constant(DAG, 0x3e65b8f3));
3225 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3226 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3227 getF32Constant(DAG, 0x3f324b07));
3228 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3229 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3230 getF32Constant(DAG, 0x3f7ff8fd));
3231 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3232 SDValue TwoToFractionalPartOfX =
3233 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3235 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3236 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3237 // For floating-point precision of 18:
3239 // TwoToFractionalPartOfX =
3243 // (0.554906021e-1f +
3244 // (0.961591928e-2f +
3245 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3246 // error 2.47208000*10^(-7), which is better than 18 bits
3247 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3248 getF32Constant(DAG, 0x3924b03e));
3249 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3250 getF32Constant(DAG, 0x3ab24b87));
3251 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3252 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3253 getF32Constant(DAG, 0x3c1d8c17));
3254 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3255 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3256 getF32Constant(DAG, 0x3d634a1d));
3257 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3258 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3259 getF32Constant(DAG, 0x3e75fe14));
3260 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3261 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3262 getF32Constant(DAG, 0x3f317234));
3263 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3264 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3265 getF32Constant(DAG, 0x3f800000));
3266 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3267 SDValue TwoToFractionalPartOfX =
3268 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3270 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3273 // No special expansion.
3274 result = DAG.getNode(ISD::FEXP2,
3275 getValue(I.getOperand(1)).getValueType(),
3276 getValue(I.getOperand(1)));
3279 setValue(&I, result);
3282 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3283 /// limited-precision mode with x == 10.0f.
3285 SelectionDAGLowering::visitPow(CallInst &I) {
3287 Value *Val = I.getOperand(1);
3288 bool IsExp10 = false;
3290 if (getValue(Val).getValueType() == MVT::f32 &&
3291 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3292 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3293 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3294 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3296 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3301 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3302 SDValue Op = getValue(I.getOperand(2));
3304 // Put the exponent in the right bit position for later addition to the
3307 // #define LOG2OF10 3.3219281f
3308 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3309 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
3310 getF32Constant(DAG, 0x40549a78));
3311 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3313 // FractionalPartOfX = x - (float)IntegerPartOfX;
3314 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3315 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3317 // IntegerPartOfX <<= 23;
3318 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3319 DAG.getConstant(23, MVT::i32));
3321 if (LimitFloatPrecision <= 6) {
3322 // For floating-point precision of 6:
3324 // twoToFractionalPartOfX =
3326 // (0.735607626f + 0.252464424f * x) * x;
3328 // error 0.0144103317, which is 6 bits
3329 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3330 getF32Constant(DAG, 0x3e814304));
3331 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3332 getF32Constant(DAG, 0x3f3c50c8));
3333 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3334 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3335 getF32Constant(DAG, 0x3f7f5e7e));
3336 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3337 SDValue TwoToFractionalPartOfX =
3338 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3340 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3341 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3342 // For floating-point precision of 12:
3344 // TwoToFractionalPartOfX =
3347 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3349 // error 0.000107046256, which is 13 to 14 bits
3350 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3351 getF32Constant(DAG, 0x3da235e3));
3352 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3353 getF32Constant(DAG, 0x3e65b8f3));
3354 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3355 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3356 getF32Constant(DAG, 0x3f324b07));
3357 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3358 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3359 getF32Constant(DAG, 0x3f7ff8fd));
3360 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3361 SDValue TwoToFractionalPartOfX =
3362 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3364 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3365 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3366 // For floating-point precision of 18:
3368 // TwoToFractionalPartOfX =
3372 // (0.554906021e-1f +
3373 // (0.961591928e-2f +
3374 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3375 // error 2.47208000*10^(-7), which is better than 18 bits
3376 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3377 getF32Constant(DAG, 0x3924b03e));
3378 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3379 getF32Constant(DAG, 0x3ab24b87));
3380 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3381 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3382 getF32Constant(DAG, 0x3c1d8c17));
3383 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3384 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3385 getF32Constant(DAG, 0x3d634a1d));
3386 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3387 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3388 getF32Constant(DAG, 0x3e75fe14));
3389 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3390 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3391 getF32Constant(DAG, 0x3f317234));
3392 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3393 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3394 getF32Constant(DAG, 0x3f800000));
3395 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3396 SDValue TwoToFractionalPartOfX =
3397 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3399 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3402 // No special expansion.
3403 result = DAG.getNode(ISD::FPOW,
3404 getValue(I.getOperand(1)).getValueType(),
3405 getValue(I.getOperand(1)),
3406 getValue(I.getOperand(2)));
3409 setValue(&I, result);
3412 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3413 /// we want to emit this as a call to a named external function, return the name
3414 /// otherwise lower it and return null.
3416 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3417 switch (Intrinsic) {
3419 // By default, turn this into a target intrinsic node.
3420 visitTargetIntrinsic(I, Intrinsic);
3422 case Intrinsic::vastart: visitVAStart(I); return 0;
3423 case Intrinsic::vaend: visitVAEnd(I); return 0;
3424 case Intrinsic::vacopy: visitVACopy(I); return 0;
3425 case Intrinsic::returnaddress:
3426 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3427 getValue(I.getOperand(1))));
3429 case Intrinsic::frameaddress:
3430 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3431 getValue(I.getOperand(1))));
3433 case Intrinsic::setjmp:
3434 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3436 case Intrinsic::longjmp:
3437 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3439 case Intrinsic::memcpy_i32:
3440 case Intrinsic::memcpy_i64: {
3441 SDValue Op1 = getValue(I.getOperand(1));
3442 SDValue Op2 = getValue(I.getOperand(2));
3443 SDValue Op3 = getValue(I.getOperand(3));
3444 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3445 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3446 I.getOperand(1), 0, I.getOperand(2), 0));
3449 case Intrinsic::memset_i32:
3450 case Intrinsic::memset_i64: {
3451 SDValue Op1 = getValue(I.getOperand(1));
3452 SDValue Op2 = getValue(I.getOperand(2));
3453 SDValue Op3 = getValue(I.getOperand(3));
3454 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3455 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3456 I.getOperand(1), 0));
3459 case Intrinsic::memmove_i32:
3460 case Intrinsic::memmove_i64: {
3461 SDValue Op1 = getValue(I.getOperand(1));
3462 SDValue Op2 = getValue(I.getOperand(2));
3463 SDValue Op3 = getValue(I.getOperand(3));
3464 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3466 // If the source and destination are known to not be aliases, we can
3467 // lower memmove as memcpy.
3468 uint64_t Size = -1ULL;
3469 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3470 Size = C->getZExtValue();
3471 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3472 AliasAnalysis::NoAlias) {
3473 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3474 I.getOperand(1), 0, I.getOperand(2), 0));
3478 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3479 I.getOperand(1), 0, I.getOperand(2), 0));
3482 case Intrinsic::dbg_stoppoint: {
3483 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3484 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3485 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3486 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3487 assert(DD && "Not a debug information descriptor");
3488 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3491 cast<CompileUnitDesc>(DD)));
3496 case Intrinsic::dbg_region_start: {
3497 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3498 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3499 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3500 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3501 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3506 case Intrinsic::dbg_region_end: {
3507 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3508 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3509 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3510 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3511 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3516 case Intrinsic::dbg_func_start: {
3517 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3519 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3520 Value *SP = FSI.getSubprogram();
3521 if (SP && MMI->Verify(SP)) {
3522 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3523 // what (most?) gdb expects.
3524 DebugInfoDesc *DD = MMI->getDescFor(SP);
3525 assert(DD && "Not a debug information descriptor");
3526 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3527 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3528 unsigned SrcFile = MMI->RecordSource(CompileUnit);
3529 // Record the source line but does create a label. It will be emitted
3530 // at asm emission time.
3531 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3536 case Intrinsic::dbg_declare: {
3537 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3538 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3539 Value *Variable = DI.getVariable();
3540 if (MMI && Variable && MMI->Verify(Variable))
3541 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3542 getValue(DI.getAddress()), getValue(Variable)));
3546 case Intrinsic::eh_exception: {
3547 if (!CurMBB->isLandingPad()) {
3548 // FIXME: Mark exception register as live in. Hack for PR1508.
3549 unsigned Reg = TLI.getExceptionAddressRegister();
3550 if (Reg) CurMBB->addLiveIn(Reg);
3552 // Insert the EXCEPTIONADDR instruction.
3553 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3555 Ops[0] = DAG.getRoot();
3556 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3558 DAG.setRoot(Op.getValue(1));
3562 case Intrinsic::eh_selector_i32:
3563 case Intrinsic::eh_selector_i64: {
3564 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3565 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3566 MVT::i32 : MVT::i64);
3569 if (CurMBB->isLandingPad())
3570 AddCatchInfo(I, MMI, CurMBB);
3573 FuncInfo.CatchInfoLost.insert(&I);
3575 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3576 unsigned Reg = TLI.getExceptionSelectorRegister();
3577 if (Reg) CurMBB->addLiveIn(Reg);
3580 // Insert the EHSELECTION instruction.
3581 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3583 Ops[0] = getValue(I.getOperand(1));
3585 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3587 DAG.setRoot(Op.getValue(1));
3589 setValue(&I, DAG.getConstant(0, VT));
3595 case Intrinsic::eh_typeid_for_i32:
3596 case Intrinsic::eh_typeid_for_i64: {
3597 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3598 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3599 MVT::i32 : MVT::i64);
3602 // Find the type id for the given typeinfo.
3603 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3605 unsigned TypeID = MMI->getTypeIDFor(GV);
3606 setValue(&I, DAG.getConstant(TypeID, VT));
3608 // Return something different to eh_selector.
3609 setValue(&I, DAG.getConstant(1, VT));
3615 case Intrinsic::eh_return_i32:
3616 case Intrinsic::eh_return_i64:
3617 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3618 MMI->setCallsEHReturn(true);
3619 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3622 getValue(I.getOperand(1)),
3623 getValue(I.getOperand(2))));
3625 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3629 case Intrinsic::eh_unwind_init:
3630 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3631 MMI->setCallsUnwindInit(true);
3636 case Intrinsic::eh_dwarf_cfa: {
3637 MVT VT = getValue(I.getOperand(1)).getValueType();
3639 if (VT.bitsGT(TLI.getPointerTy()))
3640 CfaArg = DAG.getNode(ISD::TRUNCATE,
3641 TLI.getPointerTy(), getValue(I.getOperand(1)));
3643 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3644 TLI.getPointerTy(), getValue(I.getOperand(1)));
3646 SDValue Offset = DAG.getNode(ISD::ADD,
3648 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3649 TLI.getPointerTy()),
3651 setValue(&I, DAG.getNode(ISD::ADD,
3653 DAG.getNode(ISD::FRAMEADDR,
3656 TLI.getPointerTy())),
3661 case Intrinsic::sqrt:
3662 setValue(&I, DAG.getNode(ISD::FSQRT,
3663 getValue(I.getOperand(1)).getValueType(),
3664 getValue(I.getOperand(1))));
3666 case Intrinsic::powi:
3667 setValue(&I, DAG.getNode(ISD::FPOWI,
3668 getValue(I.getOperand(1)).getValueType(),
3669 getValue(I.getOperand(1)),
3670 getValue(I.getOperand(2))));
3672 case Intrinsic::sin:
3673 setValue(&I, DAG.getNode(ISD::FSIN,
3674 getValue(I.getOperand(1)).getValueType(),
3675 getValue(I.getOperand(1))));
3677 case Intrinsic::cos:
3678 setValue(&I, DAG.getNode(ISD::FCOS,
3679 getValue(I.getOperand(1)).getValueType(),
3680 getValue(I.getOperand(1))));
3682 case Intrinsic::log:
3685 case Intrinsic::log2:
3688 case Intrinsic::log10:
3691 case Intrinsic::exp:
3694 case Intrinsic::exp2:
3697 case Intrinsic::pow:
3700 case Intrinsic::pcmarker: {
3701 SDValue Tmp = getValue(I.getOperand(1));
3702 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3705 case Intrinsic::readcyclecounter: {
3706 SDValue Op = getRoot();
3707 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3708 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3711 DAG.setRoot(Tmp.getValue(1));
3714 case Intrinsic::part_select: {
3715 // Currently not implemented: just abort
3716 assert(0 && "part_select intrinsic not implemented");
3719 case Intrinsic::part_set: {
3720 // Currently not implemented: just abort
3721 assert(0 && "part_set intrinsic not implemented");
3724 case Intrinsic::bswap:
3725 setValue(&I, DAG.getNode(ISD::BSWAP,
3726 getValue(I.getOperand(1)).getValueType(),
3727 getValue(I.getOperand(1))));
3729 case Intrinsic::cttz: {
3730 SDValue Arg = getValue(I.getOperand(1));
3731 MVT Ty = Arg.getValueType();
3732 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3733 setValue(&I, result);
3736 case Intrinsic::ctlz: {
3737 SDValue Arg = getValue(I.getOperand(1));
3738 MVT Ty = Arg.getValueType();
3739 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3740 setValue(&I, result);
3743 case Intrinsic::ctpop: {
3744 SDValue Arg = getValue(I.getOperand(1));
3745 MVT Ty = Arg.getValueType();
3746 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3747 setValue(&I, result);
3750 case Intrinsic::stacksave: {
3751 SDValue Op = getRoot();
3752 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3753 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3755 DAG.setRoot(Tmp.getValue(1));
3758 case Intrinsic::stackrestore: {
3759 SDValue Tmp = getValue(I.getOperand(1));
3760 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3763 case Intrinsic::var_annotation:
3764 // Discard annotate attributes
3767 case Intrinsic::init_trampoline: {
3768 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3772 Ops[1] = getValue(I.getOperand(1));
3773 Ops[2] = getValue(I.getOperand(2));
3774 Ops[3] = getValue(I.getOperand(3));
3775 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3776 Ops[5] = DAG.getSrcValue(F);
3778 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3779 DAG.getNodeValueTypes(TLI.getPointerTy(),
3784 DAG.setRoot(Tmp.getValue(1));
3788 case Intrinsic::gcroot:
3790 Value *Alloca = I.getOperand(1);
3791 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3793 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
3794 GFI->addStackRoot(FI->getIndex(), TypeMap);
3798 case Intrinsic::gcread:
3799 case Intrinsic::gcwrite:
3800 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3803 case Intrinsic::flt_rounds: {
3804 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3808 case Intrinsic::trap: {
3809 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3812 case Intrinsic::prefetch: {
3815 Ops[1] = getValue(I.getOperand(1));
3816 Ops[2] = getValue(I.getOperand(2));
3817 Ops[3] = getValue(I.getOperand(3));
3818 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3822 case Intrinsic::memory_barrier: {
3825 for (int x = 1; x < 6; ++x)
3826 Ops[x] = getValue(I.getOperand(x));
3828 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3831 case Intrinsic::atomic_cmp_swap: {
3832 SDValue Root = getRoot();
3834 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3836 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root,
3837 getValue(I.getOperand(1)),
3838 getValue(I.getOperand(2)),
3839 getValue(I.getOperand(3)),
3843 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root,
3844 getValue(I.getOperand(1)),
3845 getValue(I.getOperand(2)),
3846 getValue(I.getOperand(3)),
3850 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root,
3851 getValue(I.getOperand(1)),
3852 getValue(I.getOperand(2)),
3853 getValue(I.getOperand(3)),
3857 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root,
3858 getValue(I.getOperand(1)),
3859 getValue(I.getOperand(2)),
3860 getValue(I.getOperand(3)),
3864 assert(0 && "Invalid atomic type");
3868 DAG.setRoot(L.getValue(1));
3871 case Intrinsic::atomic_load_add:
3872 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3874 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3876 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3878 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3880 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3882 assert(0 && "Invalid atomic type");
3885 case Intrinsic::atomic_load_sub:
3886 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3888 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3890 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3892 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3894 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3896 assert(0 && "Invalid atomic type");
3899 case Intrinsic::atomic_load_or:
3900 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3902 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3904 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3906 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3908 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3910 assert(0 && "Invalid atomic type");
3913 case Intrinsic::atomic_load_xor:
3914 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3916 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3918 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3920 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3922 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3924 assert(0 && "Invalid atomic type");
3927 case Intrinsic::atomic_load_and:
3928 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3930 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3932 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3934 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3936 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3938 assert(0 && "Invalid atomic type");
3941 case Intrinsic::atomic_load_nand:
3942 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3944 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
3946 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
3948 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
3950 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
3952 assert(0 && "Invalid atomic type");
3955 case Intrinsic::atomic_load_max:
3956 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3958 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
3960 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
3962 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
3964 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
3966 assert(0 && "Invalid atomic type");
3969 case Intrinsic::atomic_load_min:
3970 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3972 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
3974 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
3976 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
3978 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
3980 assert(0 && "Invalid atomic type");
3983 case Intrinsic::atomic_load_umin:
3984 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3986 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
3988 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
3990 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
3992 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
3994 assert(0 && "Invalid atomic type");
3997 case Intrinsic::atomic_load_umax:
3998 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4000 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
4002 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
4004 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
4006 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
4008 assert(0 && "Invalid atomic type");
4011 case Intrinsic::atomic_swap:
4012 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4014 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
4016 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
4018 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
4020 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
4022 assert(0 && "Invalid atomic type");
4029 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4031 MachineBasicBlock *LandingPad) {
4032 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4033 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4034 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4035 unsigned BeginLabel = 0, EndLabel = 0;
4037 TargetLowering::ArgListTy Args;
4038 TargetLowering::ArgListEntry Entry;
4039 Args.reserve(CS.arg_size());
4040 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4042 SDValue ArgNode = getValue(*i);
4043 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4045 unsigned attrInd = i - CS.arg_begin() + 1;
4046 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4047 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4048 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4049 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4050 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4051 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4052 Entry.Alignment = CS.getParamAlignment(attrInd);
4053 Args.push_back(Entry);
4056 if (LandingPad && MMI) {
4057 // Insert a label before the invoke call to mark the try range. This can be
4058 // used to detect deletion of the invoke via the MachineModuleInfo.
4059 BeginLabel = MMI->NextLabelID();
4060 // Both PendingLoads and PendingExports must be flushed here;
4061 // this call might not return.
4063 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4066 std::pair<SDValue,SDValue> Result =
4067 TLI.LowerCallTo(getRoot(), CS.getType(),
4068 CS.paramHasAttr(0, Attribute::SExt),
4069 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4070 CS.paramHasAttr(0, Attribute::InReg),
4071 CS.getCallingConv(),
4072 IsTailCall && PerformTailCallOpt,
4074 if (CS.getType() != Type::VoidTy)
4075 setValue(CS.getInstruction(), Result.first);
4076 DAG.setRoot(Result.second);
4078 if (LandingPad && MMI) {
4079 // Insert a label at the end of the invoke call to mark the try range. This
4080 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4081 EndLabel = MMI->NextLabelID();
4082 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4084 // Inform MachineModuleInfo of range.
4085 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4090 void SelectionDAGLowering::visitCall(CallInst &I) {
4091 const char *RenameFn = 0;
4092 if (Function *F = I.getCalledFunction()) {
4093 if (F->isDeclaration()) {
4094 if (unsigned IID = F->getIntrinsicID()) {
4095 RenameFn = visitIntrinsicCall(I, IID);
4101 // Check for well-known libc/libm calls. If the function is internal, it
4102 // can't be a library call.
4103 unsigned NameLen = F->getNameLen();
4104 if (!F->hasInternalLinkage() && NameLen) {
4105 const char *NameStr = F->getNameStart();
4106 if (NameStr[0] == 'c' &&
4107 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4108 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4109 if (I.getNumOperands() == 3 && // Basic sanity checks.
4110 I.getOperand(1)->getType()->isFloatingPoint() &&
4111 I.getType() == I.getOperand(1)->getType() &&
4112 I.getType() == I.getOperand(2)->getType()) {
4113 SDValue LHS = getValue(I.getOperand(1));
4114 SDValue RHS = getValue(I.getOperand(2));
4115 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4119 } else if (NameStr[0] == 'f' &&
4120 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4121 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4122 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4123 if (I.getNumOperands() == 2 && // Basic sanity checks.
4124 I.getOperand(1)->getType()->isFloatingPoint() &&
4125 I.getType() == I.getOperand(1)->getType()) {
4126 SDValue Tmp = getValue(I.getOperand(1));
4127 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4130 } else if (NameStr[0] == 's' &&
4131 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4132 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4133 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4134 if (I.getNumOperands() == 2 && // Basic sanity checks.
4135 I.getOperand(1)->getType()->isFloatingPoint() &&
4136 I.getType() == I.getOperand(1)->getType()) {
4137 SDValue Tmp = getValue(I.getOperand(1));
4138 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4141 } else if (NameStr[0] == 'c' &&
4142 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4143 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4144 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4145 if (I.getNumOperands() == 2 && // Basic sanity checks.
4146 I.getOperand(1)->getType()->isFloatingPoint() &&
4147 I.getType() == I.getOperand(1)->getType()) {
4148 SDValue Tmp = getValue(I.getOperand(1));
4149 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4154 } else if (isa<InlineAsm>(I.getOperand(0))) {
4161 Callee = getValue(I.getOperand(0));
4163 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4165 LowerCallTo(&I, Callee, I.isTailCall());
4169 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4170 /// this value and returns the result as a ValueVT value. This uses
4171 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4172 /// If the Flag pointer is NULL, no flag is used.
4173 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4175 SDValue *Flag) const {
4176 // Assemble the legal parts into the final values.
4177 SmallVector<SDValue, 4> Values(ValueVTs.size());
4178 SmallVector<SDValue, 8> Parts;
4179 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4180 // Copy the legal parts from the registers.
4181 MVT ValueVT = ValueVTs[Value];
4182 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4183 MVT RegisterVT = RegVTs[Value];
4185 Parts.resize(NumRegs);
4186 for (unsigned i = 0; i != NumRegs; ++i) {
4189 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4191 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4192 *Flag = P.getValue(2);
4194 Chain = P.getValue(1);
4196 // If the source register was virtual and if we know something about it,
4197 // add an assert node.
4198 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4199 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4200 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4201 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4202 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4203 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4205 unsigned RegSize = RegisterVT.getSizeInBits();
4206 unsigned NumSignBits = LOI.NumSignBits;
4207 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4209 // FIXME: We capture more information than the dag can represent. For
4210 // now, just use the tightest assertzext/assertsext possible.
4212 MVT FromVT(MVT::Other);
4213 if (NumSignBits == RegSize)
4214 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4215 else if (NumZeroBits >= RegSize-1)
4216 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4217 else if (NumSignBits > RegSize-8)
4218 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4219 else if (NumZeroBits >= RegSize-9)
4220 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4221 else if (NumSignBits > RegSize-16)
4222 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4223 else if (NumZeroBits >= RegSize-17)
4224 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4225 else if (NumSignBits > RegSize-32)
4226 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4227 else if (NumZeroBits >= RegSize-33)
4228 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4230 if (FromVT != MVT::Other) {
4231 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4232 RegisterVT, P, DAG.getValueType(FromVT));
4241 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4247 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4248 &Values[0], ValueVTs.size());
4251 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4252 /// specified value into the registers specified by this object. This uses
4253 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4254 /// If the Flag pointer is NULL, no flag is used.
4255 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4256 SDValue &Chain, SDValue *Flag) const {
4257 // Get the list of the values's legal parts.
4258 unsigned NumRegs = Regs.size();
4259 SmallVector<SDValue, 8> Parts(NumRegs);
4260 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4261 MVT ValueVT = ValueVTs[Value];
4262 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4263 MVT RegisterVT = RegVTs[Value];
4265 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4266 &Parts[Part], NumParts, RegisterVT);
4270 // Copy the parts into the registers.
4271 SmallVector<SDValue, 8> Chains(NumRegs);
4272 for (unsigned i = 0; i != NumRegs; ++i) {
4275 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4277 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4278 *Flag = Part.getValue(1);
4280 Chains[i] = Part.getValue(0);
4283 if (NumRegs == 1 || Flag)
4284 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4285 // flagged to it. That is the CopyToReg nodes and the user are considered
4286 // a single scheduling unit. If we create a TokenFactor and return it as
4287 // chain, then the TokenFactor is both a predecessor (operand) of the
4288 // user as well as a successor (the TF operands are flagged to the user).
4289 // c1, f1 = CopyToReg
4290 // c2, f2 = CopyToReg
4291 // c3 = TokenFactor c1, c2
4294 Chain = Chains[NumRegs-1];
4296 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4299 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4300 /// operand list. This adds the code marker and includes the number of
4301 /// values added into it.
4302 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4303 std::vector<SDValue> &Ops) const {
4304 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4305 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4306 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4307 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4308 MVT RegisterVT = RegVTs[Value];
4309 for (unsigned i = 0; i != NumRegs; ++i) {
4310 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4311 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4316 /// isAllocatableRegister - If the specified register is safe to allocate,
4317 /// i.e. it isn't a stack pointer or some other special register, return the
4318 /// register class for the register. Otherwise, return null.
4319 static const TargetRegisterClass *
4320 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4321 const TargetLowering &TLI,
4322 const TargetRegisterInfo *TRI) {
4323 MVT FoundVT = MVT::Other;
4324 const TargetRegisterClass *FoundRC = 0;
4325 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4326 E = TRI->regclass_end(); RCI != E; ++RCI) {
4327 MVT ThisVT = MVT::Other;
4329 const TargetRegisterClass *RC = *RCI;
4330 // If none of the the value types for this register class are valid, we
4331 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4332 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4334 if (TLI.isTypeLegal(*I)) {
4335 // If we have already found this register in a different register class,
4336 // choose the one with the largest VT specified. For example, on
4337 // PowerPC, we favor f64 register classes over f32.
4338 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4345 if (ThisVT == MVT::Other) continue;
4347 // NOTE: This isn't ideal. In particular, this might allocate the
4348 // frame pointer in functions that need it (due to them not being taken
4349 // out of allocation, because a variable sized allocation hasn't been seen
4350 // yet). This is a slight code pessimization, but should still work.
4351 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4352 E = RC->allocation_order_end(MF); I != E; ++I)
4354 // We found a matching register class. Keep looking at others in case
4355 // we find one with larger registers that this physreg is also in.
4366 /// AsmOperandInfo - This contains information for each constraint that we are
4368 struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4369 public TargetLowering::AsmOperandInfo {
4370 /// CallOperand - If this is the result output operand or a clobber
4371 /// this is null, otherwise it is the incoming operand to the CallInst.
4372 /// This gets modified as the asm is processed.
4373 SDValue CallOperand;
4375 /// AssignedRegs - If this is a register or register class operand, this
4376 /// contains the set of register corresponding to the operand.
4377 RegsForValue AssignedRegs;
4379 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4380 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4383 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4384 /// busy in OutputRegs/InputRegs.
4385 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4386 std::set<unsigned> &OutputRegs,
4387 std::set<unsigned> &InputRegs,
4388 const TargetRegisterInfo &TRI) const {
4390 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4391 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4394 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4395 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4399 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4400 /// corresponds to. If there is no Value* for this operand, it returns
4402 MVT getCallOperandValMVT(const TargetLowering &TLI,
4403 const TargetData *TD) const {
4404 if (CallOperandVal == 0) return MVT::Other;
4406 if (isa<BasicBlock>(CallOperandVal))
4407 return TLI.getPointerTy();
4409 const llvm::Type *OpTy = CallOperandVal->getType();
4411 // If this is an indirect operand, the operand is a pointer to the
4414 OpTy = cast<PointerType>(OpTy)->getElementType();
4416 // If OpTy is not a single value, it may be a struct/union that we
4417 // can tile with integers.
4418 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4419 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4428 OpTy = IntegerType::get(BitSize);
4433 return TLI.getValueType(OpTy, true);
4437 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4439 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4440 const TargetRegisterInfo &TRI) {
4441 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4443 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4444 for (; *Aliases; ++Aliases)
4445 Regs.insert(*Aliases);
4448 } // end llvm namespace.
4451 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4452 /// specified operand. We prefer to assign virtual registers, to allow the
4453 /// register allocator handle the assignment process. However, if the asm uses
4454 /// features that we can't model on machineinstrs, we have SDISel do the
4455 /// allocation. This produces generally horrible, but correct, code.
4457 /// OpInfo describes the operand.
4458 /// Input and OutputRegs are the set of already allocated physical registers.
4460 void SelectionDAGLowering::
4461 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4462 std::set<unsigned> &OutputRegs,
4463 std::set<unsigned> &InputRegs) {
4464 // Compute whether this value requires an input register, an output register,
4466 bool isOutReg = false;
4467 bool isInReg = false;
4468 switch (OpInfo.Type) {
4469 case InlineAsm::isOutput:
4472 // If there is an input constraint that matches this, we need to reserve
4473 // the input register so no other inputs allocate to it.
4474 isInReg = OpInfo.hasMatchingInput();
4476 case InlineAsm::isInput:
4480 case InlineAsm::isClobber:
4487 MachineFunction &MF = DAG.getMachineFunction();
4488 SmallVector<unsigned, 4> Regs;
4490 // If this is a constraint for a single physreg, or a constraint for a
4491 // register class, find it.
4492 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4493 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4494 OpInfo.ConstraintVT);
4496 unsigned NumRegs = 1;
4497 if (OpInfo.ConstraintVT != MVT::Other) {
4498 // If this is a FP input in an integer register (or visa versa) insert a bit
4499 // cast of the input value. More generally, handle any case where the input
4500 // value disagrees with the register class we plan to stick this in.
4501 if (OpInfo.Type == InlineAsm::isInput &&
4502 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4503 // Try to convert to the first MVT that the reg class contains. If the
4504 // types are identical size, use a bitcast to convert (e.g. two differing
4506 MVT RegVT = *PhysReg.second->vt_begin();
4507 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4508 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4509 OpInfo.CallOperand);
4510 OpInfo.ConstraintVT = RegVT;
4511 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4512 // If the input is a FP value and we want it in FP registers, do a
4513 // bitcast to the corresponding integer type. This turns an f64 value
4514 // into i64, which can be passed with two i32 values on a 32-bit
4516 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4517 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4518 OpInfo.CallOperand);
4519 OpInfo.ConstraintVT = RegVT;
4523 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4527 MVT ValueVT = OpInfo.ConstraintVT;
4529 // If this is a constraint for a specific physical register, like {r17},
4531 if (PhysReg.first) {
4532 if (OpInfo.ConstraintVT == MVT::Other)
4533 ValueVT = *PhysReg.second->vt_begin();
4535 // Get the actual register value type. This is important, because the user
4536 // may have asked for (e.g.) the AX register in i32 type. We need to
4537 // remember that AX is actually i16 to get the right extension.
4538 RegVT = *PhysReg.second->vt_begin();
4540 // This is a explicit reference to a physical register.
4541 Regs.push_back(PhysReg.first);
4543 // If this is an expanded reference, add the rest of the regs to Regs.
4545 TargetRegisterClass::iterator I = PhysReg.second->begin();
4546 for (; *I != PhysReg.first; ++I)
4547 assert(I != PhysReg.second->end() && "Didn't find reg!");
4549 // Already added the first reg.
4551 for (; NumRegs; --NumRegs, ++I) {
4552 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4556 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4557 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4558 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4562 // Otherwise, if this was a reference to an LLVM register class, create vregs
4563 // for this reference.
4564 std::vector<unsigned> RegClassRegs;
4565 const TargetRegisterClass *RC = PhysReg.second;
4567 // If this is a tied register, our regalloc doesn't know how to maintain
4568 // the constraint, so we have to pick a register to pin the input/output to.
4569 // If it isn't a matched constraint, go ahead and create vreg and let the
4570 // regalloc do its thing.
4571 if (!OpInfo.hasMatchingInput()) {
4572 RegVT = *PhysReg.second->vt_begin();
4573 if (OpInfo.ConstraintVT == MVT::Other)
4576 // Create the appropriate number of virtual registers.
4577 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4578 for (; NumRegs; --NumRegs)
4579 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4581 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4585 // Otherwise, we can't allocate it. Let the code below figure out how to
4586 // maintain these constraints.
4587 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4590 // This is a reference to a register class that doesn't directly correspond
4591 // to an LLVM register class. Allocate NumRegs consecutive, available,
4592 // registers from the class.
4593 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4594 OpInfo.ConstraintVT);
4597 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4598 unsigned NumAllocated = 0;
4599 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4600 unsigned Reg = RegClassRegs[i];
4601 // See if this register is available.
4602 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4603 (isInReg && InputRegs.count(Reg))) { // Already used.
4604 // Make sure we find consecutive registers.
4609 // Check to see if this register is allocatable (i.e. don't give out the
4612 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4613 if (!RC) { // Couldn't allocate this register.
4614 // Reset NumAllocated to make sure we return consecutive registers.
4620 // Okay, this register is good, we can use it.
4623 // If we allocated enough consecutive registers, succeed.
4624 if (NumAllocated == NumRegs) {
4625 unsigned RegStart = (i-NumAllocated)+1;
4626 unsigned RegEnd = i+1;
4627 // Mark all of the allocated registers used.
4628 for (unsigned i = RegStart; i != RegEnd; ++i)
4629 Regs.push_back(RegClassRegs[i]);
4631 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4632 OpInfo.ConstraintVT);
4633 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4638 // Otherwise, we couldn't allocate enough registers for this.
4641 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4642 /// processed uses a memory 'm' constraint.
4644 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4645 TargetLowering &TLI) {
4646 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4647 InlineAsm::ConstraintInfo &CI = CInfos[i];
4648 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4649 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4650 if (CType == TargetLowering::C_Memory)
4658 /// visitInlineAsm - Handle a call to an InlineAsm object.
4660 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4661 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4663 /// ConstraintOperands - Information about all of the constraints.
4664 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4666 SDValue Chain = getRoot();
4669 std::set<unsigned> OutputRegs, InputRegs;
4671 // Do a prepass over the constraints, canonicalizing them, and building up the
4672 // ConstraintOperands list.
4673 std::vector<InlineAsm::ConstraintInfo>
4674 ConstraintInfos = IA->ParseConstraints();
4676 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
4678 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4679 unsigned ResNo = 0; // ResNo - The result number of the next output.
4680 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4681 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4682 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4684 MVT OpVT = MVT::Other;
4686 // Compute the value type for each operand.
4687 switch (OpInfo.Type) {
4688 case InlineAsm::isOutput:
4689 // Indirect outputs just consume an argument.
4690 if (OpInfo.isIndirect) {
4691 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4695 // The return value of the call is this value. As such, there is no
4696 // corresponding argument.
4697 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4698 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4699 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4701 assert(ResNo == 0 && "Asm only has one result!");
4702 OpVT = TLI.getValueType(CS.getType());
4706 case InlineAsm::isInput:
4707 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4709 case InlineAsm::isClobber:
4714 // If this is an input or an indirect output, process the call argument.
4715 // BasicBlocks are labels, currently appearing only in asm's.
4716 if (OpInfo.CallOperandVal) {
4717 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
4718 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4720 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4723 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
4726 OpInfo.ConstraintVT = OpVT;
4729 // Second pass over the constraints: compute which constraint option to use
4730 // and assign registers to constraints that want a specific physreg.
4731 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4732 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4734 // If this is an output operand with a matching input operand, look up the
4735 // matching input. It might have a different type (e.g. the output might be
4736 // i32 and the input i64) and we need to pick the larger width to ensure we
4737 // reserve the right number of registers.
4738 if (OpInfo.hasMatchingInput()) {
4739 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4740 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4741 assert(OpInfo.ConstraintVT.isInteger() &&
4742 Input.ConstraintVT.isInteger() &&
4743 "Asm constraints must be the same or different sized integers");
4744 if (OpInfo.ConstraintVT.getSizeInBits() <
4745 Input.ConstraintVT.getSizeInBits())
4746 OpInfo.ConstraintVT = Input.ConstraintVT;
4748 Input.ConstraintVT = OpInfo.ConstraintVT;
4752 // Compute the constraint code and ConstraintType to use.
4753 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
4755 // If this is a memory input, and if the operand is not indirect, do what we
4756 // need to to provide an address for the memory input.
4757 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4758 !OpInfo.isIndirect) {
4759 assert(OpInfo.Type == InlineAsm::isInput &&
4760 "Can only indirectify direct input operands!");
4762 // Memory operands really want the address of the value. If we don't have
4763 // an indirect input, put it in the constpool if we can, otherwise spill
4764 // it to a stack slot.
4766 // If the operand is a float, integer, or vector constant, spill to a
4767 // constant pool entry to get its address.
4768 Value *OpVal = OpInfo.CallOperandVal;
4769 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4770 isa<ConstantVector>(OpVal)) {
4771 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4772 TLI.getPointerTy());
4774 // Otherwise, create a stack slot and emit a store to it before the
4776 const Type *Ty = OpVal->getType();
4777 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4778 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4779 MachineFunction &MF = DAG.getMachineFunction();
4780 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4781 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4782 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4783 OpInfo.CallOperand = StackSlot;
4786 // There is no longer a Value* corresponding to this operand.
4787 OpInfo.CallOperandVal = 0;
4788 // It is now an indirect operand.
4789 OpInfo.isIndirect = true;
4792 // If this constraint is for a specific register, allocate it before
4794 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4795 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4797 ConstraintInfos.clear();
4800 // Second pass - Loop over all of the operands, assigning virtual or physregs
4801 // to register class operands.
4802 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4803 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4805 // C_Register operands have already been allocated, Other/Memory don't need
4807 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4808 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4811 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4812 std::vector<SDValue> AsmNodeOperands;
4813 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4814 AsmNodeOperands.push_back(
4815 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4818 // Loop over all of the inputs, copying the operand values into the
4819 // appropriate registers and processing the output regs.
4820 RegsForValue RetValRegs;
4822 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4823 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4825 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4826 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4828 switch (OpInfo.Type) {
4829 case InlineAsm::isOutput: {
4830 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4831 OpInfo.ConstraintType != TargetLowering::C_Register) {
4832 // Memory output, or 'other' output (e.g. 'X' constraint).
4833 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4835 // Add information to the INLINEASM node to know about this output.
4836 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4837 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4838 TLI.getPointerTy()));
4839 AsmNodeOperands.push_back(OpInfo.CallOperand);
4843 // Otherwise, this is a register or register class output.
4845 // Copy the output from the appropriate register. Find a register that
4847 if (OpInfo.AssignedRegs.Regs.empty()) {
4848 cerr << "Couldn't allocate output reg for constraint '"
4849 << OpInfo.ConstraintCode << "'!\n";
4853 // If this is an indirect operand, store through the pointer after the
4855 if (OpInfo.isIndirect) {
4856 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4857 OpInfo.CallOperandVal));
4859 // This is the result value of the call.
4860 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4861 // Concatenate this output onto the outputs list.
4862 RetValRegs.append(OpInfo.AssignedRegs);
4865 // Add information to the INLINEASM node to know that this register is
4867 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
4868 6 /* EARLYCLOBBER REGDEF */ :
4870 DAG, AsmNodeOperands);
4873 case InlineAsm::isInput: {
4874 SDValue InOperandVal = OpInfo.CallOperand;
4876 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
4877 // If this is required to match an output register we have already set,
4878 // just use its register.
4879 unsigned OperandNo = OpInfo.getMatchedOperand();
4881 // Scan until we find the definition we already emitted of this operand.
4882 // When we find it, create a RegsForValue operand.
4883 unsigned CurOp = 2; // The first operand.
4884 for (; OperandNo; --OperandNo) {
4885 // Advance to the next operand.
4887 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
4888 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4889 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
4890 (NumOps & 7) == 4 /*MEM*/) &&
4891 "Skipped past definitions?");
4892 CurOp += (NumOps>>3)+1;
4896 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
4897 if ((NumOps & 7) == 2 /*REGDEF*/
4898 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
4899 // Add NumOps>>3 registers to MatchedRegs.
4900 RegsForValue MatchedRegs;
4901 MatchedRegs.TLI = &TLI;
4902 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4903 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4904 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4906 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4907 MatchedRegs.Regs.push_back(Reg);
4910 // Use the produced MatchedRegs object to
4911 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4912 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4915 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
4916 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4917 // Add information to the INLINEASM node to know about this input.
4918 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
4919 TLI.getPointerTy()));
4920 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4925 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4926 assert(!OpInfo.isIndirect &&
4927 "Don't know how to handle indirect other inputs yet!");
4929 std::vector<SDValue> Ops;
4930 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4931 hasMemory, Ops, DAG);
4933 cerr << "Invalid operand for inline asm constraint '"
4934 << OpInfo.ConstraintCode << "'!\n";
4938 // Add information to the INLINEASM node to know about this input.
4939 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4940 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4941 TLI.getPointerTy()));
4942 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4944 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4945 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4946 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4947 "Memory operands expect pointer values");
4949 // Add information to the INLINEASM node to know about this input.
4950 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4951 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4952 TLI.getPointerTy()));
4953 AsmNodeOperands.push_back(InOperandVal);
4957 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4958 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4959 "Unknown constraint type!");
4960 assert(!OpInfo.isIndirect &&
4961 "Don't know how to handle indirect register inputs yet!");
4963 // Copy the input into the appropriate registers.
4964 if (OpInfo.AssignedRegs.Regs.empty()) {
4965 cerr << "Couldn't allocate output reg for constraint '"
4966 << OpInfo.ConstraintCode << "'!\n";
4970 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4972 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
4973 DAG, AsmNodeOperands);
4976 case InlineAsm::isClobber: {
4977 // Add the clobbered value to the operand list, so that the register
4978 // allocator is aware that the physreg got clobbered.
4979 if (!OpInfo.AssignedRegs.Regs.empty())
4980 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
4981 DAG, AsmNodeOperands);
4987 // Finish up input operands.
4988 AsmNodeOperands[0] = Chain;
4989 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
4991 Chain = DAG.getNode(ISD::INLINEASM,
4992 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4993 &AsmNodeOperands[0], AsmNodeOperands.size());
4994 Flag = Chain.getValue(1);
4996 // If this asm returns a register value, copy the result from that register
4997 // and set it as the value of the call.
4998 if (!RetValRegs.Regs.empty()) {
4999 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
5001 // FIXME: Why don't we do this for inline asms with MRVs?
5002 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5003 MVT ResultType = TLI.getValueType(CS.getType());
5005 // If any of the results of the inline asm is a vector, it may have the
5006 // wrong width/num elts. This can happen for register classes that can
5007 // contain multiple different value types. The preg or vreg allocated may
5008 // not have the same VT as was expected. Convert it to the right type
5009 // with bit_convert.
5010 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5011 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
5013 } else if (ResultType != Val.getValueType() &&
5014 ResultType.isInteger() && Val.getValueType().isInteger()) {
5015 // If a result value was tied to an input value, the computed result may
5016 // have a wider width than the expected result. Extract the relevant
5018 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
5021 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5024 setValue(CS.getInstruction(), Val);
5027 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5029 // Process indirect outputs, first output all of the flagged copies out of
5031 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5032 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5033 Value *Ptr = IndirectStoresToEmit[i].second;
5034 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5035 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5038 // Emit the non-flagged stores from the physregs.
5039 SmallVector<SDValue, 8> OutChains;
5040 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5041 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5042 getValue(StoresToEmit[i].second),
5043 StoresToEmit[i].second, 0));
5044 if (!OutChains.empty())
5045 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5046 &OutChains[0], OutChains.size());
5051 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5052 SDValue Src = getValue(I.getOperand(0));
5054 MVT IntPtr = TLI.getPointerTy();
5056 if (IntPtr.bitsLT(Src.getValueType()))
5057 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5058 else if (IntPtr.bitsGT(Src.getValueType()))
5059 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5061 // Scale the source by the type size.
5062 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5063 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5064 Src, DAG.getIntPtrConstant(ElementSize));
5066 TargetLowering::ArgListTy Args;
5067 TargetLowering::ArgListEntry Entry;
5069 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5070 Args.push_back(Entry);
5072 std::pair<SDValue,SDValue> Result =
5073 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5074 CallingConv::C, PerformTailCallOpt,
5075 DAG.getExternalSymbol("malloc", IntPtr),
5077 setValue(&I, Result.first); // Pointers always fit in registers
5078 DAG.setRoot(Result.second);
5081 void SelectionDAGLowering::visitFree(FreeInst &I) {
5082 TargetLowering::ArgListTy Args;
5083 TargetLowering::ArgListEntry Entry;
5084 Entry.Node = getValue(I.getOperand(0));
5085 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5086 Args.push_back(Entry);
5087 MVT IntPtr = TLI.getPointerTy();
5088 std::pair<SDValue,SDValue> Result =
5089 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5090 CallingConv::C, PerformTailCallOpt,
5091 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
5092 DAG.setRoot(Result.second);
5095 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5096 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5097 getValue(I.getOperand(1)),
5098 DAG.getSrcValue(I.getOperand(1))));
5101 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5102 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5103 getValue(I.getOperand(0)),
5104 DAG.getSrcValue(I.getOperand(0)));
5106 DAG.setRoot(V.getValue(1));
5109 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5110 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5111 getValue(I.getOperand(1)),
5112 DAG.getSrcValue(I.getOperand(1))));
5115 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5116 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5117 getValue(I.getOperand(1)),
5118 getValue(I.getOperand(2)),
5119 DAG.getSrcValue(I.getOperand(1)),
5120 DAG.getSrcValue(I.getOperand(2))));
5123 /// TargetLowering::LowerArguments - This is the default LowerArguments
5124 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5125 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5126 /// integrated into SDISel.
5127 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5128 SmallVectorImpl<SDValue> &ArgValues) {
5129 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5130 SmallVector<SDValue, 3+16> Ops;
5131 Ops.push_back(DAG.getRoot());
5132 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5133 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5135 // Add one result value for each formal argument.
5136 SmallVector<MVT, 16> RetVals;
5138 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5140 SmallVector<MVT, 4> ValueVTs;
5141 ComputeValueVTs(*this, I->getType(), ValueVTs);
5142 for (unsigned Value = 0, NumValues = ValueVTs.size();
5143 Value != NumValues; ++Value) {
5144 MVT VT = ValueVTs[Value];
5145 const Type *ArgTy = VT.getTypeForMVT();
5146 ISD::ArgFlagsTy Flags;
5147 unsigned OriginalAlignment =
5148 getTargetData()->getABITypeAlignment(ArgTy);
5150 if (F.paramHasAttr(j, Attribute::ZExt))
5152 if (F.paramHasAttr(j, Attribute::SExt))
5154 if (F.paramHasAttr(j, Attribute::InReg))
5156 if (F.paramHasAttr(j, Attribute::StructRet))
5158 if (F.paramHasAttr(j, Attribute::ByVal)) {
5160 const PointerType *Ty = cast<PointerType>(I->getType());
5161 const Type *ElementTy = Ty->getElementType();
5162 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5163 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5164 // For ByVal, alignment should be passed from FE. BE will guess if
5165 // this info is not there but there are cases it cannot get right.
5166 if (F.getParamAlignment(j))
5167 FrameAlign = F.getParamAlignment(j);
5168 Flags.setByValAlign(FrameAlign);
5169 Flags.setByValSize(FrameSize);
5171 if (F.paramHasAttr(j, Attribute::Nest))
5173 Flags.setOrigAlign(OriginalAlignment);
5175 MVT RegisterVT = getRegisterType(VT);
5176 unsigned NumRegs = getNumRegisters(VT);
5177 for (unsigned i = 0; i != NumRegs; ++i) {
5178 RetVals.push_back(RegisterVT);
5179 ISD::ArgFlagsTy MyFlags = Flags;
5180 if (NumRegs > 1 && i == 0)
5182 // if it isn't first piece, alignment must be 1
5184 MyFlags.setOrigAlign(1);
5185 Ops.push_back(DAG.getArgFlags(MyFlags));
5190 RetVals.push_back(MVT::Other);
5193 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5194 DAG.getVTList(&RetVals[0], RetVals.size()),
5195 &Ops[0], Ops.size()).getNode();
5197 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5198 // allows exposing the loads that may be part of the argument access to the
5199 // first DAGCombiner pass.
5200 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5202 // The number of results should match up, except that the lowered one may have
5203 // an extra flag result.
5204 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5205 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5206 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5207 && "Lowering produced unexpected number of results!");
5209 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5210 if (Result != TmpRes.getNode() && Result->use_empty()) {
5211 HandleSDNode Dummy(DAG.getRoot());
5212 DAG.RemoveDeadNode(Result);
5215 Result = TmpRes.getNode();
5217 unsigned NumArgRegs = Result->getNumValues() - 1;
5218 DAG.setRoot(SDValue(Result, NumArgRegs));
5220 // Set up the return result vector.
5223 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5225 SmallVector<MVT, 4> ValueVTs;
5226 ComputeValueVTs(*this, I->getType(), ValueVTs);
5227 for (unsigned Value = 0, NumValues = ValueVTs.size();
5228 Value != NumValues; ++Value) {
5229 MVT VT = ValueVTs[Value];
5230 MVT PartVT = getRegisterType(VT);
5232 unsigned NumParts = getNumRegisters(VT);
5233 SmallVector<SDValue, 4> Parts(NumParts);
5234 for (unsigned j = 0; j != NumParts; ++j)
5235 Parts[j] = SDValue(Result, i++);
5237 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5238 if (F.paramHasAttr(Idx, Attribute::SExt))
5239 AssertOp = ISD::AssertSext;
5240 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5241 AssertOp = ISD::AssertZext;
5243 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5247 assert(i == NumArgRegs && "Argument register count mismatch!");
5251 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5252 /// implementation, which just inserts an ISD::CALL node, which is later custom
5253 /// lowered by the target to something concrete. FIXME: When all targets are
5254 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5255 std::pair<SDValue, SDValue>
5256 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5257 bool RetSExt, bool RetZExt, bool isVarArg,
5259 unsigned CallingConv, bool isTailCall,
5261 ArgListTy &Args, SelectionDAG &DAG) {
5262 assert((!isTailCall || PerformTailCallOpt) &&
5263 "isTailCall set when tail-call optimizations are disabled!");
5265 SmallVector<SDValue, 32> Ops;
5266 Ops.push_back(Chain); // Op#0 - Chain
5267 Ops.push_back(Callee);
5269 // Handle all of the outgoing arguments.
5270 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5271 SmallVector<MVT, 4> ValueVTs;
5272 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5273 for (unsigned Value = 0, NumValues = ValueVTs.size();
5274 Value != NumValues; ++Value) {
5275 MVT VT = ValueVTs[Value];
5276 const Type *ArgTy = VT.getTypeForMVT();
5277 SDValue Op = SDValue(Args[i].Node.getNode(),
5278 Args[i].Node.getResNo() + Value);
5279 ISD::ArgFlagsTy Flags;
5280 unsigned OriginalAlignment =
5281 getTargetData()->getABITypeAlignment(ArgTy);
5287 if (Args[i].isInReg)
5291 if (Args[i].isByVal) {
5293 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5294 const Type *ElementTy = Ty->getElementType();
5295 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5296 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5297 // For ByVal, alignment should come from FE. BE will guess if this
5298 // info is not there but there are cases it cannot get right.
5299 if (Args[i].Alignment)
5300 FrameAlign = Args[i].Alignment;
5301 Flags.setByValAlign(FrameAlign);
5302 Flags.setByValSize(FrameSize);
5306 Flags.setOrigAlign(OriginalAlignment);
5308 MVT PartVT = getRegisterType(VT);
5309 unsigned NumParts = getNumRegisters(VT);
5310 SmallVector<SDValue, 4> Parts(NumParts);
5311 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5314 ExtendKind = ISD::SIGN_EXTEND;
5315 else if (Args[i].isZExt)
5316 ExtendKind = ISD::ZERO_EXTEND;
5318 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5320 for (unsigned i = 0; i != NumParts; ++i) {
5321 // if it isn't first piece, alignment must be 1
5322 ISD::ArgFlagsTy MyFlags = Flags;
5323 if (NumParts > 1 && i == 0)
5326 MyFlags.setOrigAlign(1);
5328 Ops.push_back(Parts[i]);
5329 Ops.push_back(DAG.getArgFlags(MyFlags));
5334 // Figure out the result value types. We start by making a list of
5335 // the potentially illegal return value types.
5336 SmallVector<MVT, 4> LoweredRetTys;
5337 SmallVector<MVT, 4> RetTys;
5338 ComputeValueVTs(*this, RetTy, RetTys);
5340 // Then we translate that to a list of legal types.
5341 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5343 MVT RegisterVT = getRegisterType(VT);
5344 unsigned NumRegs = getNumRegisters(VT);
5345 for (unsigned i = 0; i != NumRegs; ++i)
5346 LoweredRetTys.push_back(RegisterVT);
5349 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5351 // Create the CALL node.
5352 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
5353 DAG.getVTList(&LoweredRetTys[0],
5354 LoweredRetTys.size()),
5357 Chain = Res.getValue(LoweredRetTys.size() - 1);
5359 // Gather up the call result into a single value.
5360 if (RetTy != Type::VoidTy && !RetTys.empty()) {
5361 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5364 AssertOp = ISD::AssertSext;
5366 AssertOp = ISD::AssertZext;
5368 SmallVector<SDValue, 4> ReturnValues;
5370 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5372 MVT RegisterVT = getRegisterType(VT);
5373 unsigned NumRegs = getNumRegisters(VT);
5374 unsigned RegNoEnd = NumRegs + RegNo;
5375 SmallVector<SDValue, 4> Results;
5376 for (; RegNo != RegNoEnd; ++RegNo)
5377 Results.push_back(Res.getValue(RegNo));
5378 SDValue ReturnValue =
5379 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5381 ReturnValues.push_back(ReturnValue);
5383 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
5384 &ReturnValues[0], ReturnValues.size());
5387 return std::make_pair(Res, Chain);
5390 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5391 assert(0 && "LowerOperation not implemented for this target!");
5397 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5398 SDValue Op = getValue(V);
5399 assert((Op.getOpcode() != ISD::CopyFromReg ||
5400 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5401 "Copy from a reg to the same reg!");
5402 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5404 RegsForValue RFV(TLI, Reg, V->getType());
5405 SDValue Chain = DAG.getEntryNode();
5406 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5407 PendingExports.push_back(Chain);
5410 #include "llvm/CodeGen/SelectionDAGISel.h"
5412 void SelectionDAGISel::
5413 LowerArguments(BasicBlock *LLVMBB) {
5414 // If this is the entry block, emit arguments.
5415 Function &F = *LLVMBB->getParent();
5416 SDValue OldRoot = SDL->DAG.getRoot();
5417 SmallVector<SDValue, 16> Args;
5418 TLI.LowerArguments(F, SDL->DAG, Args);
5421 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5423 SmallVector<MVT, 4> ValueVTs;
5424 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5425 unsigned NumValues = ValueVTs.size();
5426 if (!AI->use_empty()) {
5427 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5428 // If this argument is live outside of the entry block, insert a copy from
5429 // whereever we got it to the vreg that other BB's will reference it as.
5430 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5431 if (VMI != FuncInfo->ValueMap.end()) {
5432 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5438 // Finally, if the target has anything special to do, allow it to do so.
5439 // FIXME: this should insert code into the DAG!
5440 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5443 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5444 /// ensure constants are generated when needed. Remember the virtual registers
5445 /// that need to be added to the Machine PHI nodes as input. We cannot just
5446 /// directly add them, because expansion might result in multiple MBB's for one
5447 /// BB. As such, the start of the BB might correspond to a different MBB than
5451 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5452 TerminatorInst *TI = LLVMBB->getTerminator();
5454 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5456 // Check successor nodes' PHI nodes that expect a constant to be available
5458 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5459 BasicBlock *SuccBB = TI->getSuccessor(succ);
5460 if (!isa<PHINode>(SuccBB->begin())) continue;
5461 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5463 // If this terminator has multiple identical successors (common for
5464 // switches), only handle each succ once.
5465 if (!SuccsHandled.insert(SuccMBB)) continue;
5467 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5470 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5471 // nodes and Machine PHI nodes, but the incoming operands have not been
5473 for (BasicBlock::iterator I = SuccBB->begin();
5474 (PN = dyn_cast<PHINode>(I)); ++I) {
5475 // Ignore dead phi's.
5476 if (PN->use_empty()) continue;
5479 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5481 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5482 unsigned &RegOut = SDL->ConstantsOut[C];
5484 RegOut = FuncInfo->CreateRegForValue(C);
5485 SDL->CopyValueToVirtualRegister(C, RegOut);
5489 Reg = FuncInfo->ValueMap[PHIOp];
5491 assert(isa<AllocaInst>(PHIOp) &&
5492 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5493 "Didn't codegen value into a register!??");
5494 Reg = FuncInfo->CreateRegForValue(PHIOp);
5495 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5499 // Remember that this register needs to added to the machine PHI node as
5500 // the input for this MBB.
5501 SmallVector<MVT, 4> ValueVTs;
5502 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5503 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5504 MVT VT = ValueVTs[vti];
5505 unsigned NumRegisters = TLI.getNumRegisters(VT);
5506 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5507 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5508 Reg += NumRegisters;
5512 SDL->ConstantsOut.clear();
5515 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5516 /// supports legal types, and it emits MachineInstrs directly instead of
5517 /// creating SelectionDAG nodes.
5520 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5522 TerminatorInst *TI = LLVMBB->getTerminator();
5524 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5525 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5527 // Check successor nodes' PHI nodes that expect a constant to be available
5529 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5530 BasicBlock *SuccBB = TI->getSuccessor(succ);
5531 if (!isa<PHINode>(SuccBB->begin())) continue;
5532 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5534 // If this terminator has multiple identical successors (common for
5535 // switches), only handle each succ once.
5536 if (!SuccsHandled.insert(SuccMBB)) continue;
5538 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5541 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5542 // nodes and Machine PHI nodes, but the incoming operands have not been
5544 for (BasicBlock::iterator I = SuccBB->begin();
5545 (PN = dyn_cast<PHINode>(I)); ++I) {
5546 // Ignore dead phi's.
5547 if (PN->use_empty()) continue;
5549 // Only handle legal types. Two interesting things to note here. First,
5550 // by bailing out early, we may leave behind some dead instructions,
5551 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5552 // own moves. Second, this check is necessary becuase FastISel doesn't
5553 // use CreateRegForValue to create registers, so it always creates
5554 // exactly one register for each non-void instruction.
5555 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5556 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5559 VT = TLI.getTypeToTransformTo(VT);
5561 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5566 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5568 unsigned Reg = F->getRegForValue(PHIOp);
5570 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5573 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));