1 //===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuild.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Module.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/GCMetadata.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetFrameInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
54 /// LimitFloatPrecision - Generate low-precision inline sequences for
55 /// some float libcalls (6, 8 or 12 bits).
56 static unsigned LimitFloatPrecision;
58 static cl::opt<unsigned, true>
59 LimitFPPrecision("limit-float-precision",
60 cl::desc("Generate low-precision inline sequences "
61 "for some float libcalls"),
62 cl::location(LimitFloatPrecision),
65 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
66 /// insertvalue or extractvalue indices that identify a member, return
67 /// the linearized index of the start of the member.
69 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
70 const unsigned *Indices,
71 const unsigned *IndicesEnd,
72 unsigned CurIndex = 0) {
73 // Base case: We're done.
74 if (Indices && Indices == IndicesEnd)
77 // Given a struct type, recursively traverse the elements.
78 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
79 for (StructType::element_iterator EB = STy->element_begin(),
81 EE = STy->element_end();
83 if (Indices && *Indices == unsigned(EI - EB))
84 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
85 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
88 // Given an array type, recursively traverse the elements.
89 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
90 const Type *EltTy = ATy->getElementType();
91 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
92 if (Indices && *Indices == i)
93 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
94 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
97 // We haven't found the type we're looking for, so keep searching.
101 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
102 /// MVTs that represent all the individual underlying
103 /// non-aggregate types that comprise it.
105 /// If Offsets is non-null, it points to a vector to be filled in
106 /// with the in-memory offsets of each of the individual values.
108 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
109 SmallVectorImpl<MVT> &ValueVTs,
110 SmallVectorImpl<uint64_t> *Offsets = 0,
111 uint64_t StartingOffset = 0) {
112 // Given a struct type, recursively traverse the elements.
113 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
114 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
115 for (StructType::element_iterator EB = STy->element_begin(),
117 EE = STy->element_end();
119 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
120 StartingOffset + SL->getElementOffset(EI - EB));
123 // Given an array type, recursively traverse the elements.
124 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
125 const Type *EltTy = ATy->getElementType();
126 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
127 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
128 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
129 StartingOffset + i * EltSize);
132 // Base case: we can get an MVT for this LLVM IR type.
133 ValueVTs.push_back(TLI.getValueType(Ty));
135 Offsets->push_back(StartingOffset);
139 /// RegsForValue - This struct represents the registers (physical or virtual)
140 /// that a particular set of values is assigned, and the type information about
141 /// the value. The most common situation is to represent one value at a time,
142 /// but struct or array values are handled element-wise as multiple values.
143 /// The splitting of aggregates is performed recursively, so that we never
144 /// have aggregate-typed registers. The values at this point do not necessarily
145 /// have legal types, so each value may require one or more registers of some
148 struct VISIBILITY_HIDDEN RegsForValue {
149 /// TLI - The TargetLowering object.
151 const TargetLowering *TLI;
153 /// ValueVTs - The value types of the values, which may not be legal, and
154 /// may need be promoted or synthesized from one or more registers.
156 SmallVector<MVT, 4> ValueVTs;
158 /// RegVTs - The value types of the registers. This is the same size as
159 /// ValueVTs and it records, for each value, what the type of the assigned
160 /// register or registers are. (Individual values are never synthesized
161 /// from more than one type of register.)
163 /// With virtual registers, the contents of RegVTs is redundant with TLI's
164 /// getRegisterType member function, however when with physical registers
165 /// it is necessary to have a separate record of the types.
167 SmallVector<MVT, 4> RegVTs;
169 /// Regs - This list holds the registers assigned to the values.
170 /// Each legal or promoted value requires one register, and each
171 /// expanded value requires multiple registers.
173 SmallVector<unsigned, 4> Regs;
175 RegsForValue() : TLI(0) {}
177 RegsForValue(const TargetLowering &tli,
178 const SmallVector<unsigned, 4> ®s,
179 MVT regvt, MVT valuevt)
180 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
181 RegsForValue(const TargetLowering &tli,
182 const SmallVector<unsigned, 4> ®s,
183 const SmallVector<MVT, 4> ®vts,
184 const SmallVector<MVT, 4> &valuevts)
185 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
186 RegsForValue(const TargetLowering &tli,
187 unsigned Reg, const Type *Ty) : TLI(&tli) {
188 ComputeValueVTs(tli, Ty, ValueVTs);
190 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
191 MVT ValueVT = ValueVTs[Value];
192 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
193 MVT RegisterVT = TLI->getRegisterType(ValueVT);
194 for (unsigned i = 0; i != NumRegs; ++i)
195 Regs.push_back(Reg + i);
196 RegVTs.push_back(RegisterVT);
201 /// append - Add the specified values to this one.
202 void append(const RegsForValue &RHS) {
204 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
205 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
206 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
210 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
211 /// this value and returns the result as a ValueVTs value. This uses
212 /// Chain/Flag as the input and updates them for the output Chain/Flag.
213 /// If the Flag pointer is NULL, no flag is used.
214 SDValue getCopyFromRegs(SelectionDAG &DAG,
215 SDValue &Chain, SDValue *Flag) const;
217 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
218 /// specified value into the registers specified by this object. This uses
219 /// Chain/Flag as the input and updates them for the output Chain/Flag.
220 /// If the Flag pointer is NULL, no flag is used.
221 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
222 SDValue &Chain, SDValue *Flag) const;
224 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
225 /// operand list. This adds the code marker and includes the number of
226 /// values added into it.
227 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
228 std::vector<SDValue> &Ops) const;
232 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
233 /// PHI nodes or outside of the basic block that defines it, or used by a
234 /// switch or atomic instruction, which may expand to multiple basic blocks.
235 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
236 if (isa<PHINode>(I)) return true;
237 BasicBlock *BB = I->getParent();
238 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
239 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
240 // FIXME: Remove switchinst special case.
241 isa<SwitchInst>(*UI))
246 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
247 /// entry block, return true. This includes arguments used by switches, since
248 /// the switch may expand into multiple basic blocks.
249 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
250 // With FastISel active, we may be splitting blocks, so force creation
251 // of virtual registers for all non-dead arguments.
252 // Don't force virtual registers for byval arguments though, because
253 // fast-isel can't handle those in all cases.
254 if (EnableFastISel && !A->hasByValAttr())
255 return A->use_empty();
257 BasicBlock *Entry = A->getParent()->begin();
258 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
259 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
260 return false; // Use not in entry block.
264 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
268 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
269 bool EnableFastISel) {
272 RegInfo = &MF->getRegInfo();
274 // Create a vreg for each argument register that is not dead and is used
275 // outside of the entry block for the function.
276 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
278 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
279 InitializeRegForValue(AI);
281 // Initialize the mapping of values to registers. This is only set up for
282 // instruction values that are used outside of the block that defines
284 Function::iterator BB = Fn->begin(), EB = Fn->end();
285 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
286 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
287 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
288 const Type *Ty = AI->getAllocatedType();
289 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
291 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
294 TySize *= CUI->getZExtValue(); // Get total allocated size.
295 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
296 StaticAllocaMap[AI] =
297 MF->getFrameInfo()->CreateStackObject(TySize, Align);
300 for (; BB != EB; ++BB)
301 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
302 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
303 if (!isa<AllocaInst>(I) ||
304 !StaticAllocaMap.count(cast<AllocaInst>(I)))
305 InitializeRegForValue(I);
307 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
308 // also creates the initial PHI MachineInstrs, though none of the input
309 // operands are populated.
310 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
311 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
315 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
318 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
319 if (PN->use_empty()) continue;
321 unsigned PHIReg = ValueMap[PN];
322 assert(PHIReg && "PHI node does not have an assigned virtual register!");
324 SmallVector<MVT, 4> ValueVTs;
325 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
326 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
327 MVT VT = ValueVTs[vti];
328 unsigned NumRegisters = TLI.getNumRegisters(VT);
329 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
330 for (unsigned i = 0; i != NumRegisters; ++i)
331 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
332 PHIReg += NumRegisters;
338 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
339 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
342 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
343 /// the correctly promoted or expanded types. Assign these registers
344 /// consecutive vreg numbers and return the first assigned number.
346 /// In the case that the given value has struct or array type, this function
347 /// will assign registers for each member or element.
349 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
350 SmallVector<MVT, 4> ValueVTs;
351 ComputeValueVTs(TLI, V->getType(), ValueVTs);
353 unsigned FirstReg = 0;
354 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
355 MVT ValueVT = ValueVTs[Value];
356 MVT RegisterVT = TLI.getRegisterType(ValueVT);
358 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
359 for (unsigned i = 0; i != NumRegs; ++i) {
360 unsigned R = MakeReg(RegisterVT);
361 if (!FirstReg) FirstReg = R;
367 /// getCopyFromParts - Create a value that contains the specified legal parts
368 /// combined into the value they represent. If the parts combine to a type
369 /// larger then ValueVT then AssertOp can be used to specify whether the extra
370 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
371 /// (ISD::AssertSext).
372 static SDValue getCopyFromParts(SelectionDAG &DAG,
373 const SDValue *Parts,
377 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
378 assert(NumParts > 0 && "No parts to assemble!");
379 TargetLowering &TLI = DAG.getTargetLoweringInfo();
380 SDValue Val = Parts[0];
383 // Assemble the value from multiple parts.
384 if (!ValueVT.isVector()) {
385 unsigned PartBits = PartVT.getSizeInBits();
386 unsigned ValueBits = ValueVT.getSizeInBits();
388 // Assemble the power of 2 part.
389 unsigned RoundParts = NumParts & (NumParts - 1) ?
390 1 << Log2_32(NumParts) : NumParts;
391 unsigned RoundBits = PartBits * RoundParts;
392 MVT RoundVT = RoundBits == ValueBits ?
393 ValueVT : MVT::getIntegerVT(RoundBits);
396 MVT HalfVT = ValueVT.isInteger() ?
397 MVT::getIntegerVT(RoundBits/2) :
398 MVT::getFloatingPointVT(RoundBits/2);
400 if (RoundParts > 2) {
401 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
402 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
405 Lo = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[0]);
406 Hi = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[1]);
408 if (TLI.isBigEndian())
410 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
412 if (RoundParts < NumParts) {
413 // Assemble the trailing non-power-of-2 part.
414 unsigned OddParts = NumParts - RoundParts;
415 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
416 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
418 // Combine the round and odd parts.
420 if (TLI.isBigEndian())
422 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
423 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
424 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
425 DAG.getConstant(Lo.getValueType().getSizeInBits(),
426 TLI.getShiftAmountTy()));
427 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
428 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
431 // Handle a multi-element vector.
432 MVT IntermediateVT, RegisterVT;
433 unsigned NumIntermediates;
435 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
437 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
438 NumParts = NumRegs; // Silence a compiler warning.
439 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
440 assert(RegisterVT == Parts[0].getValueType() &&
441 "Part type doesn't match part!");
443 // Assemble the parts into intermediate operands.
444 SmallVector<SDValue, 8> Ops(NumIntermediates);
445 if (NumIntermediates == NumParts) {
446 // If the register was not expanded, truncate or copy the value,
448 for (unsigned i = 0; i != NumParts; ++i)
449 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
450 PartVT, IntermediateVT);
451 } else if (NumParts > 0) {
452 // If the intermediate type was expanded, build the intermediate operands
454 assert(NumParts % NumIntermediates == 0 &&
455 "Must expand into a divisible number of parts!");
456 unsigned Factor = NumParts / NumIntermediates;
457 for (unsigned i = 0; i != NumIntermediates; ++i)
458 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
459 PartVT, IntermediateVT);
462 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
464 Val = DAG.getNode(IntermediateVT.isVector() ?
465 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
466 ValueVT, &Ops[0], NumIntermediates);
470 // There is now one part, held in Val. Correct it to match ValueVT.
471 PartVT = Val.getValueType();
473 if (PartVT == ValueVT)
476 if (PartVT.isVector()) {
477 assert(ValueVT.isVector() && "Unknown vector conversion!");
478 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
481 if (ValueVT.isVector()) {
482 assert(ValueVT.getVectorElementType() == PartVT &&
483 ValueVT.getVectorNumElements() == 1 &&
484 "Only trivial scalar-to-vector conversions should get here!");
485 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
488 if (PartVT.isInteger() &&
489 ValueVT.isInteger()) {
490 if (ValueVT.bitsLT(PartVT)) {
491 // For a truncate, see if we have any information to
492 // indicate whether the truncated bits will always be
493 // zero or sign-extension.
494 if (AssertOp != ISD::DELETED_NODE)
495 Val = DAG.getNode(AssertOp, PartVT, Val,
496 DAG.getValueType(ValueVT));
497 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
499 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
503 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
504 if (ValueVT.bitsLT(Val.getValueType()))
505 // FP_ROUND's are always exact here.
506 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
507 DAG.getIntPtrConstant(1));
508 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
511 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
512 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
514 assert(0 && "Unknown mismatch!");
518 /// getCopyToParts - Create a series of nodes that contain the specified value
519 /// split into legal parts. If the parts contain more bits than Val, then, for
520 /// integers, ExtendKind can be used to specify how to generate the extra bits.
521 static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
522 SDValue *Parts, unsigned NumParts, MVT PartVT,
523 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
524 TargetLowering &TLI = DAG.getTargetLoweringInfo();
525 MVT PtrVT = TLI.getPointerTy();
526 MVT ValueVT = Val.getValueType();
527 unsigned PartBits = PartVT.getSizeInBits();
528 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
533 if (!ValueVT.isVector()) {
534 if (PartVT == ValueVT) {
535 assert(NumParts == 1 && "No-op copy with multiple parts!");
540 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
541 // If the parts cover more bits than the value has, promote the value.
542 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
543 assert(NumParts == 1 && "Do not know what to promote to!");
544 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
545 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
546 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
547 Val = DAG.getNode(ExtendKind, ValueVT, Val);
549 assert(0 && "Unknown mismatch!");
551 } else if (PartBits == ValueVT.getSizeInBits()) {
552 // Different types of the same size.
553 assert(NumParts == 1 && PartVT != ValueVT);
554 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
555 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
556 // If the parts cover less bits than value has, truncate the value.
557 if (PartVT.isInteger() && ValueVT.isInteger()) {
558 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
559 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
561 assert(0 && "Unknown mismatch!");
565 // The value may have changed - recompute ValueVT.
566 ValueVT = Val.getValueType();
567 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
568 "Failed to tile the value with PartVT!");
571 assert(PartVT == ValueVT && "Type conversion failed!");
576 // Expand the value into multiple parts.
577 if (NumParts & (NumParts - 1)) {
578 // The number of parts is not a power of 2. Split off and copy the tail.
579 assert(PartVT.isInteger() && ValueVT.isInteger() &&
580 "Do not know what to expand to!");
581 unsigned RoundParts = 1 << Log2_32(NumParts);
582 unsigned RoundBits = RoundParts * PartBits;
583 unsigned OddParts = NumParts - RoundParts;
584 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
585 DAG.getConstant(RoundBits,
586 TLI.getShiftAmountTy()));
587 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
588 if (TLI.isBigEndian())
589 // The odd parts were reversed by getCopyToParts - unreverse them.
590 std::reverse(Parts + RoundParts, Parts + NumParts);
591 NumParts = RoundParts;
592 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
593 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
596 // The number of parts is a power of 2. Repeatedly bisect the value using
598 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
599 MVT::getIntegerVT(ValueVT.getSizeInBits()),
601 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
602 for (unsigned i = 0; i < NumParts; i += StepSize) {
603 unsigned ThisBits = StepSize * PartBits / 2;
604 MVT ThisVT = MVT::getIntegerVT (ThisBits);
605 SDValue &Part0 = Parts[i];
606 SDValue &Part1 = Parts[i+StepSize/2];
608 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
609 DAG.getConstant(1, PtrVT));
610 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
611 DAG.getConstant(0, PtrVT));
613 if (ThisBits == PartBits && ThisVT != PartVT) {
614 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
615 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
620 if (TLI.isBigEndian())
621 std::reverse(Parts, Parts + NumParts);
628 if (PartVT != ValueVT) {
629 if (PartVT.isVector()) {
630 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
632 assert(ValueVT.getVectorElementType() == PartVT &&
633 ValueVT.getVectorNumElements() == 1 &&
634 "Only trivial vector-to-scalar conversions should get here!");
635 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
636 DAG.getConstant(0, PtrVT));
644 // Handle a multi-element vector.
645 MVT IntermediateVT, RegisterVT;
646 unsigned NumIntermediates;
648 DAG.getTargetLoweringInfo()
649 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
651 unsigned NumElements = ValueVT.getVectorNumElements();
653 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
654 NumParts = NumRegs; // Silence a compiler warning.
655 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
657 // Split the vector into intermediate operands.
658 SmallVector<SDValue, 8> Ops(NumIntermediates);
659 for (unsigned i = 0; i != NumIntermediates; ++i)
660 if (IntermediateVT.isVector())
661 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
663 DAG.getConstant(i * (NumElements / NumIntermediates),
666 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
668 DAG.getConstant(i, PtrVT));
670 // Split the intermediate operands into legal parts.
671 if (NumParts == NumIntermediates) {
672 // If the register was not expanded, promote or copy the value,
674 for (unsigned i = 0; i != NumParts; ++i)
675 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
676 } else if (NumParts > 0) {
677 // If the intermediate type was expanded, split each the value into
679 assert(NumParts % NumIntermediates == 0 &&
680 "Must expand into a divisible number of parts!");
681 unsigned Factor = NumParts / NumIntermediates;
682 for (unsigned i = 0; i != NumIntermediates; ++i)
683 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
688 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
691 TD = DAG.getTarget().getTargetData();
694 /// clear - Clear out the curret SelectionDAG and the associated
695 /// state and prepare this SelectionDAGLowering object to be used
696 /// for a new block. This doesn't clear out information about
697 /// additional blocks that are needed to complete switch lowering
698 /// or PHI node updating; that information is cleared out as it is
700 void SelectionDAGLowering::clear() {
702 PendingLoads.clear();
703 PendingExports.clear();
707 /// getRoot - Return the current virtual root of the Selection DAG,
708 /// flushing any PendingLoad items. This must be done before emitting
709 /// a store or any other node that may need to be ordered after any
710 /// prior load instructions.
712 SDValue SelectionDAGLowering::getRoot() {
713 if (PendingLoads.empty())
714 return DAG.getRoot();
716 if (PendingLoads.size() == 1) {
717 SDValue Root = PendingLoads[0];
719 PendingLoads.clear();
723 // Otherwise, we have to make a token factor node.
724 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
725 &PendingLoads[0], PendingLoads.size());
726 PendingLoads.clear();
731 /// getControlRoot - Similar to getRoot, but instead of flushing all the
732 /// PendingLoad items, flush all the PendingExports items. It is necessary
733 /// to do this before emitting a terminator instruction.
735 SDValue SelectionDAGLowering::getControlRoot() {
736 SDValue Root = DAG.getRoot();
738 if (PendingExports.empty())
741 // Turn all of the CopyToReg chains into one factored node.
742 if (Root.getOpcode() != ISD::EntryToken) {
743 unsigned i = 0, e = PendingExports.size();
744 for (; i != e; ++i) {
745 assert(PendingExports[i].getNode()->getNumOperands() > 1);
746 if (PendingExports[i].getNode()->getOperand(0) == Root)
747 break; // Don't add the root if we already indirectly depend on it.
751 PendingExports.push_back(Root);
754 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
756 PendingExports.size());
757 PendingExports.clear();
762 void SelectionDAGLowering::visit(Instruction &I) {
763 visit(I.getOpcode(), I);
766 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
767 // Note: this doesn't use InstVisitor, because it has to work with
768 // ConstantExpr's in addition to instructions.
770 default: assert(0 && "Unknown instruction type encountered!");
772 // Build the switch statement using the Instruction.def file.
773 #define HANDLE_INST(NUM, OPCODE, CLASS) \
774 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
775 #include "llvm/Instruction.def"
779 void SelectionDAGLowering::visitAdd(User &I) {
780 if (I.getType()->isFPOrFPVector())
781 visitBinary(I, ISD::FADD);
783 visitBinary(I, ISD::ADD);
786 void SelectionDAGLowering::visitMul(User &I) {
787 if (I.getType()->isFPOrFPVector())
788 visitBinary(I, ISD::FMUL);
790 visitBinary(I, ISD::MUL);
793 SDValue SelectionDAGLowering::getValue(const Value *V) {
794 SDValue &N = NodeMap[V];
795 if (N.getNode()) return N;
797 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
798 MVT VT = TLI.getValueType(V->getType(), true);
800 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
801 return N = DAG.getConstant(*CI, VT);
803 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
804 return N = DAG.getGlobalAddress(GV, VT);
806 if (isa<ConstantPointerNull>(C))
807 return N = DAG.getConstant(0, TLI.getPointerTy());
809 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
810 return N = DAG.getConstantFP(*CFP, VT);
812 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
813 !V->getType()->isAggregateType())
814 return N = DAG.getNode(ISD::UNDEF, VT);
816 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
817 visit(CE->getOpcode(), *CE);
818 SDValue N1 = NodeMap[V];
819 assert(N1.getNode() && "visit didn't populate the ValueMap!");
823 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
824 SmallVector<SDValue, 4> Constants;
825 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
827 SDNode *Val = getValue(*OI).getNode();
828 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
829 Constants.push_back(SDValue(Val, i));
831 return DAG.getMergeValues(&Constants[0], Constants.size());
834 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
835 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
836 "Unknown struct or array constant!");
838 SmallVector<MVT, 4> ValueVTs;
839 ComputeValueVTs(TLI, C->getType(), ValueVTs);
840 unsigned NumElts = ValueVTs.size();
842 return SDValue(); // empty struct
843 SmallVector<SDValue, 4> Constants(NumElts);
844 for (unsigned i = 0; i != NumElts; ++i) {
845 MVT EltVT = ValueVTs[i];
846 if (isa<UndefValue>(C))
847 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
848 else if (EltVT.isFloatingPoint())
849 Constants[i] = DAG.getConstantFP(0, EltVT);
851 Constants[i] = DAG.getConstant(0, EltVT);
853 return DAG.getMergeValues(&Constants[0], NumElts);
856 const VectorType *VecTy = cast<VectorType>(V->getType());
857 unsigned NumElements = VecTy->getNumElements();
859 // Now that we know the number and type of the elements, get that number of
860 // elements into the Ops array based on what kind of constant it is.
861 SmallVector<SDValue, 16> Ops;
862 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
863 for (unsigned i = 0; i != NumElements; ++i)
864 Ops.push_back(getValue(CP->getOperand(i)));
866 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
867 "Unknown vector constant!");
868 MVT EltVT = TLI.getValueType(VecTy->getElementType());
871 if (isa<UndefValue>(C))
872 Op = DAG.getNode(ISD::UNDEF, EltVT);
873 else if (EltVT.isFloatingPoint())
874 Op = DAG.getConstantFP(0, EltVT);
876 Op = DAG.getConstant(0, EltVT);
877 Ops.assign(NumElements, Op);
880 // Create a BUILD_VECTOR node.
881 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
884 // If this is a static alloca, generate it as the frameindex instead of
886 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
887 DenseMap<const AllocaInst*, int>::iterator SI =
888 FuncInfo.StaticAllocaMap.find(AI);
889 if (SI != FuncInfo.StaticAllocaMap.end())
890 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
893 unsigned InReg = FuncInfo.ValueMap[V];
894 assert(InReg && "Value not in map!");
896 RegsForValue RFV(TLI, InReg, V->getType());
897 SDValue Chain = DAG.getEntryNode();
898 return RFV.getCopyFromRegs(DAG, Chain, NULL);
902 void SelectionDAGLowering::visitRet(ReturnInst &I) {
903 if (I.getNumOperands() == 0) {
904 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
908 SmallVector<SDValue, 8> NewValues;
909 NewValues.push_back(getControlRoot());
910 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
911 SmallVector<MVT, 4> ValueVTs;
912 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
913 unsigned NumValues = ValueVTs.size();
914 if (NumValues == 0) continue;
916 SDValue RetOp = getValue(I.getOperand(i));
917 for (unsigned j = 0, f = NumValues; j != f; ++j) {
918 MVT VT = ValueVTs[j];
920 // FIXME: C calling convention requires the return type to be promoted to
921 // at least 32-bit. But this is not necessary for non-C calling
923 if (VT.isInteger()) {
924 MVT MinVT = TLI.getRegisterType(MVT::i32);
925 if (VT.bitsLT(MinVT))
929 unsigned NumParts = TLI.getNumRegisters(VT);
930 MVT PartVT = TLI.getRegisterType(VT);
931 SmallVector<SDValue, 4> Parts(NumParts);
932 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
934 const Function *F = I.getParent()->getParent();
935 if (F->paramHasAttr(0, Attribute::SExt))
936 ExtendKind = ISD::SIGN_EXTEND;
937 else if (F->paramHasAttr(0, Attribute::ZExt))
938 ExtendKind = ISD::ZERO_EXTEND;
940 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
941 &Parts[0], NumParts, PartVT, ExtendKind);
943 // 'inreg' on function refers to return value
944 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
945 if (F->paramHasAttr(0, Attribute::InReg))
947 for (unsigned i = 0; i < NumParts; ++i) {
948 NewValues.push_back(Parts[i]);
949 NewValues.push_back(DAG.getArgFlags(Flags));
953 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
954 &NewValues[0], NewValues.size()));
957 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
958 /// the current basic block, add it to ValueMap now so that we'll get a
960 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
961 // No need to export constants.
962 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
965 if (FuncInfo.isExportedInst(V)) return;
967 unsigned Reg = FuncInfo.InitializeRegForValue(V);
968 CopyValueToVirtualRegister(V, Reg);
971 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
972 const BasicBlock *FromBB) {
973 // The operands of the setcc have to be in this block. We don't know
974 // how to export them from some other block.
975 if (Instruction *VI = dyn_cast<Instruction>(V)) {
976 // Can export from current BB.
977 if (VI->getParent() == FromBB)
980 // Is already exported, noop.
981 return FuncInfo.isExportedInst(V);
984 // If this is an argument, we can export it if the BB is the entry block or
985 // if it is already exported.
986 if (isa<Argument>(V)) {
987 if (FromBB == &FromBB->getParent()->getEntryBlock())
990 // Otherwise, can only export this if it is already exported.
991 return FuncInfo.isExportedInst(V);
994 // Otherwise, constants can always be exported.
998 static bool InBlock(const Value *V, const BasicBlock *BB) {
999 if (const Instruction *I = dyn_cast<Instruction>(V))
1000 return I->getParent() == BB;
1004 /// getFCmpCondCode - Return the ISD condition code corresponding to
1005 /// the given LLVM IR floating-point condition code. This includes
1006 /// consideration of global floating-point math flags.
1008 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1009 ISD::CondCode FPC, FOC;
1011 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1012 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1013 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1014 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1015 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1016 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1017 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1018 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1019 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1020 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1021 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1022 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1023 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1024 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1025 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1026 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1028 assert(0 && "Invalid FCmp predicate opcode!");
1029 FOC = FPC = ISD::SETFALSE;
1032 if (FiniteOnlyFPMath())
1038 /// getICmpCondCode - Return the ISD condition code corresponding to
1039 /// the given LLVM IR integer condition code.
1041 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1043 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1044 case ICmpInst::ICMP_NE: return ISD::SETNE;
1045 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1046 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1047 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1048 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1049 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1050 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1051 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1052 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1054 assert(0 && "Invalid ICmp predicate opcode!");
1059 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1060 /// This function emits a branch and is used at the leaves of an OR or an
1061 /// AND operator tree.
1064 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1065 MachineBasicBlock *TBB,
1066 MachineBasicBlock *FBB,
1067 MachineBasicBlock *CurBB) {
1068 const BasicBlock *BB = CurBB->getBasicBlock();
1070 // If the leaf of the tree is a comparison, merge the condition into
1072 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1073 // The operands of the cmp have to be in this block. We don't know
1074 // how to export them from some other block. If this is the first block
1075 // of the sequence, no exporting is needed.
1076 if (CurBB == CurMBB ||
1077 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1078 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1079 ISD::CondCode Condition;
1080 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1081 Condition = getICmpCondCode(IC->getPredicate());
1082 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1083 Condition = getFCmpCondCode(FC->getPredicate());
1085 Condition = ISD::SETEQ; // silence warning.
1086 assert(0 && "Unknown compare instruction");
1089 CaseBlock CB(Condition, BOp->getOperand(0),
1090 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1091 SwitchCases.push_back(CB);
1096 // Create a CaseBlock record representing this branch.
1097 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1098 NULL, TBB, FBB, CurBB);
1099 SwitchCases.push_back(CB);
1102 /// FindMergedConditions - If Cond is an expression like
1103 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1104 MachineBasicBlock *TBB,
1105 MachineBasicBlock *FBB,
1106 MachineBasicBlock *CurBB,
1108 // If this node is not part of the or/and tree, emit it as a branch.
1109 Instruction *BOp = dyn_cast<Instruction>(Cond);
1110 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1111 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1112 BOp->getParent() != CurBB->getBasicBlock() ||
1113 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1114 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1115 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1119 // Create TmpBB after CurBB.
1120 MachineFunction::iterator BBI = CurBB;
1121 MachineFunction &MF = DAG.getMachineFunction();
1122 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1123 CurBB->getParent()->insert(++BBI, TmpBB);
1125 if (Opc == Instruction::Or) {
1126 // Codegen X | Y as:
1134 // Emit the LHS condition.
1135 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1137 // Emit the RHS condition into TmpBB.
1138 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1140 assert(Opc == Instruction::And && "Unknown merge op!");
1141 // Codegen X & Y as:
1148 // This requires creation of TmpBB after CurBB.
1150 // Emit the LHS condition.
1151 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1153 // Emit the RHS condition into TmpBB.
1154 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1158 /// If the set of cases should be emitted as a series of branches, return true.
1159 /// If we should emit this as a bunch of and/or'd together conditions, return
1162 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1163 if (Cases.size() != 2) return true;
1165 // If this is two comparisons of the same values or'd or and'd together, they
1166 // will get folded into a single comparison, so don't emit two blocks.
1167 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1168 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1169 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1170 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1177 void SelectionDAGLowering::visitBr(BranchInst &I) {
1178 // Update machine-CFG edges.
1179 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1181 // Figure out which block is immediately after the current one.
1182 MachineBasicBlock *NextBlock = 0;
1183 MachineFunction::iterator BBI = CurMBB;
1184 if (++BBI != CurMBB->getParent()->end())
1187 if (I.isUnconditional()) {
1188 // Update machine-CFG edges.
1189 CurMBB->addSuccessor(Succ0MBB);
1191 // If this is not a fall-through branch, emit the branch.
1192 if (Succ0MBB != NextBlock)
1193 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1194 DAG.getBasicBlock(Succ0MBB)));
1198 // If this condition is one of the special cases we handle, do special stuff
1200 Value *CondVal = I.getCondition();
1201 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1203 // If this is a series of conditions that are or'd or and'd together, emit
1204 // this as a sequence of branches instead of setcc's with and/or operations.
1205 // For example, instead of something like:
1218 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1219 if (BOp->hasOneUse() &&
1220 (BOp->getOpcode() == Instruction::And ||
1221 BOp->getOpcode() == Instruction::Or)) {
1222 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1223 // If the compares in later blocks need to use values not currently
1224 // exported from this block, export them now. This block should always
1225 // be the first entry.
1226 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1228 // Allow some cases to be rejected.
1229 if (ShouldEmitAsBranches(SwitchCases)) {
1230 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1231 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1232 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1235 // Emit the branch for this block.
1236 visitSwitchCase(SwitchCases[0]);
1237 SwitchCases.erase(SwitchCases.begin());
1241 // Okay, we decided not to do this, remove any inserted MBB's and clear
1243 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1244 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1246 SwitchCases.clear();
1250 // Create a CaseBlock record representing this branch.
1251 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1252 NULL, Succ0MBB, Succ1MBB, CurMBB);
1253 // Use visitSwitchCase to actually insert the fast branch sequence for this
1255 visitSwitchCase(CB);
1258 /// visitSwitchCase - Emits the necessary code to represent a single node in
1259 /// the binary search tree resulting from lowering a switch instruction.
1260 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1262 SDValue CondLHS = getValue(CB.CmpLHS);
1264 // Build the setcc now.
1265 if (CB.CmpMHS == NULL) {
1266 // Fold "(X == true)" to X and "(X == false)" to !X to
1267 // handle common cases produced by branch lowering.
1268 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1270 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1271 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1272 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1274 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1276 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1278 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1279 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1281 SDValue CmpOp = getValue(CB.CmpMHS);
1282 MVT VT = CmpOp.getValueType();
1284 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1285 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1287 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1288 Cond = DAG.getSetCC(MVT::i1, SUB,
1289 DAG.getConstant(High-Low, VT), ISD::SETULE);
1293 // Update successor info
1294 CurMBB->addSuccessor(CB.TrueBB);
1295 CurMBB->addSuccessor(CB.FalseBB);
1297 // Set NextBlock to be the MBB immediately after the current one, if any.
1298 // This is used to avoid emitting unnecessary branches to the next block.
1299 MachineBasicBlock *NextBlock = 0;
1300 MachineFunction::iterator BBI = CurMBB;
1301 if (++BBI != CurMBB->getParent()->end())
1304 // If the lhs block is the next block, invert the condition so that we can
1305 // fall through to the lhs instead of the rhs block.
1306 if (CB.TrueBB == NextBlock) {
1307 std::swap(CB.TrueBB, CB.FalseBB);
1308 SDValue True = DAG.getConstant(1, Cond.getValueType());
1309 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1311 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1312 DAG.getBasicBlock(CB.TrueBB));
1314 // If the branch was constant folded, fix up the CFG.
1315 if (BrCond.getOpcode() == ISD::BR) {
1316 CurMBB->removeSuccessor(CB.FalseBB);
1317 DAG.setRoot(BrCond);
1319 // Otherwise, go ahead and insert the false branch.
1320 if (BrCond == getControlRoot())
1321 CurMBB->removeSuccessor(CB.TrueBB);
1323 if (CB.FalseBB == NextBlock)
1324 DAG.setRoot(BrCond);
1326 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1327 DAG.getBasicBlock(CB.FalseBB)));
1331 /// visitJumpTable - Emit JumpTable node in the current MBB
1332 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1333 // Emit the code for the jump table
1334 assert(JT.Reg != -1U && "Should lower JT Header first!");
1335 MVT PTy = TLI.getPointerTy();
1336 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1337 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1338 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1343 /// visitJumpTableHeader - This function emits necessary code to produce index
1344 /// in the JumpTable from switch case.
1345 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1346 JumpTableHeader &JTH) {
1347 // Subtract the lowest switch case value from the value being switched on and
1348 // conditional branch to default mbb if the result is greater than the
1349 // difference between smallest and largest cases.
1350 SDValue SwitchOp = getValue(JTH.SValue);
1351 MVT VT = SwitchOp.getValueType();
1352 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1353 DAG.getConstant(JTH.First, VT));
1355 // The SDNode we just created, which holds the value being switched on minus
1356 // the the smallest case value, needs to be copied to a virtual register so it
1357 // can be used as an index into the jump table in a subsequent basic block.
1358 // This value may be smaller or larger than the target's pointer type, and
1359 // therefore require extension or truncating.
1360 if (VT.bitsGT(TLI.getPointerTy()))
1361 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1363 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1365 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1366 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1367 JT.Reg = JumpTableReg;
1369 // Emit the range check for the jump table, and branch to the default block
1370 // for the switch statement if the value being switched on exceeds the largest
1371 // case in the switch.
1372 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1373 DAG.getConstant(JTH.Last-JTH.First,VT),
1376 // Set NextBlock to be the MBB immediately after the current one, if any.
1377 // This is used to avoid emitting unnecessary branches to the next block.
1378 MachineBasicBlock *NextBlock = 0;
1379 MachineFunction::iterator BBI = CurMBB;
1380 if (++BBI != CurMBB->getParent()->end())
1383 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1384 DAG.getBasicBlock(JT.Default));
1386 if (JT.MBB == NextBlock)
1387 DAG.setRoot(BrCond);
1389 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1390 DAG.getBasicBlock(JT.MBB)));
1395 /// visitBitTestHeader - This function emits necessary code to produce value
1396 /// suitable for "bit tests"
1397 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1398 // Subtract the minimum value
1399 SDValue SwitchOp = getValue(B.SValue);
1400 MVT VT = SwitchOp.getValueType();
1401 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1402 DAG.getConstant(B.First, VT));
1405 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1406 DAG.getConstant(B.Range, VT),
1410 if (VT.bitsGT(TLI.getShiftAmountTy()))
1411 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1413 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1415 // Make desired shift
1416 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1417 DAG.getConstant(1, TLI.getPointerTy()),
1420 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1421 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1424 // Set NextBlock to be the MBB immediately after the current one, if any.
1425 // This is used to avoid emitting unnecessary branches to the next block.
1426 MachineBasicBlock *NextBlock = 0;
1427 MachineFunction::iterator BBI = CurMBB;
1428 if (++BBI != CurMBB->getParent()->end())
1431 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1433 CurMBB->addSuccessor(B.Default);
1434 CurMBB->addSuccessor(MBB);
1436 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1437 DAG.getBasicBlock(B.Default));
1439 if (MBB == NextBlock)
1440 DAG.setRoot(BrRange);
1442 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1443 DAG.getBasicBlock(MBB)));
1448 /// visitBitTestCase - this function produces one "bit test"
1449 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1452 // Emit bit tests and jumps
1453 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1454 TLI.getPointerTy());
1456 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1457 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1458 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1459 DAG.getConstant(0, TLI.getPointerTy()),
1462 CurMBB->addSuccessor(B.TargetBB);
1463 CurMBB->addSuccessor(NextMBB);
1465 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1466 AndCmp, DAG.getBasicBlock(B.TargetBB));
1468 // Set NextBlock to be the MBB immediately after the current one, if any.
1469 // This is used to avoid emitting unnecessary branches to the next block.
1470 MachineBasicBlock *NextBlock = 0;
1471 MachineFunction::iterator BBI = CurMBB;
1472 if (++BBI != CurMBB->getParent()->end())
1475 if (NextMBB == NextBlock)
1478 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1479 DAG.getBasicBlock(NextMBB)));
1484 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1485 // Retrieve successors.
1486 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1487 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1489 if (isa<InlineAsm>(I.getCalledValue()))
1492 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1494 // If the value of the invoke is used outside of its defining block, make it
1495 // available as a virtual register.
1496 if (!I.use_empty()) {
1497 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1498 if (VMI != FuncInfo.ValueMap.end())
1499 CopyValueToVirtualRegister(&I, VMI->second);
1502 // Update successor info
1503 CurMBB->addSuccessor(Return);
1504 CurMBB->addSuccessor(LandingPad);
1506 // Drop into normal successor.
1507 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1508 DAG.getBasicBlock(Return)));
1511 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1514 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1515 /// small case ranges).
1516 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1517 CaseRecVector& WorkList,
1519 MachineBasicBlock* Default) {
1520 Case& BackCase = *(CR.Range.second-1);
1522 // Size is the number of Cases represented by this range.
1523 size_t Size = CR.Range.second - CR.Range.first;
1527 // Get the MachineFunction which holds the current MBB. This is used when
1528 // inserting any additional MBBs necessary to represent the switch.
1529 MachineFunction *CurMF = CurMBB->getParent();
1531 // Figure out which block is immediately after the current one.
1532 MachineBasicBlock *NextBlock = 0;
1533 MachineFunction::iterator BBI = CR.CaseBB;
1535 if (++BBI != CurMBB->getParent()->end())
1538 // TODO: If any two of the cases has the same destination, and if one value
1539 // is the same as the other, but has one bit unset that the other has set,
1540 // use bit manipulation to do two compares at once. For example:
1541 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1543 // Rearrange the case blocks so that the last one falls through if possible.
1544 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1545 // The last case block won't fall through into 'NextBlock' if we emit the
1546 // branches in this order. See if rearranging a case value would help.
1547 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1548 if (I->BB == NextBlock) {
1549 std::swap(*I, BackCase);
1555 // Create a CaseBlock record representing a conditional branch to
1556 // the Case's target mbb if the value being switched on SV is equal
1558 MachineBasicBlock *CurBlock = CR.CaseBB;
1559 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1560 MachineBasicBlock *FallThrough;
1562 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1563 CurMF->insert(BBI, FallThrough);
1565 // If the last case doesn't match, go to the default block.
1566 FallThrough = Default;
1569 Value *RHS, *LHS, *MHS;
1571 if (I->High == I->Low) {
1572 // This is just small small case range :) containing exactly 1 case
1574 LHS = SV; RHS = I->High; MHS = NULL;
1577 LHS = I->Low; MHS = SV; RHS = I->High;
1579 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1581 // If emitting the first comparison, just call visitSwitchCase to emit the
1582 // code into the current block. Otherwise, push the CaseBlock onto the
1583 // vector to be later processed by SDISel, and insert the node's MBB
1584 // before the next MBB.
1585 if (CurBlock == CurMBB)
1586 visitSwitchCase(CB);
1588 SwitchCases.push_back(CB);
1590 CurBlock = FallThrough;
1596 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1597 return !DisableJumpTables &&
1598 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1599 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1602 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1603 APInt LastExt(Last), FirstExt(First);
1604 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1605 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1606 return (LastExt - FirstExt + 1ULL);
1609 /// handleJTSwitchCase - Emit jumptable for current switch case range
1610 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1611 CaseRecVector& WorkList,
1613 MachineBasicBlock* Default) {
1614 Case& FrontCase = *CR.Range.first;
1615 Case& BackCase = *(CR.Range.second-1);
1617 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1618 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
1621 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1625 if (!areJTsAllowed(TLI) || TSize <= 3)
1628 APInt Range = ComputeRange(First, Last);
1629 double Density = (double)TSize / Range.roundToDouble();
1633 DEBUG(errs() << "Lowering jump table\n"
1634 << "First entry: " << First << ". Last entry: " << Last << '\n'
1635 << "Range: " << Range
1636 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1638 // Get the MachineFunction which holds the current MBB. This is used when
1639 // inserting any additional MBBs necessary to represent the switch.
1640 MachineFunction *CurMF = CurMBB->getParent();
1642 // Figure out which block is immediately after the current one.
1643 MachineBasicBlock *NextBlock = 0;
1644 MachineFunction::iterator BBI = CR.CaseBB;
1646 if (++BBI != CurMBB->getParent()->end())
1649 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1651 // Create a new basic block to hold the code for loading the address
1652 // of the jump table, and jumping to it. Update successor information;
1653 // we will either branch to the default case for the switch, or the jump
1655 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1656 CurMF->insert(BBI, JumpTableBB);
1657 CR.CaseBB->addSuccessor(Default);
1658 CR.CaseBB->addSuccessor(JumpTableBB);
1660 // Build a vector of destination BBs, corresponding to each target
1661 // of the jump table. If the value of the jump table slot corresponds to
1662 // a case statement, push the case's BB onto the vector, otherwise, push
1664 std::vector<MachineBasicBlock*> DestBBs;
1666 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1667 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1668 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1670 if (Low.sle(TEI) && TEI.sle(High)) {
1671 DestBBs.push_back(I->BB);
1675 DestBBs.push_back(Default);
1679 // Update successor info. Add one edge to each unique successor.
1680 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1681 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1682 E = DestBBs.end(); I != E; ++I) {
1683 if (!SuccsHandled[(*I)->getNumber()]) {
1684 SuccsHandled[(*I)->getNumber()] = true;
1685 JumpTableBB->addSuccessor(*I);
1689 // Create a jump table index for this jump table, or return an existing
1691 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1693 // Set the jump table information so that we can codegen it as a second
1694 // MachineBasicBlock
1695 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1696 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1697 if (CR.CaseBB == CurMBB)
1698 visitJumpTableHeader(JT, JTH);
1700 JTCases.push_back(JumpTableBlock(JTH, JT));
1705 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1707 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1708 CaseRecVector& WorkList,
1710 MachineBasicBlock* Default) {
1711 // Get the MachineFunction which holds the current MBB. This is used when
1712 // inserting any additional MBBs necessary to represent the switch.
1713 MachineFunction *CurMF = CurMBB->getParent();
1715 // Figure out which block is immediately after the current one.
1716 MachineBasicBlock *NextBlock = 0;
1717 MachineFunction::iterator BBI = CR.CaseBB;
1719 if (++BBI != CurMBB->getParent()->end())
1722 Case& FrontCase = *CR.Range.first;
1723 Case& BackCase = *(CR.Range.second-1);
1724 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1726 // Size is the number of Cases represented by this range.
1727 unsigned Size = CR.Range.second - CR.Range.first;
1729 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1730 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
1732 CaseItr Pivot = CR.Range.first + Size/2;
1734 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1735 // (heuristically) allow us to emit JumpTable's later.
1737 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1741 size_t LSize = FrontCase.size();
1742 size_t RSize = TSize-LSize;
1743 DEBUG(errs() << "Selecting best pivot: \n"
1744 << "First: " << First << ", Last: " << Last <<'\n'
1745 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1746 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1748 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1749 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
1750 APInt Range = ComputeRange(LEnd, RBegin);
1751 assert((Range - 2ULL).isNonNegative() &&
1752 "Invalid case distance");
1753 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1754 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
1755 double Metric = Range.logBase2()*(LDensity+RDensity);
1756 // Should always split in some non-trivial place
1757 DEBUG(errs() <<"=>Step\n"
1758 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1759 << "LDensity: " << LDensity
1760 << ", RDensity: " << RDensity << '\n'
1761 << "Metric: " << Metric << '\n');
1762 if (FMetric < Metric) {
1765 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1771 if (areJTsAllowed(TLI)) {
1772 // If our case is dense we *really* should handle it earlier!
1773 assert((FMetric > 0) && "Should handle dense range earlier!");
1775 Pivot = CR.Range.first + Size/2;
1778 CaseRange LHSR(CR.Range.first, Pivot);
1779 CaseRange RHSR(Pivot, CR.Range.second);
1780 Constant *C = Pivot->Low;
1781 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1783 // We know that we branch to the LHS if the Value being switched on is
1784 // less than the Pivot value, C. We use this to optimize our binary
1785 // tree a bit, by recognizing that if SV is greater than or equal to the
1786 // LHS's Case Value, and that Case Value is exactly one less than the
1787 // Pivot's Value, then we can branch directly to the LHS's Target,
1788 // rather than creating a leaf node for it.
1789 if ((LHSR.second - LHSR.first) == 1 &&
1790 LHSR.first->High == CR.GE &&
1791 cast<ConstantInt>(C)->getValue() ==
1792 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1793 TrueBB = LHSR.first->BB;
1795 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1796 CurMF->insert(BBI, TrueBB);
1797 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1800 // Similar to the optimization above, if the Value being switched on is
1801 // known to be less than the Constant CR.LT, and the current Case Value
1802 // is CR.LT - 1, then we can branch directly to the target block for
1803 // the current Case Value, rather than emitting a RHS leaf node for it.
1804 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1805 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1806 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1807 FalseBB = RHSR.first->BB;
1809 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1810 CurMF->insert(BBI, FalseBB);
1811 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1814 // Create a CaseBlock record representing a conditional branch to
1815 // the LHS node if the value being switched on SV is less than C.
1816 // Otherwise, branch to LHS.
1817 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1819 if (CR.CaseBB == CurMBB)
1820 visitSwitchCase(CB);
1822 SwitchCases.push_back(CB);
1827 /// handleBitTestsSwitchCase - if current case range has few destination and
1828 /// range span less, than machine word bitwidth, encode case range into series
1829 /// of masks and emit bit tests with these masks.
1830 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1831 CaseRecVector& WorkList,
1833 MachineBasicBlock* Default){
1834 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1836 Case& FrontCase = *CR.Range.first;
1837 Case& BackCase = *(CR.Range.second-1);
1839 // Get the MachineFunction which holds the current MBB. This is used when
1840 // inserting any additional MBBs necessary to represent the switch.
1841 MachineFunction *CurMF = CurMBB->getParent();
1844 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1846 // Single case counts one, case range - two.
1847 numCmps += (I->Low == I->High ? 1 : 2);
1850 // Count unique destinations
1851 SmallSet<MachineBasicBlock*, 4> Dests;
1852 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1853 Dests.insert(I->BB);
1854 if (Dests.size() > 3)
1855 // Don't bother the code below, if there are too much unique destinations
1858 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1859 << "Total number of comparisons: " << numCmps << '\n');
1861 // Compute span of values.
1862 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1863 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1864 APInt cmpRange = maxValue - minValue;
1866 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1867 << "Low bound: " << minValue << '\n'
1868 << "High bound: " << maxValue << '\n');
1870 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1871 (!(Dests.size() == 1 && numCmps >= 3) &&
1872 !(Dests.size() == 2 && numCmps >= 5) &&
1873 !(Dests.size() >= 3 && numCmps >= 6)))
1876 DEBUG(errs() << "Emitting bit tests\n");
1877 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1879 // Optimize the case where all the case values fit in a
1880 // word without having to subtract minValue. In this case,
1881 // we can optimize away the subtraction.
1882 if (minValue.isNonNegative() &&
1883 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1884 cmpRange = maxValue;
1886 lowBound = minValue;
1889 CaseBitsVector CasesBits;
1890 unsigned i, count = 0;
1892 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1893 MachineBasicBlock* Dest = I->BB;
1894 for (i = 0; i < count; ++i)
1895 if (Dest == CasesBits[i].BB)
1899 assert((count < 3) && "Too much destinations to test!");
1900 CasesBits.push_back(CaseBits(0, Dest, 0));
1904 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1905 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1907 uint64_t lo = (lowValue - lowBound).getZExtValue();
1908 uint64_t hi = (highValue - lowBound).getZExtValue();
1910 for (uint64_t j = lo; j <= hi; j++) {
1911 CasesBits[i].Mask |= 1ULL << j;
1912 CasesBits[i].Bits++;
1916 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1920 // Figure out which block is immediately after the current one.
1921 MachineFunction::iterator BBI = CR.CaseBB;
1924 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1926 DEBUG(errs() << "Cases:\n");
1927 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1928 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1929 << ", Bits: " << CasesBits[i].Bits
1930 << ", BB: " << CasesBits[i].BB << '\n');
1932 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1933 CurMF->insert(BBI, CaseBB);
1934 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1939 BitTestBlock BTB(lowBound, cmpRange, SV,
1940 -1U, (CR.CaseBB == CurMBB),
1941 CR.CaseBB, Default, BTC);
1943 if (CR.CaseBB == CurMBB)
1944 visitBitTestHeader(BTB);
1946 BitTestCases.push_back(BTB);
1952 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1953 size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
1954 const SwitchInst& SI) {
1957 // Start with "simple" cases
1958 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
1959 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1960 Cases.push_back(Case(SI.getSuccessorValue(i),
1961 SI.getSuccessorValue(i),
1964 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1966 // Merge case into clusters
1967 if (Cases.size() >= 2)
1968 // Must recompute end() each iteration because it may be
1969 // invalidated by erase if we hold on to it
1970 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1971 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1972 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
1973 MachineBasicBlock* nextBB = J->BB;
1974 MachineBasicBlock* currentBB = I->BB;
1976 // If the two neighboring cases go to the same destination, merge them
1977 // into a single case.
1978 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
1986 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1987 if (I->Low != I->High)
1988 // A range counts double, since it requires two compares.
1995 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1996 // Figure out which block is immediately after the current one.
1997 MachineBasicBlock *NextBlock = 0;
1998 MachineFunction::iterator BBI = CurMBB;
2000 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2002 // If there is only the default destination, branch to it if it is not the
2003 // next basic block. Otherwise, just fall through.
2004 if (SI.getNumOperands() == 2) {
2005 // Update machine-CFG edges.
2007 // If this is not a fall-through branch, emit the branch.
2008 CurMBB->addSuccessor(Default);
2009 if (Default != NextBlock)
2010 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2011 DAG.getBasicBlock(Default)));
2015 // If there are any non-default case statements, create a vector of Cases
2016 // representing each one, and sort the vector so that we can efficiently
2017 // create a binary search tree from them.
2019 size_t numCmps = Clusterify(Cases, SI);
2020 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2021 << ". Total compares: " << numCmps << '\n');
2023 // Get the Value to be switched on and default basic blocks, which will be
2024 // inserted into CaseBlock records, representing basic blocks in the binary
2026 Value *SV = SI.getOperand(0);
2028 // Push the initial CaseRec onto the worklist
2029 CaseRecVector WorkList;
2030 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2032 while (!WorkList.empty()) {
2033 // Grab a record representing a case range to process off the worklist
2034 CaseRec CR = WorkList.back();
2035 WorkList.pop_back();
2037 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2040 // If the range has few cases (two or less) emit a series of specific
2042 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2045 // If the switch has more than 5 blocks, and at least 40% dense, and the
2046 // target supports indirect branches, then emit a jump table rather than
2047 // lowering the switch to a binary tree of conditional branches.
2048 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2051 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2052 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2053 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2058 void SelectionDAGLowering::visitSub(User &I) {
2059 // -0.0 - X --> fneg
2060 const Type *Ty = I.getType();
2061 if (isa<VectorType>(Ty)) {
2062 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2063 const VectorType *DestTy = cast<VectorType>(I.getType());
2064 const Type *ElTy = DestTy->getElementType();
2065 if (ElTy->isFloatingPoint()) {
2066 unsigned VL = DestTy->getNumElements();
2067 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2068 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2070 SDValue Op2 = getValue(I.getOperand(1));
2071 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2077 if (Ty->isFloatingPoint()) {
2078 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2079 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2080 SDValue Op2 = getValue(I.getOperand(1));
2081 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2086 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2089 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2090 SDValue Op1 = getValue(I.getOperand(0));
2091 SDValue Op2 = getValue(I.getOperand(1));
2093 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2096 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2097 SDValue Op1 = getValue(I.getOperand(0));
2098 SDValue Op2 = getValue(I.getOperand(1));
2099 if (!isa<VectorType>(I.getType())) {
2100 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2101 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2102 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2103 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2106 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2109 void SelectionDAGLowering::visitICmp(User &I) {
2110 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2111 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2112 predicate = IC->getPredicate();
2113 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2114 predicate = ICmpInst::Predicate(IC->getPredicate());
2115 SDValue Op1 = getValue(I.getOperand(0));
2116 SDValue Op2 = getValue(I.getOperand(1));
2117 ISD::CondCode Opcode = getICmpCondCode(predicate);
2118 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2121 void SelectionDAGLowering::visitFCmp(User &I) {
2122 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2123 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2124 predicate = FC->getPredicate();
2125 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2126 predicate = FCmpInst::Predicate(FC->getPredicate());
2127 SDValue Op1 = getValue(I.getOperand(0));
2128 SDValue Op2 = getValue(I.getOperand(1));
2129 ISD::CondCode Condition = getFCmpCondCode(predicate);
2130 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2133 void SelectionDAGLowering::visitVICmp(User &I) {
2134 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2135 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2136 predicate = IC->getPredicate();
2137 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2138 predicate = ICmpInst::Predicate(IC->getPredicate());
2139 SDValue Op1 = getValue(I.getOperand(0));
2140 SDValue Op2 = getValue(I.getOperand(1));
2141 ISD::CondCode Opcode = getICmpCondCode(predicate);
2142 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2145 void SelectionDAGLowering::visitVFCmp(User &I) {
2146 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2147 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2148 predicate = FC->getPredicate();
2149 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2150 predicate = FCmpInst::Predicate(FC->getPredicate());
2151 SDValue Op1 = getValue(I.getOperand(0));
2152 SDValue Op2 = getValue(I.getOperand(1));
2153 ISD::CondCode Condition = getFCmpCondCode(predicate);
2154 MVT DestVT = TLI.getValueType(I.getType());
2156 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2159 void SelectionDAGLowering::visitSelect(User &I) {
2160 SmallVector<MVT, 4> ValueVTs;
2161 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2162 unsigned NumValues = ValueVTs.size();
2163 if (NumValues != 0) {
2164 SmallVector<SDValue, 4> Values(NumValues);
2165 SDValue Cond = getValue(I.getOperand(0));
2166 SDValue TrueVal = getValue(I.getOperand(1));
2167 SDValue FalseVal = getValue(I.getOperand(2));
2169 for (unsigned i = 0; i != NumValues; ++i)
2170 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2171 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2172 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2174 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2175 DAG.getVTList(&ValueVTs[0], NumValues),
2176 &Values[0], NumValues));
2181 void SelectionDAGLowering::visitTrunc(User &I) {
2182 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2183 SDValue N = getValue(I.getOperand(0));
2184 MVT DestVT = TLI.getValueType(I.getType());
2185 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2188 void SelectionDAGLowering::visitZExt(User &I) {
2189 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2190 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2191 SDValue N = getValue(I.getOperand(0));
2192 MVT DestVT = TLI.getValueType(I.getType());
2193 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2196 void SelectionDAGLowering::visitSExt(User &I) {
2197 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2198 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2199 SDValue N = getValue(I.getOperand(0));
2200 MVT DestVT = TLI.getValueType(I.getType());
2201 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2204 void SelectionDAGLowering::visitFPTrunc(User &I) {
2205 // FPTrunc is never a no-op cast, no need to check
2206 SDValue N = getValue(I.getOperand(0));
2207 MVT DestVT = TLI.getValueType(I.getType());
2208 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2211 void SelectionDAGLowering::visitFPExt(User &I){
2212 // FPTrunc is never a no-op cast, no need to check
2213 SDValue N = getValue(I.getOperand(0));
2214 MVT DestVT = TLI.getValueType(I.getType());
2215 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2218 void SelectionDAGLowering::visitFPToUI(User &I) {
2219 // FPToUI is never a no-op cast, no need to check
2220 SDValue N = getValue(I.getOperand(0));
2221 MVT DestVT = TLI.getValueType(I.getType());
2222 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2225 void SelectionDAGLowering::visitFPToSI(User &I) {
2226 // FPToSI is never a no-op cast, no need to check
2227 SDValue N = getValue(I.getOperand(0));
2228 MVT DestVT = TLI.getValueType(I.getType());
2229 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2232 void SelectionDAGLowering::visitUIToFP(User &I) {
2233 // UIToFP is never a no-op cast, no need to check
2234 SDValue N = getValue(I.getOperand(0));
2235 MVT DestVT = TLI.getValueType(I.getType());
2236 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2239 void SelectionDAGLowering::visitSIToFP(User &I){
2240 // SIToFP is never a no-op cast, no need to check
2241 SDValue N = getValue(I.getOperand(0));
2242 MVT DestVT = TLI.getValueType(I.getType());
2243 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2246 void SelectionDAGLowering::visitPtrToInt(User &I) {
2247 // What to do depends on the size of the integer and the size of the pointer.
2248 // We can either truncate, zero extend, or no-op, accordingly.
2249 SDValue N = getValue(I.getOperand(0));
2250 MVT SrcVT = N.getValueType();
2251 MVT DestVT = TLI.getValueType(I.getType());
2253 if (DestVT.bitsLT(SrcVT))
2254 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2256 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2257 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2258 setValue(&I, Result);
2261 void SelectionDAGLowering::visitIntToPtr(User &I) {
2262 // What to do depends on the size of the integer and the size of the pointer.
2263 // We can either truncate, zero extend, or no-op, accordingly.
2264 SDValue N = getValue(I.getOperand(0));
2265 MVT SrcVT = N.getValueType();
2266 MVT DestVT = TLI.getValueType(I.getType());
2267 if (DestVT.bitsLT(SrcVT))
2268 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2270 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2271 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2274 void SelectionDAGLowering::visitBitCast(User &I) {
2275 SDValue N = getValue(I.getOperand(0));
2276 MVT DestVT = TLI.getValueType(I.getType());
2278 // BitCast assures us that source and destination are the same size so this
2279 // is either a BIT_CONVERT or a no-op.
2280 if (DestVT != N.getValueType())
2281 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2283 setValue(&I, N); // noop cast.
2286 void SelectionDAGLowering::visitInsertElement(User &I) {
2287 SDValue InVec = getValue(I.getOperand(0));
2288 SDValue InVal = getValue(I.getOperand(1));
2289 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2290 getValue(I.getOperand(2)));
2292 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2293 TLI.getValueType(I.getType()),
2294 InVec, InVal, InIdx));
2297 void SelectionDAGLowering::visitExtractElement(User &I) {
2298 SDValue InVec = getValue(I.getOperand(0));
2299 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2300 getValue(I.getOperand(1)));
2301 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2302 TLI.getValueType(I.getType()), InVec, InIdx));
2306 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2307 // from SIndx and increasing to the element length (undefs are allowed).
2308 static bool SequentialMask(SDValue Mask, unsigned SIndx) {
2309 unsigned MaskNumElts = Mask.getNumOperands();
2310 for (unsigned i = 0; i != MaskNumElts; ++i) {
2311 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2312 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2313 if (Idx != i + SIndx)
2320 void SelectionDAGLowering::visitShuffleVector(User &I) {
2321 SDValue Src1 = getValue(I.getOperand(0));
2322 SDValue Src2 = getValue(I.getOperand(1));
2323 SDValue Mask = getValue(I.getOperand(2));
2325 MVT VT = TLI.getValueType(I.getType());
2326 MVT SrcVT = Src1.getValueType();
2327 int MaskNumElts = Mask.getNumOperands();
2328 int SrcNumElts = SrcVT.getVectorNumElements();
2330 if (SrcNumElts == MaskNumElts) {
2331 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
2335 // Normalize the shuffle vector since mask and vector length don't match.
2336 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2338 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2339 // Mask is longer than the source vectors and is a multiple of the source
2340 // vectors. We can use concatenate vector to make the mask and vectors
2342 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2343 // The shuffle is concatenating two vectors together.
2344 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, VT, Src1, Src2));
2348 // Pad both vectors with undefs to make them the same length as the mask.
2349 unsigned NumConcat = MaskNumElts / SrcNumElts;
2350 SDValue UndefVal = DAG.getNode(ISD::UNDEF, SrcVT);
2352 SDValue* MOps1 = new SDValue[NumConcat];
2353 SDValue* MOps2 = new SDValue[NumConcat];
2356 for (unsigned i = 1; i != NumConcat; ++i) {
2357 MOps1[i] = UndefVal;
2358 MOps2[i] = UndefVal;
2360 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps1, NumConcat);
2361 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps2, NumConcat);
2366 // Readjust mask for new input vector length.
2367 SmallVector<SDValue, 8> MappedOps;
2368 for (int i = 0; i != MaskNumElts; ++i) {
2369 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2370 MappedOps.push_back(Mask.getOperand(i));
2372 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2373 if (Idx < SrcNumElts)
2374 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2376 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2380 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2381 &MappedOps[0], MappedOps.size());
2383 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
2387 if (SrcNumElts > MaskNumElts) {
2388 // Resulting vector is shorter than the incoming vector.
2389 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
2390 // Shuffle extracts 1st vector.
2395 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
2396 // Shuffle extracts 2nd vector.
2401 // Analyze the access pattern of the vector to see if we can extract
2402 // two subvectors and do the shuffle. The analysis is done by calculating
2403 // the range of elements the mask access on both vectors.
2404 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2405 int MaxRange[2] = {-1, -1};
2407 for (int i = 0; i != MaskNumElts; ++i) {
2408 SDValue Arg = Mask.getOperand(i);
2409 if (Arg.getOpcode() != ISD::UNDEF) {
2410 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2411 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2413 if (Idx >= SrcNumElts) {
2417 if (Idx > MaxRange[Input])
2418 MaxRange[Input] = Idx;
2419 if (Idx < MinRange[Input])
2420 MinRange[Input] = Idx;
2424 // Check if the access is smaller than the vector size and can we find
2425 // a reasonable extract index.
2426 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2427 int StartIdx[2]; // StartIdx to extract from
2428 for (int Input=0; Input < 2; ++Input) {
2429 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2430 RangeUse[Input] = 0; // Unused
2431 StartIdx[Input] = 0;
2432 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2433 // Fits within range but we should see if we can find a good
2434 // start index that is a multiple of the mask length.
2435 if (MaxRange[Input] < MaskNumElts) {
2436 RangeUse[Input] = 1; // Extract from beginning of the vector
2437 StartIdx[Input] = 0;
2439 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2440 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
2441 StartIdx[Input] + MaskNumElts < SrcNumElts)
2442 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2447 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2448 setValue(&I, DAG.getNode(ISD::UNDEF, VT)); // Vectors are not used.
2451 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2452 // Extract appropriate subvector and generate a vector shuffle
2453 for (int Input=0; Input < 2; ++Input) {
2454 SDValue& Src = Input == 0 ? Src1 : Src2;
2455 if (RangeUse[Input] == 0) {
2456 Src = DAG.getNode(ISD::UNDEF, VT);
2458 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, VT, Src,
2459 DAG.getIntPtrConstant(StartIdx[Input]));
2462 // Calculate new mask.
2463 SmallVector<SDValue, 8> MappedOps;
2464 for (int i = 0; i != MaskNumElts; ++i) {
2465 SDValue Arg = Mask.getOperand(i);
2466 if (Arg.getOpcode() == ISD::UNDEF) {
2467 MappedOps.push_back(Arg);
2469 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2470 if (Idx < SrcNumElts)
2471 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2473 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2474 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2478 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2479 &MappedOps[0], MappedOps.size());
2480 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
2485 // We can't use either concat vectors or extract subvectors so fall back to
2486 // replacing the shuffle with extract and build vector.
2487 // to insert and build vector.
2488 MVT EltVT = VT.getVectorElementType();
2489 MVT PtrVT = TLI.getPointerTy();
2490 SmallVector<SDValue,8> Ops;
2491 for (int i = 0; i != MaskNumElts; ++i) {
2492 SDValue Arg = Mask.getOperand(i);
2493 if (Arg.getOpcode() == ISD::UNDEF) {
2494 Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2496 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2497 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2498 if (Idx < SrcNumElts)
2499 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src1,
2500 DAG.getConstant(Idx, PtrVT)));
2502 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src2,
2503 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
2506 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()));
2509 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2510 const Value *Op0 = I.getOperand(0);
2511 const Value *Op1 = I.getOperand(1);
2512 const Type *AggTy = I.getType();
2513 const Type *ValTy = Op1->getType();
2514 bool IntoUndef = isa<UndefValue>(Op0);
2515 bool FromUndef = isa<UndefValue>(Op1);
2517 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2518 I.idx_begin(), I.idx_end());
2520 SmallVector<MVT, 4> AggValueVTs;
2521 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2522 SmallVector<MVT, 4> ValValueVTs;
2523 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2525 unsigned NumAggValues = AggValueVTs.size();
2526 unsigned NumValValues = ValValueVTs.size();
2527 SmallVector<SDValue, 4> Values(NumAggValues);
2529 SDValue Agg = getValue(Op0);
2530 SDValue Val = getValue(Op1);
2532 // Copy the beginning value(s) from the original aggregate.
2533 for (; i != LinearIndex; ++i)
2534 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2535 SDValue(Agg.getNode(), Agg.getResNo() + i);
2536 // Copy values from the inserted value(s).
2537 for (; i != LinearIndex + NumValValues; ++i)
2538 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2539 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2540 // Copy remaining value(s) from the original aggregate.
2541 for (; i != NumAggValues; ++i)
2542 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2543 SDValue(Agg.getNode(), Agg.getResNo() + i);
2545 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2546 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2547 &Values[0], NumAggValues));
2550 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2551 const Value *Op0 = I.getOperand(0);
2552 const Type *AggTy = Op0->getType();
2553 const Type *ValTy = I.getType();
2554 bool OutOfUndef = isa<UndefValue>(Op0);
2556 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2557 I.idx_begin(), I.idx_end());
2559 SmallVector<MVT, 4> ValValueVTs;
2560 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2562 unsigned NumValValues = ValValueVTs.size();
2563 SmallVector<SDValue, 4> Values(NumValValues);
2565 SDValue Agg = getValue(Op0);
2566 // Copy out the selected value(s).
2567 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2568 Values[i - LinearIndex] =
2570 DAG.getNode(ISD::UNDEF,
2571 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2572 SDValue(Agg.getNode(), Agg.getResNo() + i);
2574 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2575 DAG.getVTList(&ValValueVTs[0], NumValValues),
2576 &Values[0], NumValValues));
2580 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2581 SDValue N = getValue(I.getOperand(0));
2582 const Type *Ty = I.getOperand(0)->getType();
2584 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2587 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2588 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2591 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2592 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2593 DAG.getIntPtrConstant(Offset));
2595 Ty = StTy->getElementType(Field);
2597 Ty = cast<SequentialType>(Ty)->getElementType();
2599 // If this is a constant subscript, handle it quickly.
2600 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2601 if (CI->getZExtValue() == 0) continue;
2603 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2604 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2605 DAG.getIntPtrConstant(Offs));
2609 // N = N + Idx * ElementSize;
2610 uint64_t ElementSize = TD->getABITypeSize(Ty);
2611 SDValue IdxN = getValue(Idx);
2613 // If the index is smaller or larger than intptr_t, truncate or extend
2615 if (IdxN.getValueType().bitsLT(N.getValueType()))
2616 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2617 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2618 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2620 // If this is a multiply by a power of two, turn it into a shl
2621 // immediately. This is a very common case.
2622 if (ElementSize != 1) {
2623 if (isPowerOf2_64(ElementSize)) {
2624 unsigned Amt = Log2_64(ElementSize);
2625 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2626 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2628 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2629 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2633 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2639 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2640 // If this is a fixed sized alloca in the entry block of the function,
2641 // allocate it statically on the stack.
2642 if (FuncInfo.StaticAllocaMap.count(&I))
2643 return; // getValue will auto-populate this.
2645 const Type *Ty = I.getAllocatedType();
2646 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2648 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2651 SDValue AllocSize = getValue(I.getArraySize());
2652 MVT IntPtr = TLI.getPointerTy();
2653 if (IntPtr.bitsLT(AllocSize.getValueType()))
2654 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2655 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2656 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2658 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2659 DAG.getIntPtrConstant(TySize));
2661 // Handle alignment. If the requested alignment is less than or equal to
2662 // the stack alignment, ignore it. If the size is greater than or equal to
2663 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2664 unsigned StackAlign =
2665 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2666 if (Align <= StackAlign)
2669 // Round the size of the allocation up to the stack alignment size
2670 // by add SA-1 to the size.
2671 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2672 DAG.getIntPtrConstant(StackAlign-1));
2673 // Mask out the low bits for alignment purposes.
2674 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2675 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2677 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2678 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2680 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2682 DAG.setRoot(DSA.getValue(1));
2684 // Inform the Frame Information that we have just allocated a variable-sized
2686 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2689 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2690 const Value *SV = I.getOperand(0);
2691 SDValue Ptr = getValue(SV);
2693 const Type *Ty = I.getType();
2694 bool isVolatile = I.isVolatile();
2695 unsigned Alignment = I.getAlignment();
2697 SmallVector<MVT, 4> ValueVTs;
2698 SmallVector<uint64_t, 4> Offsets;
2699 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2700 unsigned NumValues = ValueVTs.size();
2705 bool ConstantMemory = false;
2707 // Serialize volatile loads with other side effects.
2709 else if (AA->pointsToConstantMemory(SV)) {
2710 // Do not serialize (non-volatile) loads of constant memory with anything.
2711 Root = DAG.getEntryNode();
2712 ConstantMemory = true;
2714 // Do not serialize non-volatile loads against each other.
2715 Root = DAG.getRoot();
2718 SmallVector<SDValue, 4> Values(NumValues);
2719 SmallVector<SDValue, 4> Chains(NumValues);
2720 MVT PtrVT = Ptr.getValueType();
2721 for (unsigned i = 0; i != NumValues; ++i) {
2722 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2723 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2724 DAG.getConstant(Offsets[i], PtrVT)),
2726 isVolatile, Alignment);
2728 Chains[i] = L.getValue(1);
2731 if (!ConstantMemory) {
2732 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2733 &Chains[0], NumValues);
2737 PendingLoads.push_back(Chain);
2740 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2741 DAG.getVTList(&ValueVTs[0], NumValues),
2742 &Values[0], NumValues));
2746 void SelectionDAGLowering::visitStore(StoreInst &I) {
2747 Value *SrcV = I.getOperand(0);
2748 Value *PtrV = I.getOperand(1);
2750 SmallVector<MVT, 4> ValueVTs;
2751 SmallVector<uint64_t, 4> Offsets;
2752 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2753 unsigned NumValues = ValueVTs.size();
2757 // Get the lowered operands. Note that we do this after
2758 // checking if NumResults is zero, because with zero results
2759 // the operands won't have values in the map.
2760 SDValue Src = getValue(SrcV);
2761 SDValue Ptr = getValue(PtrV);
2763 SDValue Root = getRoot();
2764 SmallVector<SDValue, 4> Chains(NumValues);
2765 MVT PtrVT = Ptr.getValueType();
2766 bool isVolatile = I.isVolatile();
2767 unsigned Alignment = I.getAlignment();
2768 for (unsigned i = 0; i != NumValues; ++i)
2769 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2770 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2771 DAG.getConstant(Offsets[i], PtrVT)),
2773 isVolatile, Alignment);
2775 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2778 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2780 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2781 unsigned Intrinsic) {
2782 bool HasChain = !I.doesNotAccessMemory();
2783 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2785 // Build the operand list.
2786 SmallVector<SDValue, 8> Ops;
2787 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2789 // We don't need to serialize loads against other loads.
2790 Ops.push_back(DAG.getRoot());
2792 Ops.push_back(getRoot());
2796 // Info is set by getTgtMemInstrinsic
2797 TargetLowering::IntrinsicInfo Info;
2798 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2800 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2801 if (!IsTgtIntrinsic)
2802 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2804 // Add all operands of the call to the operand list.
2805 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2806 SDValue Op = getValue(I.getOperand(i));
2807 assert(TLI.isTypeLegal(Op.getValueType()) &&
2808 "Intrinsic uses a non-legal type?");
2812 std::vector<MVT> VTs;
2813 if (I.getType() != Type::VoidTy) {
2814 MVT VT = TLI.getValueType(I.getType());
2815 if (VT.isVector()) {
2816 const VectorType *DestTy = cast<VectorType>(I.getType());
2817 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2819 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2820 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2823 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2827 VTs.push_back(MVT::Other);
2829 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2833 if (IsTgtIntrinsic) {
2834 // This is target intrinsic that touches memory
2835 Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2836 &Ops[0], Ops.size(),
2837 Info.memVT, Info.ptrVal, Info.offset,
2838 Info.align, Info.vol,
2839 Info.readMem, Info.writeMem);
2842 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2843 &Ops[0], Ops.size());
2844 else if (I.getType() != Type::VoidTy)
2845 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2846 &Ops[0], Ops.size());
2848 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2849 &Ops[0], Ops.size());
2852 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2854 PendingLoads.push_back(Chain);
2858 if (I.getType() != Type::VoidTy) {
2859 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2860 MVT VT = TLI.getValueType(PTy);
2861 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2863 setValue(&I, Result);
2867 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2868 static GlobalVariable *ExtractTypeInfo(Value *V) {
2869 V = V->stripPointerCasts();
2870 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2871 assert ((GV || isa<ConstantPointerNull>(V)) &&
2872 "TypeInfo must be a global variable or NULL");
2878 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2879 /// call, and add them to the specified machine basic block.
2880 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2881 MachineBasicBlock *MBB) {
2882 // Inform the MachineModuleInfo of the personality for this landing pad.
2883 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2884 assert(CE->getOpcode() == Instruction::BitCast &&
2885 isa<Function>(CE->getOperand(0)) &&
2886 "Personality should be a function");
2887 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2889 // Gather all the type infos for this landing pad and pass them along to
2890 // MachineModuleInfo.
2891 std::vector<GlobalVariable *> TyInfo;
2892 unsigned N = I.getNumOperands();
2894 for (unsigned i = N - 1; i > 2; --i) {
2895 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2896 unsigned FilterLength = CI->getZExtValue();
2897 unsigned FirstCatch = i + FilterLength + !FilterLength;
2898 assert (FirstCatch <= N && "Invalid filter length");
2900 if (FirstCatch < N) {
2901 TyInfo.reserve(N - FirstCatch);
2902 for (unsigned j = FirstCatch; j < N; ++j)
2903 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2904 MMI->addCatchTypeInfo(MBB, TyInfo);
2908 if (!FilterLength) {
2910 MMI->addCleanup(MBB);
2913 TyInfo.reserve(FilterLength - 1);
2914 for (unsigned j = i + 1; j < FirstCatch; ++j)
2915 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2916 MMI->addFilterTypeInfo(MBB, TyInfo);
2925 TyInfo.reserve(N - 3);
2926 for (unsigned j = 3; j < N; ++j)
2927 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2928 MMI->addCatchTypeInfo(MBB, TyInfo);
2934 /// GetSignificand - Get the significand and build it into a floating-point
2935 /// number with exponent of 1:
2937 /// Op = (Op & 0x007fffff) | 0x3f800000;
2939 /// where Op is the hexidecimal representation of floating point value.
2941 GetSignificand(SelectionDAG &DAG, SDValue Op) {
2942 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2943 DAG.getConstant(0x007fffff, MVT::i32));
2944 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2945 DAG.getConstant(0x3f800000, MVT::i32));
2946 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2949 /// GetExponent - Get the exponent:
2951 /// (float)((Op1 >> 23) - 127);
2953 /// where Op is the hexidecimal representation of floating point value.
2955 GetExponent(SelectionDAG &DAG, SDValue Op) {
2956 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
2957 DAG.getConstant(23, MVT::i32));
2958 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2959 DAG.getConstant(127, MVT::i32));
2960 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
2963 /// getF32Constant - Get 32-bit floating point constant.
2965 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2966 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2969 /// Inlined utility function to implement binary input atomic intrinsics for
2970 /// visitIntrinsicCall: I is a call instruction
2971 /// Op is the associated NodeType for I
2973 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2974 SDValue Root = getRoot();
2976 DAG.getAtomic(Op, getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2978 getValue(I.getOperand(1)),
2979 getValue(I.getOperand(2)),
2982 DAG.setRoot(L.getValue(1));
2986 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
2988 SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
2989 SDValue Op1 = getValue(I.getOperand(1));
2990 SDValue Op2 = getValue(I.getOperand(2));
2992 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
2993 SDValue Ops[] = { Op1, Op2 };
2995 SDValue Result = DAG.getNode(Op, DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
2997 setValue(&I, Result);
3001 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3002 /// limited-precision mode.
3004 SelectionDAGLowering::visitExp(CallInst &I) {
3007 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3008 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3009 SDValue Op = getValue(I.getOperand(1));
3011 // Put the exponent in the right bit position for later addition to the
3014 // #define LOG2OFe 1.4426950f
3015 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3016 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
3017 getF32Constant(DAG, 0x3fb8aa3b));
3018 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3020 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3021 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3022 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3024 // IntegerPartOfX <<= 23;
3025 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3026 DAG.getConstant(23, MVT::i32));
3028 if (LimitFloatPrecision <= 6) {
3029 // For floating-point precision of 6:
3031 // TwoToFractionalPartOfX =
3033 // (0.735607626f + 0.252464424f * x) * x;
3035 // error 0.0144103317, which is 6 bits
3036 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3037 getF32Constant(DAG, 0x3e814304));
3038 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3039 getF32Constant(DAG, 0x3f3c50c8));
3040 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3041 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3042 getF32Constant(DAG, 0x3f7f5e7e));
3043 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3045 // Add the exponent into the result in integer domain.
3046 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
3047 TwoToFracPartOfX, IntegerPartOfX);
3049 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
3050 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3051 // For floating-point precision of 12:
3053 // TwoToFractionalPartOfX =
3056 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3058 // 0.000107046256 error, which is 13 to 14 bits
3059 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3060 getF32Constant(DAG, 0x3da235e3));
3061 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3062 getF32Constant(DAG, 0x3e65b8f3));
3063 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3064 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3065 getF32Constant(DAG, 0x3f324b07));
3066 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3067 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3068 getF32Constant(DAG, 0x3f7ff8fd));
3069 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3071 // Add the exponent into the result in integer domain.
3072 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
3073 TwoToFracPartOfX, IntegerPartOfX);
3075 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
3076 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3077 // For floating-point precision of 18:
3079 // TwoToFractionalPartOfX =
3083 // (0.554906021e-1f +
3084 // (0.961591928e-2f +
3085 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3087 // error 2.47208000*10^(-7), which is better than 18 bits
3088 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3089 getF32Constant(DAG, 0x3924b03e));
3090 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3091 getF32Constant(DAG, 0x3ab24b87));
3092 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3093 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3094 getF32Constant(DAG, 0x3c1d8c17));
3095 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3096 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3097 getF32Constant(DAG, 0x3d634a1d));
3098 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3099 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3100 getF32Constant(DAG, 0x3e75fe14));
3101 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3102 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3103 getF32Constant(DAG, 0x3f317234));
3104 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3105 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3106 getF32Constant(DAG, 0x3f800000));
3107 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3109 // Add the exponent into the result in integer domain.
3110 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
3111 TwoToFracPartOfX, IntegerPartOfX);
3113 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
3116 // No special expansion.
3117 result = DAG.getNode(ISD::FEXP,
3118 getValue(I.getOperand(1)).getValueType(),
3119 getValue(I.getOperand(1)));
3122 setValue(&I, result);
3125 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3126 /// limited-precision mode.
3128 SelectionDAGLowering::visitLog(CallInst &I) {
3131 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3132 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3133 SDValue Op = getValue(I.getOperand(1));
3134 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3136 // Scale the exponent by log(2) [0.69314718f].
3137 SDValue Exp = GetExponent(DAG, Op1);
3138 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
3139 getF32Constant(DAG, 0x3f317218));
3141 // Get the significand and build it into a floating-point number with
3143 SDValue X = GetSignificand(DAG, Op1);
3145 if (LimitFloatPrecision <= 6) {
3146 // For floating-point precision of 6:
3150 // (1.4034025f - 0.23903021f * x) * x;
3152 // error 0.0034276066, which is better than 8 bits
3153 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3154 getF32Constant(DAG, 0xbe74c456));
3155 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3156 getF32Constant(DAG, 0x3fb3a2b1));
3157 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3158 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3159 getF32Constant(DAG, 0x3f949a29));
3161 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3162 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3163 // For floating-point precision of 12:
3169 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3171 // error 0.000061011436, which is 14 bits
3172 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3173 getF32Constant(DAG, 0xbd67b6d6));
3174 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3175 getF32Constant(DAG, 0x3ee4f4b8));
3176 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3177 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3178 getF32Constant(DAG, 0x3fbc278b));
3179 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3180 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3181 getF32Constant(DAG, 0x40348e95));
3182 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3183 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3184 getF32Constant(DAG, 0x3fdef31a));
3186 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3187 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3188 // For floating-point precision of 18:
3196 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3198 // error 0.0000023660568, which is better than 18 bits
3199 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3200 getF32Constant(DAG, 0xbc91e5ac));
3201 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3202 getF32Constant(DAG, 0x3e4350aa));
3203 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3204 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3205 getF32Constant(DAG, 0x3f60d3e3));
3206 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3207 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3208 getF32Constant(DAG, 0x4011cdf0));
3209 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3210 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3211 getF32Constant(DAG, 0x406cfd1c));
3212 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3213 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3214 getF32Constant(DAG, 0x408797cb));
3215 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3216 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3217 getF32Constant(DAG, 0x4006dcab));
3219 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3222 // No special expansion.
3223 result = DAG.getNode(ISD::FLOG,
3224 getValue(I.getOperand(1)).getValueType(),
3225 getValue(I.getOperand(1)));
3228 setValue(&I, result);
3231 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3232 /// limited-precision mode.
3234 SelectionDAGLowering::visitLog2(CallInst &I) {
3237 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3238 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3239 SDValue Op = getValue(I.getOperand(1));
3240 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3242 // Get the exponent.
3243 SDValue LogOfExponent = GetExponent(DAG, Op1);
3245 // Get the significand and build it into a floating-point number with
3247 SDValue X = GetSignificand(DAG, Op1);
3249 // Different possible minimax approximations of significand in
3250 // floating-point for various degrees of accuracy over [1,2].
3251 if (LimitFloatPrecision <= 6) {
3252 // For floating-point precision of 6:
3254 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3256 // error 0.0049451742, which is more than 7 bits
3257 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3258 getF32Constant(DAG, 0xbeb08fe0));
3259 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3260 getF32Constant(DAG, 0x40019463));
3261 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3262 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3263 getF32Constant(DAG, 0x3fd6633d));
3265 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3266 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3267 // For floating-point precision of 12:
3273 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3275 // error 0.0000876136000, which is better than 13 bits
3276 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3277 getF32Constant(DAG, 0xbda7262e));
3278 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3279 getF32Constant(DAG, 0x3f25280b));
3280 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3281 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3282 getF32Constant(DAG, 0x4007b923));
3283 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3284 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3285 getF32Constant(DAG, 0x40823e2f));
3286 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3287 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3288 getF32Constant(DAG, 0x4020d29c));
3290 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3291 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3292 // For floating-point precision of 18:
3301 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3303 // error 0.0000018516, which is better than 18 bits
3304 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3305 getF32Constant(DAG, 0xbcd2769e));
3306 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3307 getF32Constant(DAG, 0x3e8ce0b9));
3308 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3309 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3310 getF32Constant(DAG, 0x3fa22ae7));
3311 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3312 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3313 getF32Constant(DAG, 0x40525723));
3314 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3315 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3316 getF32Constant(DAG, 0x40aaf200));
3317 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3318 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3319 getF32Constant(DAG, 0x40c39dad));
3320 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3321 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3322 getF32Constant(DAG, 0x4042902c));
3324 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3327 // No special expansion.
3328 result = DAG.getNode(ISD::FLOG2,
3329 getValue(I.getOperand(1)).getValueType(),
3330 getValue(I.getOperand(1)));
3333 setValue(&I, result);
3336 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3337 /// limited-precision mode.
3339 SelectionDAGLowering::visitLog10(CallInst &I) {
3342 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3343 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3344 SDValue Op = getValue(I.getOperand(1));
3345 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3347 // Scale the exponent by log10(2) [0.30102999f].
3348 SDValue Exp = GetExponent(DAG, Op1);
3349 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
3350 getF32Constant(DAG, 0x3e9a209a));
3352 // Get the significand and build it into a floating-point number with
3354 SDValue X = GetSignificand(DAG, Op1);
3356 if (LimitFloatPrecision <= 6) {
3357 // For floating-point precision of 6:
3359 // Log10ofMantissa =
3361 // (0.60948995f - 0.10380950f * x) * x;
3363 // error 0.0014886165, which is 6 bits
3364 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3365 getF32Constant(DAG, 0xbdd49a13));
3366 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3367 getF32Constant(DAG, 0x3f1c0789));
3368 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3369 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3370 getF32Constant(DAG, 0x3f011300));
3372 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3373 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3374 // For floating-point precision of 12:
3376 // Log10ofMantissa =
3379 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3381 // error 0.00019228036, which is better than 12 bits
3382 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3383 getF32Constant(DAG, 0x3d431f31));
3384 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3385 getF32Constant(DAG, 0x3ea21fb2));
3386 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3387 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3388 getF32Constant(DAG, 0x3f6ae232));
3389 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3390 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3391 getF32Constant(DAG, 0x3f25f7c3));
3393 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3394 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3395 // For floating-point precision of 18:
3397 // Log10ofMantissa =
3402 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3404 // error 0.0000037995730, which is better than 18 bits
3405 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3406 getF32Constant(DAG, 0x3c5d51ce));
3407 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3408 getF32Constant(DAG, 0x3e00685a));
3409 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3410 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3411 getF32Constant(DAG, 0x3efb6798));
3412 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3413 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3414 getF32Constant(DAG, 0x3f88d192));
3415 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3416 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3417 getF32Constant(DAG, 0x3fc4316c));
3418 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3419 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
3420 getF32Constant(DAG, 0x3f57ce70));
3422 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3425 // No special expansion.
3426 result = DAG.getNode(ISD::FLOG10,
3427 getValue(I.getOperand(1)).getValueType(),
3428 getValue(I.getOperand(1)));
3431 setValue(&I, result);
3434 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3435 /// limited-precision mode.
3437 SelectionDAGLowering::visitExp2(CallInst &I) {
3440 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3441 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3442 SDValue Op = getValue(I.getOperand(1));
3444 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3446 // FractionalPartOfX = x - (float)IntegerPartOfX;
3447 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3448 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3450 // IntegerPartOfX <<= 23;
3451 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3452 DAG.getConstant(23, MVT::i32));
3454 if (LimitFloatPrecision <= 6) {
3455 // For floating-point precision of 6:
3457 // TwoToFractionalPartOfX =
3459 // (0.735607626f + 0.252464424f * x) * x;
3461 // error 0.0144103317, which is 6 bits
3462 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3463 getF32Constant(DAG, 0x3e814304));
3464 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3465 getF32Constant(DAG, 0x3f3c50c8));
3466 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3467 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3468 getF32Constant(DAG, 0x3f7f5e7e));
3469 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3470 SDValue TwoToFractionalPartOfX =
3471 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3473 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3474 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3475 // For floating-point precision of 12:
3477 // TwoToFractionalPartOfX =
3480 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3482 // error 0.000107046256, which is 13 to 14 bits
3483 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3484 getF32Constant(DAG, 0x3da235e3));
3485 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3486 getF32Constant(DAG, 0x3e65b8f3));
3487 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3488 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3489 getF32Constant(DAG, 0x3f324b07));
3490 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3491 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3492 getF32Constant(DAG, 0x3f7ff8fd));
3493 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3494 SDValue TwoToFractionalPartOfX =
3495 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3497 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3498 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3499 // For floating-point precision of 18:
3501 // TwoToFractionalPartOfX =
3505 // (0.554906021e-1f +
3506 // (0.961591928e-2f +
3507 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3508 // error 2.47208000*10^(-7), which is better than 18 bits
3509 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3510 getF32Constant(DAG, 0x3924b03e));
3511 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3512 getF32Constant(DAG, 0x3ab24b87));
3513 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3514 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3515 getF32Constant(DAG, 0x3c1d8c17));
3516 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3517 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3518 getF32Constant(DAG, 0x3d634a1d));
3519 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3520 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3521 getF32Constant(DAG, 0x3e75fe14));
3522 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3523 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3524 getF32Constant(DAG, 0x3f317234));
3525 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3526 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3527 getF32Constant(DAG, 0x3f800000));
3528 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3529 SDValue TwoToFractionalPartOfX =
3530 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3532 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3535 // No special expansion.
3536 result = DAG.getNode(ISD::FEXP2,
3537 getValue(I.getOperand(1)).getValueType(),
3538 getValue(I.getOperand(1)));
3541 setValue(&I, result);
3544 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3545 /// limited-precision mode with x == 10.0f.
3547 SelectionDAGLowering::visitPow(CallInst &I) {
3549 Value *Val = I.getOperand(1);
3550 bool IsExp10 = false;
3552 if (getValue(Val).getValueType() == MVT::f32 &&
3553 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3554 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3555 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3556 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3558 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3563 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3564 SDValue Op = getValue(I.getOperand(2));
3566 // Put the exponent in the right bit position for later addition to the
3569 // #define LOG2OF10 3.3219281f
3570 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3571 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
3572 getF32Constant(DAG, 0x40549a78));
3573 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3575 // FractionalPartOfX = x - (float)IntegerPartOfX;
3576 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3577 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3579 // IntegerPartOfX <<= 23;
3580 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3581 DAG.getConstant(23, MVT::i32));
3583 if (LimitFloatPrecision <= 6) {
3584 // For floating-point precision of 6:
3586 // twoToFractionalPartOfX =
3588 // (0.735607626f + 0.252464424f * x) * x;
3590 // error 0.0144103317, which is 6 bits
3591 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3592 getF32Constant(DAG, 0x3e814304));
3593 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3594 getF32Constant(DAG, 0x3f3c50c8));
3595 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3596 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3597 getF32Constant(DAG, 0x3f7f5e7e));
3598 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3599 SDValue TwoToFractionalPartOfX =
3600 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3602 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3603 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3604 // For floating-point precision of 12:
3606 // TwoToFractionalPartOfX =
3609 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3611 // error 0.000107046256, which is 13 to 14 bits
3612 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3613 getF32Constant(DAG, 0x3da235e3));
3614 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3615 getF32Constant(DAG, 0x3e65b8f3));
3616 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3617 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3618 getF32Constant(DAG, 0x3f324b07));
3619 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3620 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3621 getF32Constant(DAG, 0x3f7ff8fd));
3622 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3623 SDValue TwoToFractionalPartOfX =
3624 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3626 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3627 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3628 // For floating-point precision of 18:
3630 // TwoToFractionalPartOfX =
3634 // (0.554906021e-1f +
3635 // (0.961591928e-2f +
3636 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3637 // error 2.47208000*10^(-7), which is better than 18 bits
3638 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3639 getF32Constant(DAG, 0x3924b03e));
3640 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3641 getF32Constant(DAG, 0x3ab24b87));
3642 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3643 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3644 getF32Constant(DAG, 0x3c1d8c17));
3645 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3646 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3647 getF32Constant(DAG, 0x3d634a1d));
3648 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3649 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3650 getF32Constant(DAG, 0x3e75fe14));
3651 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3652 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3653 getF32Constant(DAG, 0x3f317234));
3654 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3655 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3656 getF32Constant(DAG, 0x3f800000));
3657 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3658 SDValue TwoToFractionalPartOfX =
3659 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3661 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3664 // No special expansion.
3665 result = DAG.getNode(ISD::FPOW,
3666 getValue(I.getOperand(1)).getValueType(),
3667 getValue(I.getOperand(1)),
3668 getValue(I.getOperand(2)));
3671 setValue(&I, result);
3674 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3675 /// we want to emit this as a call to a named external function, return the name
3676 /// otherwise lower it and return null.
3678 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3679 switch (Intrinsic) {
3681 // By default, turn this into a target intrinsic node.
3682 visitTargetIntrinsic(I, Intrinsic);
3684 case Intrinsic::vastart: visitVAStart(I); return 0;
3685 case Intrinsic::vaend: visitVAEnd(I); return 0;
3686 case Intrinsic::vacopy: visitVACopy(I); return 0;
3687 case Intrinsic::returnaddress:
3688 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3689 getValue(I.getOperand(1))));
3691 case Intrinsic::frameaddress:
3692 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3693 getValue(I.getOperand(1))));
3695 case Intrinsic::setjmp:
3696 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3698 case Intrinsic::longjmp:
3699 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3701 case Intrinsic::memcpy: {
3702 SDValue Op1 = getValue(I.getOperand(1));
3703 SDValue Op2 = getValue(I.getOperand(2));
3704 SDValue Op3 = getValue(I.getOperand(3));
3705 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3706 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3707 I.getOperand(1), 0, I.getOperand(2), 0));
3710 case Intrinsic::memset: {
3711 SDValue Op1 = getValue(I.getOperand(1));
3712 SDValue Op2 = getValue(I.getOperand(2));
3713 SDValue Op3 = getValue(I.getOperand(3));
3714 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3715 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3716 I.getOperand(1), 0));
3719 case Intrinsic::memmove: {
3720 SDValue Op1 = getValue(I.getOperand(1));
3721 SDValue Op2 = getValue(I.getOperand(2));
3722 SDValue Op3 = getValue(I.getOperand(3));
3723 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3725 // If the source and destination are known to not be aliases, we can
3726 // lower memmove as memcpy.
3727 uint64_t Size = -1ULL;
3728 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3729 Size = C->getZExtValue();
3730 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3731 AliasAnalysis::NoAlias) {
3732 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3733 I.getOperand(1), 0, I.getOperand(2), 0));
3737 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3738 I.getOperand(1), 0, I.getOperand(2), 0));
3741 case Intrinsic::dbg_stoppoint: {
3742 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3743 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3744 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3745 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3746 assert(DD && "Not a debug information descriptor");
3747 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3750 cast<CompileUnitDesc>(DD)));
3755 case Intrinsic::dbg_region_start: {
3756 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3757 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3758 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3759 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3760 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3765 case Intrinsic::dbg_region_end: {
3766 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3767 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3768 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3769 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3770 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3775 case Intrinsic::dbg_func_start: {
3776 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3778 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3779 Value *SP = FSI.getSubprogram();
3780 if (SP && MMI->Verify(SP)) {
3781 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3782 // what (most?) gdb expects.
3783 DebugInfoDesc *DD = MMI->getDescFor(SP);
3784 assert(DD && "Not a debug information descriptor");
3785 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3786 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3787 unsigned SrcFile = MMI->RecordSource(CompileUnit);
3788 // Record the source line but does not create a label for the normal
3789 // function start. It will be emitted at asm emission time. However,
3790 // create a label if this is a beginning of inlined function.
3791 unsigned LabelID = MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3792 if (MMI->getSourceLines().size() != 1)
3793 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3798 case Intrinsic::dbg_declare: {
3799 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3800 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3801 Value *Variable = DI.getVariable();
3802 if (MMI && Variable && MMI->Verify(Variable))
3803 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3804 getValue(DI.getAddress()), getValue(Variable)));
3808 case Intrinsic::eh_exception: {
3809 if (!CurMBB->isLandingPad()) {
3810 // FIXME: Mark exception register as live in. Hack for PR1508.
3811 unsigned Reg = TLI.getExceptionAddressRegister();
3812 if (Reg) CurMBB->addLiveIn(Reg);
3814 // Insert the EXCEPTIONADDR instruction.
3815 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3817 Ops[0] = DAG.getRoot();
3818 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3820 DAG.setRoot(Op.getValue(1));
3824 case Intrinsic::eh_selector_i32:
3825 case Intrinsic::eh_selector_i64: {
3826 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3827 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3828 MVT::i32 : MVT::i64);
3831 if (CurMBB->isLandingPad())
3832 AddCatchInfo(I, MMI, CurMBB);
3835 FuncInfo.CatchInfoLost.insert(&I);
3837 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3838 unsigned Reg = TLI.getExceptionSelectorRegister();
3839 if (Reg) CurMBB->addLiveIn(Reg);
3842 // Insert the EHSELECTION instruction.
3843 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3845 Ops[0] = getValue(I.getOperand(1));
3847 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3849 DAG.setRoot(Op.getValue(1));
3851 setValue(&I, DAG.getConstant(0, VT));
3857 case Intrinsic::eh_typeid_for_i32:
3858 case Intrinsic::eh_typeid_for_i64: {
3859 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3860 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3861 MVT::i32 : MVT::i64);
3864 // Find the type id for the given typeinfo.
3865 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3867 unsigned TypeID = MMI->getTypeIDFor(GV);
3868 setValue(&I, DAG.getConstant(TypeID, VT));
3870 // Return something different to eh_selector.
3871 setValue(&I, DAG.getConstant(1, VT));
3877 case Intrinsic::eh_return_i32:
3878 case Intrinsic::eh_return_i64:
3879 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3880 MMI->setCallsEHReturn(true);
3881 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3884 getValue(I.getOperand(1)),
3885 getValue(I.getOperand(2))));
3887 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3891 case Intrinsic::eh_unwind_init:
3892 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3893 MMI->setCallsUnwindInit(true);
3898 case Intrinsic::eh_dwarf_cfa: {
3899 MVT VT = getValue(I.getOperand(1)).getValueType();
3901 if (VT.bitsGT(TLI.getPointerTy()))
3902 CfaArg = DAG.getNode(ISD::TRUNCATE,
3903 TLI.getPointerTy(), getValue(I.getOperand(1)));
3905 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3906 TLI.getPointerTy(), getValue(I.getOperand(1)));
3908 SDValue Offset = DAG.getNode(ISD::ADD,
3910 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3911 TLI.getPointerTy()),
3913 setValue(&I, DAG.getNode(ISD::ADD,
3915 DAG.getNode(ISD::FRAMEADDR,
3918 TLI.getPointerTy())),
3923 case Intrinsic::convertff:
3924 case Intrinsic::convertfsi:
3925 case Intrinsic::convertfui:
3926 case Intrinsic::convertsif:
3927 case Intrinsic::convertuif:
3928 case Intrinsic::convertss:
3929 case Intrinsic::convertsu:
3930 case Intrinsic::convertus:
3931 case Intrinsic::convertuu: {
3932 ISD::CvtCode Code = ISD::CVT_INVALID;
3933 switch (Intrinsic) {
3934 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3935 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3936 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3937 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3938 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3939 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3940 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3941 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3942 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3944 MVT DestVT = TLI.getValueType(I.getType());
3945 Value* Op1 = I.getOperand(1);
3946 setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
3947 DAG.getValueType(DestVT),
3948 DAG.getValueType(getValue(Op1).getValueType()),
3949 getValue(I.getOperand(2)),
3950 getValue(I.getOperand(3)),
3955 case Intrinsic::sqrt:
3956 setValue(&I, DAG.getNode(ISD::FSQRT,
3957 getValue(I.getOperand(1)).getValueType(),
3958 getValue(I.getOperand(1))));
3960 case Intrinsic::powi:
3961 setValue(&I, DAG.getNode(ISD::FPOWI,
3962 getValue(I.getOperand(1)).getValueType(),
3963 getValue(I.getOperand(1)),
3964 getValue(I.getOperand(2))));
3966 case Intrinsic::sin:
3967 setValue(&I, DAG.getNode(ISD::FSIN,
3968 getValue(I.getOperand(1)).getValueType(),
3969 getValue(I.getOperand(1))));
3971 case Intrinsic::cos:
3972 setValue(&I, DAG.getNode(ISD::FCOS,
3973 getValue(I.getOperand(1)).getValueType(),
3974 getValue(I.getOperand(1))));
3976 case Intrinsic::log:
3979 case Intrinsic::log2:
3982 case Intrinsic::log10:
3985 case Intrinsic::exp:
3988 case Intrinsic::exp2:
3991 case Intrinsic::pow:
3994 case Intrinsic::pcmarker: {
3995 SDValue Tmp = getValue(I.getOperand(1));
3996 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3999 case Intrinsic::readcyclecounter: {
4000 SDValue Op = getRoot();
4001 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
4002 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4005 DAG.setRoot(Tmp.getValue(1));
4008 case Intrinsic::part_select: {
4009 // Currently not implemented: just abort
4010 assert(0 && "part_select intrinsic not implemented");
4013 case Intrinsic::part_set: {
4014 // Currently not implemented: just abort
4015 assert(0 && "part_set intrinsic not implemented");
4018 case Intrinsic::bswap:
4019 setValue(&I, DAG.getNode(ISD::BSWAP,
4020 getValue(I.getOperand(1)).getValueType(),
4021 getValue(I.getOperand(1))));
4023 case Intrinsic::cttz: {
4024 SDValue Arg = getValue(I.getOperand(1));
4025 MVT Ty = Arg.getValueType();
4026 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
4027 setValue(&I, result);
4030 case Intrinsic::ctlz: {
4031 SDValue Arg = getValue(I.getOperand(1));
4032 MVT Ty = Arg.getValueType();
4033 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
4034 setValue(&I, result);
4037 case Intrinsic::ctpop: {
4038 SDValue Arg = getValue(I.getOperand(1));
4039 MVT Ty = Arg.getValueType();
4040 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
4041 setValue(&I, result);
4044 case Intrinsic::stacksave: {
4045 SDValue Op = getRoot();
4046 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
4047 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4049 DAG.setRoot(Tmp.getValue(1));
4052 case Intrinsic::stackrestore: {
4053 SDValue Tmp = getValue(I.getOperand(1));
4054 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
4057 case Intrinsic::stackprotector: {
4058 // Emit code into the DAG to store the stack guard onto the stack.
4059 MachineFunction &MF = DAG.getMachineFunction();
4060 MachineFrameInfo *MFI = MF.getFrameInfo();
4061 MVT PtrTy = TLI.getPointerTy();
4063 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4064 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4066 int FI = FuncInfo.StaticAllocaMap[Slot];
4067 MFI->setStackProtectorIndex(FI);
4069 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4071 // Store the stack protector onto the stack.
4072 SDValue Result = DAG.getStore(getRoot(), Src, FIN,
4073 PseudoSourceValue::getFixedStack(FI),
4075 setValue(&I, Result);
4076 DAG.setRoot(Result);
4079 case Intrinsic::var_annotation:
4080 // Discard annotate attributes
4083 case Intrinsic::init_trampoline: {
4084 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4088 Ops[1] = getValue(I.getOperand(1));
4089 Ops[2] = getValue(I.getOperand(2));
4090 Ops[3] = getValue(I.getOperand(3));
4091 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4092 Ops[5] = DAG.getSrcValue(F);
4094 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
4095 DAG.getNodeValueTypes(TLI.getPointerTy(),
4100 DAG.setRoot(Tmp.getValue(1));
4104 case Intrinsic::gcroot:
4106 Value *Alloca = I.getOperand(1);
4107 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4109 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4110 GFI->addStackRoot(FI->getIndex(), TypeMap);
4114 case Intrinsic::gcread:
4115 case Intrinsic::gcwrite:
4116 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4119 case Intrinsic::flt_rounds: {
4120 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
4124 case Intrinsic::trap: {
4125 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
4129 case Intrinsic::uadd_with_overflow:
4130 return implVisitAluOverflow(I, ISD::UADDO);
4131 case Intrinsic::sadd_with_overflow:
4132 return implVisitAluOverflow(I, ISD::SADDO);
4133 case Intrinsic::usub_with_overflow:
4134 return implVisitAluOverflow(I, ISD::USUBO);
4135 case Intrinsic::ssub_with_overflow:
4136 return implVisitAluOverflow(I, ISD::SSUBO);
4137 case Intrinsic::umul_with_overflow:
4138 return implVisitAluOverflow(I, ISD::UMULO);
4139 case Intrinsic::smul_with_overflow:
4140 return implVisitAluOverflow(I, ISD::SMULO);
4142 case Intrinsic::prefetch: {
4145 Ops[1] = getValue(I.getOperand(1));
4146 Ops[2] = getValue(I.getOperand(2));
4147 Ops[3] = getValue(I.getOperand(3));
4148 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
4152 case Intrinsic::memory_barrier: {
4155 for (int x = 1; x < 6; ++x)
4156 Ops[x] = getValue(I.getOperand(x));
4158 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
4161 case Intrinsic::atomic_cmp_swap: {
4162 SDValue Root = getRoot();
4164 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP,
4165 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4167 getValue(I.getOperand(1)),
4168 getValue(I.getOperand(2)),
4169 getValue(I.getOperand(3)),
4172 DAG.setRoot(L.getValue(1));
4175 case Intrinsic::atomic_load_add:
4176 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4177 case Intrinsic::atomic_load_sub:
4178 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4179 case Intrinsic::atomic_load_or:
4180 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4181 case Intrinsic::atomic_load_xor:
4182 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4183 case Intrinsic::atomic_load_and:
4184 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4185 case Intrinsic::atomic_load_nand:
4186 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4187 case Intrinsic::atomic_load_max:
4188 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4189 case Intrinsic::atomic_load_min:
4190 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4191 case Intrinsic::atomic_load_umin:
4192 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4193 case Intrinsic::atomic_load_umax:
4194 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4195 case Intrinsic::atomic_swap:
4196 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4201 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4203 MachineBasicBlock *LandingPad) {
4204 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4205 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4206 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4207 unsigned BeginLabel = 0, EndLabel = 0;
4209 TargetLowering::ArgListTy Args;
4210 TargetLowering::ArgListEntry Entry;
4211 Args.reserve(CS.arg_size());
4212 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4214 SDValue ArgNode = getValue(*i);
4215 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4217 unsigned attrInd = i - CS.arg_begin() + 1;
4218 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4219 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4220 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4221 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4222 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4223 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4224 Entry.Alignment = CS.getParamAlignment(attrInd);
4225 Args.push_back(Entry);
4228 if (LandingPad && MMI) {
4229 // Insert a label before the invoke call to mark the try range. This can be
4230 // used to detect deletion of the invoke via the MachineModuleInfo.
4231 BeginLabel = MMI->NextLabelID();
4232 // Both PendingLoads and PendingExports must be flushed here;
4233 // this call might not return.
4235 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4238 std::pair<SDValue,SDValue> Result =
4239 TLI.LowerCallTo(getRoot(), CS.getType(),
4240 CS.paramHasAttr(0, Attribute::SExt),
4241 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4242 CS.paramHasAttr(0, Attribute::InReg),
4243 CS.getCallingConv(),
4244 IsTailCall && PerformTailCallOpt,
4246 if (CS.getType() != Type::VoidTy)
4247 setValue(CS.getInstruction(), Result.first);
4248 DAG.setRoot(Result.second);
4250 if (LandingPad && MMI) {
4251 // Insert a label at the end of the invoke call to mark the try range. This
4252 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4253 EndLabel = MMI->NextLabelID();
4254 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4256 // Inform MachineModuleInfo of range.
4257 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4262 void SelectionDAGLowering::visitCall(CallInst &I) {
4263 const char *RenameFn = 0;
4264 if (Function *F = I.getCalledFunction()) {
4265 if (F->isDeclaration()) {
4266 if (unsigned IID = F->getIntrinsicID()) {
4267 RenameFn = visitIntrinsicCall(I, IID);
4273 // Check for well-known libc/libm calls. If the function is internal, it
4274 // can't be a library call.
4275 unsigned NameLen = F->getNameLen();
4276 if (!F->hasInternalLinkage() && NameLen) {
4277 const char *NameStr = F->getNameStart();
4278 if (NameStr[0] == 'c' &&
4279 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4280 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4281 if (I.getNumOperands() == 3 && // Basic sanity checks.
4282 I.getOperand(1)->getType()->isFloatingPoint() &&
4283 I.getType() == I.getOperand(1)->getType() &&
4284 I.getType() == I.getOperand(2)->getType()) {
4285 SDValue LHS = getValue(I.getOperand(1));
4286 SDValue RHS = getValue(I.getOperand(2));
4287 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4291 } else if (NameStr[0] == 'f' &&
4292 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4293 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4294 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4295 if (I.getNumOperands() == 2 && // Basic sanity checks.
4296 I.getOperand(1)->getType()->isFloatingPoint() &&
4297 I.getType() == I.getOperand(1)->getType()) {
4298 SDValue Tmp = getValue(I.getOperand(1));
4299 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4302 } else if (NameStr[0] == 's' &&
4303 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4304 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4305 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4306 if (I.getNumOperands() == 2 && // Basic sanity checks.
4307 I.getOperand(1)->getType()->isFloatingPoint() &&
4308 I.getType() == I.getOperand(1)->getType()) {
4309 SDValue Tmp = getValue(I.getOperand(1));
4310 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4313 } else if (NameStr[0] == 'c' &&
4314 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4315 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4316 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4317 if (I.getNumOperands() == 2 && // Basic sanity checks.
4318 I.getOperand(1)->getType()->isFloatingPoint() &&
4319 I.getType() == I.getOperand(1)->getType()) {
4320 SDValue Tmp = getValue(I.getOperand(1));
4321 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4326 } else if (isa<InlineAsm>(I.getOperand(0))) {
4333 Callee = getValue(I.getOperand(0));
4335 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4337 LowerCallTo(&I, Callee, I.isTailCall());
4341 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4342 /// this value and returns the result as a ValueVT value. This uses
4343 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4344 /// If the Flag pointer is NULL, no flag is used.
4345 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4347 SDValue *Flag) const {
4348 // Assemble the legal parts into the final values.
4349 SmallVector<SDValue, 4> Values(ValueVTs.size());
4350 SmallVector<SDValue, 8> Parts;
4351 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4352 // Copy the legal parts from the registers.
4353 MVT ValueVT = ValueVTs[Value];
4354 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4355 MVT RegisterVT = RegVTs[Value];
4357 Parts.resize(NumRegs);
4358 for (unsigned i = 0; i != NumRegs; ++i) {
4361 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4363 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4364 *Flag = P.getValue(2);
4366 Chain = P.getValue(1);
4368 // If the source register was virtual and if we know something about it,
4369 // add an assert node.
4370 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4371 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4372 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4373 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4374 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4375 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4377 unsigned RegSize = RegisterVT.getSizeInBits();
4378 unsigned NumSignBits = LOI.NumSignBits;
4379 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4381 // FIXME: We capture more information than the dag can represent. For
4382 // now, just use the tightest assertzext/assertsext possible.
4384 MVT FromVT(MVT::Other);
4385 if (NumSignBits == RegSize)
4386 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4387 else if (NumZeroBits >= RegSize-1)
4388 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4389 else if (NumSignBits > RegSize-8)
4390 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4391 else if (NumZeroBits >= RegSize-9)
4392 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4393 else if (NumSignBits > RegSize-16)
4394 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4395 else if (NumZeroBits >= RegSize-17)
4396 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4397 else if (NumSignBits > RegSize-32)
4398 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4399 else if (NumZeroBits >= RegSize-33)
4400 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4402 if (FromVT != MVT::Other) {
4403 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4404 RegisterVT, P, DAG.getValueType(FromVT));
4413 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4419 return DAG.getNode(ISD::MERGE_VALUES,
4420 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4421 &Values[0], ValueVTs.size());
4424 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4425 /// specified value into the registers specified by this object. This uses
4426 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4427 /// If the Flag pointer is NULL, no flag is used.
4428 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4429 SDValue &Chain, SDValue *Flag) const {
4430 // Get the list of the values's legal parts.
4431 unsigned NumRegs = Regs.size();
4432 SmallVector<SDValue, 8> Parts(NumRegs);
4433 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4434 MVT ValueVT = ValueVTs[Value];
4435 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4436 MVT RegisterVT = RegVTs[Value];
4438 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4439 &Parts[Part], NumParts, RegisterVT);
4443 // Copy the parts into the registers.
4444 SmallVector<SDValue, 8> Chains(NumRegs);
4445 for (unsigned i = 0; i != NumRegs; ++i) {
4448 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4450 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4451 *Flag = Part.getValue(1);
4453 Chains[i] = Part.getValue(0);
4456 if (NumRegs == 1 || Flag)
4457 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4458 // flagged to it. That is the CopyToReg nodes and the user are considered
4459 // a single scheduling unit. If we create a TokenFactor and return it as
4460 // chain, then the TokenFactor is both a predecessor (operand) of the
4461 // user as well as a successor (the TF operands are flagged to the user).
4462 // c1, f1 = CopyToReg
4463 // c2, f2 = CopyToReg
4464 // c3 = TokenFactor c1, c2
4467 Chain = Chains[NumRegs-1];
4469 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4472 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4473 /// operand list. This adds the code marker and includes the number of
4474 /// values added into it.
4475 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4476 std::vector<SDValue> &Ops) const {
4477 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4478 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4479 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4480 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4481 MVT RegisterVT = RegVTs[Value];
4482 for (unsigned i = 0; i != NumRegs; ++i) {
4483 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4484 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4489 /// isAllocatableRegister - If the specified register is safe to allocate,
4490 /// i.e. it isn't a stack pointer or some other special register, return the
4491 /// register class for the register. Otherwise, return null.
4492 static const TargetRegisterClass *
4493 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4494 const TargetLowering &TLI,
4495 const TargetRegisterInfo *TRI) {
4496 MVT FoundVT = MVT::Other;
4497 const TargetRegisterClass *FoundRC = 0;
4498 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4499 E = TRI->regclass_end(); RCI != E; ++RCI) {
4500 MVT ThisVT = MVT::Other;
4502 const TargetRegisterClass *RC = *RCI;
4503 // If none of the the value types for this register class are valid, we
4504 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4505 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4507 if (TLI.isTypeLegal(*I)) {
4508 // If we have already found this register in a different register class,
4509 // choose the one with the largest VT specified. For example, on
4510 // PowerPC, we favor f64 register classes over f32.
4511 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4518 if (ThisVT == MVT::Other) continue;
4520 // NOTE: This isn't ideal. In particular, this might allocate the
4521 // frame pointer in functions that need it (due to them not being taken
4522 // out of allocation, because a variable sized allocation hasn't been seen
4523 // yet). This is a slight code pessimization, but should still work.
4524 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4525 E = RC->allocation_order_end(MF); I != E; ++I)
4527 // We found a matching register class. Keep looking at others in case
4528 // we find one with larger registers that this physreg is also in.
4539 /// AsmOperandInfo - This contains information for each constraint that we are
4541 struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4542 public TargetLowering::AsmOperandInfo {
4543 /// CallOperand - If this is the result output operand or a clobber
4544 /// this is null, otherwise it is the incoming operand to the CallInst.
4545 /// This gets modified as the asm is processed.
4546 SDValue CallOperand;
4548 /// AssignedRegs - If this is a register or register class operand, this
4549 /// contains the set of register corresponding to the operand.
4550 RegsForValue AssignedRegs;
4552 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4553 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4556 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4557 /// busy in OutputRegs/InputRegs.
4558 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4559 std::set<unsigned> &OutputRegs,
4560 std::set<unsigned> &InputRegs,
4561 const TargetRegisterInfo &TRI) const {
4563 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4564 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4567 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4568 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4572 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4573 /// corresponds to. If there is no Value* for this operand, it returns
4575 MVT getCallOperandValMVT(const TargetLowering &TLI,
4576 const TargetData *TD) const {
4577 if (CallOperandVal == 0) return MVT::Other;
4579 if (isa<BasicBlock>(CallOperandVal))
4580 return TLI.getPointerTy();
4582 const llvm::Type *OpTy = CallOperandVal->getType();
4584 // If this is an indirect operand, the operand is a pointer to the
4587 OpTy = cast<PointerType>(OpTy)->getElementType();
4589 // If OpTy is not a single value, it may be a struct/union that we
4590 // can tile with integers.
4591 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4592 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4601 OpTy = IntegerType::get(BitSize);
4606 return TLI.getValueType(OpTy, true);
4610 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4612 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4613 const TargetRegisterInfo &TRI) {
4614 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4616 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4617 for (; *Aliases; ++Aliases)
4618 Regs.insert(*Aliases);
4621 } // end llvm namespace.
4624 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4625 /// specified operand. We prefer to assign virtual registers, to allow the
4626 /// register allocator handle the assignment process. However, if the asm uses
4627 /// features that we can't model on machineinstrs, we have SDISel do the
4628 /// allocation. This produces generally horrible, but correct, code.
4630 /// OpInfo describes the operand.
4631 /// Input and OutputRegs are the set of already allocated physical registers.
4633 void SelectionDAGLowering::
4634 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4635 std::set<unsigned> &OutputRegs,
4636 std::set<unsigned> &InputRegs) {
4637 // Compute whether this value requires an input register, an output register,
4639 bool isOutReg = false;
4640 bool isInReg = false;
4641 switch (OpInfo.Type) {
4642 case InlineAsm::isOutput:
4645 // If there is an input constraint that matches this, we need to reserve
4646 // the input register so no other inputs allocate to it.
4647 isInReg = OpInfo.hasMatchingInput();
4649 case InlineAsm::isInput:
4653 case InlineAsm::isClobber:
4660 MachineFunction &MF = DAG.getMachineFunction();
4661 SmallVector<unsigned, 4> Regs;
4663 // If this is a constraint for a single physreg, or a constraint for a
4664 // register class, find it.
4665 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4666 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4667 OpInfo.ConstraintVT);
4669 unsigned NumRegs = 1;
4670 if (OpInfo.ConstraintVT != MVT::Other) {
4671 // If this is a FP input in an integer register (or visa versa) insert a bit
4672 // cast of the input value. More generally, handle any case where the input
4673 // value disagrees with the register class we plan to stick this in.
4674 if (OpInfo.Type == InlineAsm::isInput &&
4675 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4676 // Try to convert to the first MVT that the reg class contains. If the
4677 // types are identical size, use a bitcast to convert (e.g. two differing
4679 MVT RegVT = *PhysReg.second->vt_begin();
4680 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4681 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4682 OpInfo.CallOperand);
4683 OpInfo.ConstraintVT = RegVT;
4684 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4685 // If the input is a FP value and we want it in FP registers, do a
4686 // bitcast to the corresponding integer type. This turns an f64 value
4687 // into i64, which can be passed with two i32 values on a 32-bit
4689 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4690 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4691 OpInfo.CallOperand);
4692 OpInfo.ConstraintVT = RegVT;
4696 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4700 MVT ValueVT = OpInfo.ConstraintVT;
4702 // If this is a constraint for a specific physical register, like {r17},
4704 if (PhysReg.first) {
4705 if (OpInfo.ConstraintVT == MVT::Other)
4706 ValueVT = *PhysReg.second->vt_begin();
4708 // Get the actual register value type. This is important, because the user
4709 // may have asked for (e.g.) the AX register in i32 type. We need to
4710 // remember that AX is actually i16 to get the right extension.
4711 RegVT = *PhysReg.second->vt_begin();
4713 // This is a explicit reference to a physical register.
4714 Regs.push_back(PhysReg.first);
4716 // If this is an expanded reference, add the rest of the regs to Regs.
4718 TargetRegisterClass::iterator I = PhysReg.second->begin();
4719 for (; *I != PhysReg.first; ++I)
4720 assert(I != PhysReg.second->end() && "Didn't find reg!");
4722 // Already added the first reg.
4724 for (; NumRegs; --NumRegs, ++I) {
4725 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4729 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4730 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4731 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4735 // Otherwise, if this was a reference to an LLVM register class, create vregs
4736 // for this reference.
4737 std::vector<unsigned> RegClassRegs;
4738 const TargetRegisterClass *RC = PhysReg.second;
4740 // If this is a tied register, our regalloc doesn't know how to maintain
4741 // the constraint, so we have to pick a register to pin the input/output to.
4742 // If it isn't a matched constraint, go ahead and create vreg and let the
4743 // regalloc do its thing.
4744 if (!OpInfo.hasMatchingInput()) {
4745 RegVT = *PhysReg.second->vt_begin();
4746 if (OpInfo.ConstraintVT == MVT::Other)
4749 // Create the appropriate number of virtual registers.
4750 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4751 for (; NumRegs; --NumRegs)
4752 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4754 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4758 // Otherwise, we can't allocate it. Let the code below figure out how to
4759 // maintain these constraints.
4760 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4763 // This is a reference to a register class that doesn't directly correspond
4764 // to an LLVM register class. Allocate NumRegs consecutive, available,
4765 // registers from the class.
4766 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4767 OpInfo.ConstraintVT);
4770 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4771 unsigned NumAllocated = 0;
4772 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4773 unsigned Reg = RegClassRegs[i];
4774 // See if this register is available.
4775 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4776 (isInReg && InputRegs.count(Reg))) { // Already used.
4777 // Make sure we find consecutive registers.
4782 // Check to see if this register is allocatable (i.e. don't give out the
4785 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4786 if (!RC) { // Couldn't allocate this register.
4787 // Reset NumAllocated to make sure we return consecutive registers.
4793 // Okay, this register is good, we can use it.
4796 // If we allocated enough consecutive registers, succeed.
4797 if (NumAllocated == NumRegs) {
4798 unsigned RegStart = (i-NumAllocated)+1;
4799 unsigned RegEnd = i+1;
4800 // Mark all of the allocated registers used.
4801 for (unsigned i = RegStart; i != RegEnd; ++i)
4802 Regs.push_back(RegClassRegs[i]);
4804 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4805 OpInfo.ConstraintVT);
4806 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4811 // Otherwise, we couldn't allocate enough registers for this.
4814 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4815 /// processed uses a memory 'm' constraint.
4817 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4818 TargetLowering &TLI) {
4819 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4820 InlineAsm::ConstraintInfo &CI = CInfos[i];
4821 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4822 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4823 if (CType == TargetLowering::C_Memory)
4831 /// visitInlineAsm - Handle a call to an InlineAsm object.
4833 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4834 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4836 /// ConstraintOperands - Information about all of the constraints.
4837 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4839 SDValue Chain = getRoot();
4842 std::set<unsigned> OutputRegs, InputRegs;
4844 // Do a prepass over the constraints, canonicalizing them, and building up the
4845 // ConstraintOperands list.
4846 std::vector<InlineAsm::ConstraintInfo>
4847 ConstraintInfos = IA->ParseConstraints();
4849 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
4851 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4852 unsigned ResNo = 0; // ResNo - The result number of the next output.
4853 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4854 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4855 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4857 MVT OpVT = MVT::Other;
4859 // Compute the value type for each operand.
4860 switch (OpInfo.Type) {
4861 case InlineAsm::isOutput:
4862 // Indirect outputs just consume an argument.
4863 if (OpInfo.isIndirect) {
4864 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4868 // The return value of the call is this value. As such, there is no
4869 // corresponding argument.
4870 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4871 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4872 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4874 assert(ResNo == 0 && "Asm only has one result!");
4875 OpVT = TLI.getValueType(CS.getType());
4879 case InlineAsm::isInput:
4880 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4882 case InlineAsm::isClobber:
4887 // If this is an input or an indirect output, process the call argument.
4888 // BasicBlocks are labels, currently appearing only in asm's.
4889 if (OpInfo.CallOperandVal) {
4890 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
4891 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4893 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4896 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
4899 OpInfo.ConstraintVT = OpVT;
4902 // Second pass over the constraints: compute which constraint option to use
4903 // and assign registers to constraints that want a specific physreg.
4904 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4905 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4907 // If this is an output operand with a matching input operand, look up the
4908 // matching input. If their types mismatch, e.g. one is an integer, the
4909 // other is floating point, or their sizes are different, flag it as an
4911 if (OpInfo.hasMatchingInput()) {
4912 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4913 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4914 if ((OpInfo.ConstraintVT.isInteger() !=
4915 Input.ConstraintVT.isInteger()) ||
4916 (OpInfo.ConstraintVT.getSizeInBits() !=
4917 Input.ConstraintVT.getSizeInBits())) {
4918 cerr << "Unsupported asm: input constraint with a matching output "
4919 << "constraint of incompatible type!\n";
4922 Input.ConstraintVT = OpInfo.ConstraintVT;
4926 // Compute the constraint code and ConstraintType to use.
4927 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
4929 // If this is a memory input, and if the operand is not indirect, do what we
4930 // need to to provide an address for the memory input.
4931 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4932 !OpInfo.isIndirect) {
4933 assert(OpInfo.Type == InlineAsm::isInput &&
4934 "Can only indirectify direct input operands!");
4936 // Memory operands really want the address of the value. If we don't have
4937 // an indirect input, put it in the constpool if we can, otherwise spill
4938 // it to a stack slot.
4940 // If the operand is a float, integer, or vector constant, spill to a
4941 // constant pool entry to get its address.
4942 Value *OpVal = OpInfo.CallOperandVal;
4943 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4944 isa<ConstantVector>(OpVal)) {
4945 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4946 TLI.getPointerTy());
4948 // Otherwise, create a stack slot and emit a store to it before the
4950 const Type *Ty = OpVal->getType();
4951 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4952 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4953 MachineFunction &MF = DAG.getMachineFunction();
4954 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4955 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4956 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4957 OpInfo.CallOperand = StackSlot;
4960 // There is no longer a Value* corresponding to this operand.
4961 OpInfo.CallOperandVal = 0;
4962 // It is now an indirect operand.
4963 OpInfo.isIndirect = true;
4966 // If this constraint is for a specific register, allocate it before
4968 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4969 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4971 ConstraintInfos.clear();
4974 // Second pass - Loop over all of the operands, assigning virtual or physregs
4975 // to register class operands.
4976 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4977 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4979 // C_Register operands have already been allocated, Other/Memory don't need
4981 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4982 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4985 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4986 std::vector<SDValue> AsmNodeOperands;
4987 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4988 AsmNodeOperands.push_back(
4989 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4992 // Loop over all of the inputs, copying the operand values into the
4993 // appropriate registers and processing the output regs.
4994 RegsForValue RetValRegs;
4996 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4997 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4999 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5000 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5002 switch (OpInfo.Type) {
5003 case InlineAsm::isOutput: {
5004 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5005 OpInfo.ConstraintType != TargetLowering::C_Register) {
5006 // Memory output, or 'other' output (e.g. 'X' constraint).
5007 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5009 // Add information to the INLINEASM node to know about this output.
5010 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5011 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5012 TLI.getPointerTy()));
5013 AsmNodeOperands.push_back(OpInfo.CallOperand);
5017 // Otherwise, this is a register or register class output.
5019 // Copy the output from the appropriate register. Find a register that
5021 if (OpInfo.AssignedRegs.Regs.empty()) {
5022 cerr << "Couldn't allocate output reg for constraint '"
5023 << OpInfo.ConstraintCode << "'!\n";
5027 // If this is an indirect operand, store through the pointer after the
5029 if (OpInfo.isIndirect) {
5030 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5031 OpInfo.CallOperandVal));
5033 // This is the result value of the call.
5034 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5035 // Concatenate this output onto the outputs list.
5036 RetValRegs.append(OpInfo.AssignedRegs);
5039 // Add information to the INLINEASM node to know that this register is
5041 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5042 6 /* EARLYCLOBBER REGDEF */ :
5044 DAG, AsmNodeOperands);
5047 case InlineAsm::isInput: {
5048 SDValue InOperandVal = OpInfo.CallOperand;
5050 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5051 // If this is required to match an output register we have already set,
5052 // just use its register.
5053 unsigned OperandNo = OpInfo.getMatchedOperand();
5055 // Scan until we find the definition we already emitted of this operand.
5056 // When we find it, create a RegsForValue operand.
5057 unsigned CurOp = 2; // The first operand.
5058 for (; OperandNo; --OperandNo) {
5059 // Advance to the next operand.
5061 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5062 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
5063 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5064 (NumOps & 7) == 4 /*MEM*/) &&
5065 "Skipped past definitions?");
5066 CurOp += (NumOps>>3)+1;
5070 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5071 if ((NumOps & 7) == 2 /*REGDEF*/
5072 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5073 // Add NumOps>>3 registers to MatchedRegs.
5074 RegsForValue MatchedRegs;
5075 MatchedRegs.TLI = &TLI;
5076 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5077 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5078 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5080 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5081 MatchedRegs.Regs.push_back(Reg);
5084 // Use the produced MatchedRegs object to
5085 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5086 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
5089 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
5090 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
5091 // Add information to the INLINEASM node to know about this input.
5092 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
5093 TLI.getPointerTy()));
5094 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5099 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5100 assert(!OpInfo.isIndirect &&
5101 "Don't know how to handle indirect other inputs yet!");
5103 std::vector<SDValue> Ops;
5104 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5105 hasMemory, Ops, DAG);
5107 cerr << "Invalid operand for inline asm constraint '"
5108 << OpInfo.ConstraintCode << "'!\n";
5112 // Add information to the INLINEASM node to know about this input.
5113 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5114 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5115 TLI.getPointerTy()));
5116 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5118 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5119 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5120 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5121 "Memory operands expect pointer values");
5123 // Add information to the INLINEASM node to know about this input.
5124 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5125 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5126 TLI.getPointerTy()));
5127 AsmNodeOperands.push_back(InOperandVal);
5131 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5132 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5133 "Unknown constraint type!");
5134 assert(!OpInfo.isIndirect &&
5135 "Don't know how to handle indirect register inputs yet!");
5137 // Copy the input into the appropriate registers.
5138 if (OpInfo.AssignedRegs.Regs.empty()) {
5139 cerr << "Couldn't allocate output reg for constraint '"
5140 << OpInfo.ConstraintCode << "'!\n";
5144 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5146 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5147 DAG, AsmNodeOperands);
5150 case InlineAsm::isClobber: {
5151 // Add the clobbered value to the operand list, so that the register
5152 // allocator is aware that the physreg got clobbered.
5153 if (!OpInfo.AssignedRegs.Regs.empty())
5154 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5155 DAG, AsmNodeOperands);
5161 // Finish up input operands.
5162 AsmNodeOperands[0] = Chain;
5163 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5165 Chain = DAG.getNode(ISD::INLINEASM,
5166 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5167 &AsmNodeOperands[0], AsmNodeOperands.size());
5168 Flag = Chain.getValue(1);
5170 // If this asm returns a register value, copy the result from that register
5171 // and set it as the value of the call.
5172 if (!RetValRegs.Regs.empty()) {
5173 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
5175 // FIXME: Why don't we do this for inline asms with MRVs?
5176 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5177 MVT ResultType = TLI.getValueType(CS.getType());
5179 // If any of the results of the inline asm is a vector, it may have the
5180 // wrong width/num elts. This can happen for register classes that can
5181 // contain multiple different value types. The preg or vreg allocated may
5182 // not have the same VT as was expected. Convert it to the right type
5183 // with bit_convert.
5184 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5185 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
5187 } else if (ResultType != Val.getValueType() &&
5188 ResultType.isInteger() && Val.getValueType().isInteger()) {
5189 // If a result value was tied to an input value, the computed result may
5190 // have a wider width than the expected result. Extract the relevant
5192 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
5195 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5198 setValue(CS.getInstruction(), Val);
5201 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5203 // Process indirect outputs, first output all of the flagged copies out of
5205 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5206 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5207 Value *Ptr = IndirectStoresToEmit[i].second;
5208 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5209 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5212 // Emit the non-flagged stores from the physregs.
5213 SmallVector<SDValue, 8> OutChains;
5214 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5215 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5216 getValue(StoresToEmit[i].second),
5217 StoresToEmit[i].second, 0));
5218 if (!OutChains.empty())
5219 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5220 &OutChains[0], OutChains.size());
5225 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5226 SDValue Src = getValue(I.getOperand(0));
5228 MVT IntPtr = TLI.getPointerTy();
5230 if (IntPtr.bitsLT(Src.getValueType()))
5231 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5232 else if (IntPtr.bitsGT(Src.getValueType()))
5233 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5235 // Scale the source by the type size.
5236 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5237 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5238 Src, DAG.getIntPtrConstant(ElementSize));
5240 TargetLowering::ArgListTy Args;
5241 TargetLowering::ArgListEntry Entry;
5243 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5244 Args.push_back(Entry);
5246 std::pair<SDValue,SDValue> Result =
5247 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5248 CallingConv::C, PerformTailCallOpt,
5249 DAG.getExternalSymbol("malloc", IntPtr),
5251 setValue(&I, Result.first); // Pointers always fit in registers
5252 DAG.setRoot(Result.second);
5255 void SelectionDAGLowering::visitFree(FreeInst &I) {
5256 TargetLowering::ArgListTy Args;
5257 TargetLowering::ArgListEntry Entry;
5258 Entry.Node = getValue(I.getOperand(0));
5259 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5260 Args.push_back(Entry);
5261 MVT IntPtr = TLI.getPointerTy();
5262 std::pair<SDValue,SDValue> Result =
5263 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5264 CallingConv::C, PerformTailCallOpt,
5265 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
5266 DAG.setRoot(Result.second);
5269 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5270 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5271 getValue(I.getOperand(1)),
5272 DAG.getSrcValue(I.getOperand(1))));
5275 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5276 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5277 getValue(I.getOperand(0)),
5278 DAG.getSrcValue(I.getOperand(0)));
5280 DAG.setRoot(V.getValue(1));
5283 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5284 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5285 getValue(I.getOperand(1)),
5286 DAG.getSrcValue(I.getOperand(1))));
5289 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5290 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5291 getValue(I.getOperand(1)),
5292 getValue(I.getOperand(2)),
5293 DAG.getSrcValue(I.getOperand(1)),
5294 DAG.getSrcValue(I.getOperand(2))));
5297 /// TargetLowering::LowerArguments - This is the default LowerArguments
5298 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5299 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5300 /// integrated into SDISel.
5301 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5302 SmallVectorImpl<SDValue> &ArgValues) {
5303 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5304 SmallVector<SDValue, 3+16> Ops;
5305 Ops.push_back(DAG.getRoot());
5306 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5307 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5309 // Add one result value for each formal argument.
5310 SmallVector<MVT, 16> RetVals;
5312 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5314 SmallVector<MVT, 4> ValueVTs;
5315 ComputeValueVTs(*this, I->getType(), ValueVTs);
5316 for (unsigned Value = 0, NumValues = ValueVTs.size();
5317 Value != NumValues; ++Value) {
5318 MVT VT = ValueVTs[Value];
5319 const Type *ArgTy = VT.getTypeForMVT();
5320 ISD::ArgFlagsTy Flags;
5321 unsigned OriginalAlignment =
5322 getTargetData()->getABITypeAlignment(ArgTy);
5324 if (F.paramHasAttr(j, Attribute::ZExt))
5326 if (F.paramHasAttr(j, Attribute::SExt))
5328 if (F.paramHasAttr(j, Attribute::InReg))
5330 if (F.paramHasAttr(j, Attribute::StructRet))
5332 if (F.paramHasAttr(j, Attribute::ByVal)) {
5334 const PointerType *Ty = cast<PointerType>(I->getType());
5335 const Type *ElementTy = Ty->getElementType();
5336 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5337 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5338 // For ByVal, alignment should be passed from FE. BE will guess if
5339 // this info is not there but there are cases it cannot get right.
5340 if (F.getParamAlignment(j))
5341 FrameAlign = F.getParamAlignment(j);
5342 Flags.setByValAlign(FrameAlign);
5343 Flags.setByValSize(FrameSize);
5345 if (F.paramHasAttr(j, Attribute::Nest))
5347 Flags.setOrigAlign(OriginalAlignment);
5349 MVT RegisterVT = getRegisterType(VT);
5350 unsigned NumRegs = getNumRegisters(VT);
5351 for (unsigned i = 0; i != NumRegs; ++i) {
5352 RetVals.push_back(RegisterVT);
5353 ISD::ArgFlagsTy MyFlags = Flags;
5354 if (NumRegs > 1 && i == 0)
5356 // if it isn't first piece, alignment must be 1
5358 MyFlags.setOrigAlign(1);
5359 Ops.push_back(DAG.getArgFlags(MyFlags));
5364 RetVals.push_back(MVT::Other);
5367 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5368 DAG.getVTList(&RetVals[0], RetVals.size()),
5369 &Ops[0], Ops.size()).getNode();
5371 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5372 // allows exposing the loads that may be part of the argument access to the
5373 // first DAGCombiner pass.
5374 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5376 // The number of results should match up, except that the lowered one may have
5377 // an extra flag result.
5378 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5379 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5380 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5381 && "Lowering produced unexpected number of results!");
5383 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5384 if (Result != TmpRes.getNode() && Result->use_empty()) {
5385 HandleSDNode Dummy(DAG.getRoot());
5386 DAG.RemoveDeadNode(Result);
5389 Result = TmpRes.getNode();
5391 unsigned NumArgRegs = Result->getNumValues() - 1;
5392 DAG.setRoot(SDValue(Result, NumArgRegs));
5394 // Set up the return result vector.
5397 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5399 SmallVector<MVT, 4> ValueVTs;
5400 ComputeValueVTs(*this, I->getType(), ValueVTs);
5401 for (unsigned Value = 0, NumValues = ValueVTs.size();
5402 Value != NumValues; ++Value) {
5403 MVT VT = ValueVTs[Value];
5404 MVT PartVT = getRegisterType(VT);
5406 unsigned NumParts = getNumRegisters(VT);
5407 SmallVector<SDValue, 4> Parts(NumParts);
5408 for (unsigned j = 0; j != NumParts; ++j)
5409 Parts[j] = SDValue(Result, i++);
5411 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5412 if (F.paramHasAttr(Idx, Attribute::SExt))
5413 AssertOp = ISD::AssertSext;
5414 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5415 AssertOp = ISD::AssertZext;
5417 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5421 assert(i == NumArgRegs && "Argument register count mismatch!");
5425 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5426 /// implementation, which just inserts an ISD::CALL node, which is later custom
5427 /// lowered by the target to something concrete. FIXME: When all targets are
5428 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5429 std::pair<SDValue, SDValue>
5430 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5431 bool RetSExt, bool RetZExt, bool isVarArg,
5433 unsigned CallingConv, bool isTailCall,
5435 ArgListTy &Args, SelectionDAG &DAG) {
5436 assert((!isTailCall || PerformTailCallOpt) &&
5437 "isTailCall set when tail-call optimizations are disabled!");
5439 SmallVector<SDValue, 32> Ops;
5440 Ops.push_back(Chain); // Op#0 - Chain
5441 Ops.push_back(Callee);
5443 // Handle all of the outgoing arguments.
5444 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5445 SmallVector<MVT, 4> ValueVTs;
5446 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5447 for (unsigned Value = 0, NumValues = ValueVTs.size();
5448 Value != NumValues; ++Value) {
5449 MVT VT = ValueVTs[Value];
5450 const Type *ArgTy = VT.getTypeForMVT();
5451 SDValue Op = SDValue(Args[i].Node.getNode(),
5452 Args[i].Node.getResNo() + Value);
5453 ISD::ArgFlagsTy Flags;
5454 unsigned OriginalAlignment =
5455 getTargetData()->getABITypeAlignment(ArgTy);
5461 if (Args[i].isInReg)
5465 if (Args[i].isByVal) {
5467 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5468 const Type *ElementTy = Ty->getElementType();
5469 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5470 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5471 // For ByVal, alignment should come from FE. BE will guess if this
5472 // info is not there but there are cases it cannot get right.
5473 if (Args[i].Alignment)
5474 FrameAlign = Args[i].Alignment;
5475 Flags.setByValAlign(FrameAlign);
5476 Flags.setByValSize(FrameSize);
5480 Flags.setOrigAlign(OriginalAlignment);
5482 MVT PartVT = getRegisterType(VT);
5483 unsigned NumParts = getNumRegisters(VT);
5484 SmallVector<SDValue, 4> Parts(NumParts);
5485 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5488 ExtendKind = ISD::SIGN_EXTEND;
5489 else if (Args[i].isZExt)
5490 ExtendKind = ISD::ZERO_EXTEND;
5492 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5494 for (unsigned i = 0; i != NumParts; ++i) {
5495 // if it isn't first piece, alignment must be 1
5496 ISD::ArgFlagsTy MyFlags = Flags;
5497 if (NumParts > 1 && i == 0)
5500 MyFlags.setOrigAlign(1);
5502 Ops.push_back(Parts[i]);
5503 Ops.push_back(DAG.getArgFlags(MyFlags));
5508 // Figure out the result value types. We start by making a list of
5509 // the potentially illegal return value types.
5510 SmallVector<MVT, 4> LoweredRetTys;
5511 SmallVector<MVT, 4> RetTys;
5512 ComputeValueVTs(*this, RetTy, RetTys);
5514 // Then we translate that to a list of legal types.
5515 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5517 MVT RegisterVT = getRegisterType(VT);
5518 unsigned NumRegs = getNumRegisters(VT);
5519 for (unsigned i = 0; i != NumRegs; ++i)
5520 LoweredRetTys.push_back(RegisterVT);
5523 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5525 // Create the CALL node.
5526 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
5527 DAG.getVTList(&LoweredRetTys[0],
5528 LoweredRetTys.size()),
5531 Chain = Res.getValue(LoweredRetTys.size() - 1);
5533 // Gather up the call result into a single value.
5534 if (RetTy != Type::VoidTy && !RetTys.empty()) {
5535 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5538 AssertOp = ISD::AssertSext;
5540 AssertOp = ISD::AssertZext;
5542 SmallVector<SDValue, 4> ReturnValues;
5544 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5546 MVT RegisterVT = getRegisterType(VT);
5547 unsigned NumRegs = getNumRegisters(VT);
5548 unsigned RegNoEnd = NumRegs + RegNo;
5549 SmallVector<SDValue, 4> Results;
5550 for (; RegNo != RegNoEnd; ++RegNo)
5551 Results.push_back(Res.getValue(RegNo));
5552 SDValue ReturnValue =
5553 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5555 ReturnValues.push_back(ReturnValue);
5557 Res = DAG.getNode(ISD::MERGE_VALUES,
5558 DAG.getVTList(&RetTys[0], RetTys.size()),
5559 &ReturnValues[0], ReturnValues.size());
5562 return std::make_pair(Res, Chain);
5565 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5566 assert(0 && "LowerOperation not implemented for this target!");
5572 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5573 SDValue Op = getValue(V);
5574 assert((Op.getOpcode() != ISD::CopyFromReg ||
5575 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5576 "Copy from a reg to the same reg!");
5577 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5579 RegsForValue RFV(TLI, Reg, V->getType());
5580 SDValue Chain = DAG.getEntryNode();
5581 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5582 PendingExports.push_back(Chain);
5585 #include "llvm/CodeGen/SelectionDAGISel.h"
5587 void SelectionDAGISel::
5588 LowerArguments(BasicBlock *LLVMBB) {
5589 // If this is the entry block, emit arguments.
5590 Function &F = *LLVMBB->getParent();
5591 SDValue OldRoot = SDL->DAG.getRoot();
5592 SmallVector<SDValue, 16> Args;
5593 TLI.LowerArguments(F, SDL->DAG, Args);
5596 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5598 SmallVector<MVT, 4> ValueVTs;
5599 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5600 unsigned NumValues = ValueVTs.size();
5601 if (!AI->use_empty()) {
5602 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5603 // If this argument is live outside of the entry block, insert a copy from
5604 // whereever we got it to the vreg that other BB's will reference it as.
5605 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5606 if (VMI != FuncInfo->ValueMap.end()) {
5607 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5613 // Finally, if the target has anything special to do, allow it to do so.
5614 // FIXME: this should insert code into the DAG!
5615 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5618 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5619 /// ensure constants are generated when needed. Remember the virtual registers
5620 /// that need to be added to the Machine PHI nodes as input. We cannot just
5621 /// directly add them, because expansion might result in multiple MBB's for one
5622 /// BB. As such, the start of the BB might correspond to a different MBB than
5626 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5627 TerminatorInst *TI = LLVMBB->getTerminator();
5629 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5631 // Check successor nodes' PHI nodes that expect a constant to be available
5633 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5634 BasicBlock *SuccBB = TI->getSuccessor(succ);
5635 if (!isa<PHINode>(SuccBB->begin())) continue;
5636 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5638 // If this terminator has multiple identical successors (common for
5639 // switches), only handle each succ once.
5640 if (!SuccsHandled.insert(SuccMBB)) continue;
5642 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5645 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5646 // nodes and Machine PHI nodes, but the incoming operands have not been
5648 for (BasicBlock::iterator I = SuccBB->begin();
5649 (PN = dyn_cast<PHINode>(I)); ++I) {
5650 // Ignore dead phi's.
5651 if (PN->use_empty()) continue;
5654 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5656 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5657 unsigned &RegOut = SDL->ConstantsOut[C];
5659 RegOut = FuncInfo->CreateRegForValue(C);
5660 SDL->CopyValueToVirtualRegister(C, RegOut);
5664 Reg = FuncInfo->ValueMap[PHIOp];
5666 assert(isa<AllocaInst>(PHIOp) &&
5667 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5668 "Didn't codegen value into a register!??");
5669 Reg = FuncInfo->CreateRegForValue(PHIOp);
5670 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5674 // Remember that this register needs to added to the machine PHI node as
5675 // the input for this MBB.
5676 SmallVector<MVT, 4> ValueVTs;
5677 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5678 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5679 MVT VT = ValueVTs[vti];
5680 unsigned NumRegisters = TLI.getNumRegisters(VT);
5681 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5682 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5683 Reg += NumRegisters;
5687 SDL->ConstantsOut.clear();
5690 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5691 /// supports legal types, and it emits MachineInstrs directly instead of
5692 /// creating SelectionDAG nodes.
5695 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5697 TerminatorInst *TI = LLVMBB->getTerminator();
5699 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5700 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5702 // Check successor nodes' PHI nodes that expect a constant to be available
5704 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5705 BasicBlock *SuccBB = TI->getSuccessor(succ);
5706 if (!isa<PHINode>(SuccBB->begin())) continue;
5707 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5709 // If this terminator has multiple identical successors (common for
5710 // switches), only handle each succ once.
5711 if (!SuccsHandled.insert(SuccMBB)) continue;
5713 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5716 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5717 // nodes and Machine PHI nodes, but the incoming operands have not been
5719 for (BasicBlock::iterator I = SuccBB->begin();
5720 (PN = dyn_cast<PHINode>(I)); ++I) {
5721 // Ignore dead phi's.
5722 if (PN->use_empty()) continue;
5724 // Only handle legal types. Two interesting things to note here. First,
5725 // by bailing out early, we may leave behind some dead instructions,
5726 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5727 // own moves. Second, this check is necessary becuase FastISel doesn't
5728 // use CreateRegForValue to create registers, so it always creates
5729 // exactly one register for each non-void instruction.
5730 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5731 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5734 VT = TLI.getTypeToTransformTo(VT);
5736 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5741 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5743 unsigned Reg = F->getRegForValue(PHIOp);
5745 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5748 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));