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/Constants.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/Module.h"
30 #include "llvm/CodeGen/FastISel.h"
31 #include "llvm/CodeGen/GCStrategy.h"
32 #include "llvm/CodeGen/GCMetadata.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineJumpTableInfo.h"
37 #include "llvm/CodeGen/MachineModuleInfo.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/PseudoSourceValue.h"
40 #include "llvm/CodeGen/SelectionDAG.h"
41 #include "llvm/CodeGen/DwarfWriter.h"
42 #include "llvm/Analysis/DebugInfo.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Target/TargetFrameInfo.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetIntrinsicInfo.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/raw_ostream.h"
59 /// LimitFloatPrecision - Generate low-precision inline sequences for
60 /// some float libcalls (6, 8 or 12 bits).
61 static unsigned LimitFloatPrecision;
63 static cl::opt<unsigned, true>
64 LimitFPPrecision("limit-float-precision",
65 cl::desc("Generate low-precision inline sequences "
66 "for some float libcalls"),
67 cl::location(LimitFloatPrecision),
70 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
71 /// of insertvalue or extractvalue indices that identify a member, return
72 /// the linearized index of the start of the member.
74 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
75 const unsigned *Indices,
76 const unsigned *IndicesEnd,
77 unsigned CurIndex = 0) {
78 // Base case: We're done.
79 if (Indices && Indices == IndicesEnd)
82 // Given a struct type, recursively traverse the elements.
83 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
84 for (StructType::element_iterator EB = STy->element_begin(),
86 EE = STy->element_end();
88 if (Indices && *Indices == unsigned(EI - EB))
89 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
90 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
94 // Given an array type, recursively traverse the elements.
95 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
96 const Type *EltTy = ATy->getElementType();
97 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
98 if (Indices && *Indices == i)
99 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
100 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
104 // We haven't found the type we're looking for, so keep searching.
108 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
109 /// EVTs that represent all the individual underlying
110 /// non-aggregate types that comprise it.
112 /// If Offsets is non-null, it points to a vector to be filled in
113 /// with the in-memory offsets of each of the individual values.
115 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
116 SmallVectorImpl<EVT> &ValueVTs,
117 SmallVectorImpl<uint64_t> *Offsets = 0,
118 uint64_t StartingOffset = 0) {
119 // Given a struct type, recursively traverse the elements.
120 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
121 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
122 for (StructType::element_iterator EB = STy->element_begin(),
124 EE = STy->element_end();
126 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
127 StartingOffset + SL->getElementOffset(EI - EB));
130 // Given an array type, recursively traverse the elements.
131 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
132 const Type *EltTy = ATy->getElementType();
133 uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
134 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
135 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
136 StartingOffset + i * EltSize);
139 // Interpret void as zero return values.
140 if (Ty == Type::getVoidTy(Ty->getContext()))
142 // Base case: we can get an EVT for this LLVM IR type.
143 ValueVTs.push_back(TLI.getValueType(Ty));
145 Offsets->push_back(StartingOffset);
149 /// RegsForValue - This struct represents the registers (physical or virtual)
150 /// that a particular set of values is assigned, and the type information about
151 /// the value. The most common situation is to represent one value at a time,
152 /// but struct or array values are handled element-wise as multiple values.
153 /// The splitting of aggregates is performed recursively, so that we never
154 /// have aggregate-typed registers. The values at this point do not necessarily
155 /// have legal types, so each value may require one or more registers of some
158 struct VISIBILITY_HIDDEN RegsForValue {
159 /// TLI - The TargetLowering object.
161 const TargetLowering *TLI;
163 /// ValueVTs - The value types of the values, which may not be legal, and
164 /// may need be promoted or synthesized from one or more registers.
166 SmallVector<EVT, 4> ValueVTs;
168 /// RegVTs - The value types of the registers. This is the same size as
169 /// ValueVTs and it records, for each value, what the type of the assigned
170 /// register or registers are. (Individual values are never synthesized
171 /// from more than one type of register.)
173 /// With virtual registers, the contents of RegVTs is redundant with TLI's
174 /// getRegisterType member function, however when with physical registers
175 /// it is necessary to have a separate record of the types.
177 SmallVector<EVT, 4> RegVTs;
179 /// Regs - This list holds the registers assigned to the values.
180 /// Each legal or promoted value requires one register, and each
181 /// expanded value requires multiple registers.
183 SmallVector<unsigned, 4> Regs;
185 RegsForValue() : TLI(0) {}
187 RegsForValue(const TargetLowering &tli,
188 const SmallVector<unsigned, 4> ®s,
189 EVT regvt, EVT valuevt)
190 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
191 RegsForValue(const TargetLowering &tli,
192 const SmallVector<unsigned, 4> ®s,
193 const SmallVector<EVT, 4> ®vts,
194 const SmallVector<EVT, 4> &valuevts)
195 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
196 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
197 unsigned Reg, const Type *Ty) : TLI(&tli) {
198 ComputeValueVTs(tli, Ty, ValueVTs);
200 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
201 EVT ValueVT = ValueVTs[Value];
202 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
203 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
204 for (unsigned i = 0; i != NumRegs; ++i)
205 Regs.push_back(Reg + i);
206 RegVTs.push_back(RegisterVT);
211 /// append - Add the specified values to this one.
212 void append(const RegsForValue &RHS) {
214 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
215 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
216 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
220 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
221 /// this value and returns the result as a ValueVTs value. This uses
222 /// Chain/Flag as the input and updates them for the output Chain/Flag.
223 /// If the Flag pointer is NULL, no flag is used.
224 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
225 SDValue &Chain, SDValue *Flag) const;
227 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
228 /// specified value into the registers specified by this object. This uses
229 /// Chain/Flag as the input and updates them for the output Chain/Flag.
230 /// If the Flag pointer is NULL, no flag is used.
231 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
232 SDValue &Chain, SDValue *Flag) const;
234 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
235 /// operand list. This adds the code marker, matching input operand index
236 /// (if applicable), and includes the number of values added into it.
237 void AddInlineAsmOperands(unsigned Code,
238 bool HasMatching, unsigned MatchingIdx,
239 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
243 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
244 /// PHI nodes or outside of the basic block that defines it, or used by a
245 /// switch or atomic instruction, which may expand to multiple basic blocks.
246 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
247 if (isa<PHINode>(I)) return true;
248 BasicBlock *BB = I->getParent();
249 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
250 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
255 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
256 /// entry block, return true. This includes arguments used by switches, since
257 /// the switch may expand into multiple basic blocks.
258 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
259 // With FastISel active, we may be splitting blocks, so force creation
260 // of virtual registers for all non-dead arguments.
261 // Don't force virtual registers for byval arguments though, because
262 // fast-isel can't handle those in all cases.
263 if (EnableFastISel && !A->hasByValAttr())
264 return A->use_empty();
266 BasicBlock *Entry = A->getParent()->begin();
267 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
268 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
269 return false; // Use not in entry block.
273 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
277 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
279 bool EnableFastISel) {
282 RegInfo = &MF->getRegInfo();
284 // Create a vreg for each argument register that is not dead and is used
285 // outside of the entry block for the function.
286 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
288 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
289 InitializeRegForValue(AI);
291 // Initialize the mapping of values to registers. This is only set up for
292 // instruction values that are used outside of the block that defines
294 Function::iterator BB = Fn->begin(), EB = Fn->end();
295 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
296 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
297 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
298 const Type *Ty = AI->getAllocatedType();
299 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
301 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
304 TySize *= CUI->getZExtValue(); // Get total allocated size.
305 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
306 StaticAllocaMap[AI] =
307 MF->getFrameInfo()->CreateStackObject(TySize, Align);
310 for (; BB != EB; ++BB)
311 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
312 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
313 if (!isa<AllocaInst>(I) ||
314 !StaticAllocaMap.count(cast<AllocaInst>(I)))
315 InitializeRegForValue(I);
317 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
318 // also creates the initial PHI MachineInstrs, though none of the input
319 // operands are populated.
320 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
321 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
325 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
329 for (BasicBlock::iterator
330 I = BB->begin(), E = BB->end(); I != E; ++I) {
331 if (CallInst *CI = dyn_cast<CallInst>(I)) {
332 if (Function *F = CI->getCalledFunction()) {
333 switch (F->getIntrinsicID()) {
335 case Intrinsic::dbg_stoppoint: {
336 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
337 if (isValidDebugInfoIntrinsic(*SPI, CodeGenOpt::Default))
338 DL = ExtractDebugLocation(*SPI, MF->getDebugLocInfo());
341 case Intrinsic::dbg_func_start: {
342 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
343 if (isValidDebugInfoIntrinsic(*FSI, CodeGenOpt::Default))
344 DL = ExtractDebugLocation(*FSI, MF->getDebugLocInfo());
351 PN = dyn_cast<PHINode>(I);
352 if (!PN || PN->use_empty()) continue;
354 unsigned PHIReg = ValueMap[PN];
355 assert(PHIReg && "PHI node does not have an assigned virtual register!");
357 SmallVector<EVT, 4> ValueVTs;
358 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
359 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
360 EVT VT = ValueVTs[vti];
361 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
362 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
363 for (unsigned i = 0; i != NumRegisters; ++i)
364 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
365 PHIReg += NumRegisters;
371 unsigned FunctionLoweringInfo::MakeReg(EVT VT) {
372 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
375 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
376 /// the correctly promoted or expanded types. Assign these registers
377 /// consecutive vreg numbers and return the first assigned number.
379 /// In the case that the given value has struct or array type, this function
380 /// will assign registers for each member or element.
382 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
383 SmallVector<EVT, 4> ValueVTs;
384 ComputeValueVTs(TLI, V->getType(), ValueVTs);
386 unsigned FirstReg = 0;
387 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
388 EVT ValueVT = ValueVTs[Value];
389 EVT RegisterVT = TLI.getRegisterType(V->getContext(), ValueVT);
391 unsigned NumRegs = TLI.getNumRegisters(V->getContext(), ValueVT);
392 for (unsigned i = 0; i != NumRegs; ++i) {
393 unsigned R = MakeReg(RegisterVT);
394 if (!FirstReg) FirstReg = R;
400 /// getCopyFromParts - Create a value that contains the specified legal parts
401 /// combined into the value they represent. If the parts combine to a type
402 /// larger then ValueVT then AssertOp can be used to specify whether the extra
403 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
404 /// (ISD::AssertSext).
405 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
406 const SDValue *Parts,
407 unsigned NumParts, EVT PartVT, EVT ValueVT,
408 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
409 assert(NumParts > 0 && "No parts to assemble!");
410 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
411 SDValue Val = Parts[0];
414 // Assemble the value from multiple parts.
415 if (!ValueVT.isVector() && ValueVT.isInteger()) {
416 unsigned PartBits = PartVT.getSizeInBits();
417 unsigned ValueBits = ValueVT.getSizeInBits();
419 // Assemble the power of 2 part.
420 unsigned RoundParts = NumParts & (NumParts - 1) ?
421 1 << Log2_32(NumParts) : NumParts;
422 unsigned RoundBits = PartBits * RoundParts;
423 EVT RoundVT = RoundBits == ValueBits ?
424 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
427 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
429 if (RoundParts > 2) {
430 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
431 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
434 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
435 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
437 if (TLI.isBigEndian())
439 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
441 if (RoundParts < NumParts) {
442 // Assemble the trailing non-power-of-2 part.
443 unsigned OddParts = NumParts - RoundParts;
444 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
445 Hi = getCopyFromParts(DAG, dl,
446 Parts+RoundParts, OddParts, PartVT, OddVT);
448 // Combine the round and odd parts.
450 if (TLI.isBigEndian())
452 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
453 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
454 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
455 DAG.getConstant(Lo.getValueType().getSizeInBits(),
456 TLI.getPointerTy()));
457 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
458 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
460 } else if (ValueVT.isVector()) {
461 // Handle a multi-element vector.
462 EVT IntermediateVT, RegisterVT;
463 unsigned NumIntermediates;
465 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
466 NumIntermediates, RegisterVT);
467 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
468 NumParts = NumRegs; // Silence a compiler warning.
469 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
470 assert(RegisterVT == Parts[0].getValueType() &&
471 "Part type doesn't match part!");
473 // Assemble the parts into intermediate operands.
474 SmallVector<SDValue, 8> Ops(NumIntermediates);
475 if (NumIntermediates == NumParts) {
476 // If the register was not expanded, truncate or copy the value,
478 for (unsigned i = 0; i != NumParts; ++i)
479 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
480 PartVT, IntermediateVT);
481 } else if (NumParts > 0) {
482 // If the intermediate type was expanded, build the intermediate operands
484 assert(NumParts % NumIntermediates == 0 &&
485 "Must expand into a divisible number of parts!");
486 unsigned Factor = NumParts / NumIntermediates;
487 for (unsigned i = 0; i != NumIntermediates; ++i)
488 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
489 PartVT, IntermediateVT);
492 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
494 Val = DAG.getNode(IntermediateVT.isVector() ?
495 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
496 ValueVT, &Ops[0], NumIntermediates);
497 } else if (PartVT.isFloatingPoint()) {
498 // FP split into multiple FP parts (for ppcf128)
499 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
502 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
503 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
504 if (TLI.isBigEndian())
506 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
508 // FP split into integer parts (soft fp)
509 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
510 !PartVT.isVector() && "Unexpected split");
511 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
512 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
516 // There is now one part, held in Val. Correct it to match ValueVT.
517 PartVT = Val.getValueType();
519 if (PartVT == ValueVT)
522 if (PartVT.isVector()) {
523 assert(ValueVT.isVector() && "Unknown vector conversion!");
524 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
527 if (ValueVT.isVector()) {
528 assert(ValueVT.getVectorElementType() == PartVT &&
529 ValueVT.getVectorNumElements() == 1 &&
530 "Only trivial scalar-to-vector conversions should get here!");
531 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
534 if (PartVT.isInteger() &&
535 ValueVT.isInteger()) {
536 if (ValueVT.bitsLT(PartVT)) {
537 // For a truncate, see if we have any information to
538 // indicate whether the truncated bits will always be
539 // zero or sign-extension.
540 if (AssertOp != ISD::DELETED_NODE)
541 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
542 DAG.getValueType(ValueVT));
543 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
545 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
549 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
550 if (ValueVT.bitsLT(Val.getValueType()))
551 // FP_ROUND's are always exact here.
552 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
553 DAG.getIntPtrConstant(1));
554 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
557 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
558 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
560 llvm_unreachable("Unknown mismatch!");
564 /// getCopyToParts - Create a series of nodes that contain the specified value
565 /// split into legal parts. If the parts contain more bits than Val, then, for
566 /// integers, ExtendKind can be used to specify how to generate the extra bits.
567 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
568 SDValue *Parts, unsigned NumParts, EVT PartVT,
569 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
570 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
571 EVT PtrVT = TLI.getPointerTy();
572 EVT ValueVT = Val.getValueType();
573 unsigned PartBits = PartVT.getSizeInBits();
574 unsigned OrigNumParts = NumParts;
575 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
580 if (!ValueVT.isVector()) {
581 if (PartVT == ValueVT) {
582 assert(NumParts == 1 && "No-op copy with multiple parts!");
587 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
588 // If the parts cover more bits than the value has, promote the value.
589 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
590 assert(NumParts == 1 && "Do not know what to promote to!");
591 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
592 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
593 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
594 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
596 llvm_unreachable("Unknown mismatch!");
598 } else if (PartBits == ValueVT.getSizeInBits()) {
599 // Different types of the same size.
600 assert(NumParts == 1 && PartVT != ValueVT);
601 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
602 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
603 // If the parts cover less bits than value has, truncate the value.
604 if (PartVT.isInteger() && ValueVT.isInteger()) {
605 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
606 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
608 llvm_unreachable("Unknown mismatch!");
612 // The value may have changed - recompute ValueVT.
613 ValueVT = Val.getValueType();
614 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
615 "Failed to tile the value with PartVT!");
618 assert(PartVT == ValueVT && "Type conversion failed!");
623 // Expand the value into multiple parts.
624 if (NumParts & (NumParts - 1)) {
625 // The number of parts is not a power of 2. Split off and copy the tail.
626 assert(PartVT.isInteger() && ValueVT.isInteger() &&
627 "Do not know what to expand to!");
628 unsigned RoundParts = 1 << Log2_32(NumParts);
629 unsigned RoundBits = RoundParts * PartBits;
630 unsigned OddParts = NumParts - RoundParts;
631 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
632 DAG.getConstant(RoundBits,
633 TLI.getPointerTy()));
634 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
635 if (TLI.isBigEndian())
636 // The odd parts were reversed by getCopyToParts - unreverse them.
637 std::reverse(Parts + RoundParts, Parts + NumParts);
638 NumParts = RoundParts;
639 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
640 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
643 // The number of parts is a power of 2. Repeatedly bisect the value using
645 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
646 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()),
648 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
649 for (unsigned i = 0; i < NumParts; i += StepSize) {
650 unsigned ThisBits = StepSize * PartBits / 2;
651 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
652 SDValue &Part0 = Parts[i];
653 SDValue &Part1 = Parts[i+StepSize/2];
655 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
657 DAG.getConstant(1, PtrVT));
658 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
660 DAG.getConstant(0, PtrVT));
662 if (ThisBits == PartBits && ThisVT != PartVT) {
663 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
665 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
671 if (TLI.isBigEndian())
672 std::reverse(Parts, Parts + OrigNumParts);
679 if (PartVT != ValueVT) {
680 if (PartVT.isVector()) {
681 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
683 assert(ValueVT.getVectorElementType() == PartVT &&
684 ValueVT.getVectorNumElements() == 1 &&
685 "Only trivial vector-to-scalar conversions should get here!");
686 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
688 DAG.getConstant(0, PtrVT));
696 // Handle a multi-element vector.
697 EVT IntermediateVT, RegisterVT;
698 unsigned NumIntermediates;
699 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
700 IntermediateVT, NumIntermediates, RegisterVT);
701 unsigned NumElements = ValueVT.getVectorNumElements();
703 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
704 NumParts = NumRegs; // Silence a compiler warning.
705 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
707 // Split the vector into intermediate operands.
708 SmallVector<SDValue, 8> Ops(NumIntermediates);
709 for (unsigned i = 0; i != NumIntermediates; ++i)
710 if (IntermediateVT.isVector())
711 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
713 DAG.getConstant(i * (NumElements / NumIntermediates),
716 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
718 DAG.getConstant(i, PtrVT));
720 // Split the intermediate operands into legal parts.
721 if (NumParts == NumIntermediates) {
722 // If the register was not expanded, promote or copy the value,
724 for (unsigned i = 0; i != NumParts; ++i)
725 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
726 } else if (NumParts > 0) {
727 // If the intermediate type was expanded, split each the value into
729 assert(NumParts % NumIntermediates == 0 &&
730 "Must expand into a divisible number of parts!");
731 unsigned Factor = NumParts / NumIntermediates;
732 for (unsigned i = 0; i != NumIntermediates; ++i)
733 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
738 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
741 TD = DAG.getTarget().getTargetData();
744 /// clear - Clear out the curret SelectionDAG and the associated
745 /// state and prepare this SelectionDAGLowering object to be used
746 /// for a new block. This doesn't clear out information about
747 /// additional blocks that are needed to complete switch lowering
748 /// or PHI node updating; that information is cleared out as it is
750 void SelectionDAGLowering::clear() {
752 PendingLoads.clear();
753 PendingExports.clear();
756 CurDebugLoc = DebugLoc::getUnknownLoc();
760 /// getRoot - Return the current virtual root of the Selection DAG,
761 /// flushing any PendingLoad items. This must be done before emitting
762 /// a store or any other node that may need to be ordered after any
763 /// prior load instructions.
765 SDValue SelectionDAGLowering::getRoot() {
766 if (PendingLoads.empty())
767 return DAG.getRoot();
769 if (PendingLoads.size() == 1) {
770 SDValue Root = PendingLoads[0];
772 PendingLoads.clear();
776 // Otherwise, we have to make a token factor node.
777 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
778 &PendingLoads[0], PendingLoads.size());
779 PendingLoads.clear();
784 /// getControlRoot - Similar to getRoot, but instead of flushing all the
785 /// PendingLoad items, flush all the PendingExports items. It is necessary
786 /// to do this before emitting a terminator instruction.
788 SDValue SelectionDAGLowering::getControlRoot() {
789 SDValue Root = DAG.getRoot();
791 if (PendingExports.empty())
794 // Turn all of the CopyToReg chains into one factored node.
795 if (Root.getOpcode() != ISD::EntryToken) {
796 unsigned i = 0, e = PendingExports.size();
797 for (; i != e; ++i) {
798 assert(PendingExports[i].getNode()->getNumOperands() > 1);
799 if (PendingExports[i].getNode()->getOperand(0) == Root)
800 break; // Don't add the root if we already indirectly depend on it.
804 PendingExports.push_back(Root);
807 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
809 PendingExports.size());
810 PendingExports.clear();
815 void SelectionDAGLowering::visit(Instruction &I) {
816 visit(I.getOpcode(), I);
819 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
820 // Note: this doesn't use InstVisitor, because it has to work with
821 // ConstantExpr's in addition to instructions.
823 default: llvm_unreachable("Unknown instruction type encountered!");
824 // Build the switch statement using the Instruction.def file.
825 #define HANDLE_INST(NUM, OPCODE, CLASS) \
826 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
827 #include "llvm/Instruction.def"
831 SDValue SelectionDAGLowering::getValue(const Value *V) {
832 SDValue &N = NodeMap[V];
833 if (N.getNode()) return N;
835 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
836 EVT VT = TLI.getValueType(V->getType(), true);
838 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
839 return N = DAG.getConstant(*CI, VT);
841 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
842 return N = DAG.getGlobalAddress(GV, VT);
844 if (isa<ConstantPointerNull>(C))
845 return N = DAG.getConstant(0, TLI.getPointerTy());
847 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
848 return N = DAG.getConstantFP(*CFP, VT);
850 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
851 return N = DAG.getUNDEF(VT);
853 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
854 visit(CE->getOpcode(), *CE);
855 SDValue N1 = NodeMap[V];
856 assert(N1.getNode() && "visit didn't populate the ValueMap!");
860 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
861 SmallVector<SDValue, 4> Constants;
862 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
864 SDNode *Val = getValue(*OI).getNode();
865 // If the operand is an empty aggregate, there are no values.
867 // Add each leaf value from the operand to the Constants list
868 // to form a flattened list of all the values.
869 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
870 Constants.push_back(SDValue(Val, i));
872 return DAG.getMergeValues(&Constants[0], Constants.size(),
876 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
877 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
878 "Unknown struct or array constant!");
880 SmallVector<EVT, 4> ValueVTs;
881 ComputeValueVTs(TLI, C->getType(), ValueVTs);
882 unsigned NumElts = ValueVTs.size();
884 return SDValue(); // empty struct
885 SmallVector<SDValue, 4> Constants(NumElts);
886 for (unsigned i = 0; i != NumElts; ++i) {
887 EVT EltVT = ValueVTs[i];
888 if (isa<UndefValue>(C))
889 Constants[i] = DAG.getUNDEF(EltVT);
890 else if (EltVT.isFloatingPoint())
891 Constants[i] = DAG.getConstantFP(0, EltVT);
893 Constants[i] = DAG.getConstant(0, EltVT);
895 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
898 const VectorType *VecTy = cast<VectorType>(V->getType());
899 unsigned NumElements = VecTy->getNumElements();
901 // Now that we know the number and type of the elements, get that number of
902 // elements into the Ops array based on what kind of constant it is.
903 SmallVector<SDValue, 16> Ops;
904 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
905 for (unsigned i = 0; i != NumElements; ++i)
906 Ops.push_back(getValue(CP->getOperand(i)));
908 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
909 EVT EltVT = TLI.getValueType(VecTy->getElementType());
912 if (EltVT.isFloatingPoint())
913 Op = DAG.getConstantFP(0, EltVT);
915 Op = DAG.getConstant(0, EltVT);
916 Ops.assign(NumElements, Op);
919 // Create a BUILD_VECTOR node.
920 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
921 VT, &Ops[0], Ops.size());
924 // If this is a static alloca, generate it as the frameindex instead of
926 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
927 DenseMap<const AllocaInst*, int>::iterator SI =
928 FuncInfo.StaticAllocaMap.find(AI);
929 if (SI != FuncInfo.StaticAllocaMap.end())
930 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
933 unsigned InReg = FuncInfo.ValueMap[V];
934 assert(InReg && "Value not in map!");
936 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
937 SDValue Chain = DAG.getEntryNode();
938 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
942 void SelectionDAGLowering::visitRet(ReturnInst &I) {
943 SDValue Chain = getControlRoot();
944 SmallVector<ISD::OutputArg, 8> Outs;
945 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
946 SmallVector<EVT, 4> ValueVTs;
947 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
948 unsigned NumValues = ValueVTs.size();
949 if (NumValues == 0) continue;
951 SDValue RetOp = getValue(I.getOperand(i));
952 for (unsigned j = 0, f = NumValues; j != f; ++j) {
953 EVT VT = ValueVTs[j];
955 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
957 const Function *F = I.getParent()->getParent();
958 if (F->paramHasAttr(0, Attribute::SExt))
959 ExtendKind = ISD::SIGN_EXTEND;
960 else if (F->paramHasAttr(0, Attribute::ZExt))
961 ExtendKind = ISD::ZERO_EXTEND;
963 // FIXME: C calling convention requires the return type to be promoted to
964 // at least 32-bit. But this is not necessary for non-C calling
965 // conventions. The frontend should mark functions whose return values
966 // require promoting with signext or zeroext attributes.
967 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
968 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
969 if (VT.bitsLT(MinVT))
973 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
974 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
975 SmallVector<SDValue, 4> Parts(NumParts);
976 getCopyToParts(DAG, getCurDebugLoc(),
977 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
978 &Parts[0], NumParts, PartVT, ExtendKind);
980 // 'inreg' on function refers to return value
981 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
982 if (F->paramHasAttr(0, Attribute::InReg))
985 // Propagate extension type if any
986 if (F->paramHasAttr(0, Attribute::SExt))
988 else if (F->paramHasAttr(0, Attribute::ZExt))
991 for (unsigned i = 0; i < NumParts; ++i)
992 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
996 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
997 CallingConv::ID CallConv =
998 DAG.getMachineFunction().getFunction()->getCallingConv();
999 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1000 Outs, getCurDebugLoc(), DAG);
1002 // Verify that the target's LowerReturn behaved as expected.
1003 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1004 "LowerReturn didn't return a valid chain!");
1006 // Update the DAG with the new chain value resulting from return lowering.
1010 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1011 /// created for it, emit nodes to copy the value into the virtual
1013 void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
1014 if (!V->use_empty()) {
1015 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1016 if (VMI != FuncInfo.ValueMap.end())
1017 CopyValueToVirtualRegister(V, VMI->second);
1021 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1022 /// the current basic block, add it to ValueMap now so that we'll get a
1024 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1025 // No need to export constants.
1026 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1028 // Already exported?
1029 if (FuncInfo.isExportedInst(V)) return;
1031 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1032 CopyValueToVirtualRegister(V, Reg);
1035 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1036 const BasicBlock *FromBB) {
1037 // The operands of the setcc have to be in this block. We don't know
1038 // how to export them from some other block.
1039 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1040 // Can export from current BB.
1041 if (VI->getParent() == FromBB)
1044 // Is already exported, noop.
1045 return FuncInfo.isExportedInst(V);
1048 // If this is an argument, we can export it if the BB is the entry block or
1049 // if it is already exported.
1050 if (isa<Argument>(V)) {
1051 if (FromBB == &FromBB->getParent()->getEntryBlock())
1054 // Otherwise, can only export this if it is already exported.
1055 return FuncInfo.isExportedInst(V);
1058 // Otherwise, constants can always be exported.
1062 static bool InBlock(const Value *V, const BasicBlock *BB) {
1063 if (const Instruction *I = dyn_cast<Instruction>(V))
1064 return I->getParent() == BB;
1068 /// getFCmpCondCode - Return the ISD condition code corresponding to
1069 /// the given LLVM IR floating-point condition code. This includes
1070 /// consideration of global floating-point math flags.
1072 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1073 ISD::CondCode FPC, FOC;
1075 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1076 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1077 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1078 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1079 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1080 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1081 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1082 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1083 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1084 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1085 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1086 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1087 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1088 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1089 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1090 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1092 llvm_unreachable("Invalid FCmp predicate opcode!");
1093 FOC = FPC = ISD::SETFALSE;
1096 if (FiniteOnlyFPMath())
1102 /// getICmpCondCode - Return the ISD condition code corresponding to
1103 /// the given LLVM IR integer condition code.
1105 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1107 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1108 case ICmpInst::ICMP_NE: return ISD::SETNE;
1109 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1110 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1111 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1112 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1113 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1114 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1115 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1116 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1118 llvm_unreachable("Invalid ICmp predicate opcode!");
1123 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1124 /// This function emits a branch and is used at the leaves of an OR or an
1125 /// AND operator tree.
1128 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1129 MachineBasicBlock *TBB,
1130 MachineBasicBlock *FBB,
1131 MachineBasicBlock *CurBB) {
1132 const BasicBlock *BB = CurBB->getBasicBlock();
1134 // If the leaf of the tree is a comparison, merge the condition into
1136 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1137 // The operands of the cmp have to be in this block. We don't know
1138 // how to export them from some other block. If this is the first block
1139 // of the sequence, no exporting is needed.
1140 if (CurBB == CurMBB ||
1141 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1142 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1143 ISD::CondCode Condition;
1144 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1145 Condition = getICmpCondCode(IC->getPredicate());
1146 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1147 Condition = getFCmpCondCode(FC->getPredicate());
1149 Condition = ISD::SETEQ; // silence warning.
1150 llvm_unreachable("Unknown compare instruction");
1153 CaseBlock CB(Condition, BOp->getOperand(0),
1154 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1155 SwitchCases.push_back(CB);
1160 // Create a CaseBlock record representing this branch.
1161 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1162 NULL, TBB, FBB, CurBB);
1163 SwitchCases.push_back(CB);
1166 /// FindMergedConditions - If Cond is an expression like
1167 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1168 MachineBasicBlock *TBB,
1169 MachineBasicBlock *FBB,
1170 MachineBasicBlock *CurBB,
1172 // If this node is not part of the or/and tree, emit it as a branch.
1173 Instruction *BOp = dyn_cast<Instruction>(Cond);
1174 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1175 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1176 BOp->getParent() != CurBB->getBasicBlock() ||
1177 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1178 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1179 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1183 // Create TmpBB after CurBB.
1184 MachineFunction::iterator BBI = CurBB;
1185 MachineFunction &MF = DAG.getMachineFunction();
1186 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1187 CurBB->getParent()->insert(++BBI, TmpBB);
1189 if (Opc == Instruction::Or) {
1190 // Codegen X | Y as:
1198 // Emit the LHS condition.
1199 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1201 // Emit the RHS condition into TmpBB.
1202 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1204 assert(Opc == Instruction::And && "Unknown merge op!");
1205 // Codegen X & Y as:
1212 // This requires creation of TmpBB after CurBB.
1214 // Emit the LHS condition.
1215 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1217 // Emit the RHS condition into TmpBB.
1218 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1222 /// If the set of cases should be emitted as a series of branches, return true.
1223 /// If we should emit this as a bunch of and/or'd together conditions, return
1226 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1227 if (Cases.size() != 2) return true;
1229 // If this is two comparisons of the same values or'd or and'd together, they
1230 // will get folded into a single comparison, so don't emit two blocks.
1231 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1232 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1233 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1234 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1241 void SelectionDAGLowering::visitBr(BranchInst &I) {
1242 // Update machine-CFG edges.
1243 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1245 // Figure out which block is immediately after the current one.
1246 MachineBasicBlock *NextBlock = 0;
1247 MachineFunction::iterator BBI = CurMBB;
1248 if (++BBI != FuncInfo.MF->end())
1251 if (I.isUnconditional()) {
1252 // Update machine-CFG edges.
1253 CurMBB->addSuccessor(Succ0MBB);
1255 // If this is not a fall-through branch, emit the branch.
1256 if (Succ0MBB != NextBlock)
1257 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1258 MVT::Other, getControlRoot(),
1259 DAG.getBasicBlock(Succ0MBB)));
1263 // If this condition is one of the special cases we handle, do special stuff
1265 Value *CondVal = I.getCondition();
1266 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1268 // If this is a series of conditions that are or'd or and'd together, emit
1269 // this as a sequence of branches instead of setcc's with and/or operations.
1270 // For example, instead of something like:
1283 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1284 if (BOp->hasOneUse() &&
1285 (BOp->getOpcode() == Instruction::And ||
1286 BOp->getOpcode() == Instruction::Or)) {
1287 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1288 // If the compares in later blocks need to use values not currently
1289 // exported from this block, export them now. This block should always
1290 // be the first entry.
1291 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1293 // Allow some cases to be rejected.
1294 if (ShouldEmitAsBranches(SwitchCases)) {
1295 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1296 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1297 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1300 // Emit the branch for this block.
1301 visitSwitchCase(SwitchCases[0]);
1302 SwitchCases.erase(SwitchCases.begin());
1306 // Okay, we decided not to do this, remove any inserted MBB's and clear
1308 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1309 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1311 SwitchCases.clear();
1315 // Create a CaseBlock record representing this branch.
1316 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1317 NULL, Succ0MBB, Succ1MBB, CurMBB);
1318 // Use visitSwitchCase to actually insert the fast branch sequence for this
1320 visitSwitchCase(CB);
1323 /// visitSwitchCase - Emits the necessary code to represent a single node in
1324 /// the binary search tree resulting from lowering a switch instruction.
1325 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1327 SDValue CondLHS = getValue(CB.CmpLHS);
1328 DebugLoc dl = getCurDebugLoc();
1330 // Build the setcc now.
1331 if (CB.CmpMHS == NULL) {
1332 // Fold "(X == true)" to X and "(X == false)" to !X to
1333 // handle common cases produced by branch lowering.
1334 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1335 CB.CC == ISD::SETEQ)
1337 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1338 CB.CC == ISD::SETEQ) {
1339 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1340 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1342 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1344 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1346 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1347 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1349 SDValue CmpOp = getValue(CB.CmpMHS);
1350 EVT VT = CmpOp.getValueType();
1352 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1353 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1356 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1357 VT, CmpOp, DAG.getConstant(Low, VT));
1358 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1359 DAG.getConstant(High-Low, VT), ISD::SETULE);
1363 // Update successor info
1364 CurMBB->addSuccessor(CB.TrueBB);
1365 CurMBB->addSuccessor(CB.FalseBB);
1367 // Set NextBlock to be the MBB immediately after the current one, if any.
1368 // This is used to avoid emitting unnecessary branches to the next block.
1369 MachineBasicBlock *NextBlock = 0;
1370 MachineFunction::iterator BBI = CurMBB;
1371 if (++BBI != FuncInfo.MF->end())
1374 // If the lhs block is the next block, invert the condition so that we can
1375 // fall through to the lhs instead of the rhs block.
1376 if (CB.TrueBB == NextBlock) {
1377 std::swap(CB.TrueBB, CB.FalseBB);
1378 SDValue True = DAG.getConstant(1, Cond.getValueType());
1379 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1381 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1382 MVT::Other, getControlRoot(), Cond,
1383 DAG.getBasicBlock(CB.TrueBB));
1385 // If the branch was constant folded, fix up the CFG.
1386 if (BrCond.getOpcode() == ISD::BR) {
1387 CurMBB->removeSuccessor(CB.FalseBB);
1388 DAG.setRoot(BrCond);
1390 // Otherwise, go ahead and insert the false branch.
1391 if (BrCond == getControlRoot())
1392 CurMBB->removeSuccessor(CB.TrueBB);
1394 if (CB.FalseBB == NextBlock)
1395 DAG.setRoot(BrCond);
1397 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1398 DAG.getBasicBlock(CB.FalseBB)));
1402 /// visitJumpTable - Emit JumpTable node in the current MBB
1403 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1404 // Emit the code for the jump table
1405 assert(JT.Reg != -1U && "Should lower JT Header first!");
1406 EVT PTy = TLI.getPointerTy();
1407 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1409 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1410 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1411 MVT::Other, Index.getValue(1),
1415 /// visitJumpTableHeader - This function emits necessary code to produce index
1416 /// in the JumpTable from switch case.
1417 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1418 JumpTableHeader &JTH) {
1419 // Subtract the lowest switch case value from the value being switched on and
1420 // conditional branch to default mbb if the result is greater than the
1421 // difference between smallest and largest cases.
1422 SDValue SwitchOp = getValue(JTH.SValue);
1423 EVT VT = SwitchOp.getValueType();
1424 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1425 DAG.getConstant(JTH.First, VT));
1427 // The SDNode we just created, which holds the value being switched on minus
1428 // the the smallest case value, needs to be copied to a virtual register so it
1429 // can be used as an index into the jump table in a subsequent basic block.
1430 // This value may be smaller or larger than the target's pointer type, and
1431 // therefore require extension or truncating.
1432 SwitchOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
1434 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1435 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1436 JumpTableReg, SwitchOp);
1437 JT.Reg = JumpTableReg;
1439 // Emit the range check for the jump table, and branch to the default block
1440 // for the switch statement if the value being switched on exceeds the largest
1441 // case in the switch.
1442 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1443 TLI.getSetCCResultType(SUB.getValueType()), SUB,
1444 DAG.getConstant(JTH.Last-JTH.First,VT),
1447 // Set NextBlock to be the MBB immediately after the current one, if any.
1448 // This is used to avoid emitting unnecessary branches to the next block.
1449 MachineBasicBlock *NextBlock = 0;
1450 MachineFunction::iterator BBI = CurMBB;
1451 if (++BBI != FuncInfo.MF->end())
1454 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1455 MVT::Other, CopyTo, CMP,
1456 DAG.getBasicBlock(JT.Default));
1458 if (JT.MBB == NextBlock)
1459 DAG.setRoot(BrCond);
1461 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1462 DAG.getBasicBlock(JT.MBB)));
1465 /// visitBitTestHeader - This function emits necessary code to produce value
1466 /// suitable for "bit tests"
1467 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1468 // Subtract the minimum value
1469 SDValue SwitchOp = getValue(B.SValue);
1470 EVT VT = SwitchOp.getValueType();
1471 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1472 DAG.getConstant(B.First, VT));
1475 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1476 TLI.getSetCCResultType(SUB.getValueType()),
1477 SUB, DAG.getConstant(B.Range, VT),
1480 SDValue ShiftOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
1482 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1483 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1486 // Set NextBlock to be the MBB immediately after the current one, if any.
1487 // This is used to avoid emitting unnecessary branches to the next block.
1488 MachineBasicBlock *NextBlock = 0;
1489 MachineFunction::iterator BBI = CurMBB;
1490 if (++BBI != FuncInfo.MF->end())
1493 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1495 CurMBB->addSuccessor(B.Default);
1496 CurMBB->addSuccessor(MBB);
1498 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1499 MVT::Other, CopyTo, RangeCmp,
1500 DAG.getBasicBlock(B.Default));
1502 if (MBB == NextBlock)
1503 DAG.setRoot(BrRange);
1505 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1506 DAG.getBasicBlock(MBB)));
1509 /// visitBitTestCase - this function produces one "bit test"
1510 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1513 // Make desired shift
1514 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1515 TLI.getPointerTy());
1516 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1518 DAG.getConstant(1, TLI.getPointerTy()),
1521 // Emit bit tests and jumps
1522 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1523 TLI.getPointerTy(), SwitchVal,
1524 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1525 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1526 TLI.getSetCCResultType(AndOp.getValueType()),
1527 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1530 CurMBB->addSuccessor(B.TargetBB);
1531 CurMBB->addSuccessor(NextMBB);
1533 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1534 MVT::Other, getControlRoot(),
1535 AndCmp, DAG.getBasicBlock(B.TargetBB));
1537 // Set NextBlock to be the MBB immediately after the current one, if any.
1538 // This is used to avoid emitting unnecessary branches to the next block.
1539 MachineBasicBlock *NextBlock = 0;
1540 MachineFunction::iterator BBI = CurMBB;
1541 if (++BBI != FuncInfo.MF->end())
1544 if (NextMBB == NextBlock)
1547 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1548 DAG.getBasicBlock(NextMBB)));
1551 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1552 // Retrieve successors.
1553 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1554 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1556 const Value *Callee(I.getCalledValue());
1557 if (isa<InlineAsm>(Callee))
1560 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1562 // If the value of the invoke is used outside of its defining block, make it
1563 // available as a virtual register.
1564 CopyToExportRegsIfNeeded(&I);
1566 // Update successor info
1567 CurMBB->addSuccessor(Return);
1568 CurMBB->addSuccessor(LandingPad);
1570 // Drop into normal successor.
1571 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1572 MVT::Other, getControlRoot(),
1573 DAG.getBasicBlock(Return)));
1576 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1579 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1580 /// small case ranges).
1581 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1582 CaseRecVector& WorkList,
1584 MachineBasicBlock* Default) {
1585 Case& BackCase = *(CR.Range.second-1);
1587 // Size is the number of Cases represented by this range.
1588 size_t Size = CR.Range.second - CR.Range.first;
1592 // Get the MachineFunction which holds the current MBB. This is used when
1593 // inserting any additional MBBs necessary to represent the switch.
1594 MachineFunction *CurMF = FuncInfo.MF;
1596 // Figure out which block is immediately after the current one.
1597 MachineBasicBlock *NextBlock = 0;
1598 MachineFunction::iterator BBI = CR.CaseBB;
1600 if (++BBI != FuncInfo.MF->end())
1603 // TODO: If any two of the cases has the same destination, and if one value
1604 // is the same as the other, but has one bit unset that the other has set,
1605 // use bit manipulation to do two compares at once. For example:
1606 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1608 // Rearrange the case blocks so that the last one falls through if possible.
1609 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1610 // The last case block won't fall through into 'NextBlock' if we emit the
1611 // branches in this order. See if rearranging a case value would help.
1612 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1613 if (I->BB == NextBlock) {
1614 std::swap(*I, BackCase);
1620 // Create a CaseBlock record representing a conditional branch to
1621 // the Case's target mbb if the value being switched on SV is equal
1623 MachineBasicBlock *CurBlock = CR.CaseBB;
1624 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1625 MachineBasicBlock *FallThrough;
1627 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1628 CurMF->insert(BBI, FallThrough);
1630 // Put SV in a virtual register to make it available from the new blocks.
1631 ExportFromCurrentBlock(SV);
1633 // If the last case doesn't match, go to the default block.
1634 FallThrough = Default;
1637 Value *RHS, *LHS, *MHS;
1639 if (I->High == I->Low) {
1640 // This is just small small case range :) containing exactly 1 case
1642 LHS = SV; RHS = I->High; MHS = NULL;
1645 LHS = I->Low; MHS = SV; RHS = I->High;
1647 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1649 // If emitting the first comparison, just call visitSwitchCase to emit the
1650 // code into the current block. Otherwise, push the CaseBlock onto the
1651 // vector to be later processed by SDISel, and insert the node's MBB
1652 // before the next MBB.
1653 if (CurBlock == CurMBB)
1654 visitSwitchCase(CB);
1656 SwitchCases.push_back(CB);
1658 CurBlock = FallThrough;
1664 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1665 return !DisableJumpTables &&
1666 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1667 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1670 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1671 APInt LastExt(Last), FirstExt(First);
1672 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1673 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1674 return (LastExt - FirstExt + 1ULL);
1677 /// handleJTSwitchCase - Emit jumptable for current switch case range
1678 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1679 CaseRecVector& WorkList,
1681 MachineBasicBlock* Default) {
1682 Case& FrontCase = *CR.Range.first;
1683 Case& BackCase = *(CR.Range.second-1);
1685 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1686 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
1689 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1693 if (!areJTsAllowed(TLI) || TSize <= 3)
1696 APInt Range = ComputeRange(First, Last);
1697 double Density = (double)TSize / Range.roundToDouble();
1701 DEBUG(errs() << "Lowering jump table\n"
1702 << "First entry: " << First << ". Last entry: " << Last << '\n'
1703 << "Range: " << Range
1704 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1706 // Get the MachineFunction which holds the current MBB. This is used when
1707 // inserting any additional MBBs necessary to represent the switch.
1708 MachineFunction *CurMF = FuncInfo.MF;
1710 // Figure out which block is immediately after the current one.
1711 MachineFunction::iterator BBI = CR.CaseBB;
1714 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1716 // Create a new basic block to hold the code for loading the address
1717 // of the jump table, and jumping to it. Update successor information;
1718 // we will either branch to the default case for the switch, or the jump
1720 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1721 CurMF->insert(BBI, JumpTableBB);
1722 CR.CaseBB->addSuccessor(Default);
1723 CR.CaseBB->addSuccessor(JumpTableBB);
1725 // Build a vector of destination BBs, corresponding to each target
1726 // of the jump table. If the value of the jump table slot corresponds to
1727 // a case statement, push the case's BB onto the vector, otherwise, push
1729 std::vector<MachineBasicBlock*> DestBBs;
1731 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1732 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1733 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1735 if (Low.sle(TEI) && TEI.sle(High)) {
1736 DestBBs.push_back(I->BB);
1740 DestBBs.push_back(Default);
1744 // Update successor info. Add one edge to each unique successor.
1745 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1746 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1747 E = DestBBs.end(); I != E; ++I) {
1748 if (!SuccsHandled[(*I)->getNumber()]) {
1749 SuccsHandled[(*I)->getNumber()] = true;
1750 JumpTableBB->addSuccessor(*I);
1754 // Create a jump table index for this jump table, or return an existing
1756 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1758 // Set the jump table information so that we can codegen it as a second
1759 // MachineBasicBlock
1760 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1761 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1762 if (CR.CaseBB == CurMBB)
1763 visitJumpTableHeader(JT, JTH);
1765 JTCases.push_back(JumpTableBlock(JTH, JT));
1770 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1772 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1773 CaseRecVector& WorkList,
1775 MachineBasicBlock* Default) {
1776 // Get the MachineFunction which holds the current MBB. This is used when
1777 // inserting any additional MBBs necessary to represent the switch.
1778 MachineFunction *CurMF = FuncInfo.MF;
1780 // Figure out which block is immediately after the current one.
1781 MachineFunction::iterator BBI = CR.CaseBB;
1784 Case& FrontCase = *CR.Range.first;
1785 Case& BackCase = *(CR.Range.second-1);
1786 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1788 // Size is the number of Cases represented by this range.
1789 unsigned Size = CR.Range.second - CR.Range.first;
1791 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1792 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
1794 CaseItr Pivot = CR.Range.first + Size/2;
1796 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1797 // (heuristically) allow us to emit JumpTable's later.
1799 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1803 size_t LSize = FrontCase.size();
1804 size_t RSize = TSize-LSize;
1805 DEBUG(errs() << "Selecting best pivot: \n"
1806 << "First: " << First << ", Last: " << Last <<'\n'
1807 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1808 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1810 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1811 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
1812 APInt Range = ComputeRange(LEnd, RBegin);
1813 assert((Range - 2ULL).isNonNegative() &&
1814 "Invalid case distance");
1815 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1816 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
1817 double Metric = Range.logBase2()*(LDensity+RDensity);
1818 // Should always split in some non-trivial place
1819 DEBUG(errs() <<"=>Step\n"
1820 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1821 << "LDensity: " << LDensity
1822 << ", RDensity: " << RDensity << '\n'
1823 << "Metric: " << Metric << '\n');
1824 if (FMetric < Metric) {
1827 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1833 if (areJTsAllowed(TLI)) {
1834 // If our case is dense we *really* should handle it earlier!
1835 assert((FMetric > 0) && "Should handle dense range earlier!");
1837 Pivot = CR.Range.first + Size/2;
1840 CaseRange LHSR(CR.Range.first, Pivot);
1841 CaseRange RHSR(Pivot, CR.Range.second);
1842 Constant *C = Pivot->Low;
1843 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1845 // We know that we branch to the LHS if the Value being switched on is
1846 // less than the Pivot value, C. We use this to optimize our binary
1847 // tree a bit, by recognizing that if SV is greater than or equal to the
1848 // LHS's Case Value, and that Case Value is exactly one less than the
1849 // Pivot's Value, then we can branch directly to the LHS's Target,
1850 // rather than creating a leaf node for it.
1851 if ((LHSR.second - LHSR.first) == 1 &&
1852 LHSR.first->High == CR.GE &&
1853 cast<ConstantInt>(C)->getValue() ==
1854 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1855 TrueBB = LHSR.first->BB;
1857 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1858 CurMF->insert(BBI, TrueBB);
1859 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1861 // Put SV in a virtual register to make it available from the new blocks.
1862 ExportFromCurrentBlock(SV);
1865 // Similar to the optimization above, if the Value being switched on is
1866 // known to be less than the Constant CR.LT, and the current Case Value
1867 // is CR.LT - 1, then we can branch directly to the target block for
1868 // the current Case Value, rather than emitting a RHS leaf node for it.
1869 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1870 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1871 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1872 FalseBB = RHSR.first->BB;
1874 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1875 CurMF->insert(BBI, FalseBB);
1876 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1878 // Put SV in a virtual register to make it available from the new blocks.
1879 ExportFromCurrentBlock(SV);
1882 // Create a CaseBlock record representing a conditional branch to
1883 // the LHS node if the value being switched on SV is less than C.
1884 // Otherwise, branch to LHS.
1885 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1887 if (CR.CaseBB == CurMBB)
1888 visitSwitchCase(CB);
1890 SwitchCases.push_back(CB);
1895 /// handleBitTestsSwitchCase - if current case range has few destination and
1896 /// range span less, than machine word bitwidth, encode case range into series
1897 /// of masks and emit bit tests with these masks.
1898 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1899 CaseRecVector& WorkList,
1901 MachineBasicBlock* Default){
1902 EVT PTy = TLI.getPointerTy();
1903 unsigned IntPtrBits = PTy.getSizeInBits();
1905 Case& FrontCase = *CR.Range.first;
1906 Case& BackCase = *(CR.Range.second-1);
1908 // Get the MachineFunction which holds the current MBB. This is used when
1909 // inserting any additional MBBs necessary to represent the switch.
1910 MachineFunction *CurMF = FuncInfo.MF;
1912 // If target does not have legal shift left, do not emit bit tests at all.
1913 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1917 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1919 // Single case counts one, case range - two.
1920 numCmps += (I->Low == I->High ? 1 : 2);
1923 // Count unique destinations
1924 SmallSet<MachineBasicBlock*, 4> Dests;
1925 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1926 Dests.insert(I->BB);
1927 if (Dests.size() > 3)
1928 // Don't bother the code below, if there are too much unique destinations
1931 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1932 << "Total number of comparisons: " << numCmps << '\n');
1934 // Compute span of values.
1935 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1936 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1937 APInt cmpRange = maxValue - minValue;
1939 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1940 << "Low bound: " << minValue << '\n'
1941 << "High bound: " << maxValue << '\n');
1943 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1944 (!(Dests.size() == 1 && numCmps >= 3) &&
1945 !(Dests.size() == 2 && numCmps >= 5) &&
1946 !(Dests.size() >= 3 && numCmps >= 6)))
1949 DEBUG(errs() << "Emitting bit tests\n");
1950 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1952 // Optimize the case where all the case values fit in a
1953 // word without having to subtract minValue. In this case,
1954 // we can optimize away the subtraction.
1955 if (minValue.isNonNegative() &&
1956 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1957 cmpRange = maxValue;
1959 lowBound = minValue;
1962 CaseBitsVector CasesBits;
1963 unsigned i, count = 0;
1965 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1966 MachineBasicBlock* Dest = I->BB;
1967 for (i = 0; i < count; ++i)
1968 if (Dest == CasesBits[i].BB)
1972 assert((count < 3) && "Too much destinations to test!");
1973 CasesBits.push_back(CaseBits(0, Dest, 0));
1977 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1978 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1980 uint64_t lo = (lowValue - lowBound).getZExtValue();
1981 uint64_t hi = (highValue - lowBound).getZExtValue();
1983 for (uint64_t j = lo; j <= hi; j++) {
1984 CasesBits[i].Mask |= 1ULL << j;
1985 CasesBits[i].Bits++;
1989 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1993 // Figure out which block is immediately after the current one.
1994 MachineFunction::iterator BBI = CR.CaseBB;
1997 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1999 DEBUG(errs() << "Cases:\n");
2000 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2001 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2002 << ", Bits: " << CasesBits[i].Bits
2003 << ", BB: " << CasesBits[i].BB << '\n');
2005 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2006 CurMF->insert(BBI, CaseBB);
2007 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2011 // Put SV in a virtual register to make it available from the new blocks.
2012 ExportFromCurrentBlock(SV);
2015 BitTestBlock BTB(lowBound, cmpRange, SV,
2016 -1U, (CR.CaseBB == CurMBB),
2017 CR.CaseBB, Default, BTC);
2019 if (CR.CaseBB == CurMBB)
2020 visitBitTestHeader(BTB);
2022 BitTestCases.push_back(BTB);
2028 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2029 size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
2030 const SwitchInst& SI) {
2033 // Start with "simple" cases
2034 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2035 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2036 Cases.push_back(Case(SI.getSuccessorValue(i),
2037 SI.getSuccessorValue(i),
2040 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2042 // Merge case into clusters
2043 if (Cases.size() >= 2)
2044 // Must recompute end() each iteration because it may be
2045 // invalidated by erase if we hold on to it
2046 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2047 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2048 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2049 MachineBasicBlock* nextBB = J->BB;
2050 MachineBasicBlock* currentBB = I->BB;
2052 // If the two neighboring cases go to the same destination, merge them
2053 // into a single case.
2054 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2062 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2063 if (I->Low != I->High)
2064 // A range counts double, since it requires two compares.
2071 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2072 // Figure out which block is immediately after the current one.
2073 MachineBasicBlock *NextBlock = 0;
2075 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2077 // If there is only the default destination, branch to it if it is not the
2078 // next basic block. Otherwise, just fall through.
2079 if (SI.getNumOperands() == 2) {
2080 // Update machine-CFG edges.
2082 // If this is not a fall-through branch, emit the branch.
2083 CurMBB->addSuccessor(Default);
2084 if (Default != NextBlock)
2085 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2086 MVT::Other, getControlRoot(),
2087 DAG.getBasicBlock(Default)));
2091 // If there are any non-default case statements, create a vector of Cases
2092 // representing each one, and sort the vector so that we can efficiently
2093 // create a binary search tree from them.
2095 size_t numCmps = Clusterify(Cases, SI);
2096 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2097 << ". Total compares: " << numCmps << '\n');
2100 // Get the Value to be switched on and default basic blocks, which will be
2101 // inserted into CaseBlock records, representing basic blocks in the binary
2103 Value *SV = SI.getOperand(0);
2105 // Push the initial CaseRec onto the worklist
2106 CaseRecVector WorkList;
2107 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2109 while (!WorkList.empty()) {
2110 // Grab a record representing a case range to process off the worklist
2111 CaseRec CR = WorkList.back();
2112 WorkList.pop_back();
2114 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2117 // If the range has few cases (two or less) emit a series of specific
2119 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2122 // If the switch has more than 5 blocks, and at least 40% dense, and the
2123 // target supports indirect branches, then emit a jump table rather than
2124 // lowering the switch to a binary tree of conditional branches.
2125 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2128 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2129 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2130 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2135 void SelectionDAGLowering::visitFSub(User &I) {
2136 // -0.0 - X --> fneg
2137 const Type *Ty = I.getType();
2138 if (isa<VectorType>(Ty)) {
2139 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2140 const VectorType *DestTy = cast<VectorType>(I.getType());
2141 const Type *ElTy = DestTy->getElementType();
2142 unsigned VL = DestTy->getNumElements();
2143 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2144 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2146 SDValue Op2 = getValue(I.getOperand(1));
2147 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2148 Op2.getValueType(), Op2));
2153 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2154 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2155 SDValue Op2 = getValue(I.getOperand(1));
2156 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2157 Op2.getValueType(), Op2));
2161 visitBinary(I, ISD::FSUB);
2164 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2165 SDValue Op1 = getValue(I.getOperand(0));
2166 SDValue Op2 = getValue(I.getOperand(1));
2168 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2169 Op1.getValueType(), Op1, Op2));
2172 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2173 SDValue Op1 = getValue(I.getOperand(0));
2174 SDValue Op2 = getValue(I.getOperand(1));
2175 if (!isa<VectorType>(I.getType()) &&
2176 Op2.getValueType() != TLI.getShiftAmountTy()) {
2177 // If the operand is smaller than the shift count type, promote it.
2178 EVT PTy = TLI.getPointerTy();
2179 EVT STy = TLI.getShiftAmountTy();
2180 if (STy.bitsGT(Op2.getValueType()))
2181 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2182 TLI.getShiftAmountTy(), Op2);
2183 // If the operand is larger than the shift count type but the shift
2184 // count type has enough bits to represent any shift value, truncate
2185 // it now. This is a common case and it exposes the truncate to
2186 // optimization early.
2187 else if (STy.getSizeInBits() >=
2188 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2189 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2190 TLI.getShiftAmountTy(), Op2);
2191 // Otherwise we'll need to temporarily settle for some other
2192 // convenient type; type legalization will make adjustments as
2194 else if (PTy.bitsLT(Op2.getValueType()))
2195 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2196 TLI.getPointerTy(), Op2);
2197 else if (PTy.bitsGT(Op2.getValueType()))
2198 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2199 TLI.getPointerTy(), Op2);
2202 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2203 Op1.getValueType(), Op1, Op2));
2206 void SelectionDAGLowering::visitICmp(User &I) {
2207 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2208 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2209 predicate = IC->getPredicate();
2210 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2211 predicate = ICmpInst::Predicate(IC->getPredicate());
2212 SDValue Op1 = getValue(I.getOperand(0));
2213 SDValue Op2 = getValue(I.getOperand(1));
2214 ISD::CondCode Opcode = getICmpCondCode(predicate);
2216 EVT DestVT = TLI.getValueType(I.getType());
2217 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2220 void SelectionDAGLowering::visitFCmp(User &I) {
2221 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2222 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2223 predicate = FC->getPredicate();
2224 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2225 predicate = FCmpInst::Predicate(FC->getPredicate());
2226 SDValue Op1 = getValue(I.getOperand(0));
2227 SDValue Op2 = getValue(I.getOperand(1));
2228 ISD::CondCode Condition = getFCmpCondCode(predicate);
2229 EVT DestVT = TLI.getValueType(I.getType());
2230 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2233 void SelectionDAGLowering::visitSelect(User &I) {
2234 SmallVector<EVT, 4> ValueVTs;
2235 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2236 unsigned NumValues = ValueVTs.size();
2237 if (NumValues != 0) {
2238 SmallVector<SDValue, 4> Values(NumValues);
2239 SDValue Cond = getValue(I.getOperand(0));
2240 SDValue TrueVal = getValue(I.getOperand(1));
2241 SDValue FalseVal = getValue(I.getOperand(2));
2243 for (unsigned i = 0; i != NumValues; ++i)
2244 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2245 TrueVal.getValueType(), Cond,
2246 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2247 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2249 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2250 DAG.getVTList(&ValueVTs[0], NumValues),
2251 &Values[0], NumValues));
2256 void SelectionDAGLowering::visitTrunc(User &I) {
2257 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2258 SDValue N = getValue(I.getOperand(0));
2259 EVT DestVT = TLI.getValueType(I.getType());
2260 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2263 void SelectionDAGLowering::visitZExt(User &I) {
2264 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2265 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2266 SDValue N = getValue(I.getOperand(0));
2267 EVT DestVT = TLI.getValueType(I.getType());
2268 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2271 void SelectionDAGLowering::visitSExt(User &I) {
2272 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2273 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2274 SDValue N = getValue(I.getOperand(0));
2275 EVT DestVT = TLI.getValueType(I.getType());
2276 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2279 void SelectionDAGLowering::visitFPTrunc(User &I) {
2280 // FPTrunc is never a no-op cast, no need to check
2281 SDValue N = getValue(I.getOperand(0));
2282 EVT DestVT = TLI.getValueType(I.getType());
2283 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2284 DestVT, N, DAG.getIntPtrConstant(0)));
2287 void SelectionDAGLowering::visitFPExt(User &I){
2288 // FPTrunc is never a no-op cast, no need to check
2289 SDValue N = getValue(I.getOperand(0));
2290 EVT DestVT = TLI.getValueType(I.getType());
2291 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2294 void SelectionDAGLowering::visitFPToUI(User &I) {
2295 // FPToUI is never a no-op cast, no need to check
2296 SDValue N = getValue(I.getOperand(0));
2297 EVT DestVT = TLI.getValueType(I.getType());
2298 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2301 void SelectionDAGLowering::visitFPToSI(User &I) {
2302 // FPToSI is never a no-op cast, no need to check
2303 SDValue N = getValue(I.getOperand(0));
2304 EVT DestVT = TLI.getValueType(I.getType());
2305 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2308 void SelectionDAGLowering::visitUIToFP(User &I) {
2309 // UIToFP is never a no-op cast, no need to check
2310 SDValue N = getValue(I.getOperand(0));
2311 EVT DestVT = TLI.getValueType(I.getType());
2312 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2315 void SelectionDAGLowering::visitSIToFP(User &I){
2316 // SIToFP is never a no-op cast, no need to check
2317 SDValue N = getValue(I.getOperand(0));
2318 EVT DestVT = TLI.getValueType(I.getType());
2319 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2322 void SelectionDAGLowering::visitPtrToInt(User &I) {
2323 // What to do depends on the size of the integer and the size of the pointer.
2324 // We can either truncate, zero extend, or no-op, accordingly.
2325 SDValue N = getValue(I.getOperand(0));
2326 EVT SrcVT = N.getValueType();
2327 EVT DestVT = TLI.getValueType(I.getType());
2328 SDValue Result = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2329 setValue(&I, Result);
2332 void SelectionDAGLowering::visitIntToPtr(User &I) {
2333 // What to do depends on the size of the integer and the size of the pointer.
2334 // We can either truncate, zero extend, or no-op, accordingly.
2335 SDValue N = getValue(I.getOperand(0));
2336 EVT SrcVT = N.getValueType();
2337 EVT DestVT = TLI.getValueType(I.getType());
2338 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2341 void SelectionDAGLowering::visitBitCast(User &I) {
2342 SDValue N = getValue(I.getOperand(0));
2343 EVT DestVT = TLI.getValueType(I.getType());
2345 // BitCast assures us that source and destination are the same size so this
2346 // is either a BIT_CONVERT or a no-op.
2347 if (DestVT != N.getValueType())
2348 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2349 DestVT, N)); // convert types
2351 setValue(&I, N); // noop cast.
2354 void SelectionDAGLowering::visitInsertElement(User &I) {
2355 SDValue InVec = getValue(I.getOperand(0));
2356 SDValue InVal = getValue(I.getOperand(1));
2357 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2359 getValue(I.getOperand(2)));
2361 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2362 TLI.getValueType(I.getType()),
2363 InVec, InVal, InIdx));
2366 void SelectionDAGLowering::visitExtractElement(User &I) {
2367 SDValue InVec = getValue(I.getOperand(0));
2368 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2370 getValue(I.getOperand(1)));
2371 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2372 TLI.getValueType(I.getType()), InVec, InIdx));
2376 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2377 // from SIndx and increasing to the element length (undefs are allowed).
2378 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2379 unsigned MaskNumElts = Mask.size();
2380 for (unsigned i = 0; i != MaskNumElts; ++i)
2381 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2386 void SelectionDAGLowering::visitShuffleVector(User &I) {
2387 SmallVector<int, 8> Mask;
2388 SDValue Src1 = getValue(I.getOperand(0));
2389 SDValue Src2 = getValue(I.getOperand(1));
2391 // Convert the ConstantVector mask operand into an array of ints, with -1
2392 // representing undef values.
2393 SmallVector<Constant*, 8> MaskElts;
2394 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
2396 unsigned MaskNumElts = MaskElts.size();
2397 for (unsigned i = 0; i != MaskNumElts; ++i) {
2398 if (isa<UndefValue>(MaskElts[i]))
2401 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2404 EVT VT = TLI.getValueType(I.getType());
2405 EVT SrcVT = Src1.getValueType();
2406 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2408 if (SrcNumElts == MaskNumElts) {
2409 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2414 // Normalize the shuffle vector since mask and vector length don't match.
2415 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2416 // Mask is longer than the source vectors and is a multiple of the source
2417 // vectors. We can use concatenate vector to make the mask and vectors
2419 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2420 // The shuffle is concatenating two vectors together.
2421 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2426 // Pad both vectors with undefs to make them the same length as the mask.
2427 unsigned NumConcat = MaskNumElts / SrcNumElts;
2428 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2429 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2430 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2432 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2433 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2437 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2438 getCurDebugLoc(), VT,
2439 &MOps1[0], NumConcat);
2440 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2441 getCurDebugLoc(), VT,
2442 &MOps2[0], NumConcat);
2444 // Readjust mask for new input vector length.
2445 SmallVector<int, 8> MappedOps;
2446 for (unsigned i = 0; i != MaskNumElts; ++i) {
2448 if (Idx < (int)SrcNumElts)
2449 MappedOps.push_back(Idx);
2451 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2453 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2458 if (SrcNumElts > MaskNumElts) {
2459 // Analyze the access pattern of the vector to see if we can extract
2460 // two subvectors and do the shuffle. The analysis is done by calculating
2461 // the range of elements the mask access on both vectors.
2462 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2463 int MaxRange[2] = {-1, -1};
2465 for (unsigned i = 0; i != MaskNumElts; ++i) {
2471 if (Idx >= (int)SrcNumElts) {
2475 if (Idx > MaxRange[Input])
2476 MaxRange[Input] = Idx;
2477 if (Idx < MinRange[Input])
2478 MinRange[Input] = Idx;
2481 // Check if the access is smaller than the vector size and can we find
2482 // a reasonable extract index.
2483 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2484 int StartIdx[2]; // StartIdx to extract from
2485 for (int Input=0; Input < 2; ++Input) {
2486 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2487 RangeUse[Input] = 0; // Unused
2488 StartIdx[Input] = 0;
2489 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2490 // Fits within range but we should see if we can find a good
2491 // start index that is a multiple of the mask length.
2492 if (MaxRange[Input] < (int)MaskNumElts) {
2493 RangeUse[Input] = 1; // Extract from beginning of the vector
2494 StartIdx[Input] = 0;
2496 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2497 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2498 StartIdx[Input] + MaskNumElts < SrcNumElts)
2499 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2504 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2505 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2508 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2509 // Extract appropriate subvector and generate a vector shuffle
2510 for (int Input=0; Input < 2; ++Input) {
2511 SDValue& Src = Input == 0 ? Src1 : Src2;
2512 if (RangeUse[Input] == 0) {
2513 Src = DAG.getUNDEF(VT);
2515 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2516 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2519 // Calculate new mask.
2520 SmallVector<int, 8> MappedOps;
2521 for (unsigned i = 0; i != MaskNumElts; ++i) {
2524 MappedOps.push_back(Idx);
2525 else if (Idx < (int)SrcNumElts)
2526 MappedOps.push_back(Idx - StartIdx[0]);
2528 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2530 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2536 // We can't use either concat vectors or extract subvectors so fall back to
2537 // replacing the shuffle with extract and build vector.
2538 // to insert and build vector.
2539 EVT EltVT = VT.getVectorElementType();
2540 EVT PtrVT = TLI.getPointerTy();
2541 SmallVector<SDValue,8> Ops;
2542 for (unsigned i = 0; i != MaskNumElts; ++i) {
2544 Ops.push_back(DAG.getUNDEF(EltVT));
2547 if (Idx < (int)SrcNumElts)
2548 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2549 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
2551 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2553 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
2556 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2557 VT, &Ops[0], Ops.size()));
2560 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2561 const Value *Op0 = I.getOperand(0);
2562 const Value *Op1 = I.getOperand(1);
2563 const Type *AggTy = I.getType();
2564 const Type *ValTy = Op1->getType();
2565 bool IntoUndef = isa<UndefValue>(Op0);
2566 bool FromUndef = isa<UndefValue>(Op1);
2568 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2569 I.idx_begin(), I.idx_end());
2571 SmallVector<EVT, 4> AggValueVTs;
2572 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2573 SmallVector<EVT, 4> ValValueVTs;
2574 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2576 unsigned NumAggValues = AggValueVTs.size();
2577 unsigned NumValValues = ValValueVTs.size();
2578 SmallVector<SDValue, 4> Values(NumAggValues);
2580 SDValue Agg = getValue(Op0);
2581 SDValue Val = getValue(Op1);
2583 // Copy the beginning value(s) from the original aggregate.
2584 for (; i != LinearIndex; ++i)
2585 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2586 SDValue(Agg.getNode(), Agg.getResNo() + i);
2587 // Copy values from the inserted value(s).
2588 for (; i != LinearIndex + NumValValues; ++i)
2589 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2590 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2591 // Copy remaining value(s) from the original aggregate.
2592 for (; i != NumAggValues; ++i)
2593 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2594 SDValue(Agg.getNode(), Agg.getResNo() + i);
2596 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2597 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2598 &Values[0], NumAggValues));
2601 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2602 const Value *Op0 = I.getOperand(0);
2603 const Type *AggTy = Op0->getType();
2604 const Type *ValTy = I.getType();
2605 bool OutOfUndef = isa<UndefValue>(Op0);
2607 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2608 I.idx_begin(), I.idx_end());
2610 SmallVector<EVT, 4> ValValueVTs;
2611 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2613 unsigned NumValValues = ValValueVTs.size();
2614 SmallVector<SDValue, 4> Values(NumValValues);
2616 SDValue Agg = getValue(Op0);
2617 // Copy out the selected value(s).
2618 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2619 Values[i - LinearIndex] =
2621 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2622 SDValue(Agg.getNode(), Agg.getResNo() + i);
2624 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2625 DAG.getVTList(&ValValueVTs[0], NumValValues),
2626 &Values[0], NumValValues));
2630 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2631 SDValue N = getValue(I.getOperand(0));
2632 const Type *Ty = I.getOperand(0)->getType();
2634 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2637 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2638 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2641 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2642 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2643 DAG.getIntPtrConstant(Offset));
2645 Ty = StTy->getElementType(Field);
2647 Ty = cast<SequentialType>(Ty)->getElementType();
2649 // If this is a constant subscript, handle it quickly.
2650 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2651 if (CI->getZExtValue() == 0) continue;
2653 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2655 EVT PTy = TLI.getPointerTy();
2656 unsigned PtrBits = PTy.getSizeInBits();
2658 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2660 DAG.getConstant(Offs, MVT::i64));
2662 OffsVal = DAG.getIntPtrConstant(Offs);
2663 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2668 // N = N + Idx * ElementSize;
2669 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2670 TD->getTypeAllocSize(Ty));
2671 SDValue IdxN = getValue(Idx);
2673 // If the index is smaller or larger than intptr_t, truncate or extend
2675 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2677 // If this is a multiply by a power of two, turn it into a shl
2678 // immediately. This is a very common case.
2679 if (ElementSize != 1) {
2680 if (ElementSize.isPowerOf2()) {
2681 unsigned Amt = ElementSize.logBase2();
2682 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2683 N.getValueType(), IdxN,
2684 DAG.getConstant(Amt, TLI.getPointerTy()));
2686 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2687 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2688 N.getValueType(), IdxN, Scale);
2692 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2693 N.getValueType(), N, IdxN);
2699 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2700 // If this is a fixed sized alloca in the entry block of the function,
2701 // allocate it statically on the stack.
2702 if (FuncInfo.StaticAllocaMap.count(&I))
2703 return; // getValue will auto-populate this.
2705 const Type *Ty = I.getAllocatedType();
2706 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2708 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2711 SDValue AllocSize = getValue(I.getArraySize());
2713 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2715 DAG.getConstant(TySize, AllocSize.getValueType()));
2719 EVT IntPtr = TLI.getPointerTy();
2720 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2722 // Handle alignment. If the requested alignment is less than or equal to
2723 // the stack alignment, ignore it. If the size is greater than or equal to
2724 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2725 unsigned StackAlign =
2726 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2727 if (Align <= StackAlign)
2730 // Round the size of the allocation up to the stack alignment size
2731 // by add SA-1 to the size.
2732 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2733 AllocSize.getValueType(), AllocSize,
2734 DAG.getIntPtrConstant(StackAlign-1));
2735 // Mask out the low bits for alignment purposes.
2736 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2737 AllocSize.getValueType(), AllocSize,
2738 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2740 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2741 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2742 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2745 DAG.setRoot(DSA.getValue(1));
2747 // Inform the Frame Information that we have just allocated a variable-sized
2749 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2752 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2753 const Value *SV = I.getOperand(0);
2754 SDValue Ptr = getValue(SV);
2756 const Type *Ty = I.getType();
2757 bool isVolatile = I.isVolatile();
2758 unsigned Alignment = I.getAlignment();
2760 SmallVector<EVT, 4> ValueVTs;
2761 SmallVector<uint64_t, 4> Offsets;
2762 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2763 unsigned NumValues = ValueVTs.size();
2768 bool ConstantMemory = false;
2770 // Serialize volatile loads with other side effects.
2772 else if (AA->pointsToConstantMemory(SV)) {
2773 // Do not serialize (non-volatile) loads of constant memory with anything.
2774 Root = DAG.getEntryNode();
2775 ConstantMemory = true;
2777 // Do not serialize non-volatile loads against each other.
2778 Root = DAG.getRoot();
2781 SmallVector<SDValue, 4> Values(NumValues);
2782 SmallVector<SDValue, 4> Chains(NumValues);
2783 EVT PtrVT = Ptr.getValueType();
2784 for (unsigned i = 0; i != NumValues; ++i) {
2785 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2786 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2788 DAG.getConstant(Offsets[i], PtrVT)),
2789 SV, Offsets[i], isVolatile, Alignment);
2791 Chains[i] = L.getValue(1);
2794 if (!ConstantMemory) {
2795 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2797 &Chains[0], NumValues);
2801 PendingLoads.push_back(Chain);
2804 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2805 DAG.getVTList(&ValueVTs[0], NumValues),
2806 &Values[0], NumValues));
2810 void SelectionDAGLowering::visitStore(StoreInst &I) {
2811 Value *SrcV = I.getOperand(0);
2812 Value *PtrV = I.getOperand(1);
2814 SmallVector<EVT, 4> ValueVTs;
2815 SmallVector<uint64_t, 4> Offsets;
2816 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2817 unsigned NumValues = ValueVTs.size();
2821 // Get the lowered operands. Note that we do this after
2822 // checking if NumResults is zero, because with zero results
2823 // the operands won't have values in the map.
2824 SDValue Src = getValue(SrcV);
2825 SDValue Ptr = getValue(PtrV);
2827 SDValue Root = getRoot();
2828 SmallVector<SDValue, 4> Chains(NumValues);
2829 EVT PtrVT = Ptr.getValueType();
2830 bool isVolatile = I.isVolatile();
2831 unsigned Alignment = I.getAlignment();
2832 for (unsigned i = 0; i != NumValues; ++i)
2833 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2834 SDValue(Src.getNode(), Src.getResNo() + i),
2835 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2837 DAG.getConstant(Offsets[i], PtrVT)),
2838 PtrV, Offsets[i], isVolatile, Alignment);
2840 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2841 MVT::Other, &Chains[0], NumValues));
2844 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2846 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2847 unsigned Intrinsic) {
2848 bool HasChain = !I.doesNotAccessMemory();
2849 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2851 // Build the operand list.
2852 SmallVector<SDValue, 8> Ops;
2853 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2855 // We don't need to serialize loads against other loads.
2856 Ops.push_back(DAG.getRoot());
2858 Ops.push_back(getRoot());
2862 // Info is set by getTgtMemInstrinsic
2863 TargetLowering::IntrinsicInfo Info;
2864 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2866 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2867 if (!IsTgtIntrinsic)
2868 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2870 // Add all operands of the call to the operand list.
2871 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2872 SDValue Op = getValue(I.getOperand(i));
2873 assert(TLI.isTypeLegal(Op.getValueType()) &&
2874 "Intrinsic uses a non-legal type?");
2878 SmallVector<EVT, 4> ValueVTs;
2879 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2881 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2882 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2883 "Intrinsic uses a non-legal type?");
2887 ValueVTs.push_back(MVT::Other);
2889 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
2893 if (IsTgtIntrinsic) {
2894 // This is target intrinsic that touches memory
2895 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2896 VTs, &Ops[0], Ops.size(),
2897 Info.memVT, Info.ptrVal, Info.offset,
2898 Info.align, Info.vol,
2899 Info.readMem, Info.writeMem);
2902 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2903 VTs, &Ops[0], Ops.size());
2904 else if (I.getType() != Type::getVoidTy(*DAG.getContext()))
2905 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2906 VTs, &Ops[0], Ops.size());
2908 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2909 VTs, &Ops[0], Ops.size());
2912 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2914 PendingLoads.push_back(Chain);
2918 if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
2919 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2920 EVT VT = TLI.getValueType(PTy);
2921 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2923 setValue(&I, Result);
2927 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2928 static GlobalVariable *ExtractTypeInfo(Value *V) {
2929 V = V->stripPointerCasts();
2930 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2931 assert ((GV || isa<ConstantPointerNull>(V)) &&
2932 "TypeInfo must be a global variable or NULL");
2938 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2939 /// call, and add them to the specified machine basic block.
2940 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2941 MachineBasicBlock *MBB) {
2942 // Inform the MachineModuleInfo of the personality for this landing pad.
2943 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2944 assert(CE->getOpcode() == Instruction::BitCast &&
2945 isa<Function>(CE->getOperand(0)) &&
2946 "Personality should be a function");
2947 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2949 // Gather all the type infos for this landing pad and pass them along to
2950 // MachineModuleInfo.
2951 std::vector<GlobalVariable *> TyInfo;
2952 unsigned N = I.getNumOperands();
2954 for (unsigned i = N - 1; i > 2; --i) {
2955 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2956 unsigned FilterLength = CI->getZExtValue();
2957 unsigned FirstCatch = i + FilterLength + !FilterLength;
2958 assert (FirstCatch <= N && "Invalid filter length");
2960 if (FirstCatch < N) {
2961 TyInfo.reserve(N - FirstCatch);
2962 for (unsigned j = FirstCatch; j < N; ++j)
2963 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2964 MMI->addCatchTypeInfo(MBB, TyInfo);
2968 if (!FilterLength) {
2970 MMI->addCleanup(MBB);
2973 TyInfo.reserve(FilterLength - 1);
2974 for (unsigned j = i + 1; j < FirstCatch; ++j)
2975 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2976 MMI->addFilterTypeInfo(MBB, TyInfo);
2985 TyInfo.reserve(N - 3);
2986 for (unsigned j = 3; j < N; ++j)
2987 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2988 MMI->addCatchTypeInfo(MBB, TyInfo);
2994 /// GetSignificand - Get the significand and build it into a floating-point
2995 /// number with exponent of 1:
2997 /// Op = (Op & 0x007fffff) | 0x3f800000;
2999 /// where Op is the hexidecimal representation of floating point value.
3001 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3002 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3003 DAG.getConstant(0x007fffff, MVT::i32));
3004 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3005 DAG.getConstant(0x3f800000, MVT::i32));
3006 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3009 /// GetExponent - Get the exponent:
3011 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3013 /// where Op is the hexidecimal representation of floating point value.
3015 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3017 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3018 DAG.getConstant(0x7f800000, MVT::i32));
3019 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3020 DAG.getConstant(23, TLI.getPointerTy()));
3021 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3022 DAG.getConstant(127, MVT::i32));
3023 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3026 /// getF32Constant - Get 32-bit floating point constant.
3028 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3029 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3032 /// Inlined utility function to implement binary input atomic intrinsics for
3033 /// visitIntrinsicCall: I is a call instruction
3034 /// Op is the associated NodeType for I
3036 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3037 SDValue Root = getRoot();
3039 DAG.getAtomic(Op, getCurDebugLoc(),
3040 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
3042 getValue(I.getOperand(1)),
3043 getValue(I.getOperand(2)),
3046 DAG.setRoot(L.getValue(1));
3050 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3052 SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
3053 SDValue Op1 = getValue(I.getOperand(1));
3054 SDValue Op2 = getValue(I.getOperand(2));
3056 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3057 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
3059 setValue(&I, Result);
3063 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3064 /// limited-precision mode.
3066 SelectionDAGLowering::visitExp(CallInst &I) {
3068 DebugLoc dl = getCurDebugLoc();
3070 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3071 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3072 SDValue Op = getValue(I.getOperand(1));
3074 // Put the exponent in the right bit position for later addition to the
3077 // #define LOG2OFe 1.4426950f
3078 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3079 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3080 getF32Constant(DAG, 0x3fb8aa3b));
3081 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3083 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3084 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3085 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3087 // IntegerPartOfX <<= 23;
3088 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3089 DAG.getConstant(23, TLI.getPointerTy()));
3091 if (LimitFloatPrecision <= 6) {
3092 // For floating-point precision of 6:
3094 // TwoToFractionalPartOfX =
3096 // (0.735607626f + 0.252464424f * x) * x;
3098 // error 0.0144103317, which is 6 bits
3099 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3100 getF32Constant(DAG, 0x3e814304));
3101 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3102 getF32Constant(DAG, 0x3f3c50c8));
3103 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3104 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3105 getF32Constant(DAG, 0x3f7f5e7e));
3106 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3108 // Add the exponent into the result in integer domain.
3109 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3110 TwoToFracPartOfX, IntegerPartOfX);
3112 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3113 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3114 // For floating-point precision of 12:
3116 // TwoToFractionalPartOfX =
3119 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3121 // 0.000107046256 error, which is 13 to 14 bits
3122 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3123 getF32Constant(DAG, 0x3da235e3));
3124 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3125 getF32Constant(DAG, 0x3e65b8f3));
3126 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3127 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3128 getF32Constant(DAG, 0x3f324b07));
3129 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3130 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3131 getF32Constant(DAG, 0x3f7ff8fd));
3132 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3134 // Add the exponent into the result in integer domain.
3135 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3136 TwoToFracPartOfX, IntegerPartOfX);
3138 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3139 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3140 // For floating-point precision of 18:
3142 // TwoToFractionalPartOfX =
3146 // (0.554906021e-1f +
3147 // (0.961591928e-2f +
3148 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3150 // error 2.47208000*10^(-7), which is better than 18 bits
3151 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3152 getF32Constant(DAG, 0x3924b03e));
3153 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3154 getF32Constant(DAG, 0x3ab24b87));
3155 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3156 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3157 getF32Constant(DAG, 0x3c1d8c17));
3158 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3159 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3160 getF32Constant(DAG, 0x3d634a1d));
3161 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3162 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3163 getF32Constant(DAG, 0x3e75fe14));
3164 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3165 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3166 getF32Constant(DAG, 0x3f317234));
3167 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3168 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3169 getF32Constant(DAG, 0x3f800000));
3170 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3173 // Add the exponent into the result in integer domain.
3174 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3175 TwoToFracPartOfX, IntegerPartOfX);
3177 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3180 // No special expansion.
3181 result = DAG.getNode(ISD::FEXP, dl,
3182 getValue(I.getOperand(1)).getValueType(),
3183 getValue(I.getOperand(1)));
3186 setValue(&I, result);
3189 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3190 /// limited-precision mode.
3192 SelectionDAGLowering::visitLog(CallInst &I) {
3194 DebugLoc dl = getCurDebugLoc();
3196 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3197 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3198 SDValue Op = getValue(I.getOperand(1));
3199 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3201 // Scale the exponent by log(2) [0.69314718f].
3202 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3203 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3204 getF32Constant(DAG, 0x3f317218));
3206 // Get the significand and build it into a floating-point number with
3208 SDValue X = GetSignificand(DAG, Op1, dl);
3210 if (LimitFloatPrecision <= 6) {
3211 // For floating-point precision of 6:
3215 // (1.4034025f - 0.23903021f * x) * x;
3217 // error 0.0034276066, which is better than 8 bits
3218 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3219 getF32Constant(DAG, 0xbe74c456));
3220 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3221 getF32Constant(DAG, 0x3fb3a2b1));
3222 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3223 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3224 getF32Constant(DAG, 0x3f949a29));
3226 result = DAG.getNode(ISD::FADD, dl,
3227 MVT::f32, LogOfExponent, LogOfMantissa);
3228 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3229 // For floating-point precision of 12:
3235 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3237 // error 0.000061011436, which is 14 bits
3238 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3239 getF32Constant(DAG, 0xbd67b6d6));
3240 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3241 getF32Constant(DAG, 0x3ee4f4b8));
3242 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3243 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3244 getF32Constant(DAG, 0x3fbc278b));
3245 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3246 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3247 getF32Constant(DAG, 0x40348e95));
3248 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3249 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3250 getF32Constant(DAG, 0x3fdef31a));
3252 result = DAG.getNode(ISD::FADD, dl,
3253 MVT::f32, LogOfExponent, LogOfMantissa);
3254 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3255 // For floating-point precision of 18:
3263 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3265 // error 0.0000023660568, which is better than 18 bits
3266 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3267 getF32Constant(DAG, 0xbc91e5ac));
3268 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3269 getF32Constant(DAG, 0x3e4350aa));
3270 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3271 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3272 getF32Constant(DAG, 0x3f60d3e3));
3273 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3274 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3275 getF32Constant(DAG, 0x4011cdf0));
3276 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3277 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3278 getF32Constant(DAG, 0x406cfd1c));
3279 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3280 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3281 getF32Constant(DAG, 0x408797cb));
3282 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3283 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3284 getF32Constant(DAG, 0x4006dcab));
3286 result = DAG.getNode(ISD::FADD, dl,
3287 MVT::f32, LogOfExponent, LogOfMantissa);
3290 // No special expansion.
3291 result = DAG.getNode(ISD::FLOG, dl,
3292 getValue(I.getOperand(1)).getValueType(),
3293 getValue(I.getOperand(1)));
3296 setValue(&I, result);
3299 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3300 /// limited-precision mode.
3302 SelectionDAGLowering::visitLog2(CallInst &I) {
3304 DebugLoc dl = getCurDebugLoc();
3306 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3307 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3308 SDValue Op = getValue(I.getOperand(1));
3309 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3311 // Get the exponent.
3312 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3314 // Get the significand and build it into a floating-point number with
3316 SDValue X = GetSignificand(DAG, Op1, dl);
3318 // Different possible minimax approximations of significand in
3319 // floating-point for various degrees of accuracy over [1,2].
3320 if (LimitFloatPrecision <= 6) {
3321 // For floating-point precision of 6:
3323 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3325 // error 0.0049451742, which is more than 7 bits
3326 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3327 getF32Constant(DAG, 0xbeb08fe0));
3328 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3329 getF32Constant(DAG, 0x40019463));
3330 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3331 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3332 getF32Constant(DAG, 0x3fd6633d));
3334 result = DAG.getNode(ISD::FADD, dl,
3335 MVT::f32, LogOfExponent, Log2ofMantissa);
3336 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3337 // For floating-point precision of 12:
3343 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3345 // error 0.0000876136000, which is better than 13 bits
3346 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3347 getF32Constant(DAG, 0xbda7262e));
3348 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3349 getF32Constant(DAG, 0x3f25280b));
3350 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3351 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3352 getF32Constant(DAG, 0x4007b923));
3353 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3354 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3355 getF32Constant(DAG, 0x40823e2f));
3356 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3357 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3358 getF32Constant(DAG, 0x4020d29c));
3360 result = DAG.getNode(ISD::FADD, dl,
3361 MVT::f32, LogOfExponent, Log2ofMantissa);
3362 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3363 // For floating-point precision of 18:
3372 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3374 // error 0.0000018516, which is better than 18 bits
3375 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3376 getF32Constant(DAG, 0xbcd2769e));
3377 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3378 getF32Constant(DAG, 0x3e8ce0b9));
3379 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3380 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3381 getF32Constant(DAG, 0x3fa22ae7));
3382 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3383 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3384 getF32Constant(DAG, 0x40525723));
3385 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3386 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3387 getF32Constant(DAG, 0x40aaf200));
3388 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3389 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3390 getF32Constant(DAG, 0x40c39dad));
3391 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3392 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3393 getF32Constant(DAG, 0x4042902c));
3395 result = DAG.getNode(ISD::FADD, dl,
3396 MVT::f32, LogOfExponent, Log2ofMantissa);
3399 // No special expansion.
3400 result = DAG.getNode(ISD::FLOG2, dl,
3401 getValue(I.getOperand(1)).getValueType(),
3402 getValue(I.getOperand(1)));
3405 setValue(&I, result);
3408 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3409 /// limited-precision mode.
3411 SelectionDAGLowering::visitLog10(CallInst &I) {
3413 DebugLoc dl = getCurDebugLoc();
3415 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3416 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3417 SDValue Op = getValue(I.getOperand(1));
3418 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3420 // Scale the exponent by log10(2) [0.30102999f].
3421 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3422 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3423 getF32Constant(DAG, 0x3e9a209a));
3425 // Get the significand and build it into a floating-point number with
3427 SDValue X = GetSignificand(DAG, Op1, dl);
3429 if (LimitFloatPrecision <= 6) {
3430 // For floating-point precision of 6:
3432 // Log10ofMantissa =
3434 // (0.60948995f - 0.10380950f * x) * x;
3436 // error 0.0014886165, which is 6 bits
3437 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3438 getF32Constant(DAG, 0xbdd49a13));
3439 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3440 getF32Constant(DAG, 0x3f1c0789));
3441 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3442 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3443 getF32Constant(DAG, 0x3f011300));
3445 result = DAG.getNode(ISD::FADD, dl,
3446 MVT::f32, LogOfExponent, Log10ofMantissa);
3447 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3448 // For floating-point precision of 12:
3450 // Log10ofMantissa =
3453 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3455 // error 0.00019228036, which is better than 12 bits
3456 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3457 getF32Constant(DAG, 0x3d431f31));
3458 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3459 getF32Constant(DAG, 0x3ea21fb2));
3460 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3461 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3462 getF32Constant(DAG, 0x3f6ae232));
3463 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3464 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3465 getF32Constant(DAG, 0x3f25f7c3));
3467 result = DAG.getNode(ISD::FADD, dl,
3468 MVT::f32, LogOfExponent, Log10ofMantissa);
3469 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3470 // For floating-point precision of 18:
3472 // Log10ofMantissa =
3477 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3479 // error 0.0000037995730, which is better than 18 bits
3480 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3481 getF32Constant(DAG, 0x3c5d51ce));
3482 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3483 getF32Constant(DAG, 0x3e00685a));
3484 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3485 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3486 getF32Constant(DAG, 0x3efb6798));
3487 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3488 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3489 getF32Constant(DAG, 0x3f88d192));
3490 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3491 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3492 getF32Constant(DAG, 0x3fc4316c));
3493 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3494 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3495 getF32Constant(DAG, 0x3f57ce70));
3497 result = DAG.getNode(ISD::FADD, dl,
3498 MVT::f32, LogOfExponent, Log10ofMantissa);
3501 // No special expansion.
3502 result = DAG.getNode(ISD::FLOG10, dl,
3503 getValue(I.getOperand(1)).getValueType(),
3504 getValue(I.getOperand(1)));
3507 setValue(&I, result);
3510 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3511 /// limited-precision mode.
3513 SelectionDAGLowering::visitExp2(CallInst &I) {
3515 DebugLoc dl = getCurDebugLoc();
3517 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3518 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3519 SDValue Op = getValue(I.getOperand(1));
3521 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3523 // FractionalPartOfX = x - (float)IntegerPartOfX;
3524 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3525 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3527 // IntegerPartOfX <<= 23;
3528 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3529 DAG.getConstant(23, TLI.getPointerTy()));
3531 if (LimitFloatPrecision <= 6) {
3532 // For floating-point precision of 6:
3534 // TwoToFractionalPartOfX =
3536 // (0.735607626f + 0.252464424f * x) * x;
3538 // error 0.0144103317, which is 6 bits
3539 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3540 getF32Constant(DAG, 0x3e814304));
3541 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3542 getF32Constant(DAG, 0x3f3c50c8));
3543 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3544 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3545 getF32Constant(DAG, 0x3f7f5e7e));
3546 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3547 SDValue TwoToFractionalPartOfX =
3548 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3550 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3551 MVT::f32, TwoToFractionalPartOfX);
3552 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3553 // For floating-point precision of 12:
3555 // TwoToFractionalPartOfX =
3558 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3560 // error 0.000107046256, which is 13 to 14 bits
3561 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3562 getF32Constant(DAG, 0x3da235e3));
3563 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3564 getF32Constant(DAG, 0x3e65b8f3));
3565 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3566 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3567 getF32Constant(DAG, 0x3f324b07));
3568 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3569 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3570 getF32Constant(DAG, 0x3f7ff8fd));
3571 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3572 SDValue TwoToFractionalPartOfX =
3573 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3575 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3576 MVT::f32, TwoToFractionalPartOfX);
3577 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3578 // For floating-point precision of 18:
3580 // TwoToFractionalPartOfX =
3584 // (0.554906021e-1f +
3585 // (0.961591928e-2f +
3586 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3587 // error 2.47208000*10^(-7), which is better than 18 bits
3588 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3589 getF32Constant(DAG, 0x3924b03e));
3590 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3591 getF32Constant(DAG, 0x3ab24b87));
3592 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3593 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3594 getF32Constant(DAG, 0x3c1d8c17));
3595 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3596 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3597 getF32Constant(DAG, 0x3d634a1d));
3598 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3599 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3600 getF32Constant(DAG, 0x3e75fe14));
3601 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3602 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3603 getF32Constant(DAG, 0x3f317234));
3604 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3605 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3606 getF32Constant(DAG, 0x3f800000));
3607 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3608 SDValue TwoToFractionalPartOfX =
3609 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3611 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3612 MVT::f32, TwoToFractionalPartOfX);
3615 // No special expansion.
3616 result = DAG.getNode(ISD::FEXP2, dl,
3617 getValue(I.getOperand(1)).getValueType(),
3618 getValue(I.getOperand(1)));
3621 setValue(&I, result);
3624 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3625 /// limited-precision mode with x == 10.0f.
3627 SelectionDAGLowering::visitPow(CallInst &I) {
3629 Value *Val = I.getOperand(1);
3630 DebugLoc dl = getCurDebugLoc();
3631 bool IsExp10 = false;
3633 if (getValue(Val).getValueType() == MVT::f32 &&
3634 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3635 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3636 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3637 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3639 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3644 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3645 SDValue Op = getValue(I.getOperand(2));
3647 // Put the exponent in the right bit position for later addition to the
3650 // #define LOG2OF10 3.3219281f
3651 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3652 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3653 getF32Constant(DAG, 0x40549a78));
3654 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3656 // FractionalPartOfX = x - (float)IntegerPartOfX;
3657 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3658 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3660 // IntegerPartOfX <<= 23;
3661 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3662 DAG.getConstant(23, TLI.getPointerTy()));
3664 if (LimitFloatPrecision <= 6) {
3665 // For floating-point precision of 6:
3667 // twoToFractionalPartOfX =
3669 // (0.735607626f + 0.252464424f * x) * x;
3671 // error 0.0144103317, which is 6 bits
3672 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3673 getF32Constant(DAG, 0x3e814304));
3674 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3675 getF32Constant(DAG, 0x3f3c50c8));
3676 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3677 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3678 getF32Constant(DAG, 0x3f7f5e7e));
3679 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3680 SDValue TwoToFractionalPartOfX =
3681 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3683 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3684 MVT::f32, TwoToFractionalPartOfX);
3685 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3686 // For floating-point precision of 12:
3688 // TwoToFractionalPartOfX =
3691 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3693 // error 0.000107046256, which is 13 to 14 bits
3694 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3695 getF32Constant(DAG, 0x3da235e3));
3696 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3697 getF32Constant(DAG, 0x3e65b8f3));
3698 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3699 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3700 getF32Constant(DAG, 0x3f324b07));
3701 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3702 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3703 getF32Constant(DAG, 0x3f7ff8fd));
3704 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3705 SDValue TwoToFractionalPartOfX =
3706 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3708 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3709 MVT::f32, TwoToFractionalPartOfX);
3710 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3711 // For floating-point precision of 18:
3713 // TwoToFractionalPartOfX =
3717 // (0.554906021e-1f +
3718 // (0.961591928e-2f +
3719 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3720 // error 2.47208000*10^(-7), which is better than 18 bits
3721 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3722 getF32Constant(DAG, 0x3924b03e));
3723 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3724 getF32Constant(DAG, 0x3ab24b87));
3725 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3726 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3727 getF32Constant(DAG, 0x3c1d8c17));
3728 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3729 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3730 getF32Constant(DAG, 0x3d634a1d));
3731 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3732 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3733 getF32Constant(DAG, 0x3e75fe14));
3734 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3735 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3736 getF32Constant(DAG, 0x3f317234));
3737 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3738 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3739 getF32Constant(DAG, 0x3f800000));
3740 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3741 SDValue TwoToFractionalPartOfX =
3742 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3744 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3745 MVT::f32, TwoToFractionalPartOfX);
3748 // No special expansion.
3749 result = DAG.getNode(ISD::FPOW, dl,
3750 getValue(I.getOperand(1)).getValueType(),
3751 getValue(I.getOperand(1)),
3752 getValue(I.getOperand(2)));
3755 setValue(&I, result);
3758 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3759 /// we want to emit this as a call to a named external function, return the name
3760 /// otherwise lower it and return null.
3762 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3763 DebugLoc dl = getCurDebugLoc();
3764 switch (Intrinsic) {
3766 // By default, turn this into a target intrinsic node.
3767 visitTargetIntrinsic(I, Intrinsic);
3769 case Intrinsic::vastart: visitVAStart(I); return 0;
3770 case Intrinsic::vaend: visitVAEnd(I); return 0;
3771 case Intrinsic::vacopy: visitVACopy(I); return 0;
3772 case Intrinsic::returnaddress:
3773 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3774 getValue(I.getOperand(1))));
3776 case Intrinsic::frameaddress:
3777 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3778 getValue(I.getOperand(1))));
3780 case Intrinsic::setjmp:
3781 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3783 case Intrinsic::longjmp:
3784 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3786 case Intrinsic::memcpy: {
3787 SDValue Op1 = getValue(I.getOperand(1));
3788 SDValue Op2 = getValue(I.getOperand(2));
3789 SDValue Op3 = getValue(I.getOperand(3));
3790 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3791 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3792 I.getOperand(1), 0, I.getOperand(2), 0));
3795 case Intrinsic::memset: {
3796 SDValue Op1 = getValue(I.getOperand(1));
3797 SDValue Op2 = getValue(I.getOperand(2));
3798 SDValue Op3 = getValue(I.getOperand(3));
3799 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3800 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3801 I.getOperand(1), 0));
3804 case Intrinsic::memmove: {
3805 SDValue Op1 = getValue(I.getOperand(1));
3806 SDValue Op2 = getValue(I.getOperand(2));
3807 SDValue Op3 = getValue(I.getOperand(3));
3808 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3810 // If the source and destination are known to not be aliases, we can
3811 // lower memmove as memcpy.
3812 uint64_t Size = -1ULL;
3813 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3814 Size = C->getZExtValue();
3815 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3816 AliasAnalysis::NoAlias) {
3817 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3818 I.getOperand(1), 0, I.getOperand(2), 0));
3822 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3823 I.getOperand(1), 0, I.getOperand(2), 0));
3826 case Intrinsic::dbg_stoppoint: {
3827 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3828 if (isValidDebugInfoIntrinsic(SPI, CodeGenOpt::Default)) {
3829 MachineFunction &MF = DAG.getMachineFunction();
3830 DebugLoc Loc = ExtractDebugLocation(SPI, MF.getDebugLocInfo());
3831 setCurDebugLoc(Loc);
3833 if (OptLevel == CodeGenOpt::None)
3834 DAG.setRoot(DAG.getDbgStopPoint(Loc, getRoot(),
3841 case Intrinsic::dbg_region_start: {
3842 DwarfWriter *DW = DAG.getDwarfWriter();
3843 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3844 if (isValidDebugInfoIntrinsic(RSI, OptLevel) && DW
3845 && DW->ShouldEmitDwarfDebug()) {
3847 DW->RecordRegionStart(RSI.getContext());
3848 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3849 getRoot(), LabelID));
3853 case Intrinsic::dbg_region_end: {
3854 DwarfWriter *DW = DAG.getDwarfWriter();
3855 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3857 if (!isValidDebugInfoIntrinsic(REI, OptLevel) || !DW
3858 || !DW->ShouldEmitDwarfDebug())
3861 MachineFunction &MF = DAG.getMachineFunction();
3862 DISubprogram Subprogram(REI.getContext());
3864 if (isInlinedFnEnd(REI, MF.getFunction())) {
3865 // This is end of inlined function. Debugging information for inlined
3866 // function is not handled yet (only supported by FastISel).
3867 if (OptLevel == CodeGenOpt::None) {
3868 unsigned ID = DW->RecordInlinedFnEnd(Subprogram);
3870 // Returned ID is 0 if this is unbalanced "end of inlined
3871 // scope". This could happen if optimizer eats dbg intrinsics or
3872 // "beginning of inlined scope" is not recoginized due to missing
3873 // location info. In such cases, do ignore this region.end.
3874 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3881 DW->RecordRegionEnd(REI.getContext());
3882 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3883 getRoot(), LabelID));
3886 case Intrinsic::dbg_func_start: {
3887 DwarfWriter *DW = DAG.getDwarfWriter();
3888 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3889 if (!isValidDebugInfoIntrinsic(FSI, CodeGenOpt::None))
3892 MachineFunction &MF = DAG.getMachineFunction();
3893 // This is a beginning of an inlined function.
3894 if (isInlinedFnStart(FSI, MF.getFunction())) {
3895 if (OptLevel != CodeGenOpt::None)
3896 // FIXME: Debugging informaation for inlined function is only
3897 // supported at CodeGenOpt::Node.
3900 DebugLoc PrevLoc = CurDebugLoc;
3901 // If llvm.dbg.func.start is seen in a new block before any
3902 // llvm.dbg.stoppoint intrinsic then the location info is unknown.
3903 // FIXME : Why DebugLoc is reset at the beginning of each block ?
3904 if (PrevLoc.isUnknown())
3907 // Record the source line.
3908 setCurDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
3910 if (!DW || !DW->ShouldEmitDwarfDebug())
3912 DebugLocTuple PrevLocTpl = MF.getDebugLocTuple(PrevLoc);
3913 DISubprogram SP(FSI.getSubprogram());
3914 DICompileUnit CU(PrevLocTpl.Scope);
3915 unsigned LabelID = DW->RecordInlinedFnStart(SP, CU,
3918 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3919 getRoot(), LabelID));
3923 // This is a beginning of a new function.
3924 MF.setDefaultDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
3926 if (!DW || !DW->ShouldEmitDwarfDebug())
3928 // llvm.dbg.func_start also defines beginning of function scope.
3929 DW->RecordRegionStart(FSI.getSubprogram());
3932 case Intrinsic::dbg_declare: {
3933 if (OptLevel != CodeGenOpt::None)
3934 // FIXME: Variable debug info is not supported here.
3936 DwarfWriter *DW = DAG.getDwarfWriter();
3939 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3940 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
3943 MDNode *Variable = DI.getVariable();
3944 Value *Address = DI.getAddress();
3945 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3946 Address = BCI->getOperand(0);
3947 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3948 // Don't handle byval struct arguments or VLAs, for example.
3951 DenseMap<const AllocaInst*, int>::iterator SI =
3952 FuncInfo.StaticAllocaMap.find(AI);
3953 if (SI == FuncInfo.StaticAllocaMap.end())
3955 int FI = SI->second;
3956 #ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
3957 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3959 MMI->setVariableDbgInfo(Variable, FI);
3961 DW->RecordVariable(Variable, FI);
3965 case Intrinsic::eh_exception: {
3966 // Insert the EXCEPTIONADDR instruction.
3967 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
3968 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3970 Ops[0] = DAG.getRoot();
3971 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
3973 DAG.setRoot(Op.getValue(1));
3977 case Intrinsic::eh_selector: {
3978 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3980 if (CurMBB->isLandingPad())
3981 AddCatchInfo(I, MMI, CurMBB);
3984 FuncInfo.CatchInfoLost.insert(&I);
3986 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3987 unsigned Reg = TLI.getExceptionSelectorRegister();
3988 if (Reg) CurMBB->addLiveIn(Reg);
3991 // Insert the EHSELECTION instruction.
3992 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3994 Ops[0] = getValue(I.getOperand(1));
3996 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
3998 DAG.setRoot(Op.getValue(1));
4000 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
4004 case Intrinsic::eh_typeid_for: {
4005 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4008 // Find the type id for the given typeinfo.
4009 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4011 unsigned TypeID = MMI->getTypeIDFor(GV);
4012 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
4014 // Return something different to eh_selector.
4015 setValue(&I, DAG.getConstant(1, MVT::i32));
4021 case Intrinsic::eh_return_i32:
4022 case Intrinsic::eh_return_i64:
4023 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4024 MMI->setCallsEHReturn(true);
4025 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4028 getValue(I.getOperand(1)),
4029 getValue(I.getOperand(2))));
4031 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4035 case Intrinsic::eh_unwind_init:
4036 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4037 MMI->setCallsUnwindInit(true);
4042 case Intrinsic::eh_dwarf_cfa: {
4043 EVT VT = getValue(I.getOperand(1)).getValueType();
4044 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
4045 TLI.getPointerTy());
4047 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4049 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4050 TLI.getPointerTy()),
4052 setValue(&I, DAG.getNode(ISD::ADD, dl,
4054 DAG.getNode(ISD::FRAMEADDR, dl,
4057 TLI.getPointerTy())),
4061 case Intrinsic::convertff:
4062 case Intrinsic::convertfsi:
4063 case Intrinsic::convertfui:
4064 case Intrinsic::convertsif:
4065 case Intrinsic::convertuif:
4066 case Intrinsic::convertss:
4067 case Intrinsic::convertsu:
4068 case Intrinsic::convertus:
4069 case Intrinsic::convertuu: {
4070 ISD::CvtCode Code = ISD::CVT_INVALID;
4071 switch (Intrinsic) {
4072 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4073 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4074 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4075 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4076 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4077 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4078 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4079 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4080 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4082 EVT DestVT = TLI.getValueType(I.getType());
4083 Value* Op1 = I.getOperand(1);
4084 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4085 DAG.getValueType(DestVT),
4086 DAG.getValueType(getValue(Op1).getValueType()),
4087 getValue(I.getOperand(2)),
4088 getValue(I.getOperand(3)),
4093 case Intrinsic::sqrt:
4094 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4095 getValue(I.getOperand(1)).getValueType(),
4096 getValue(I.getOperand(1))));
4098 case Intrinsic::powi:
4099 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
4100 getValue(I.getOperand(1)).getValueType(),
4101 getValue(I.getOperand(1)),
4102 getValue(I.getOperand(2))));
4104 case Intrinsic::sin:
4105 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4106 getValue(I.getOperand(1)).getValueType(),
4107 getValue(I.getOperand(1))));
4109 case Intrinsic::cos:
4110 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4111 getValue(I.getOperand(1)).getValueType(),
4112 getValue(I.getOperand(1))));
4114 case Intrinsic::log:
4117 case Intrinsic::log2:
4120 case Intrinsic::log10:
4123 case Intrinsic::exp:
4126 case Intrinsic::exp2:
4129 case Intrinsic::pow:
4132 case Intrinsic::pcmarker: {
4133 SDValue Tmp = getValue(I.getOperand(1));
4134 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4137 case Intrinsic::readcyclecounter: {
4138 SDValue Op = getRoot();
4139 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4140 DAG.getVTList(MVT::i64, MVT::Other),
4143 DAG.setRoot(Tmp.getValue(1));
4146 case Intrinsic::bswap:
4147 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4148 getValue(I.getOperand(1)).getValueType(),
4149 getValue(I.getOperand(1))));
4151 case Intrinsic::cttz: {
4152 SDValue Arg = getValue(I.getOperand(1));
4153 EVT Ty = Arg.getValueType();
4154 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
4155 setValue(&I, result);
4158 case Intrinsic::ctlz: {
4159 SDValue Arg = getValue(I.getOperand(1));
4160 EVT Ty = Arg.getValueType();
4161 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
4162 setValue(&I, result);
4165 case Intrinsic::ctpop: {
4166 SDValue Arg = getValue(I.getOperand(1));
4167 EVT Ty = Arg.getValueType();
4168 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
4169 setValue(&I, result);
4172 case Intrinsic::stacksave: {
4173 SDValue Op = getRoot();
4174 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
4175 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4177 DAG.setRoot(Tmp.getValue(1));
4180 case Intrinsic::stackrestore: {
4181 SDValue Tmp = getValue(I.getOperand(1));
4182 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
4185 case Intrinsic::stackprotector: {
4186 // Emit code into the DAG to store the stack guard onto the stack.
4187 MachineFunction &MF = DAG.getMachineFunction();
4188 MachineFrameInfo *MFI = MF.getFrameInfo();
4189 EVT PtrTy = TLI.getPointerTy();
4191 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4192 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4194 int FI = FuncInfo.StaticAllocaMap[Slot];
4195 MFI->setStackProtectorIndex(FI);
4197 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4199 // Store the stack protector onto the stack.
4200 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4201 PseudoSourceValue::getFixedStack(FI),
4203 setValue(&I, Result);
4204 DAG.setRoot(Result);
4207 case Intrinsic::var_annotation:
4208 // Discard annotate attributes
4211 case Intrinsic::init_trampoline: {
4212 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4216 Ops[1] = getValue(I.getOperand(1));
4217 Ops[2] = getValue(I.getOperand(2));
4218 Ops[3] = getValue(I.getOperand(3));
4219 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4220 Ops[5] = DAG.getSrcValue(F);
4222 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
4223 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4227 DAG.setRoot(Tmp.getValue(1));
4231 case Intrinsic::gcroot:
4233 Value *Alloca = I.getOperand(1);
4234 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4236 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4237 GFI->addStackRoot(FI->getIndex(), TypeMap);
4241 case Intrinsic::gcread:
4242 case Intrinsic::gcwrite:
4243 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4246 case Intrinsic::flt_rounds: {
4247 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4251 case Intrinsic::trap: {
4252 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4256 case Intrinsic::uadd_with_overflow:
4257 return implVisitAluOverflow(I, ISD::UADDO);
4258 case Intrinsic::sadd_with_overflow:
4259 return implVisitAluOverflow(I, ISD::SADDO);
4260 case Intrinsic::usub_with_overflow:
4261 return implVisitAluOverflow(I, ISD::USUBO);
4262 case Intrinsic::ssub_with_overflow:
4263 return implVisitAluOverflow(I, ISD::SSUBO);
4264 case Intrinsic::umul_with_overflow:
4265 return implVisitAluOverflow(I, ISD::UMULO);
4266 case Intrinsic::smul_with_overflow:
4267 return implVisitAluOverflow(I, ISD::SMULO);
4269 case Intrinsic::prefetch: {
4272 Ops[1] = getValue(I.getOperand(1));
4273 Ops[2] = getValue(I.getOperand(2));
4274 Ops[3] = getValue(I.getOperand(3));
4275 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4279 case Intrinsic::memory_barrier: {
4282 for (int x = 1; x < 6; ++x)
4283 Ops[x] = getValue(I.getOperand(x));
4285 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4288 case Intrinsic::atomic_cmp_swap: {
4289 SDValue Root = getRoot();
4291 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4292 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4294 getValue(I.getOperand(1)),
4295 getValue(I.getOperand(2)),
4296 getValue(I.getOperand(3)),
4299 DAG.setRoot(L.getValue(1));
4302 case Intrinsic::atomic_load_add:
4303 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4304 case Intrinsic::atomic_load_sub:
4305 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4306 case Intrinsic::atomic_load_or:
4307 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4308 case Intrinsic::atomic_load_xor:
4309 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4310 case Intrinsic::atomic_load_and:
4311 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4312 case Intrinsic::atomic_load_nand:
4313 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4314 case Intrinsic::atomic_load_max:
4315 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4316 case Intrinsic::atomic_load_min:
4317 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4318 case Intrinsic::atomic_load_umin:
4319 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4320 case Intrinsic::atomic_load_umax:
4321 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4322 case Intrinsic::atomic_swap:
4323 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4327 /// Test if the given instruction is in a position to be optimized
4328 /// with a tail-call. This roughly means that it's in a block with
4329 /// a return and there's nothing that needs to be scheduled
4330 /// between it and the return.
4332 /// This function only tests target-independent requirements.
4333 /// For target-dependent requirements, a target should override
4334 /// TargetLowering::IsEligibleForTailCallOptimization.
4337 isInTailCallPosition(const Instruction *I, Attributes RetAttr,
4338 const TargetLowering &TLI) {
4339 const BasicBlock *ExitBB = I->getParent();
4340 const TerminatorInst *Term = ExitBB->getTerminator();
4341 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4342 const Function *F = ExitBB->getParent();
4344 // The block must end in a return statement or an unreachable.
4345 if (!Ret && !isa<UnreachableInst>(Term)) return false;
4347 // If I will have a chain, make sure no other instruction that will have a
4348 // chain interposes between I and the return.
4349 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4350 !I->isSafeToSpeculativelyExecute())
4351 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4355 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4356 !BBI->isSafeToSpeculativelyExecute())
4360 // If the block ends with a void return or unreachable, it doesn't matter
4361 // what the call's return type is.
4362 if (!Ret || Ret->getNumOperands() == 0) return true;
4364 // Conservatively require the attributes of the call to match those of
4366 if (F->getAttributes().getRetAttributes() != RetAttr)
4369 // Otherwise, make sure the unmodified return value of I is the return value.
4370 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4371 U = dyn_cast<Instruction>(U->getOperand(0))) {
4374 if (!U->hasOneUse())
4378 // Check for a truly no-op truncate.
4379 if (isa<TruncInst>(U) &&
4380 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4382 // Check for a truly no-op bitcast.
4383 if (isa<BitCastInst>(U) &&
4384 (U->getOperand(0)->getType() == U->getType() ||
4385 (isa<PointerType>(U->getOperand(0)->getType()) &&
4386 isa<PointerType>(U->getType()))))
4388 // Otherwise it's not a true no-op.
4395 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4397 MachineBasicBlock *LandingPad) {
4398 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4399 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4400 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4401 unsigned BeginLabel = 0, EndLabel = 0;
4403 TargetLowering::ArgListTy Args;
4404 TargetLowering::ArgListEntry Entry;
4405 Args.reserve(CS.arg_size());
4407 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4409 SDValue ArgNode = getValue(*i);
4410 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4412 unsigned attrInd = i - CS.arg_begin() + 1;
4413 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4414 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4415 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4416 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4417 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4418 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4419 Entry.Alignment = CS.getParamAlignment(attrInd);
4420 Args.push_back(Entry);
4423 if (LandingPad && MMI) {
4424 // Insert a label before the invoke call to mark the try range. This can be
4425 // used to detect deletion of the invoke via the MachineModuleInfo.
4426 BeginLabel = MMI->NextLabelID();
4428 // Both PendingLoads and PendingExports must be flushed here;
4429 // this call might not return.
4431 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4432 getControlRoot(), BeginLabel));
4435 // Check if target-independent constraints permit a tail call here.
4436 // Target-dependent constraints are checked within TLI.LowerCallTo.
4438 !isInTailCallPosition(CS.getInstruction(),
4439 CS.getAttributes().getRetAttributes(),
4443 std::pair<SDValue,SDValue> Result =
4444 TLI.LowerCallTo(getRoot(), CS.getType(),
4445 CS.paramHasAttr(0, Attribute::SExt),
4446 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4447 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4448 CS.getCallingConv(),
4450 !CS.getInstruction()->use_empty(),
4451 Callee, Args, DAG, getCurDebugLoc());
4452 assert((isTailCall || Result.second.getNode()) &&
4453 "Non-null chain expected with non-tail call!");
4454 assert((Result.second.getNode() || !Result.first.getNode()) &&
4455 "Null value expected with tail call!");
4456 if (Result.first.getNode())
4457 setValue(CS.getInstruction(), Result.first);
4458 // As a special case, a null chain means that a tail call has
4459 // been emitted and the DAG root is already updated.
4460 if (Result.second.getNode())
4461 DAG.setRoot(Result.second);
4465 if (LandingPad && MMI) {
4466 // Insert a label at the end of the invoke call to mark the try range. This
4467 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4468 EndLabel = MMI->NextLabelID();
4469 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4470 getRoot(), EndLabel));
4472 // Inform MachineModuleInfo of range.
4473 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4478 void SelectionDAGLowering::visitCall(CallInst &I) {
4479 const char *RenameFn = 0;
4480 if (Function *F = I.getCalledFunction()) {
4481 if (F->isDeclaration()) {
4482 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4484 if (unsigned IID = II->getIntrinsicID(F)) {
4485 RenameFn = visitIntrinsicCall(I, IID);
4490 if (unsigned IID = F->getIntrinsicID()) {
4491 RenameFn = visitIntrinsicCall(I, IID);
4497 // Check for well-known libc/libm calls. If the function is internal, it
4498 // can't be a library call.
4499 if (!F->hasLocalLinkage() && F->hasName()) {
4500 StringRef Name = F->getName();
4501 if (Name == "copysign" || Name == "copysignf") {
4502 if (I.getNumOperands() == 3 && // Basic sanity checks.
4503 I.getOperand(1)->getType()->isFloatingPoint() &&
4504 I.getType() == I.getOperand(1)->getType() &&
4505 I.getType() == I.getOperand(2)->getType()) {
4506 SDValue LHS = getValue(I.getOperand(1));
4507 SDValue RHS = getValue(I.getOperand(2));
4508 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4509 LHS.getValueType(), LHS, RHS));
4512 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4513 if (I.getNumOperands() == 2 && // Basic sanity checks.
4514 I.getOperand(1)->getType()->isFloatingPoint() &&
4515 I.getType() == I.getOperand(1)->getType()) {
4516 SDValue Tmp = getValue(I.getOperand(1));
4517 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4518 Tmp.getValueType(), Tmp));
4521 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4522 if (I.getNumOperands() == 2 && // Basic sanity checks.
4523 I.getOperand(1)->getType()->isFloatingPoint() &&
4524 I.getType() == I.getOperand(1)->getType() &&
4525 I.onlyReadsMemory()) {
4526 SDValue Tmp = getValue(I.getOperand(1));
4527 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4528 Tmp.getValueType(), Tmp));
4531 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4532 if (I.getNumOperands() == 2 && // Basic sanity checks.
4533 I.getOperand(1)->getType()->isFloatingPoint() &&
4534 I.getType() == I.getOperand(1)->getType() &&
4535 I.onlyReadsMemory()) {
4536 SDValue Tmp = getValue(I.getOperand(1));
4537 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4538 Tmp.getValueType(), Tmp));
4541 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4542 if (I.getNumOperands() == 2 && // Basic sanity checks.
4543 I.getOperand(1)->getType()->isFloatingPoint() &&
4544 I.getType() == I.getOperand(1)->getType() &&
4545 I.onlyReadsMemory()) {
4546 SDValue Tmp = getValue(I.getOperand(1));
4547 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4548 Tmp.getValueType(), Tmp));
4553 } else if (isa<InlineAsm>(I.getOperand(0))) {
4560 Callee = getValue(I.getOperand(0));
4562 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4564 // Check if we can potentially perform a tail call. More detailed
4565 // checking is be done within LowerCallTo, after more information
4566 // about the call is known.
4567 bool isTailCall = PerformTailCallOpt && I.isTailCall();
4569 LowerCallTo(&I, Callee, isTailCall);
4573 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4574 /// this value and returns the result as a ValueVT value. This uses
4575 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4576 /// If the Flag pointer is NULL, no flag is used.
4577 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4579 SDValue *Flag) const {
4580 // Assemble the legal parts into the final values.
4581 SmallVector<SDValue, 4> Values(ValueVTs.size());
4582 SmallVector<SDValue, 8> Parts;
4583 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4584 // Copy the legal parts from the registers.
4585 EVT ValueVT = ValueVTs[Value];
4586 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4587 EVT RegisterVT = RegVTs[Value];
4589 Parts.resize(NumRegs);
4590 for (unsigned i = 0; i != NumRegs; ++i) {
4593 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4595 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4596 *Flag = P.getValue(2);
4598 Chain = P.getValue(1);
4600 // If the source register was virtual and if we know something about it,
4601 // add an assert node.
4602 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4603 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4604 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4605 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4606 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4607 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4609 unsigned RegSize = RegisterVT.getSizeInBits();
4610 unsigned NumSignBits = LOI.NumSignBits;
4611 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4613 // FIXME: We capture more information than the dag can represent. For
4614 // now, just use the tightest assertzext/assertsext possible.
4616 EVT FromVT(MVT::Other);
4617 if (NumSignBits == RegSize)
4618 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4619 else if (NumZeroBits >= RegSize-1)
4620 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4621 else if (NumSignBits > RegSize-8)
4622 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4623 else if (NumZeroBits >= RegSize-8)
4624 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4625 else if (NumSignBits > RegSize-16)
4626 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4627 else if (NumZeroBits >= RegSize-16)
4628 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4629 else if (NumSignBits > RegSize-32)
4630 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4631 else if (NumZeroBits >= RegSize-32)
4632 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4634 if (FromVT != MVT::Other) {
4635 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4636 RegisterVT, P, DAG.getValueType(FromVT));
4645 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4646 NumRegs, RegisterVT, ValueVT);
4651 return DAG.getNode(ISD::MERGE_VALUES, dl,
4652 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4653 &Values[0], ValueVTs.size());
4656 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4657 /// specified value into the registers specified by this object. This uses
4658 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4659 /// If the Flag pointer is NULL, no flag is used.
4660 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4661 SDValue &Chain, SDValue *Flag) const {
4662 // Get the list of the values's legal parts.
4663 unsigned NumRegs = Regs.size();
4664 SmallVector<SDValue, 8> Parts(NumRegs);
4665 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4666 EVT ValueVT = ValueVTs[Value];
4667 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4668 EVT RegisterVT = RegVTs[Value];
4670 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
4671 &Parts[Part], NumParts, RegisterVT);
4675 // Copy the parts into the registers.
4676 SmallVector<SDValue, 8> Chains(NumRegs);
4677 for (unsigned i = 0; i != NumRegs; ++i) {
4680 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4682 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4683 *Flag = Part.getValue(1);
4685 Chains[i] = Part.getValue(0);
4688 if (NumRegs == 1 || Flag)
4689 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4690 // flagged to it. That is the CopyToReg nodes and the user are considered
4691 // a single scheduling unit. If we create a TokenFactor and return it as
4692 // chain, then the TokenFactor is both a predecessor (operand) of the
4693 // user as well as a successor (the TF operands are flagged to the user).
4694 // c1, f1 = CopyToReg
4695 // c2, f2 = CopyToReg
4696 // c3 = TokenFactor c1, c2
4699 Chain = Chains[NumRegs-1];
4701 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4704 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4705 /// operand list. This adds the code marker and includes the number of
4706 /// values added into it.
4707 void RegsForValue::AddInlineAsmOperands(unsigned Code,
4708 bool HasMatching,unsigned MatchingIdx,
4710 std::vector<SDValue> &Ops) const {
4711 EVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4712 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4713 unsigned Flag = Code | (Regs.size() << 3);
4715 Flag |= 0x80000000 | (MatchingIdx << 16);
4716 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
4717 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4718 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
4719 EVT RegisterVT = RegVTs[Value];
4720 for (unsigned i = 0; i != NumRegs; ++i) {
4721 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4722 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4727 /// isAllocatableRegister - If the specified register is safe to allocate,
4728 /// i.e. it isn't a stack pointer or some other special register, return the
4729 /// register class for the register. Otherwise, return null.
4730 static const TargetRegisterClass *
4731 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4732 const TargetLowering &TLI,
4733 const TargetRegisterInfo *TRI) {
4734 EVT FoundVT = MVT::Other;
4735 const TargetRegisterClass *FoundRC = 0;
4736 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4737 E = TRI->regclass_end(); RCI != E; ++RCI) {
4738 EVT ThisVT = MVT::Other;
4740 const TargetRegisterClass *RC = *RCI;
4741 // If none of the the value types for this register class are valid, we
4742 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4743 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4745 if (TLI.isTypeLegal(*I)) {
4746 // If we have already found this register in a different register class,
4747 // choose the one with the largest VT specified. For example, on
4748 // PowerPC, we favor f64 register classes over f32.
4749 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4756 if (ThisVT == MVT::Other) continue;
4758 // NOTE: This isn't ideal. In particular, this might allocate the
4759 // frame pointer in functions that need it (due to them not being taken
4760 // out of allocation, because a variable sized allocation hasn't been seen
4761 // yet). This is a slight code pessimization, but should still work.
4762 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4763 E = RC->allocation_order_end(MF); I != E; ++I)
4765 // We found a matching register class. Keep looking at others in case
4766 // we find one with larger registers that this physreg is also in.
4777 /// AsmOperandInfo - This contains information for each constraint that we are
4779 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4780 public TargetLowering::AsmOperandInfo {
4782 /// CallOperand - If this is the result output operand or a clobber
4783 /// this is null, otherwise it is the incoming operand to the CallInst.
4784 /// This gets modified as the asm is processed.
4785 SDValue CallOperand;
4787 /// AssignedRegs - If this is a register or register class operand, this
4788 /// contains the set of register corresponding to the operand.
4789 RegsForValue AssignedRegs;
4791 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4792 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4795 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4796 /// busy in OutputRegs/InputRegs.
4797 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4798 std::set<unsigned> &OutputRegs,
4799 std::set<unsigned> &InputRegs,
4800 const TargetRegisterInfo &TRI) const {
4802 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4803 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4806 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4807 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4811 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
4812 /// corresponds to. If there is no Value* for this operand, it returns
4814 EVT getCallOperandValEVT(LLVMContext &Context,
4815 const TargetLowering &TLI,
4816 const TargetData *TD) const {
4817 if (CallOperandVal == 0) return MVT::Other;
4819 if (isa<BasicBlock>(CallOperandVal))
4820 return TLI.getPointerTy();
4822 const llvm::Type *OpTy = CallOperandVal->getType();
4824 // If this is an indirect operand, the operand is a pointer to the
4827 OpTy = cast<PointerType>(OpTy)->getElementType();
4829 // If OpTy is not a single value, it may be a struct/union that we
4830 // can tile with integers.
4831 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4832 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4841 OpTy = IntegerType::get(Context, BitSize);
4846 return TLI.getValueType(OpTy, true);
4850 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4852 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4853 const TargetRegisterInfo &TRI) {
4854 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4856 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4857 for (; *Aliases; ++Aliases)
4858 Regs.insert(*Aliases);
4861 } // end llvm namespace.
4864 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4865 /// specified operand. We prefer to assign virtual registers, to allow the
4866 /// register allocator handle the assignment process. However, if the asm uses
4867 /// features that we can't model on machineinstrs, we have SDISel do the
4868 /// allocation. This produces generally horrible, but correct, code.
4870 /// OpInfo describes the operand.
4871 /// Input and OutputRegs are the set of already allocated physical registers.
4873 void SelectionDAGLowering::
4874 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4875 std::set<unsigned> &OutputRegs,
4876 std::set<unsigned> &InputRegs) {
4877 LLVMContext &Context = FuncInfo.Fn->getContext();
4879 // Compute whether this value requires an input register, an output register,
4881 bool isOutReg = false;
4882 bool isInReg = false;
4883 switch (OpInfo.Type) {
4884 case InlineAsm::isOutput:
4887 // If there is an input constraint that matches this, we need to reserve
4888 // the input register so no other inputs allocate to it.
4889 isInReg = OpInfo.hasMatchingInput();
4891 case InlineAsm::isInput:
4895 case InlineAsm::isClobber:
4902 MachineFunction &MF = DAG.getMachineFunction();
4903 SmallVector<unsigned, 4> Regs;
4905 // If this is a constraint for a single physreg, or a constraint for a
4906 // register class, find it.
4907 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4908 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4909 OpInfo.ConstraintVT);
4911 unsigned NumRegs = 1;
4912 if (OpInfo.ConstraintVT != MVT::Other) {
4913 // If this is a FP input in an integer register (or visa versa) insert a bit
4914 // cast of the input value. More generally, handle any case where the input
4915 // value disagrees with the register class we plan to stick this in.
4916 if (OpInfo.Type == InlineAsm::isInput &&
4917 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4918 // Try to convert to the first EVT that the reg class contains. If the
4919 // types are identical size, use a bitcast to convert (e.g. two differing
4921 EVT RegVT = *PhysReg.second->vt_begin();
4922 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4923 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4924 RegVT, OpInfo.CallOperand);
4925 OpInfo.ConstraintVT = RegVT;
4926 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4927 // If the input is a FP value and we want it in FP registers, do a
4928 // bitcast to the corresponding integer type. This turns an f64 value
4929 // into i64, which can be passed with two i32 values on a 32-bit
4931 RegVT = EVT::getIntegerVT(Context,
4932 OpInfo.ConstraintVT.getSizeInBits());
4933 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4934 RegVT, OpInfo.CallOperand);
4935 OpInfo.ConstraintVT = RegVT;
4939 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
4943 EVT ValueVT = OpInfo.ConstraintVT;
4945 // If this is a constraint for a specific physical register, like {r17},
4947 if (unsigned AssignedReg = PhysReg.first) {
4948 const TargetRegisterClass *RC = PhysReg.second;
4949 if (OpInfo.ConstraintVT == MVT::Other)
4950 ValueVT = *RC->vt_begin();
4952 // Get the actual register value type. This is important, because the user
4953 // may have asked for (e.g.) the AX register in i32 type. We need to
4954 // remember that AX is actually i16 to get the right extension.
4955 RegVT = *RC->vt_begin();
4957 // This is a explicit reference to a physical register.
4958 Regs.push_back(AssignedReg);
4960 // If this is an expanded reference, add the rest of the regs to Regs.
4962 TargetRegisterClass::iterator I = RC->begin();
4963 for (; *I != AssignedReg; ++I)
4964 assert(I != RC->end() && "Didn't find reg!");
4966 // Already added the first reg.
4968 for (; NumRegs; --NumRegs, ++I) {
4969 assert(I != RC->end() && "Ran out of registers to allocate!");
4973 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4974 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4975 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4979 // Otherwise, if this was a reference to an LLVM register class, create vregs
4980 // for this reference.
4981 if (const TargetRegisterClass *RC = PhysReg.second) {
4982 RegVT = *RC->vt_begin();
4983 if (OpInfo.ConstraintVT == MVT::Other)
4986 // Create the appropriate number of virtual registers.
4987 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4988 for (; NumRegs; --NumRegs)
4989 Regs.push_back(RegInfo.createVirtualRegister(RC));
4991 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4995 // This is a reference to a register class that doesn't directly correspond
4996 // to an LLVM register class. Allocate NumRegs consecutive, available,
4997 // registers from the class.
4998 std::vector<unsigned> RegClassRegs
4999 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5000 OpInfo.ConstraintVT);
5002 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5003 unsigned NumAllocated = 0;
5004 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5005 unsigned Reg = RegClassRegs[i];
5006 // See if this register is available.
5007 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5008 (isInReg && InputRegs.count(Reg))) { // Already used.
5009 // Make sure we find consecutive registers.
5014 // Check to see if this register is allocatable (i.e. don't give out the
5016 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5017 if (!RC) { // Couldn't allocate this register.
5018 // Reset NumAllocated to make sure we return consecutive registers.
5023 // Okay, this register is good, we can use it.
5026 // If we allocated enough consecutive registers, succeed.
5027 if (NumAllocated == NumRegs) {
5028 unsigned RegStart = (i-NumAllocated)+1;
5029 unsigned RegEnd = i+1;
5030 // Mark all of the allocated registers used.
5031 for (unsigned i = RegStart; i != RegEnd; ++i)
5032 Regs.push_back(RegClassRegs[i]);
5034 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5035 OpInfo.ConstraintVT);
5036 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5041 // Otherwise, we couldn't allocate enough registers for this.
5044 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5045 /// processed uses a memory 'm' constraint.
5047 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5048 const TargetLowering &TLI) {
5049 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5050 InlineAsm::ConstraintInfo &CI = CInfos[i];
5051 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5052 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5053 if (CType == TargetLowering::C_Memory)
5057 // Indirect operand accesses access memory.
5065 /// visitInlineAsm - Handle a call to an InlineAsm object.
5067 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5068 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5070 /// ConstraintOperands - Information about all of the constraints.
5071 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5073 std::set<unsigned> OutputRegs, InputRegs;
5075 // Do a prepass over the constraints, canonicalizing them, and building up the
5076 // ConstraintOperands list.
5077 std::vector<InlineAsm::ConstraintInfo>
5078 ConstraintInfos = IA->ParseConstraints();
5080 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5082 SDValue Chain, Flag;
5084 // We won't need to flush pending loads if this asm doesn't touch
5085 // memory and is nonvolatile.
5086 if (hasMemory || IA->hasSideEffects())
5089 Chain = DAG.getRoot();
5091 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5092 unsigned ResNo = 0; // ResNo - The result number of the next output.
5093 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5094 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5095 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5097 EVT OpVT = MVT::Other;
5099 // Compute the value type for each operand.
5100 switch (OpInfo.Type) {
5101 case InlineAsm::isOutput:
5102 // Indirect outputs just consume an argument.
5103 if (OpInfo.isIndirect) {
5104 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5108 // The return value of the call is this value. As such, there is no
5109 // corresponding argument.
5110 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5112 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5113 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5115 assert(ResNo == 0 && "Asm only has one result!");
5116 OpVT = TLI.getValueType(CS.getType());
5120 case InlineAsm::isInput:
5121 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5123 case InlineAsm::isClobber:
5128 // If this is an input or an indirect output, process the call argument.
5129 // BasicBlocks are labels, currently appearing only in asm's.
5130 if (OpInfo.CallOperandVal) {
5131 // Strip bitcasts, if any. This mostly comes up for functions.
5132 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5134 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5135 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5137 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5140 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5143 OpInfo.ConstraintVT = OpVT;
5146 // Second pass over the constraints: compute which constraint option to use
5147 // and assign registers to constraints that want a specific physreg.
5148 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5149 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5151 // If this is an output operand with a matching input operand, look up the
5152 // matching input. If their types mismatch, e.g. one is an integer, the
5153 // other is floating point, or their sizes are different, flag it as an
5155 if (OpInfo.hasMatchingInput()) {
5156 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5157 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5158 if ((OpInfo.ConstraintVT.isInteger() !=
5159 Input.ConstraintVT.isInteger()) ||
5160 (OpInfo.ConstraintVT.getSizeInBits() !=
5161 Input.ConstraintVT.getSizeInBits())) {
5162 llvm_report_error("Unsupported asm: input constraint"
5163 " with a matching output constraint of incompatible"
5166 Input.ConstraintVT = OpInfo.ConstraintVT;
5170 // Compute the constraint code and ConstraintType to use.
5171 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5173 // If this is a memory input, and if the operand is not indirect, do what we
5174 // need to to provide an address for the memory input.
5175 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5176 !OpInfo.isIndirect) {
5177 assert(OpInfo.Type == InlineAsm::isInput &&
5178 "Can only indirectify direct input operands!");
5180 // Memory operands really want the address of the value. If we don't have
5181 // an indirect input, put it in the constpool if we can, otherwise spill
5182 // it to a stack slot.
5184 // If the operand is a float, integer, or vector constant, spill to a
5185 // constant pool entry to get its address.
5186 Value *OpVal = OpInfo.CallOperandVal;
5187 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5188 isa<ConstantVector>(OpVal)) {
5189 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5190 TLI.getPointerTy());
5192 // Otherwise, create a stack slot and emit a store to it before the
5194 const Type *Ty = OpVal->getType();
5195 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5196 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5197 MachineFunction &MF = DAG.getMachineFunction();
5198 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5199 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5200 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5201 OpInfo.CallOperand, StackSlot, NULL, 0);
5202 OpInfo.CallOperand = StackSlot;
5205 // There is no longer a Value* corresponding to this operand.
5206 OpInfo.CallOperandVal = 0;
5207 // It is now an indirect operand.
5208 OpInfo.isIndirect = true;
5211 // If this constraint is for a specific register, allocate it before
5213 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5214 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5216 ConstraintInfos.clear();
5219 // Second pass - Loop over all of the operands, assigning virtual or physregs
5220 // to register class operands.
5221 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5222 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5224 // C_Register operands have already been allocated, Other/Memory don't need
5226 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5227 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5230 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5231 std::vector<SDValue> AsmNodeOperands;
5232 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5233 AsmNodeOperands.push_back(
5234 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
5237 // Loop over all of the inputs, copying the operand values into the
5238 // appropriate registers and processing the output regs.
5239 RegsForValue RetValRegs;
5241 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5242 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5244 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5245 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5247 switch (OpInfo.Type) {
5248 case InlineAsm::isOutput: {
5249 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5250 OpInfo.ConstraintType != TargetLowering::C_Register) {
5251 // Memory output, or 'other' output (e.g. 'X' constraint).
5252 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5254 // Add information to the INLINEASM node to know about this output.
5255 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5256 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5257 TLI.getPointerTy()));
5258 AsmNodeOperands.push_back(OpInfo.CallOperand);
5262 // Otherwise, this is a register or register class output.
5264 // Copy the output from the appropriate register. Find a register that
5266 if (OpInfo.AssignedRegs.Regs.empty()) {
5267 llvm_report_error("Couldn't allocate output reg for"
5268 " constraint '" + OpInfo.ConstraintCode + "'!");
5271 // If this is an indirect operand, store through the pointer after the
5273 if (OpInfo.isIndirect) {
5274 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5275 OpInfo.CallOperandVal));
5277 // This is the result value of the call.
5278 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5280 // Concatenate this output onto the outputs list.
5281 RetValRegs.append(OpInfo.AssignedRegs);
5284 // Add information to the INLINEASM node to know that this register is
5286 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5287 6 /* EARLYCLOBBER REGDEF */ :
5291 DAG, AsmNodeOperands);
5294 case InlineAsm::isInput: {
5295 SDValue InOperandVal = OpInfo.CallOperand;
5297 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5298 // If this is required to match an output register we have already set,
5299 // just use its register.
5300 unsigned OperandNo = OpInfo.getMatchedOperand();
5302 // Scan until we find the definition we already emitted of this operand.
5303 // When we find it, create a RegsForValue operand.
5304 unsigned CurOp = 2; // The first operand.
5305 for (; OperandNo; --OperandNo) {
5306 // Advance to the next operand.
5308 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5309 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5310 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5311 (OpFlag & 7) == 4 /*MEM*/) &&
5312 "Skipped past definitions?");
5313 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5317 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5318 if ((OpFlag & 7) == 2 /*REGDEF*/
5319 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5320 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5321 if (OpInfo.isIndirect) {
5322 llvm_report_error("Don't know how to handle tied indirect "
5323 "register inputs yet!");
5325 RegsForValue MatchedRegs;
5326 MatchedRegs.TLI = &TLI;
5327 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5328 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5329 MatchedRegs.RegVTs.push_back(RegVT);
5330 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5331 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5334 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5336 // Use the produced MatchedRegs object to
5337 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5339 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5340 true, OpInfo.getMatchedOperand(),
5341 DAG, AsmNodeOperands);
5344 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5345 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5346 "Unexpected number of operands");
5347 // Add information to the INLINEASM node to know about this input.
5348 // See InlineAsm.h isUseOperandTiedToDef.
5349 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5350 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5351 TLI.getPointerTy()));
5352 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5357 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5358 assert(!OpInfo.isIndirect &&
5359 "Don't know how to handle indirect other inputs yet!");
5361 std::vector<SDValue> Ops;
5362 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5363 hasMemory, Ops, DAG);
5365 llvm_report_error("Invalid operand for inline asm"
5366 " constraint '" + OpInfo.ConstraintCode + "'!");
5369 // Add information to the INLINEASM node to know about this input.
5370 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5371 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5372 TLI.getPointerTy()));
5373 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5375 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5376 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5377 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5378 "Memory operands expect pointer values");
5380 // Add information to the INLINEASM node to know about this input.
5381 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5382 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5383 TLI.getPointerTy()));
5384 AsmNodeOperands.push_back(InOperandVal);
5388 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5389 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5390 "Unknown constraint type!");
5391 assert(!OpInfo.isIndirect &&
5392 "Don't know how to handle indirect register inputs yet!");
5394 // Copy the input into the appropriate registers.
5395 if (OpInfo.AssignedRegs.Regs.empty()) {
5396 llvm_report_error("Couldn't allocate input reg for"
5397 " constraint '"+ OpInfo.ConstraintCode +"'!");
5400 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5403 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
5404 DAG, AsmNodeOperands);
5407 case InlineAsm::isClobber: {
5408 // Add the clobbered value to the operand list, so that the register
5409 // allocator is aware that the physreg got clobbered.
5410 if (!OpInfo.AssignedRegs.Regs.empty())
5411 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5412 false, 0, DAG,AsmNodeOperands);
5418 // Finish up input operands.
5419 AsmNodeOperands[0] = Chain;
5420 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5422 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5423 DAG.getVTList(MVT::Other, MVT::Flag),
5424 &AsmNodeOperands[0], AsmNodeOperands.size());
5425 Flag = Chain.getValue(1);
5427 // If this asm returns a register value, copy the result from that register
5428 // and set it as the value of the call.
5429 if (!RetValRegs.Regs.empty()) {
5430 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5433 // FIXME: Why don't we do this for inline asms with MRVs?
5434 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5435 EVT ResultType = TLI.getValueType(CS.getType());
5437 // If any of the results of the inline asm is a vector, it may have the
5438 // wrong width/num elts. This can happen for register classes that can
5439 // contain multiple different value types. The preg or vreg allocated may
5440 // not have the same VT as was expected. Convert it to the right type
5441 // with bit_convert.
5442 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5443 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5446 } else if (ResultType != Val.getValueType() &&
5447 ResultType.isInteger() && Val.getValueType().isInteger()) {
5448 // If a result value was tied to an input value, the computed result may
5449 // have a wider width than the expected result. Extract the relevant
5451 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5454 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5457 setValue(CS.getInstruction(), Val);
5458 // Don't need to use this as a chain in this case.
5459 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5463 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5465 // Process indirect outputs, first output all of the flagged copies out of
5467 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5468 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5469 Value *Ptr = IndirectStoresToEmit[i].second;
5470 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5472 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5476 // Emit the non-flagged stores from the physregs.
5477 SmallVector<SDValue, 8> OutChains;
5478 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5479 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
5480 StoresToEmit[i].first,
5481 getValue(StoresToEmit[i].second),
5482 StoresToEmit[i].second, 0));
5483 if (!OutChains.empty())
5484 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5485 &OutChains[0], OutChains.size());
5489 void SelectionDAGLowering::visitFree(FreeInst &I) {
5490 TargetLowering::ArgListTy Args;
5491 TargetLowering::ArgListEntry Entry;
5492 Entry.Node = getValue(I.getOperand(0));
5493 Entry.Ty = TLI.getTargetData()->getIntPtrType(*DAG.getContext());
5494 Args.push_back(Entry);
5495 EVT IntPtr = TLI.getPointerTy();
5496 bool isTailCall = PerformTailCallOpt &&
5497 isInTailCallPosition(&I, Attribute::None, TLI);
5498 std::pair<SDValue,SDValue> Result =
5499 TLI.LowerCallTo(getRoot(), Type::getVoidTy(*DAG.getContext()),
5500 false, false, false, false,
5501 0, CallingConv::C, isTailCall,
5502 /*isReturnValueUsed=*/true,
5503 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
5505 if (Result.second.getNode())
5506 DAG.setRoot(Result.second);
5509 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5510 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5511 MVT::Other, getRoot(),
5512 getValue(I.getOperand(1)),
5513 DAG.getSrcValue(I.getOperand(1))));
5516 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5517 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5518 getRoot(), getValue(I.getOperand(0)),
5519 DAG.getSrcValue(I.getOperand(0)));
5521 DAG.setRoot(V.getValue(1));
5524 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5525 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5526 MVT::Other, getRoot(),
5527 getValue(I.getOperand(1)),
5528 DAG.getSrcValue(I.getOperand(1))));
5531 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5532 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5533 MVT::Other, getRoot(),
5534 getValue(I.getOperand(1)),
5535 getValue(I.getOperand(2)),
5536 DAG.getSrcValue(I.getOperand(1)),
5537 DAG.getSrcValue(I.getOperand(2))));
5540 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5541 /// implementation, which just calls LowerCall.
5542 /// FIXME: When all targets are
5543 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5544 std::pair<SDValue, SDValue>
5545 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5546 bool RetSExt, bool RetZExt, bool isVarArg,
5547 bool isInreg, unsigned NumFixedArgs,
5548 CallingConv::ID CallConv, bool isTailCall,
5549 bool isReturnValueUsed,
5551 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
5553 assert((!isTailCall || PerformTailCallOpt) &&
5554 "isTailCall set when tail-call optimizations are disabled!");
5556 // Handle all of the outgoing arguments.
5557 SmallVector<ISD::OutputArg, 32> Outs;
5558 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5559 SmallVector<EVT, 4> ValueVTs;
5560 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5561 for (unsigned Value = 0, NumValues = ValueVTs.size();
5562 Value != NumValues; ++Value) {
5563 EVT VT = ValueVTs[Value];
5564 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5565 SDValue Op = SDValue(Args[i].Node.getNode(),
5566 Args[i].Node.getResNo() + Value);
5567 ISD::ArgFlagsTy Flags;
5568 unsigned OriginalAlignment =
5569 getTargetData()->getABITypeAlignment(ArgTy);
5575 if (Args[i].isInReg)
5579 if (Args[i].isByVal) {
5581 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5582 const Type *ElementTy = Ty->getElementType();
5583 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5584 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5585 // For ByVal, alignment should come from FE. BE will guess if this
5586 // info is not there but there are cases it cannot get right.
5587 if (Args[i].Alignment)
5588 FrameAlign = Args[i].Alignment;
5589 Flags.setByValAlign(FrameAlign);
5590 Flags.setByValSize(FrameSize);
5594 Flags.setOrigAlign(OriginalAlignment);
5596 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5597 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
5598 SmallVector<SDValue, 4> Parts(NumParts);
5599 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5602 ExtendKind = ISD::SIGN_EXTEND;
5603 else if (Args[i].isZExt)
5604 ExtendKind = ISD::ZERO_EXTEND;
5606 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5608 for (unsigned j = 0; j != NumParts; ++j) {
5609 // if it isn't first piece, alignment must be 1
5610 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5611 if (NumParts > 1 && j == 0)
5612 MyFlags.Flags.setSplit();
5614 MyFlags.Flags.setOrigAlign(1);
5616 Outs.push_back(MyFlags);
5621 // Handle the incoming return values from the call.
5622 SmallVector<ISD::InputArg, 32> Ins;
5623 SmallVector<EVT, 4> RetTys;
5624 ComputeValueVTs(*this, RetTy, RetTys);
5625 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5627 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5628 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5629 for (unsigned i = 0; i != NumRegs; ++i) {
5630 ISD::InputArg MyFlags;
5631 MyFlags.VT = RegisterVT;
5632 MyFlags.Used = isReturnValueUsed;
5634 MyFlags.Flags.setSExt();
5636 MyFlags.Flags.setZExt();
5638 MyFlags.Flags.setInReg();
5639 Ins.push_back(MyFlags);
5643 // Check if target-dependent constraints permit a tail call here.
5644 // Target-independent constraints should be checked by the caller.
5646 !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
5649 SmallVector<SDValue, 4> InVals;
5650 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5651 Outs, Ins, dl, DAG, InVals);
5653 // Verify that the target's LowerCall behaved as expected.
5654 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
5655 "LowerCall didn't return a valid chain!");
5656 assert((!isTailCall || InVals.empty()) &&
5657 "LowerCall emitted a return value for a tail call!");
5658 assert((isTailCall || InVals.size() == Ins.size()) &&
5659 "LowerCall didn't emit the correct number of values!");
5660 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5661 assert(InVals[i].getNode() &&
5662 "LowerCall emitted a null value!");
5663 assert(Ins[i].VT == InVals[i].getValueType() &&
5664 "LowerCall emitted a value with the wrong type!");
5667 // For a tail call, the return value is merely live-out and there aren't
5668 // any nodes in the DAG representing it. Return a special value to
5669 // indicate that a tail call has been emitted and no more Instructions
5670 // should be processed in the current block.
5673 return std::make_pair(SDValue(), SDValue());
5676 // Collect the legal value parts into potentially illegal values
5677 // that correspond to the original function's return values.
5678 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5680 AssertOp = ISD::AssertSext;
5682 AssertOp = ISD::AssertZext;
5683 SmallVector<SDValue, 4> ReturnValues;
5684 unsigned CurReg = 0;
5685 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5687 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5688 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5690 SDValue ReturnValue =
5691 getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT,
5693 ReturnValues.push_back(ReturnValue);
5697 // For a function returning void, there is no return value. We can't create
5698 // such a node, so we just return a null return value in that case. In
5699 // that case, nothing will actualy look at the value.
5700 if (ReturnValues.empty())
5701 return std::make_pair(SDValue(), Chain);
5703 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5704 DAG.getVTList(&RetTys[0], RetTys.size()),
5705 &ReturnValues[0], ReturnValues.size());
5707 return std::make_pair(Res, Chain);
5710 void TargetLowering::LowerOperationWrapper(SDNode *N,
5711 SmallVectorImpl<SDValue> &Results,
5712 SelectionDAG &DAG) {
5713 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5715 Results.push_back(Res);
5718 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5719 llvm_unreachable("LowerOperation not implemented for this target!");
5724 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5725 SDValue Op = getValue(V);
5726 assert((Op.getOpcode() != ISD::CopyFromReg ||
5727 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5728 "Copy from a reg to the same reg!");
5729 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5731 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
5732 SDValue Chain = DAG.getEntryNode();
5733 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5734 PendingExports.push_back(Chain);
5737 #include "llvm/CodeGen/SelectionDAGISel.h"
5739 void SelectionDAGISel::
5740 LowerArguments(BasicBlock *LLVMBB) {
5741 // If this is the entry block, emit arguments.
5742 Function &F = *LLVMBB->getParent();
5743 SelectionDAG &DAG = SDL->DAG;
5744 SDValue OldRoot = DAG.getRoot();
5745 DebugLoc dl = SDL->getCurDebugLoc();
5746 const TargetData *TD = TLI.getTargetData();
5748 // Set up the incoming argument description vector.
5749 SmallVector<ISD::InputArg, 16> Ins;
5751 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5752 I != E; ++I, ++Idx) {
5753 SmallVector<EVT, 4> ValueVTs;
5754 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5755 bool isArgValueUsed = !I->use_empty();
5756 for (unsigned Value = 0, NumValues = ValueVTs.size();
5757 Value != NumValues; ++Value) {
5758 EVT VT = ValueVTs[Value];
5759 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5760 ISD::ArgFlagsTy Flags;
5761 unsigned OriginalAlignment =
5762 TD->getABITypeAlignment(ArgTy);
5764 if (F.paramHasAttr(Idx, Attribute::ZExt))
5766 if (F.paramHasAttr(Idx, Attribute::SExt))
5768 if (F.paramHasAttr(Idx, Attribute::InReg))
5770 if (F.paramHasAttr(Idx, Attribute::StructRet))
5772 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5774 const PointerType *Ty = cast<PointerType>(I->getType());
5775 const Type *ElementTy = Ty->getElementType();
5776 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5777 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5778 // For ByVal, alignment should be passed from FE. BE will guess if
5779 // this info is not there but there are cases it cannot get right.
5780 if (F.getParamAlignment(Idx))
5781 FrameAlign = F.getParamAlignment(Idx);
5782 Flags.setByValAlign(FrameAlign);
5783 Flags.setByValSize(FrameSize);
5785 if (F.paramHasAttr(Idx, Attribute::Nest))
5787 Flags.setOrigAlign(OriginalAlignment);
5789 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5790 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5791 for (unsigned i = 0; i != NumRegs; ++i) {
5792 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5793 if (NumRegs > 1 && i == 0)
5794 MyFlags.Flags.setSplit();
5795 // if it isn't first piece, alignment must be 1
5797 MyFlags.Flags.setOrigAlign(1);
5798 Ins.push_back(MyFlags);
5803 // Call the target to set up the argument values.
5804 SmallVector<SDValue, 8> InVals;
5805 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5809 // Verify that the target's LowerFormalArguments behaved as expected.
5810 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
5811 "LowerFormalArguments didn't return a valid chain!");
5812 assert(InVals.size() == Ins.size() &&
5813 "LowerFormalArguments didn't emit the correct number of values!");
5814 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5815 assert(InVals[i].getNode() &&
5816 "LowerFormalArguments emitted a null value!");
5817 assert(Ins[i].VT == InVals[i].getValueType() &&
5818 "LowerFormalArguments emitted a value with the wrong type!");
5821 // Update the DAG with the new chain value resulting from argument lowering.
5822 DAG.setRoot(NewRoot);
5824 // Set up the argument values.
5827 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5829 SmallVector<SDValue, 4> ArgValues;
5830 SmallVector<EVT, 4> ValueVTs;
5831 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5832 unsigned NumValues = ValueVTs.size();
5833 for (unsigned Value = 0; Value != NumValues; ++Value) {
5834 EVT VT = ValueVTs[Value];
5835 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5836 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5838 if (!I->use_empty()) {
5839 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5840 if (F.paramHasAttr(Idx, Attribute::SExt))
5841 AssertOp = ISD::AssertSext;
5842 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5843 AssertOp = ISD::AssertZext;
5845 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
5846 PartVT, VT, AssertOp));
5850 if (!I->use_empty()) {
5851 SDL->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues,
5852 SDL->getCurDebugLoc()));
5853 // If this argument is live outside of the entry block, insert a copy from
5854 // whereever we got it to the vreg that other BB's will reference it as.
5855 SDL->CopyToExportRegsIfNeeded(I);
5858 assert(i == InVals.size() && "Argument register count mismatch!");
5860 // Finally, if the target has anything special to do, allow it to do so.
5861 // FIXME: this should insert code into the DAG!
5862 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5865 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5866 /// ensure constants are generated when needed. Remember the virtual registers
5867 /// that need to be added to the Machine PHI nodes as input. We cannot just
5868 /// directly add them, because expansion might result in multiple MBB's for one
5869 /// BB. As such, the start of the BB might correspond to a different MBB than
5873 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5874 TerminatorInst *TI = LLVMBB->getTerminator();
5876 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5878 // Check successor nodes' PHI nodes that expect a constant to be available
5880 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5881 BasicBlock *SuccBB = TI->getSuccessor(succ);
5882 if (!isa<PHINode>(SuccBB->begin())) continue;
5883 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5885 // If this terminator has multiple identical successors (common for
5886 // switches), only handle each succ once.
5887 if (!SuccsHandled.insert(SuccMBB)) continue;
5889 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5892 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5893 // nodes and Machine PHI nodes, but the incoming operands have not been
5895 for (BasicBlock::iterator I = SuccBB->begin();
5896 (PN = dyn_cast<PHINode>(I)); ++I) {
5897 // Ignore dead phi's.
5898 if (PN->use_empty()) continue;
5901 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5903 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5904 unsigned &RegOut = SDL->ConstantsOut[C];
5906 RegOut = FuncInfo->CreateRegForValue(C);
5907 SDL->CopyValueToVirtualRegister(C, RegOut);
5911 Reg = FuncInfo->ValueMap[PHIOp];
5913 assert(isa<AllocaInst>(PHIOp) &&
5914 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5915 "Didn't codegen value into a register!??");
5916 Reg = FuncInfo->CreateRegForValue(PHIOp);
5917 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5921 // Remember that this register needs to added to the machine PHI node as
5922 // the input for this MBB.
5923 SmallVector<EVT, 4> ValueVTs;
5924 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5925 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5926 EVT VT = ValueVTs[vti];
5927 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5928 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5929 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5930 Reg += NumRegisters;
5934 SDL->ConstantsOut.clear();
5937 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5938 /// supports legal types, and it emits MachineInstrs directly instead of
5939 /// creating SelectionDAG nodes.
5942 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5944 TerminatorInst *TI = LLVMBB->getTerminator();
5946 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5947 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5949 // Check successor nodes' PHI nodes that expect a constant to be available
5951 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5952 BasicBlock *SuccBB = TI->getSuccessor(succ);
5953 if (!isa<PHINode>(SuccBB->begin())) continue;
5954 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5956 // If this terminator has multiple identical successors (common for
5957 // switches), only handle each succ once.
5958 if (!SuccsHandled.insert(SuccMBB)) continue;
5960 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5963 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5964 // nodes and Machine PHI nodes, but the incoming operands have not been
5966 for (BasicBlock::iterator I = SuccBB->begin();
5967 (PN = dyn_cast<PHINode>(I)); ++I) {
5968 // Ignore dead phi's.
5969 if (PN->use_empty()) continue;
5971 // Only handle legal types. Two interesting things to note here. First,
5972 // by bailing out early, we may leave behind some dead instructions,
5973 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5974 // own moves. Second, this check is necessary becuase FastISel doesn't
5975 // use CreateRegForValue to create registers, so it always creates
5976 // exactly one register for each non-void instruction.
5977 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5978 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5981 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
5983 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5988 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5990 unsigned Reg = F->getRegForValue(PHIOp);
5992 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5995 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));