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/CodeGen/DwarfWriter.h"
41 #include "llvm/Analysis/DebugInfo.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetFrameInfo.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
57 /// LimitFloatPrecision - Generate low-precision inline sequences for
58 /// some float libcalls (6, 8 or 12 bits).
59 static unsigned LimitFloatPrecision;
61 static cl::opt<unsigned, true>
62 LimitFPPrecision("limit-float-precision",
63 cl::desc("Generate low-precision inline sequences "
64 "for some float libcalls"),
65 cl::location(LimitFloatPrecision),
68 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
69 /// of insertvalue or extractvalue indices that identify a member, return
70 /// the linearized index of the start of the member.
72 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
73 const unsigned *Indices,
74 const unsigned *IndicesEnd,
75 unsigned CurIndex = 0) {
76 // Base case: We're done.
77 if (Indices && Indices == IndicesEnd)
80 // Given a struct type, recursively traverse the elements.
81 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
82 for (StructType::element_iterator EB = STy->element_begin(),
84 EE = STy->element_end();
86 if (Indices && *Indices == unsigned(EI - EB))
87 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
88 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
92 // Given an array type, recursively traverse the elements.
93 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
94 const Type *EltTy = ATy->getElementType();
95 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
96 if (Indices && *Indices == i)
97 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
98 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
102 // We haven't found the type we're looking for, so keep searching.
106 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
107 /// MVTs that represent all the individual underlying
108 /// non-aggregate types that comprise it.
110 /// If Offsets is non-null, it points to a vector to be filled in
111 /// with the in-memory offsets of each of the individual values.
113 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
114 SmallVectorImpl<MVT> &ValueVTs,
115 SmallVectorImpl<uint64_t> *Offsets = 0,
116 uint64_t StartingOffset = 0) {
117 // Given a struct type, recursively traverse the elements.
118 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
119 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
120 for (StructType::element_iterator EB = STy->element_begin(),
122 EE = STy->element_end();
124 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
125 StartingOffset + SL->getElementOffset(EI - EB));
128 // Given an array type, recursively traverse the elements.
129 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
130 const Type *EltTy = ATy->getElementType();
131 uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
132 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
133 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
134 StartingOffset + i * EltSize);
137 // Base case: we can get an MVT for this LLVM IR type.
138 ValueVTs.push_back(TLI.getValueType(Ty));
140 Offsets->push_back(StartingOffset);
144 /// RegsForValue - This struct represents the registers (physical or virtual)
145 /// that a particular set of values is assigned, and the type information about
146 /// the value. The most common situation is to represent one value at a time,
147 /// but struct or array values are handled element-wise as multiple values.
148 /// The splitting of aggregates is performed recursively, so that we never
149 /// have aggregate-typed registers. The values at this point do not necessarily
150 /// have legal types, so each value may require one or more registers of some
153 struct VISIBILITY_HIDDEN RegsForValue {
154 /// TLI - The TargetLowering object.
156 const TargetLowering *TLI;
158 /// ValueVTs - The value types of the values, which may not be legal, and
159 /// may need be promoted or synthesized from one or more registers.
161 SmallVector<MVT, 4> ValueVTs;
163 /// RegVTs - The value types of the registers. This is the same size as
164 /// ValueVTs and it records, for each value, what the type of the assigned
165 /// register or registers are. (Individual values are never synthesized
166 /// from more than one type of register.)
168 /// With virtual registers, the contents of RegVTs is redundant with TLI's
169 /// getRegisterType member function, however when with physical registers
170 /// it is necessary to have a separate record of the types.
172 SmallVector<MVT, 4> RegVTs;
174 /// Regs - This list holds the registers assigned to the values.
175 /// Each legal or promoted value requires one register, and each
176 /// expanded value requires multiple registers.
178 SmallVector<unsigned, 4> Regs;
180 RegsForValue() : TLI(0) {}
182 RegsForValue(const TargetLowering &tli,
183 const SmallVector<unsigned, 4> ®s,
184 MVT regvt, MVT valuevt)
185 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
186 RegsForValue(const TargetLowering &tli,
187 const SmallVector<unsigned, 4> ®s,
188 const SmallVector<MVT, 4> ®vts,
189 const SmallVector<MVT, 4> &valuevts)
190 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
191 RegsForValue(const TargetLowering &tli,
192 unsigned Reg, const Type *Ty) : TLI(&tli) {
193 ComputeValueVTs(tli, Ty, ValueVTs);
195 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
196 MVT ValueVT = ValueVTs[Value];
197 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
198 MVT RegisterVT = TLI->getRegisterType(ValueVT);
199 for (unsigned i = 0; i != NumRegs; ++i)
200 Regs.push_back(Reg + i);
201 RegVTs.push_back(RegisterVT);
206 /// append - Add the specified values to this one.
207 void append(const RegsForValue &RHS) {
209 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
210 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
211 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
215 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
216 /// this value and returns the result as a ValueVTs value. This uses
217 /// Chain/Flag as the input and updates them for the output Chain/Flag.
218 /// If the Flag pointer is NULL, no flag is used.
219 SDValue getCopyFromRegs(SelectionDAG &DAG,
220 SDValue &Chain, SDValue *Flag) const;
222 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
223 /// specified value into the registers specified by this object. This uses
224 /// Chain/Flag as the input and updates them for the output Chain/Flag.
225 /// If the Flag pointer is NULL, no flag is used.
226 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
227 SDValue &Chain, SDValue *Flag) const;
229 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
230 /// operand list. This adds the code marker and includes the number of
231 /// values added into it.
232 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
233 std::vector<SDValue> &Ops) const;
237 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
238 /// PHI nodes or outside of the basic block that defines it, or used by a
239 /// switch or atomic instruction, which may expand to multiple basic blocks.
240 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
241 if (isa<PHINode>(I)) return true;
242 BasicBlock *BB = I->getParent();
243 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
244 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
245 // FIXME: Remove switchinst special case.
246 isa<SwitchInst>(*UI))
251 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
252 /// entry block, return true. This includes arguments used by switches, since
253 /// the switch may expand into multiple basic blocks.
254 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
255 // With FastISel active, we may be splitting blocks, so force creation
256 // of virtual registers for all non-dead arguments.
257 // Don't force virtual registers for byval arguments though, because
258 // fast-isel can't handle those in all cases.
259 if (EnableFastISel && !A->hasByValAttr())
260 return A->use_empty();
262 BasicBlock *Entry = A->getParent()->begin();
263 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
264 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
265 return false; // Use not in entry block.
269 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
273 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
274 bool EnableFastISel) {
277 RegInfo = &MF->getRegInfo();
279 // Create a vreg for each argument register that is not dead and is used
280 // outside of the entry block for the function.
281 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
283 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
284 InitializeRegForValue(AI);
286 // Initialize the mapping of values to registers. This is only set up for
287 // instruction values that are used outside of the block that defines
289 Function::iterator BB = Fn->begin(), EB = Fn->end();
290 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
291 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
292 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
293 const Type *Ty = AI->getAllocatedType();
294 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
296 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
299 TySize *= CUI->getZExtValue(); // Get total allocated size.
300 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
301 StaticAllocaMap[AI] =
302 MF->getFrameInfo()->CreateStackObject(TySize, Align);
305 for (; BB != EB; ++BB)
306 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
307 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
308 if (!isa<AllocaInst>(I) ||
309 !StaticAllocaMap.count(cast<AllocaInst>(I)))
310 InitializeRegForValue(I);
312 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
313 // also creates the initial PHI MachineInstrs, though none of the input
314 // operands are populated.
315 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
316 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
320 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
323 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
324 if (PN->use_empty()) continue;
326 unsigned PHIReg = ValueMap[PN];
327 assert(PHIReg && "PHI node does not have an assigned virtual register!");
329 SmallVector<MVT, 4> ValueVTs;
330 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
331 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
332 MVT VT = ValueVTs[vti];
333 unsigned NumRegisters = TLI.getNumRegisters(VT);
334 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
335 for (unsigned i = 0; i != NumRegisters; ++i)
336 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
337 PHIReg += NumRegisters;
343 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
344 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
347 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
348 /// the correctly promoted or expanded types. Assign these registers
349 /// consecutive vreg numbers and return the first assigned number.
351 /// In the case that the given value has struct or array type, this function
352 /// will assign registers for each member or element.
354 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
355 SmallVector<MVT, 4> ValueVTs;
356 ComputeValueVTs(TLI, V->getType(), ValueVTs);
358 unsigned FirstReg = 0;
359 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
360 MVT ValueVT = ValueVTs[Value];
361 MVT RegisterVT = TLI.getRegisterType(ValueVT);
363 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
364 for (unsigned i = 0; i != NumRegs; ++i) {
365 unsigned R = MakeReg(RegisterVT);
366 if (!FirstReg) FirstReg = R;
372 /// getCopyFromParts - Create a value that contains the specified legal parts
373 /// combined into the value they represent. If the parts combine to a type
374 /// larger then ValueVT then AssertOp can be used to specify whether the extra
375 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
376 /// (ISD::AssertSext).
377 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDValue *Parts,
378 unsigned NumParts, MVT PartVT, MVT ValueVT,
379 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
380 assert(NumParts > 0 && "No parts to assemble!");
381 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
382 SDValue Val = Parts[0];
385 // Assemble the value from multiple parts.
386 if (!ValueVT.isVector()) {
387 unsigned PartBits = PartVT.getSizeInBits();
388 unsigned ValueBits = ValueVT.getSizeInBits();
390 // Assemble the power of 2 part.
391 unsigned RoundParts = NumParts & (NumParts - 1) ?
392 1 << Log2_32(NumParts) : NumParts;
393 unsigned RoundBits = PartBits * RoundParts;
394 MVT RoundVT = RoundBits == ValueBits ?
395 ValueVT : MVT::getIntegerVT(RoundBits);
398 MVT HalfVT = ValueVT.isInteger() ?
399 MVT::getIntegerVT(RoundBits/2) :
400 MVT::getFloatingPointVT(RoundBits/2);
402 if (RoundParts > 2) {
403 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
404 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
407 Lo = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[0]);
408 Hi = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[1]);
410 if (TLI.isBigEndian())
412 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
414 if (RoundParts < NumParts) {
415 // Assemble the trailing non-power-of-2 part.
416 unsigned OddParts = NumParts - RoundParts;
417 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
418 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
420 // Combine the round and odd parts.
422 if (TLI.isBigEndian())
424 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
425 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
426 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
427 DAG.getConstant(Lo.getValueType().getSizeInBits(),
428 TLI.getShiftAmountTy()));
429 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
430 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
433 // Handle a multi-element vector.
434 MVT IntermediateVT, RegisterVT;
435 unsigned NumIntermediates;
437 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
439 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
440 NumParts = NumRegs; // Silence a compiler warning.
441 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
442 assert(RegisterVT == Parts[0].getValueType() &&
443 "Part type doesn't match part!");
445 // Assemble the parts into intermediate operands.
446 SmallVector<SDValue, 8> Ops(NumIntermediates);
447 if (NumIntermediates == NumParts) {
448 // If the register was not expanded, truncate or copy the value,
450 for (unsigned i = 0; i != NumParts; ++i)
451 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
452 PartVT, IntermediateVT);
453 } else if (NumParts > 0) {
454 // If the intermediate type was expanded, build the intermediate operands
456 assert(NumParts % NumIntermediates == 0 &&
457 "Must expand into a divisible number of parts!");
458 unsigned Factor = NumParts / NumIntermediates;
459 for (unsigned i = 0; i != NumIntermediates; ++i)
460 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
461 PartVT, IntermediateVT);
464 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
466 Val = DAG.getNode(IntermediateVT.isVector() ?
467 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
468 ValueVT, &Ops[0], NumIntermediates);
472 // There is now one part, held in Val. Correct it to match ValueVT.
473 PartVT = Val.getValueType();
475 if (PartVT == ValueVT)
478 if (PartVT.isVector()) {
479 assert(ValueVT.isVector() && "Unknown vector conversion!");
480 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
483 if (ValueVT.isVector()) {
484 assert(ValueVT.getVectorElementType() == PartVT &&
485 ValueVT.getVectorNumElements() == 1 &&
486 "Only trivial scalar-to-vector conversions should get here!");
487 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
490 if (PartVT.isInteger() &&
491 ValueVT.isInteger()) {
492 if (ValueVT.bitsLT(PartVT)) {
493 // For a truncate, see if we have any information to
494 // indicate whether the truncated bits will always be
495 // zero or sign-extension.
496 if (AssertOp != ISD::DELETED_NODE)
497 Val = DAG.getNode(AssertOp, PartVT, Val,
498 DAG.getValueType(ValueVT));
499 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
501 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
505 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
506 if (ValueVT.bitsLT(Val.getValueType()))
507 // FP_ROUND's are always exact here.
508 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
509 DAG.getIntPtrConstant(1));
510 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
513 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
514 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
516 assert(0 && "Unknown mismatch!");
520 /// getCopyToParts - Create a series of nodes that contain the specified value
521 /// split into legal parts. If the parts contain more bits than Val, then, for
522 /// integers, ExtendKind can be used to specify how to generate the extra bits.
523 static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
524 SDValue *Parts, unsigned NumParts, MVT PartVT,
525 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
527 MVT PtrVT = TLI.getPointerTy();
528 MVT ValueVT = Val.getValueType();
529 unsigned PartBits = PartVT.getSizeInBits();
530 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
535 if (!ValueVT.isVector()) {
536 if (PartVT == ValueVT) {
537 assert(NumParts == 1 && "No-op copy with multiple parts!");
542 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
543 // If the parts cover more bits than the value has, promote the value.
544 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
545 assert(NumParts == 1 && "Do not know what to promote to!");
546 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
547 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
548 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
549 Val = DAG.getNode(ExtendKind, ValueVT, Val);
551 assert(0 && "Unknown mismatch!");
553 } else if (PartBits == ValueVT.getSizeInBits()) {
554 // Different types of the same size.
555 assert(NumParts == 1 && PartVT != ValueVT);
556 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
557 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
558 // If the parts cover less bits than value has, truncate the value.
559 if (PartVT.isInteger() && ValueVT.isInteger()) {
560 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
561 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
563 assert(0 && "Unknown mismatch!");
567 // The value may have changed - recompute ValueVT.
568 ValueVT = Val.getValueType();
569 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
570 "Failed to tile the value with PartVT!");
573 assert(PartVT == ValueVT && "Type conversion failed!");
578 // Expand the value into multiple parts.
579 if (NumParts & (NumParts - 1)) {
580 // The number of parts is not a power of 2. Split off and copy the tail.
581 assert(PartVT.isInteger() && ValueVT.isInteger() &&
582 "Do not know what to expand to!");
583 unsigned RoundParts = 1 << Log2_32(NumParts);
584 unsigned RoundBits = RoundParts * PartBits;
585 unsigned OddParts = NumParts - RoundParts;
586 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
587 DAG.getConstant(RoundBits,
588 TLI.getShiftAmountTy()));
589 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
590 if (TLI.isBigEndian())
591 // The odd parts were reversed by getCopyToParts - unreverse them.
592 std::reverse(Parts + RoundParts, Parts + NumParts);
593 NumParts = RoundParts;
594 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
595 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
598 // The number of parts is a power of 2. Repeatedly bisect the value using
600 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
601 MVT::getIntegerVT(ValueVT.getSizeInBits()),
603 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
604 for (unsigned i = 0; i < NumParts; i += StepSize) {
605 unsigned ThisBits = StepSize * PartBits / 2;
606 MVT ThisVT = MVT::getIntegerVT (ThisBits);
607 SDValue &Part0 = Parts[i];
608 SDValue &Part1 = Parts[i+StepSize/2];
610 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
611 DAG.getConstant(1, PtrVT));
612 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
613 DAG.getConstant(0, PtrVT));
615 if (ThisBits == PartBits && ThisVT != PartVT) {
616 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
617 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
622 if (TLI.isBigEndian())
623 std::reverse(Parts, Parts + NumParts);
630 if (PartVT != ValueVT) {
631 if (PartVT.isVector()) {
632 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
634 assert(ValueVT.getVectorElementType() == PartVT &&
635 ValueVT.getVectorNumElements() == 1 &&
636 "Only trivial vector-to-scalar conversions should get here!");
637 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
638 DAG.getConstant(0, PtrVT));
646 // Handle a multi-element vector.
647 MVT IntermediateVT, RegisterVT;
648 unsigned NumIntermediates;
649 unsigned NumRegs = TLI
650 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
652 unsigned NumElements = ValueVT.getVectorNumElements();
654 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
655 NumParts = NumRegs; // Silence a compiler warning.
656 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
658 // Split the vector into intermediate operands.
659 SmallVector<SDValue, 8> Ops(NumIntermediates);
660 for (unsigned i = 0; i != NumIntermediates; ++i)
661 if (IntermediateVT.isVector())
662 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
664 DAG.getConstant(i * (NumElements / NumIntermediates),
667 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
669 DAG.getConstant(i, PtrVT));
671 // Split the intermediate operands into legal parts.
672 if (NumParts == NumIntermediates) {
673 // If the register was not expanded, promote or copy the value,
675 for (unsigned i = 0; i != NumParts; ++i)
676 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
677 } else if (NumParts > 0) {
678 // If the intermediate type was expanded, split each the value into
680 assert(NumParts % NumIntermediates == 0 &&
681 "Must expand into a divisible number of parts!");
682 unsigned Factor = NumParts / NumIntermediates;
683 for (unsigned i = 0; i != NumIntermediates; ++i)
684 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
689 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
692 TD = DAG.getTarget().getTargetData();
695 /// clear - Clear out the curret SelectionDAG and the associated
696 /// state and prepare this SelectionDAGLowering object to be used
697 /// for a new block. This doesn't clear out information about
698 /// additional blocks that are needed to complete switch lowering
699 /// or PHI node updating; that information is cleared out as it is
701 void SelectionDAGLowering::clear() {
703 PendingLoads.clear();
704 PendingExports.clear();
708 /// getRoot - Return the current virtual root of the Selection DAG,
709 /// flushing any PendingLoad items. This must be done before emitting
710 /// a store or any other node that may need to be ordered after any
711 /// prior load instructions.
713 SDValue SelectionDAGLowering::getRoot() {
714 if (PendingLoads.empty())
715 return DAG.getRoot();
717 if (PendingLoads.size() == 1) {
718 SDValue Root = PendingLoads[0];
720 PendingLoads.clear();
724 // Otherwise, we have to make a token factor node.
725 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
726 &PendingLoads[0], PendingLoads.size());
727 PendingLoads.clear();
732 /// getControlRoot - Similar to getRoot, but instead of flushing all the
733 /// PendingLoad items, flush all the PendingExports items. It is necessary
734 /// to do this before emitting a terminator instruction.
736 SDValue SelectionDAGLowering::getControlRoot() {
737 SDValue Root = DAG.getRoot();
739 if (PendingExports.empty())
742 // Turn all of the CopyToReg chains into one factored node.
743 if (Root.getOpcode() != ISD::EntryToken) {
744 unsigned i = 0, e = PendingExports.size();
745 for (; i != e; ++i) {
746 assert(PendingExports[i].getNode()->getNumOperands() > 1);
747 if (PendingExports[i].getNode()->getOperand(0) == Root)
748 break; // Don't add the root if we already indirectly depend on it.
752 PendingExports.push_back(Root);
755 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
757 PendingExports.size());
758 PendingExports.clear();
763 void SelectionDAGLowering::visit(Instruction &I) {
764 visit(I.getOpcode(), I);
767 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
768 // Note: this doesn't use InstVisitor, because it has to work with
769 // ConstantExpr's in addition to instructions.
771 default: assert(0 && "Unknown instruction type encountered!");
773 // Build the switch statement using the Instruction.def file.
774 #define HANDLE_INST(NUM, OPCODE, CLASS) \
775 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
776 #include "llvm/Instruction.def"
780 void SelectionDAGLowering::visitAdd(User &I) {
781 if (I.getType()->isFPOrFPVector())
782 visitBinary(I, ISD::FADD);
784 visitBinary(I, ISD::ADD);
787 void SelectionDAGLowering::visitMul(User &I) {
788 if (I.getType()->isFPOrFPVector())
789 visitBinary(I, ISD::FMUL);
791 visitBinary(I, ISD::MUL);
794 SDValue SelectionDAGLowering::getValue(const Value *V) {
795 SDValue &N = NodeMap[V];
796 if (N.getNode()) return N;
798 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
799 MVT VT = TLI.getValueType(V->getType(), true);
801 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
802 return N = DAG.getConstant(*CI, VT);
804 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
805 return N = DAG.getGlobalAddress(GV, VT);
807 if (isa<ConstantPointerNull>(C))
808 return N = DAG.getConstant(0, TLI.getPointerTy());
810 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
811 return N = DAG.getConstantFP(*CFP, VT);
813 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
814 !V->getType()->isAggregateType())
815 return N = DAG.getNode(ISD::UNDEF, VT);
817 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
818 visit(CE->getOpcode(), *CE);
819 SDValue N1 = NodeMap[V];
820 assert(N1.getNode() && "visit didn't populate the ValueMap!");
824 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
825 SmallVector<SDValue, 4> Constants;
826 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
828 SDNode *Val = getValue(*OI).getNode();
829 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
830 Constants.push_back(SDValue(Val, i));
832 return DAG.getMergeValues(&Constants[0], Constants.size());
835 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
836 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
837 "Unknown struct or array constant!");
839 SmallVector<MVT, 4> ValueVTs;
840 ComputeValueVTs(TLI, C->getType(), ValueVTs);
841 unsigned NumElts = ValueVTs.size();
843 return SDValue(); // empty struct
844 SmallVector<SDValue, 4> Constants(NumElts);
845 for (unsigned i = 0; i != NumElts; ++i) {
846 MVT EltVT = ValueVTs[i];
847 if (isa<UndefValue>(C))
848 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
849 else if (EltVT.isFloatingPoint())
850 Constants[i] = DAG.getConstantFP(0, EltVT);
852 Constants[i] = DAG.getConstant(0, EltVT);
854 return DAG.getMergeValues(&Constants[0], NumElts);
857 const VectorType *VecTy = cast<VectorType>(V->getType());
858 unsigned NumElements = VecTy->getNumElements();
860 // Now that we know the number and type of the elements, get that number of
861 // elements into the Ops array based on what kind of constant it is.
862 SmallVector<SDValue, 16> Ops;
863 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
864 for (unsigned i = 0; i != NumElements; ++i)
865 Ops.push_back(getValue(CP->getOperand(i)));
867 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
868 "Unknown vector constant!");
869 MVT EltVT = TLI.getValueType(VecTy->getElementType());
872 if (isa<UndefValue>(C))
873 Op = DAG.getNode(ISD::UNDEF, EltVT);
874 else if (EltVT.isFloatingPoint())
875 Op = DAG.getConstantFP(0, EltVT);
877 Op = DAG.getConstant(0, EltVT);
878 Ops.assign(NumElements, Op);
881 // Create a BUILD_VECTOR node.
882 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
885 // If this is a static alloca, generate it as the frameindex instead of
887 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
888 DenseMap<const AllocaInst*, int>::iterator SI =
889 FuncInfo.StaticAllocaMap.find(AI);
890 if (SI != FuncInfo.StaticAllocaMap.end())
891 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
894 unsigned InReg = FuncInfo.ValueMap[V];
895 assert(InReg && "Value not in map!");
897 RegsForValue RFV(TLI, InReg, V->getType());
898 SDValue Chain = DAG.getEntryNode();
899 return RFV.getCopyFromRegs(DAG, Chain, NULL);
903 void SelectionDAGLowering::visitRet(ReturnInst &I) {
904 if (I.getNumOperands() == 0) {
905 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
909 SmallVector<SDValue, 8> NewValues;
910 NewValues.push_back(getControlRoot());
911 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
912 SmallVector<MVT, 4> ValueVTs;
913 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
914 unsigned NumValues = ValueVTs.size();
915 if (NumValues == 0) continue;
917 SDValue RetOp = getValue(I.getOperand(i));
918 for (unsigned j = 0, f = NumValues; j != f; ++j) {
919 MVT VT = ValueVTs[j];
921 // FIXME: C calling convention requires the return type to be promoted to
922 // at least 32-bit. But this is not necessary for non-C calling
924 if (VT.isInteger()) {
925 MVT MinVT = TLI.getRegisterType(MVT::i32);
926 if (VT.bitsLT(MinVT))
930 unsigned NumParts = TLI.getNumRegisters(VT);
931 MVT PartVT = TLI.getRegisterType(VT);
932 SmallVector<SDValue, 4> Parts(NumParts);
933 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
935 const Function *F = I.getParent()->getParent();
936 if (F->paramHasAttr(0, Attribute::SExt))
937 ExtendKind = ISD::SIGN_EXTEND;
938 else if (F->paramHasAttr(0, Attribute::ZExt))
939 ExtendKind = ISD::ZERO_EXTEND;
941 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
942 &Parts[0], NumParts, PartVT, ExtendKind);
944 // 'inreg' on function refers to return value
945 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
946 if (F->paramHasAttr(0, Attribute::InReg))
948 for (unsigned i = 0; i < NumParts; ++i) {
949 NewValues.push_back(Parts[i]);
950 NewValues.push_back(DAG.getArgFlags(Flags));
954 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
955 &NewValues[0], NewValues.size()));
958 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
959 /// the current basic block, add it to ValueMap now so that we'll get a
961 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
962 // No need to export constants.
963 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
966 if (FuncInfo.isExportedInst(V)) return;
968 unsigned Reg = FuncInfo.InitializeRegForValue(V);
969 CopyValueToVirtualRegister(V, Reg);
972 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
973 const BasicBlock *FromBB) {
974 // The operands of the setcc have to be in this block. We don't know
975 // how to export them from some other block.
976 if (Instruction *VI = dyn_cast<Instruction>(V)) {
977 // Can export from current BB.
978 if (VI->getParent() == FromBB)
981 // Is already exported, noop.
982 return FuncInfo.isExportedInst(V);
985 // If this is an argument, we can export it if the BB is the entry block or
986 // if it is already exported.
987 if (isa<Argument>(V)) {
988 if (FromBB == &FromBB->getParent()->getEntryBlock())
991 // Otherwise, can only export this if it is already exported.
992 return FuncInfo.isExportedInst(V);
995 // Otherwise, constants can always be exported.
999 static bool InBlock(const Value *V, const BasicBlock *BB) {
1000 if (const Instruction *I = dyn_cast<Instruction>(V))
1001 return I->getParent() == BB;
1005 /// getFCmpCondCode - Return the ISD condition code corresponding to
1006 /// the given LLVM IR floating-point condition code. This includes
1007 /// consideration of global floating-point math flags.
1009 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1010 ISD::CondCode FPC, FOC;
1012 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1013 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1014 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1015 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1016 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1017 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1018 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1019 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1020 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1021 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1022 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1023 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1024 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1025 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1026 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1027 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1029 assert(0 && "Invalid FCmp predicate opcode!");
1030 FOC = FPC = ISD::SETFALSE;
1033 if (FiniteOnlyFPMath())
1039 /// getICmpCondCode - Return the ISD condition code corresponding to
1040 /// the given LLVM IR integer condition code.
1042 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1044 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1045 case ICmpInst::ICMP_NE: return ISD::SETNE;
1046 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1047 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1048 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1049 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1050 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1051 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1052 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1053 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1055 assert(0 && "Invalid ICmp predicate opcode!");
1060 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1061 /// This function emits a branch and is used at the leaves of an OR or an
1062 /// AND operator tree.
1065 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1066 MachineBasicBlock *TBB,
1067 MachineBasicBlock *FBB,
1068 MachineBasicBlock *CurBB) {
1069 const BasicBlock *BB = CurBB->getBasicBlock();
1071 // If the leaf of the tree is a comparison, merge the condition into
1073 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1074 // The operands of the cmp have to be in this block. We don't know
1075 // how to export them from some other block. If this is the first block
1076 // of the sequence, no exporting is needed.
1077 if (CurBB == CurMBB ||
1078 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1079 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1080 ISD::CondCode Condition;
1081 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1082 Condition = getICmpCondCode(IC->getPredicate());
1083 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1084 Condition = getFCmpCondCode(FC->getPredicate());
1086 Condition = ISD::SETEQ; // silence warning.
1087 assert(0 && "Unknown compare instruction");
1090 CaseBlock CB(Condition, BOp->getOperand(0),
1091 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1092 SwitchCases.push_back(CB);
1097 // Create a CaseBlock record representing this branch.
1098 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1099 NULL, TBB, FBB, CurBB);
1100 SwitchCases.push_back(CB);
1103 /// FindMergedConditions - If Cond is an expression like
1104 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1105 MachineBasicBlock *TBB,
1106 MachineBasicBlock *FBB,
1107 MachineBasicBlock *CurBB,
1109 // If this node is not part of the or/and tree, emit it as a branch.
1110 Instruction *BOp = dyn_cast<Instruction>(Cond);
1111 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1112 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1113 BOp->getParent() != CurBB->getBasicBlock() ||
1114 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1115 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1116 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1120 // Create TmpBB after CurBB.
1121 MachineFunction::iterator BBI = CurBB;
1122 MachineFunction &MF = DAG.getMachineFunction();
1123 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1124 CurBB->getParent()->insert(++BBI, TmpBB);
1126 if (Opc == Instruction::Or) {
1127 // Codegen X | Y as:
1135 // Emit the LHS condition.
1136 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1138 // Emit the RHS condition into TmpBB.
1139 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1141 assert(Opc == Instruction::And && "Unknown merge op!");
1142 // Codegen X & Y as:
1149 // This requires creation of TmpBB after CurBB.
1151 // Emit the LHS condition.
1152 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1154 // Emit the RHS condition into TmpBB.
1155 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1159 /// If the set of cases should be emitted as a series of branches, return true.
1160 /// If we should emit this as a bunch of and/or'd together conditions, return
1163 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1164 if (Cases.size() != 2) return true;
1166 // If this is two comparisons of the same values or'd or and'd together, they
1167 // will get folded into a single comparison, so don't emit two blocks.
1168 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1169 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1170 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1171 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1178 void SelectionDAGLowering::visitBr(BranchInst &I) {
1179 // Update machine-CFG edges.
1180 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1182 // Figure out which block is immediately after the current one.
1183 MachineBasicBlock *NextBlock = 0;
1184 MachineFunction::iterator BBI = CurMBB;
1185 if (++BBI != CurMBB->getParent()->end())
1188 if (I.isUnconditional()) {
1189 // Update machine-CFG edges.
1190 CurMBB->addSuccessor(Succ0MBB);
1192 // If this is not a fall-through branch, emit the branch.
1193 if (Succ0MBB != NextBlock)
1194 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1195 DAG.getBasicBlock(Succ0MBB)));
1199 // If this condition is one of the special cases we handle, do special stuff
1201 Value *CondVal = I.getCondition();
1202 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1204 // If this is a series of conditions that are or'd or and'd together, emit
1205 // this as a sequence of branches instead of setcc's with and/or operations.
1206 // For example, instead of something like:
1219 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1220 if (BOp->hasOneUse() &&
1221 (BOp->getOpcode() == Instruction::And ||
1222 BOp->getOpcode() == Instruction::Or)) {
1223 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1224 // If the compares in later blocks need to use values not currently
1225 // exported from this block, export them now. This block should always
1226 // be the first entry.
1227 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1229 // Allow some cases to be rejected.
1230 if (ShouldEmitAsBranches(SwitchCases)) {
1231 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1232 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1233 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1236 // Emit the branch for this block.
1237 visitSwitchCase(SwitchCases[0]);
1238 SwitchCases.erase(SwitchCases.begin());
1242 // Okay, we decided not to do this, remove any inserted MBB's and clear
1244 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1245 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1247 SwitchCases.clear();
1251 // Create a CaseBlock record representing this branch.
1252 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1253 NULL, Succ0MBB, Succ1MBB, CurMBB);
1254 // Use visitSwitchCase to actually insert the fast branch sequence for this
1256 visitSwitchCase(CB);
1259 /// visitSwitchCase - Emits the necessary code to represent a single node in
1260 /// the binary search tree resulting from lowering a switch instruction.
1261 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1263 SDValue CondLHS = getValue(CB.CmpLHS);
1265 // Build the setcc now.
1266 if (CB.CmpMHS == NULL) {
1267 // Fold "(X == true)" to X and "(X == false)" to !X to
1268 // handle common cases produced by branch lowering.
1269 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1271 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1272 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1273 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1275 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1277 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1279 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1280 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1282 SDValue CmpOp = getValue(CB.CmpMHS);
1283 MVT VT = CmpOp.getValueType();
1285 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1286 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1288 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1289 Cond = DAG.getSetCC(MVT::i1, SUB,
1290 DAG.getConstant(High-Low, VT), ISD::SETULE);
1294 // Update successor info
1295 CurMBB->addSuccessor(CB.TrueBB);
1296 CurMBB->addSuccessor(CB.FalseBB);
1298 // Set NextBlock to be the MBB immediately after the current one, if any.
1299 // This is used to avoid emitting unnecessary branches to the next block.
1300 MachineBasicBlock *NextBlock = 0;
1301 MachineFunction::iterator BBI = CurMBB;
1302 if (++BBI != CurMBB->getParent()->end())
1305 // If the lhs block is the next block, invert the condition so that we can
1306 // fall through to the lhs instead of the rhs block.
1307 if (CB.TrueBB == NextBlock) {
1308 std::swap(CB.TrueBB, CB.FalseBB);
1309 SDValue True = DAG.getConstant(1, Cond.getValueType());
1310 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1312 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1313 DAG.getBasicBlock(CB.TrueBB));
1315 // If the branch was constant folded, fix up the CFG.
1316 if (BrCond.getOpcode() == ISD::BR) {
1317 CurMBB->removeSuccessor(CB.FalseBB);
1318 DAG.setRoot(BrCond);
1320 // Otherwise, go ahead and insert the false branch.
1321 if (BrCond == getControlRoot())
1322 CurMBB->removeSuccessor(CB.TrueBB);
1324 if (CB.FalseBB == NextBlock)
1325 DAG.setRoot(BrCond);
1327 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1328 DAG.getBasicBlock(CB.FalseBB)));
1332 /// visitJumpTable - Emit JumpTable node in the current MBB
1333 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1334 // Emit the code for the jump table
1335 assert(JT.Reg != -1U && "Should lower JT Header first!");
1336 MVT PTy = TLI.getPointerTy();
1337 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1338 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1339 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.getValueType()), 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)));
1393 /// visitBitTestHeader - This function emits necessary code to produce value
1394 /// suitable for "bit tests"
1395 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1396 // Subtract the minimum value
1397 SDValue SwitchOp = getValue(B.SValue);
1398 MVT VT = SwitchOp.getValueType();
1399 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1400 DAG.getConstant(B.First, VT));
1403 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
1404 DAG.getConstant(B.Range, VT),
1408 if (VT.bitsGT(TLI.getShiftAmountTy()))
1409 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1411 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1413 B.Reg = FuncInfo.MakeReg(TLI.getShiftAmountTy());
1414 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), B.Reg, ShiftOp);
1416 // Set NextBlock to be the MBB immediately after the current one, if any.
1417 // This is used to avoid emitting unnecessary branches to the next block.
1418 MachineBasicBlock *NextBlock = 0;
1419 MachineFunction::iterator BBI = CurMBB;
1420 if (++BBI != CurMBB->getParent()->end())
1423 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1425 CurMBB->addSuccessor(B.Default);
1426 CurMBB->addSuccessor(MBB);
1428 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1429 DAG.getBasicBlock(B.Default));
1431 if (MBB == NextBlock)
1432 DAG.setRoot(BrRange);
1434 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1435 DAG.getBasicBlock(MBB)));
1438 /// visitBitTestCase - this function produces one "bit test"
1439 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1442 // Make desired shift
1443 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), Reg,
1444 TLI.getShiftAmountTy());
1445 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1446 DAG.getConstant(1, TLI.getPointerTy()),
1449 // Emit bit tests and jumps
1450 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1451 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1452 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp.getValueType()),
1453 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1456 CurMBB->addSuccessor(B.TargetBB);
1457 CurMBB->addSuccessor(NextMBB);
1459 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1460 AndCmp, DAG.getBasicBlock(B.TargetBB));
1462 // Set NextBlock to be the MBB immediately after the current one, if any.
1463 // This is used to avoid emitting unnecessary branches to the next block.
1464 MachineBasicBlock *NextBlock = 0;
1465 MachineFunction::iterator BBI = CurMBB;
1466 if (++BBI != CurMBB->getParent()->end())
1469 if (NextMBB == NextBlock)
1472 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1473 DAG.getBasicBlock(NextMBB)));
1476 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1477 // Retrieve successors.
1478 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1479 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1481 const Value *Callee(I.getCalledValue());
1482 if (isa<InlineAsm>(Callee))
1485 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1487 // If the value of the invoke is used outside of its defining block, make it
1488 // available as a virtual register.
1489 if (!I.use_empty()) {
1490 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1491 if (VMI != FuncInfo.ValueMap.end())
1492 CopyValueToVirtualRegister(&I, VMI->second);
1495 // Update successor info
1496 CurMBB->addSuccessor(Return);
1497 CurMBB->addSuccessor(LandingPad);
1499 // Drop into normal successor.
1500 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1501 DAG.getBasicBlock(Return)));
1504 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1507 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1508 /// small case ranges).
1509 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1510 CaseRecVector& WorkList,
1512 MachineBasicBlock* Default) {
1513 Case& BackCase = *(CR.Range.second-1);
1515 // Size is the number of Cases represented by this range.
1516 size_t Size = CR.Range.second - CR.Range.first;
1520 // Get the MachineFunction which holds the current MBB. This is used when
1521 // inserting any additional MBBs necessary to represent the switch.
1522 MachineFunction *CurMF = CurMBB->getParent();
1524 // Figure out which block is immediately after the current one.
1525 MachineBasicBlock *NextBlock = 0;
1526 MachineFunction::iterator BBI = CR.CaseBB;
1528 if (++BBI != CurMBB->getParent()->end())
1531 // TODO: If any two of the cases has the same destination, and if one value
1532 // is the same as the other, but has one bit unset that the other has set,
1533 // use bit manipulation to do two compares at once. For example:
1534 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1536 // Rearrange the case blocks so that the last one falls through if possible.
1537 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1538 // The last case block won't fall through into 'NextBlock' if we emit the
1539 // branches in this order. See if rearranging a case value would help.
1540 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1541 if (I->BB == NextBlock) {
1542 std::swap(*I, BackCase);
1548 // Create a CaseBlock record representing a conditional branch to
1549 // the Case's target mbb if the value being switched on SV is equal
1551 MachineBasicBlock *CurBlock = CR.CaseBB;
1552 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1553 MachineBasicBlock *FallThrough;
1555 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1556 CurMF->insert(BBI, FallThrough);
1558 // If the last case doesn't match, go to the default block.
1559 FallThrough = Default;
1562 Value *RHS, *LHS, *MHS;
1564 if (I->High == I->Low) {
1565 // This is just small small case range :) containing exactly 1 case
1567 LHS = SV; RHS = I->High; MHS = NULL;
1570 LHS = I->Low; MHS = SV; RHS = I->High;
1572 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1574 // If emitting the first comparison, just call visitSwitchCase to emit the
1575 // code into the current block. Otherwise, push the CaseBlock onto the
1576 // vector to be later processed by SDISel, and insert the node's MBB
1577 // before the next MBB.
1578 if (CurBlock == CurMBB)
1579 visitSwitchCase(CB);
1581 SwitchCases.push_back(CB);
1583 CurBlock = FallThrough;
1589 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1590 return !DisableJumpTables &&
1591 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1592 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1595 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1596 APInt LastExt(Last), FirstExt(First);
1597 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1598 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1599 return (LastExt - FirstExt + 1ULL);
1602 /// handleJTSwitchCase - Emit jumptable for current switch case range
1603 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1604 CaseRecVector& WorkList,
1606 MachineBasicBlock* Default) {
1607 Case& FrontCase = *CR.Range.first;
1608 Case& BackCase = *(CR.Range.second-1);
1610 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1611 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
1614 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1618 if (!areJTsAllowed(TLI) || TSize <= 3)
1621 APInt Range = ComputeRange(First, Last);
1622 double Density = (double)TSize / Range.roundToDouble();
1626 DEBUG(errs() << "Lowering jump table\n"
1627 << "First entry: " << First << ". Last entry: " << Last << '\n'
1628 << "Range: " << Range
1629 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1631 // Get the MachineFunction which holds the current MBB. This is used when
1632 // inserting any additional MBBs necessary to represent the switch.
1633 MachineFunction *CurMF = CurMBB->getParent();
1635 // Figure out which block is immediately after the current one.
1636 MachineBasicBlock *NextBlock = 0;
1637 MachineFunction::iterator BBI = CR.CaseBB;
1639 if (++BBI != CurMBB->getParent()->end())
1642 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1644 // Create a new basic block to hold the code for loading the address
1645 // of the jump table, and jumping to it. Update successor information;
1646 // we will either branch to the default case for the switch, or the jump
1648 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1649 CurMF->insert(BBI, JumpTableBB);
1650 CR.CaseBB->addSuccessor(Default);
1651 CR.CaseBB->addSuccessor(JumpTableBB);
1653 // Build a vector of destination BBs, corresponding to each target
1654 // of the jump table. If the value of the jump table slot corresponds to
1655 // a case statement, push the case's BB onto the vector, otherwise, push
1657 std::vector<MachineBasicBlock*> DestBBs;
1659 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1660 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1661 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1663 if (Low.sle(TEI) && TEI.sle(High)) {
1664 DestBBs.push_back(I->BB);
1668 DestBBs.push_back(Default);
1672 // Update successor info. Add one edge to each unique successor.
1673 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1674 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1675 E = DestBBs.end(); I != E; ++I) {
1676 if (!SuccsHandled[(*I)->getNumber()]) {
1677 SuccsHandled[(*I)->getNumber()] = true;
1678 JumpTableBB->addSuccessor(*I);
1682 // Create a jump table index for this jump table, or return an existing
1684 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1686 // Set the jump table information so that we can codegen it as a second
1687 // MachineBasicBlock
1688 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1689 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1690 if (CR.CaseBB == CurMBB)
1691 visitJumpTableHeader(JT, JTH);
1693 JTCases.push_back(JumpTableBlock(JTH, JT));
1698 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1700 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1701 CaseRecVector& WorkList,
1703 MachineBasicBlock* Default) {
1704 // Get the MachineFunction which holds the current MBB. This is used when
1705 // inserting any additional MBBs necessary to represent the switch.
1706 MachineFunction *CurMF = CurMBB->getParent();
1708 // Figure out which block is immediately after the current one.
1709 MachineBasicBlock *NextBlock = 0;
1710 MachineFunction::iterator BBI = CR.CaseBB;
1712 if (++BBI != CurMBB->getParent()->end())
1715 Case& FrontCase = *CR.Range.first;
1716 Case& BackCase = *(CR.Range.second-1);
1717 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1719 // Size is the number of Cases represented by this range.
1720 unsigned Size = CR.Range.second - CR.Range.first;
1722 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1723 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
1725 CaseItr Pivot = CR.Range.first + Size/2;
1727 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1728 // (heuristically) allow us to emit JumpTable's later.
1730 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1734 size_t LSize = FrontCase.size();
1735 size_t RSize = TSize-LSize;
1736 DEBUG(errs() << "Selecting best pivot: \n"
1737 << "First: " << First << ", Last: " << Last <<'\n'
1738 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1739 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1741 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1742 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
1743 APInt Range = ComputeRange(LEnd, RBegin);
1744 assert((Range - 2ULL).isNonNegative() &&
1745 "Invalid case distance");
1746 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1747 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
1748 double Metric = Range.logBase2()*(LDensity+RDensity);
1749 // Should always split in some non-trivial place
1750 DEBUG(errs() <<"=>Step\n"
1751 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1752 << "LDensity: " << LDensity
1753 << ", RDensity: " << RDensity << '\n'
1754 << "Metric: " << Metric << '\n');
1755 if (FMetric < Metric) {
1758 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1764 if (areJTsAllowed(TLI)) {
1765 // If our case is dense we *really* should handle it earlier!
1766 assert((FMetric > 0) && "Should handle dense range earlier!");
1768 Pivot = CR.Range.first + Size/2;
1771 CaseRange LHSR(CR.Range.first, Pivot);
1772 CaseRange RHSR(Pivot, CR.Range.second);
1773 Constant *C = Pivot->Low;
1774 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1776 // We know that we branch to the LHS if the Value being switched on is
1777 // less than the Pivot value, C. We use this to optimize our binary
1778 // tree a bit, by recognizing that if SV is greater than or equal to the
1779 // LHS's Case Value, and that Case Value is exactly one less than the
1780 // Pivot's Value, then we can branch directly to the LHS's Target,
1781 // rather than creating a leaf node for it.
1782 if ((LHSR.second - LHSR.first) == 1 &&
1783 LHSR.first->High == CR.GE &&
1784 cast<ConstantInt>(C)->getValue() ==
1785 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1786 TrueBB = LHSR.first->BB;
1788 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1789 CurMF->insert(BBI, TrueBB);
1790 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1793 // Similar to the optimization above, if the Value being switched on is
1794 // known to be less than the Constant CR.LT, and the current Case Value
1795 // is CR.LT - 1, then we can branch directly to the target block for
1796 // the current Case Value, rather than emitting a RHS leaf node for it.
1797 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1798 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1799 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1800 FalseBB = RHSR.first->BB;
1802 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1803 CurMF->insert(BBI, FalseBB);
1804 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1807 // Create a CaseBlock record representing a conditional branch to
1808 // the LHS node if the value being switched on SV is less than C.
1809 // Otherwise, branch to LHS.
1810 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1812 if (CR.CaseBB == CurMBB)
1813 visitSwitchCase(CB);
1815 SwitchCases.push_back(CB);
1820 /// handleBitTestsSwitchCase - if current case range has few destination and
1821 /// range span less, than machine word bitwidth, encode case range into series
1822 /// of masks and emit bit tests with these masks.
1823 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1824 CaseRecVector& WorkList,
1826 MachineBasicBlock* Default){
1827 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1829 Case& FrontCase = *CR.Range.first;
1830 Case& BackCase = *(CR.Range.second-1);
1832 // Get the MachineFunction which holds the current MBB. This is used when
1833 // inserting any additional MBBs necessary to represent the switch.
1834 MachineFunction *CurMF = CurMBB->getParent();
1837 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1839 // Single case counts one, case range - two.
1840 numCmps += (I->Low == I->High ? 1 : 2);
1843 // Count unique destinations
1844 SmallSet<MachineBasicBlock*, 4> Dests;
1845 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1846 Dests.insert(I->BB);
1847 if (Dests.size() > 3)
1848 // Don't bother the code below, if there are too much unique destinations
1851 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1852 << "Total number of comparisons: " << numCmps << '\n');
1854 // Compute span of values.
1855 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1856 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1857 APInt cmpRange = maxValue - minValue;
1859 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1860 << "Low bound: " << minValue << '\n'
1861 << "High bound: " << maxValue << '\n');
1863 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1864 (!(Dests.size() == 1 && numCmps >= 3) &&
1865 !(Dests.size() == 2 && numCmps >= 5) &&
1866 !(Dests.size() >= 3 && numCmps >= 6)))
1869 DEBUG(errs() << "Emitting bit tests\n");
1870 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1872 // Optimize the case where all the case values fit in a
1873 // word without having to subtract minValue. In this case,
1874 // we can optimize away the subtraction.
1875 if (minValue.isNonNegative() &&
1876 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1877 cmpRange = maxValue;
1879 lowBound = minValue;
1882 CaseBitsVector CasesBits;
1883 unsigned i, count = 0;
1885 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1886 MachineBasicBlock* Dest = I->BB;
1887 for (i = 0; i < count; ++i)
1888 if (Dest == CasesBits[i].BB)
1892 assert((count < 3) && "Too much destinations to test!");
1893 CasesBits.push_back(CaseBits(0, Dest, 0));
1897 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1898 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1900 uint64_t lo = (lowValue - lowBound).getZExtValue();
1901 uint64_t hi = (highValue - lowBound).getZExtValue();
1903 for (uint64_t j = lo; j <= hi; j++) {
1904 CasesBits[i].Mask |= 1ULL << j;
1905 CasesBits[i].Bits++;
1909 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1913 // Figure out which block is immediately after the current one.
1914 MachineFunction::iterator BBI = CR.CaseBB;
1917 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1919 DEBUG(errs() << "Cases:\n");
1920 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1921 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1922 << ", Bits: " << CasesBits[i].Bits
1923 << ", BB: " << CasesBits[i].BB << '\n');
1925 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1926 CurMF->insert(BBI, CaseBB);
1927 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1932 BitTestBlock BTB(lowBound, cmpRange, SV,
1933 -1U, (CR.CaseBB == CurMBB),
1934 CR.CaseBB, Default, BTC);
1936 if (CR.CaseBB == CurMBB)
1937 visitBitTestHeader(BTB);
1939 BitTestCases.push_back(BTB);
1945 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1946 size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
1947 const SwitchInst& SI) {
1950 // Start with "simple" cases
1951 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
1952 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1953 Cases.push_back(Case(SI.getSuccessorValue(i),
1954 SI.getSuccessorValue(i),
1957 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1959 // Merge case into clusters
1960 if (Cases.size() >= 2)
1961 // Must recompute end() each iteration because it may be
1962 // invalidated by erase if we hold on to it
1963 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1964 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1965 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
1966 MachineBasicBlock* nextBB = J->BB;
1967 MachineBasicBlock* currentBB = I->BB;
1969 // If the two neighboring cases go to the same destination, merge them
1970 // into a single case.
1971 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
1979 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1980 if (I->Low != I->High)
1981 // A range counts double, since it requires two compares.
1988 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1989 // Figure out which block is immediately after the current one.
1990 MachineBasicBlock *NextBlock = 0;
1991 MachineFunction::iterator BBI = CurMBB;
1993 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1995 // If there is only the default destination, branch to it if it is not the
1996 // next basic block. Otherwise, just fall through.
1997 if (SI.getNumOperands() == 2) {
1998 // Update machine-CFG edges.
2000 // If this is not a fall-through branch, emit the branch.
2001 CurMBB->addSuccessor(Default);
2002 if (Default != NextBlock)
2003 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2004 DAG.getBasicBlock(Default)));
2008 // If there are any non-default case statements, create a vector of Cases
2009 // representing each one, and sort the vector so that we can efficiently
2010 // create a binary search tree from them.
2012 size_t numCmps = Clusterify(Cases, SI);
2013 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2014 << ". Total compares: " << numCmps << '\n');
2017 // Get the Value to be switched on and default basic blocks, which will be
2018 // inserted into CaseBlock records, representing basic blocks in the binary
2020 Value *SV = SI.getOperand(0);
2022 // Push the initial CaseRec onto the worklist
2023 CaseRecVector WorkList;
2024 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2026 while (!WorkList.empty()) {
2027 // Grab a record representing a case range to process off the worklist
2028 CaseRec CR = WorkList.back();
2029 WorkList.pop_back();
2031 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2034 // If the range has few cases (two or less) emit a series of specific
2036 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2039 // If the switch has more than 5 blocks, and at least 40% dense, and the
2040 // target supports indirect branches, then emit a jump table rather than
2041 // lowering the switch to a binary tree of conditional branches.
2042 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2045 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2046 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2047 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2052 void SelectionDAGLowering::visitSub(User &I) {
2053 // -0.0 - X --> fneg
2054 const Type *Ty = I.getType();
2055 if (isa<VectorType>(Ty)) {
2056 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2057 const VectorType *DestTy = cast<VectorType>(I.getType());
2058 const Type *ElTy = DestTy->getElementType();
2059 if (ElTy->isFloatingPoint()) {
2060 unsigned VL = DestTy->getNumElements();
2061 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2062 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2064 SDValue Op2 = getValue(I.getOperand(1));
2065 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2071 if (Ty->isFloatingPoint()) {
2072 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2073 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2074 SDValue Op2 = getValue(I.getOperand(1));
2075 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2080 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2083 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2084 SDValue Op1 = getValue(I.getOperand(0));
2085 SDValue Op2 = getValue(I.getOperand(1));
2087 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2090 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2091 SDValue Op1 = getValue(I.getOperand(0));
2092 SDValue Op2 = getValue(I.getOperand(1));
2093 if (!isa<VectorType>(I.getType())) {
2094 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2095 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2096 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2097 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2100 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2103 void SelectionDAGLowering::visitICmp(User &I) {
2104 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2105 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2106 predicate = IC->getPredicate();
2107 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2108 predicate = ICmpInst::Predicate(IC->getPredicate());
2109 SDValue Op1 = getValue(I.getOperand(0));
2110 SDValue Op2 = getValue(I.getOperand(1));
2111 ISD::CondCode Opcode = getICmpCondCode(predicate);
2112 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2115 void SelectionDAGLowering::visitFCmp(User &I) {
2116 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2117 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2118 predicate = FC->getPredicate();
2119 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2120 predicate = FCmpInst::Predicate(FC->getPredicate());
2121 SDValue Op1 = getValue(I.getOperand(0));
2122 SDValue Op2 = getValue(I.getOperand(1));
2123 ISD::CondCode Condition = getFCmpCondCode(predicate);
2124 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2127 void SelectionDAGLowering::visitVICmp(User &I) {
2128 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2129 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2130 predicate = IC->getPredicate();
2131 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2132 predicate = ICmpInst::Predicate(IC->getPredicate());
2133 SDValue Op1 = getValue(I.getOperand(0));
2134 SDValue Op2 = getValue(I.getOperand(1));
2135 ISD::CondCode Opcode = getICmpCondCode(predicate);
2136 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2139 void SelectionDAGLowering::visitVFCmp(User &I) {
2140 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2141 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2142 predicate = FC->getPredicate();
2143 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2144 predicate = FCmpInst::Predicate(FC->getPredicate());
2145 SDValue Op1 = getValue(I.getOperand(0));
2146 SDValue Op2 = getValue(I.getOperand(1));
2147 ISD::CondCode Condition = getFCmpCondCode(predicate);
2148 MVT DestVT = TLI.getValueType(I.getType());
2150 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2153 void SelectionDAGLowering::visitSelect(User &I) {
2154 SmallVector<MVT, 4> ValueVTs;
2155 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2156 unsigned NumValues = ValueVTs.size();
2157 if (NumValues != 0) {
2158 SmallVector<SDValue, 4> Values(NumValues);
2159 SDValue Cond = getValue(I.getOperand(0));
2160 SDValue TrueVal = getValue(I.getOperand(1));
2161 SDValue FalseVal = getValue(I.getOperand(2));
2163 for (unsigned i = 0; i != NumValues; ++i)
2164 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2165 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2166 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2168 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2169 DAG.getVTList(&ValueVTs[0], NumValues),
2170 &Values[0], NumValues));
2175 void SelectionDAGLowering::visitTrunc(User &I) {
2176 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2177 SDValue N = getValue(I.getOperand(0));
2178 MVT DestVT = TLI.getValueType(I.getType());
2179 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2182 void SelectionDAGLowering::visitZExt(User &I) {
2183 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2184 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2185 SDValue N = getValue(I.getOperand(0));
2186 MVT DestVT = TLI.getValueType(I.getType());
2187 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2190 void SelectionDAGLowering::visitSExt(User &I) {
2191 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2192 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2193 SDValue N = getValue(I.getOperand(0));
2194 MVT DestVT = TLI.getValueType(I.getType());
2195 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2198 void SelectionDAGLowering::visitFPTrunc(User &I) {
2199 // FPTrunc is never a no-op cast, no need to check
2200 SDValue N = getValue(I.getOperand(0));
2201 MVT DestVT = TLI.getValueType(I.getType());
2202 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2205 void SelectionDAGLowering::visitFPExt(User &I){
2206 // FPTrunc is never a no-op cast, no need to check
2207 SDValue N = getValue(I.getOperand(0));
2208 MVT DestVT = TLI.getValueType(I.getType());
2209 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2212 void SelectionDAGLowering::visitFPToUI(User &I) {
2213 // FPToUI is never a no-op cast, no need to check
2214 SDValue N = getValue(I.getOperand(0));
2215 MVT DestVT = TLI.getValueType(I.getType());
2216 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2219 void SelectionDAGLowering::visitFPToSI(User &I) {
2220 // FPToSI is never a no-op cast, no need to check
2221 SDValue N = getValue(I.getOperand(0));
2222 MVT DestVT = TLI.getValueType(I.getType());
2223 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2226 void SelectionDAGLowering::visitUIToFP(User &I) {
2227 // UIToFP is never a no-op cast, no need to check
2228 SDValue N = getValue(I.getOperand(0));
2229 MVT DestVT = TLI.getValueType(I.getType());
2230 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2233 void SelectionDAGLowering::visitSIToFP(User &I){
2234 // SIToFP is never a no-op cast, no need to check
2235 SDValue N = getValue(I.getOperand(0));
2236 MVT DestVT = TLI.getValueType(I.getType());
2237 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2240 void SelectionDAGLowering::visitPtrToInt(User &I) {
2241 // What to do depends on the size of the integer and the size of the pointer.
2242 // We can either truncate, zero extend, or no-op, accordingly.
2243 SDValue N = getValue(I.getOperand(0));
2244 MVT SrcVT = N.getValueType();
2245 MVT DestVT = TLI.getValueType(I.getType());
2247 if (DestVT.bitsLT(SrcVT))
2248 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2250 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2251 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2252 setValue(&I, Result);
2255 void SelectionDAGLowering::visitIntToPtr(User &I) {
2256 // What to do depends on the size of the integer and the size of the pointer.
2257 // We can either truncate, zero extend, or no-op, accordingly.
2258 SDValue N = getValue(I.getOperand(0));
2259 MVT SrcVT = N.getValueType();
2260 MVT DestVT = TLI.getValueType(I.getType());
2261 if (DestVT.bitsLT(SrcVT))
2262 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2264 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2265 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2268 void SelectionDAGLowering::visitBitCast(User &I) {
2269 SDValue N = getValue(I.getOperand(0));
2270 MVT DestVT = TLI.getValueType(I.getType());
2272 // BitCast assures us that source and destination are the same size so this
2273 // is either a BIT_CONVERT or a no-op.
2274 if (DestVT != N.getValueType())
2275 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2277 setValue(&I, N); // noop cast.
2280 void SelectionDAGLowering::visitInsertElement(User &I) {
2281 SDValue InVec = getValue(I.getOperand(0));
2282 SDValue InVal = getValue(I.getOperand(1));
2283 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2284 getValue(I.getOperand(2)));
2286 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2287 TLI.getValueType(I.getType()),
2288 InVec, InVal, InIdx));
2291 void SelectionDAGLowering::visitExtractElement(User &I) {
2292 SDValue InVec = getValue(I.getOperand(0));
2293 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2294 getValue(I.getOperand(1)));
2295 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2296 TLI.getValueType(I.getType()), InVec, InIdx));
2300 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2301 // from SIndx and increasing to the element length (undefs are allowed).
2302 static bool SequentialMask(SDValue Mask, unsigned SIndx) {
2303 unsigned MaskNumElts = Mask.getNumOperands();
2304 for (unsigned i = 0; i != MaskNumElts; ++i) {
2305 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2306 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2307 if (Idx != i + SIndx)
2314 void SelectionDAGLowering::visitShuffleVector(User &I) {
2315 SDValue Src1 = getValue(I.getOperand(0));
2316 SDValue Src2 = getValue(I.getOperand(1));
2317 SDValue Mask = getValue(I.getOperand(2));
2319 MVT VT = TLI.getValueType(I.getType());
2320 MVT SrcVT = Src1.getValueType();
2321 int MaskNumElts = Mask.getNumOperands();
2322 int SrcNumElts = SrcVT.getVectorNumElements();
2324 if (SrcNumElts == MaskNumElts) {
2325 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
2329 // Normalize the shuffle vector since mask and vector length don't match.
2330 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2332 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2333 // Mask is longer than the source vectors and is a multiple of the source
2334 // vectors. We can use concatenate vector to make the mask and vectors
2336 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2337 // The shuffle is concatenating two vectors together.
2338 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, VT, Src1, Src2));
2342 // Pad both vectors with undefs to make them the same length as the mask.
2343 unsigned NumConcat = MaskNumElts / SrcNumElts;
2344 SDValue UndefVal = DAG.getNode(ISD::UNDEF, SrcVT);
2346 SDValue* MOps1 = new SDValue[NumConcat];
2347 SDValue* MOps2 = new SDValue[NumConcat];
2350 for (unsigned i = 1; i != NumConcat; ++i) {
2351 MOps1[i] = UndefVal;
2352 MOps2[i] = UndefVal;
2354 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps1, NumConcat);
2355 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps2, NumConcat);
2360 // Readjust mask for new input vector length.
2361 SmallVector<SDValue, 8> MappedOps;
2362 for (int i = 0; i != MaskNumElts; ++i) {
2363 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2364 MappedOps.push_back(Mask.getOperand(i));
2366 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2367 if (Idx < SrcNumElts)
2368 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2370 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2374 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2375 &MappedOps[0], MappedOps.size());
2377 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
2381 if (SrcNumElts > MaskNumElts) {
2382 // Resulting vector is shorter than the incoming vector.
2383 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
2384 // Shuffle extracts 1st vector.
2389 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
2390 // Shuffle extracts 2nd vector.
2395 // Analyze the access pattern of the vector to see if we can extract
2396 // two subvectors and do the shuffle. The analysis is done by calculating
2397 // the range of elements the mask access on both vectors.
2398 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2399 int MaxRange[2] = {-1, -1};
2401 for (int i = 0; i != MaskNumElts; ++i) {
2402 SDValue Arg = Mask.getOperand(i);
2403 if (Arg.getOpcode() != ISD::UNDEF) {
2404 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2405 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2407 if (Idx >= SrcNumElts) {
2411 if (Idx > MaxRange[Input])
2412 MaxRange[Input] = Idx;
2413 if (Idx < MinRange[Input])
2414 MinRange[Input] = Idx;
2418 // Check if the access is smaller than the vector size and can we find
2419 // a reasonable extract index.
2420 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2421 int StartIdx[2]; // StartIdx to extract from
2422 for (int Input=0; Input < 2; ++Input) {
2423 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2424 RangeUse[Input] = 0; // Unused
2425 StartIdx[Input] = 0;
2426 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2427 // Fits within range but we should see if we can find a good
2428 // start index that is a multiple of the mask length.
2429 if (MaxRange[Input] < MaskNumElts) {
2430 RangeUse[Input] = 1; // Extract from beginning of the vector
2431 StartIdx[Input] = 0;
2433 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2434 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
2435 StartIdx[Input] + MaskNumElts < SrcNumElts)
2436 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2441 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2442 setValue(&I, DAG.getNode(ISD::UNDEF, VT)); // Vectors are not used.
2445 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2446 // Extract appropriate subvector and generate a vector shuffle
2447 for (int Input=0; Input < 2; ++Input) {
2448 SDValue& Src = Input == 0 ? Src1 : Src2;
2449 if (RangeUse[Input] == 0) {
2450 Src = DAG.getNode(ISD::UNDEF, VT);
2452 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, VT, Src,
2453 DAG.getIntPtrConstant(StartIdx[Input]));
2456 // Calculate new mask.
2457 SmallVector<SDValue, 8> MappedOps;
2458 for (int i = 0; i != MaskNumElts; ++i) {
2459 SDValue Arg = Mask.getOperand(i);
2460 if (Arg.getOpcode() == ISD::UNDEF) {
2461 MappedOps.push_back(Arg);
2463 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2464 if (Idx < SrcNumElts)
2465 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2467 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2468 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2472 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2473 &MappedOps[0], MappedOps.size());
2474 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
2479 // We can't use either concat vectors or extract subvectors so fall back to
2480 // replacing the shuffle with extract and build vector.
2481 // to insert and build vector.
2482 MVT EltVT = VT.getVectorElementType();
2483 MVT PtrVT = TLI.getPointerTy();
2484 SmallVector<SDValue,8> Ops;
2485 for (int i = 0; i != MaskNumElts; ++i) {
2486 SDValue Arg = Mask.getOperand(i);
2487 if (Arg.getOpcode() == ISD::UNDEF) {
2488 Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2490 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2491 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2492 if (Idx < SrcNumElts)
2493 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src1,
2494 DAG.getConstant(Idx, PtrVT)));
2496 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src2,
2497 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
2500 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()));
2503 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2504 const Value *Op0 = I.getOperand(0);
2505 const Value *Op1 = I.getOperand(1);
2506 const Type *AggTy = I.getType();
2507 const Type *ValTy = Op1->getType();
2508 bool IntoUndef = isa<UndefValue>(Op0);
2509 bool FromUndef = isa<UndefValue>(Op1);
2511 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2512 I.idx_begin(), I.idx_end());
2514 SmallVector<MVT, 4> AggValueVTs;
2515 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2516 SmallVector<MVT, 4> ValValueVTs;
2517 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2519 unsigned NumAggValues = AggValueVTs.size();
2520 unsigned NumValValues = ValValueVTs.size();
2521 SmallVector<SDValue, 4> Values(NumAggValues);
2523 SDValue Agg = getValue(Op0);
2524 SDValue Val = getValue(Op1);
2526 // Copy the beginning value(s) from the original aggregate.
2527 for (; i != LinearIndex; ++i)
2528 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2529 SDValue(Agg.getNode(), Agg.getResNo() + i);
2530 // Copy values from the inserted value(s).
2531 for (; i != LinearIndex + NumValValues; ++i)
2532 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2533 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2534 // Copy remaining value(s) from the original aggregate.
2535 for (; i != NumAggValues; ++i)
2536 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2537 SDValue(Agg.getNode(), Agg.getResNo() + i);
2539 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2540 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2541 &Values[0], NumAggValues));
2544 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2545 const Value *Op0 = I.getOperand(0);
2546 const Type *AggTy = Op0->getType();
2547 const Type *ValTy = I.getType();
2548 bool OutOfUndef = isa<UndefValue>(Op0);
2550 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2551 I.idx_begin(), I.idx_end());
2553 SmallVector<MVT, 4> ValValueVTs;
2554 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2556 unsigned NumValValues = ValValueVTs.size();
2557 SmallVector<SDValue, 4> Values(NumValValues);
2559 SDValue Agg = getValue(Op0);
2560 // Copy out the selected value(s).
2561 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2562 Values[i - LinearIndex] =
2564 DAG.getNode(ISD::UNDEF,
2565 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2566 SDValue(Agg.getNode(), Agg.getResNo() + i);
2568 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2569 DAG.getVTList(&ValValueVTs[0], NumValValues),
2570 &Values[0], NumValValues));
2574 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2575 SDValue N = getValue(I.getOperand(0));
2576 const Type *Ty = I.getOperand(0)->getType();
2578 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2581 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2582 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2585 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2586 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2587 DAG.getIntPtrConstant(Offset));
2589 Ty = StTy->getElementType(Field);
2591 Ty = cast<SequentialType>(Ty)->getElementType();
2593 // If this is a constant subscript, handle it quickly.
2594 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2595 if (CI->getZExtValue() == 0) continue;
2597 TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2598 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2599 DAG.getIntPtrConstant(Offs));
2603 // N = N + Idx * ElementSize;
2604 uint64_t ElementSize = TD->getTypePaddedSize(Ty);
2605 SDValue IdxN = getValue(Idx);
2607 // If the index is smaller or larger than intptr_t, truncate or extend
2609 if (IdxN.getValueType().bitsLT(N.getValueType()))
2610 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2611 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2612 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2614 // If this is a multiply by a power of two, turn it into a shl
2615 // immediately. This is a very common case.
2616 if (ElementSize != 1) {
2617 if (isPowerOf2_64(ElementSize)) {
2618 unsigned Amt = Log2_64(ElementSize);
2619 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2620 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2622 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2623 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2627 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2633 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2634 // If this is a fixed sized alloca in the entry block of the function,
2635 // allocate it statically on the stack.
2636 if (FuncInfo.StaticAllocaMap.count(&I))
2637 return; // getValue will auto-populate this.
2639 const Type *Ty = I.getAllocatedType();
2640 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
2642 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2645 SDValue AllocSize = getValue(I.getArraySize());
2646 MVT IntPtr = TLI.getPointerTy();
2647 if (IntPtr.bitsLT(AllocSize.getValueType()))
2648 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2649 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2650 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2652 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2653 DAG.getIntPtrConstant(TySize));
2655 // Handle alignment. If the requested alignment is less than or equal to
2656 // the stack alignment, ignore it. If the size is greater than or equal to
2657 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2658 unsigned StackAlign =
2659 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2660 if (Align <= StackAlign)
2663 // Round the size of the allocation up to the stack alignment size
2664 // by add SA-1 to the size.
2665 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2666 DAG.getIntPtrConstant(StackAlign-1));
2667 // Mask out the low bits for alignment purposes.
2668 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2669 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2671 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2672 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2674 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2676 DAG.setRoot(DSA.getValue(1));
2678 // Inform the Frame Information that we have just allocated a variable-sized
2680 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2683 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2684 const Value *SV = I.getOperand(0);
2685 SDValue Ptr = getValue(SV);
2687 const Type *Ty = I.getType();
2688 bool isVolatile = I.isVolatile();
2689 unsigned Alignment = I.getAlignment();
2691 SmallVector<MVT, 4> ValueVTs;
2692 SmallVector<uint64_t, 4> Offsets;
2693 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2694 unsigned NumValues = ValueVTs.size();
2699 bool ConstantMemory = false;
2701 // Serialize volatile loads with other side effects.
2703 else if (AA->pointsToConstantMemory(SV)) {
2704 // Do not serialize (non-volatile) loads of constant memory with anything.
2705 Root = DAG.getEntryNode();
2706 ConstantMemory = true;
2708 // Do not serialize non-volatile loads against each other.
2709 Root = DAG.getRoot();
2712 SmallVector<SDValue, 4> Values(NumValues);
2713 SmallVector<SDValue, 4> Chains(NumValues);
2714 MVT PtrVT = Ptr.getValueType();
2715 for (unsigned i = 0; i != NumValues; ++i) {
2716 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2717 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2718 DAG.getConstant(Offsets[i], PtrVT)),
2720 isVolatile, Alignment);
2722 Chains[i] = L.getValue(1);
2725 if (!ConstantMemory) {
2726 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2727 &Chains[0], NumValues);
2731 PendingLoads.push_back(Chain);
2734 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2735 DAG.getVTList(&ValueVTs[0], NumValues),
2736 &Values[0], NumValues));
2740 void SelectionDAGLowering::visitStore(StoreInst &I) {
2741 Value *SrcV = I.getOperand(0);
2742 Value *PtrV = I.getOperand(1);
2744 SmallVector<MVT, 4> ValueVTs;
2745 SmallVector<uint64_t, 4> Offsets;
2746 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2747 unsigned NumValues = ValueVTs.size();
2751 // Get the lowered operands. Note that we do this after
2752 // checking if NumResults is zero, because with zero results
2753 // the operands won't have values in the map.
2754 SDValue Src = getValue(SrcV);
2755 SDValue Ptr = getValue(PtrV);
2757 SDValue Root = getRoot();
2758 SmallVector<SDValue, 4> Chains(NumValues);
2759 MVT PtrVT = Ptr.getValueType();
2760 bool isVolatile = I.isVolatile();
2761 unsigned Alignment = I.getAlignment();
2762 for (unsigned i = 0; i != NumValues; ++i)
2763 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2764 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2765 DAG.getConstant(Offsets[i], PtrVT)),
2767 isVolatile, Alignment);
2769 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2772 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2774 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2775 unsigned Intrinsic) {
2776 bool HasChain = !I.doesNotAccessMemory();
2777 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2779 // Build the operand list.
2780 SmallVector<SDValue, 8> Ops;
2781 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2783 // We don't need to serialize loads against other loads.
2784 Ops.push_back(DAG.getRoot());
2786 Ops.push_back(getRoot());
2790 // Info is set by getTgtMemInstrinsic
2791 TargetLowering::IntrinsicInfo Info;
2792 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2794 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2795 if (!IsTgtIntrinsic)
2796 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2798 // Add all operands of the call to the operand list.
2799 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2800 SDValue Op = getValue(I.getOperand(i));
2801 assert(TLI.isTypeLegal(Op.getValueType()) &&
2802 "Intrinsic uses a non-legal type?");
2806 std::vector<MVT> VTs;
2807 if (I.getType() != Type::VoidTy) {
2808 MVT VT = TLI.getValueType(I.getType());
2809 if (VT.isVector()) {
2810 const VectorType *DestTy = cast<VectorType>(I.getType());
2811 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2813 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2814 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2817 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2821 VTs.push_back(MVT::Other);
2823 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2827 if (IsTgtIntrinsic) {
2828 // This is target intrinsic that touches memory
2829 Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2830 &Ops[0], Ops.size(),
2831 Info.memVT, Info.ptrVal, Info.offset,
2832 Info.align, Info.vol,
2833 Info.readMem, Info.writeMem);
2836 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2837 &Ops[0], Ops.size());
2838 else if (I.getType() != Type::VoidTy)
2839 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2840 &Ops[0], Ops.size());
2842 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2843 &Ops[0], Ops.size());
2846 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2848 PendingLoads.push_back(Chain);
2852 if (I.getType() != Type::VoidTy) {
2853 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2854 MVT VT = TLI.getValueType(PTy);
2855 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2857 setValue(&I, Result);
2861 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2862 static GlobalVariable *ExtractTypeInfo(Value *V) {
2863 V = V->stripPointerCasts();
2864 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2865 assert ((GV || isa<ConstantPointerNull>(V)) &&
2866 "TypeInfo must be a global variable or NULL");
2872 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2873 /// call, and add them to the specified machine basic block.
2874 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2875 MachineBasicBlock *MBB) {
2876 // Inform the MachineModuleInfo of the personality for this landing pad.
2877 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2878 assert(CE->getOpcode() == Instruction::BitCast &&
2879 isa<Function>(CE->getOperand(0)) &&
2880 "Personality should be a function");
2881 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2883 // Gather all the type infos for this landing pad and pass them along to
2884 // MachineModuleInfo.
2885 std::vector<GlobalVariable *> TyInfo;
2886 unsigned N = I.getNumOperands();
2888 for (unsigned i = N - 1; i > 2; --i) {
2889 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2890 unsigned FilterLength = CI->getZExtValue();
2891 unsigned FirstCatch = i + FilterLength + !FilterLength;
2892 assert (FirstCatch <= N && "Invalid filter length");
2894 if (FirstCatch < N) {
2895 TyInfo.reserve(N - FirstCatch);
2896 for (unsigned j = FirstCatch; j < N; ++j)
2897 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2898 MMI->addCatchTypeInfo(MBB, TyInfo);
2902 if (!FilterLength) {
2904 MMI->addCleanup(MBB);
2907 TyInfo.reserve(FilterLength - 1);
2908 for (unsigned j = i + 1; j < FirstCatch; ++j)
2909 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2910 MMI->addFilterTypeInfo(MBB, TyInfo);
2919 TyInfo.reserve(N - 3);
2920 for (unsigned j = 3; j < N; ++j)
2921 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2922 MMI->addCatchTypeInfo(MBB, TyInfo);
2928 /// GetSignificand - Get the significand and build it into a floating-point
2929 /// number with exponent of 1:
2931 /// Op = (Op & 0x007fffff) | 0x3f800000;
2933 /// where Op is the hexidecimal representation of floating point value.
2935 GetSignificand(SelectionDAG &DAG, SDValue Op) {
2936 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2937 DAG.getConstant(0x007fffff, MVT::i32));
2938 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2939 DAG.getConstant(0x3f800000, MVT::i32));
2940 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2943 /// GetExponent - Get the exponent:
2945 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
2947 /// where Op is the hexidecimal representation of floating point value.
2949 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI) {
2950 SDValue t0 = DAG.getNode(ISD::AND, MVT::i32, Op,
2951 DAG.getConstant(0x7f800000, MVT::i32));
2952 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, t0,
2953 DAG.getConstant(23, TLI.getShiftAmountTy()));
2954 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2955 DAG.getConstant(127, MVT::i32));
2956 return DAG.getNode(ISD::SINT_TO_FP, MVT::f32, t2);
2959 /// getF32Constant - Get 32-bit floating point constant.
2961 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2962 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2965 /// Inlined utility function to implement binary input atomic intrinsics for
2966 /// visitIntrinsicCall: I is a call instruction
2967 /// Op is the associated NodeType for I
2969 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2970 SDValue Root = getRoot();
2972 DAG.getAtomic(Op, getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2974 getValue(I.getOperand(1)),
2975 getValue(I.getOperand(2)),
2978 DAG.setRoot(L.getValue(1));
2982 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
2984 SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
2985 SDValue Op1 = getValue(I.getOperand(1));
2986 SDValue Op2 = getValue(I.getOperand(2));
2988 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
2989 SDValue Ops[] = { Op1, Op2 };
2991 SDValue Result = DAG.getNode(Op, DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
2993 setValue(&I, Result);
2997 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2998 /// limited-precision mode.
3000 SelectionDAGLowering::visitExp(CallInst &I) {
3003 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3004 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3005 SDValue Op = getValue(I.getOperand(1));
3007 // Put the exponent in the right bit position for later addition to the
3010 // #define LOG2OFe 1.4426950f
3011 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3012 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
3013 getF32Constant(DAG, 0x3fb8aa3b));
3014 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3016 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3017 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3018 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3020 // IntegerPartOfX <<= 23;
3021 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3022 DAG.getConstant(23, TLI.getShiftAmountTy()));
3024 if (LimitFloatPrecision <= 6) {
3025 // For floating-point precision of 6:
3027 // TwoToFractionalPartOfX =
3029 // (0.735607626f + 0.252464424f * x) * x;
3031 // error 0.0144103317, which is 6 bits
3032 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3033 getF32Constant(DAG, 0x3e814304));
3034 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3035 getF32Constant(DAG, 0x3f3c50c8));
3036 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3037 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3038 getF32Constant(DAG, 0x3f7f5e7e));
3039 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3041 // Add the exponent into the result in integer domain.
3042 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
3043 TwoToFracPartOfX, IntegerPartOfX);
3045 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
3046 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3047 // For floating-point precision of 12:
3049 // TwoToFractionalPartOfX =
3052 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3054 // 0.000107046256 error, which is 13 to 14 bits
3055 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3056 getF32Constant(DAG, 0x3da235e3));
3057 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3058 getF32Constant(DAG, 0x3e65b8f3));
3059 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3060 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3061 getF32Constant(DAG, 0x3f324b07));
3062 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3063 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3064 getF32Constant(DAG, 0x3f7ff8fd));
3065 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3067 // Add the exponent into the result in integer domain.
3068 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
3069 TwoToFracPartOfX, IntegerPartOfX);
3071 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
3072 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3073 // For floating-point precision of 18:
3075 // TwoToFractionalPartOfX =
3079 // (0.554906021e-1f +
3080 // (0.961591928e-2f +
3081 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3083 // error 2.47208000*10^(-7), which is better than 18 bits
3084 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3085 getF32Constant(DAG, 0x3924b03e));
3086 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3087 getF32Constant(DAG, 0x3ab24b87));
3088 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3089 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3090 getF32Constant(DAG, 0x3c1d8c17));
3091 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3092 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3093 getF32Constant(DAG, 0x3d634a1d));
3094 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3095 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3096 getF32Constant(DAG, 0x3e75fe14));
3097 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3098 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3099 getF32Constant(DAG, 0x3f317234));
3100 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3101 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3102 getF32Constant(DAG, 0x3f800000));
3103 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3105 // Add the exponent into the result in integer domain.
3106 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
3107 TwoToFracPartOfX, IntegerPartOfX);
3109 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
3112 // No special expansion.
3113 result = DAG.getNode(ISD::FEXP,
3114 getValue(I.getOperand(1)).getValueType(),
3115 getValue(I.getOperand(1)));
3118 setValue(&I, result);
3121 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3122 /// limited-precision mode.
3124 SelectionDAGLowering::visitLog(CallInst &I) {
3127 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3128 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3129 SDValue Op = getValue(I.getOperand(1));
3130 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3132 // Scale the exponent by log(2) [0.69314718f].
3133 SDValue Exp = GetExponent(DAG, Op1, TLI);
3134 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
3135 getF32Constant(DAG, 0x3f317218));
3137 // Get the significand and build it into a floating-point number with
3139 SDValue X = GetSignificand(DAG, Op1);
3141 if (LimitFloatPrecision <= 6) {
3142 // For floating-point precision of 6:
3146 // (1.4034025f - 0.23903021f * x) * x;
3148 // error 0.0034276066, which is better than 8 bits
3149 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3150 getF32Constant(DAG, 0xbe74c456));
3151 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3152 getF32Constant(DAG, 0x3fb3a2b1));
3153 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3154 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3155 getF32Constant(DAG, 0x3f949a29));
3157 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3158 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3159 // For floating-point precision of 12:
3165 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3167 // error 0.000061011436, which is 14 bits
3168 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3169 getF32Constant(DAG, 0xbd67b6d6));
3170 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3171 getF32Constant(DAG, 0x3ee4f4b8));
3172 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3173 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3174 getF32Constant(DAG, 0x3fbc278b));
3175 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3176 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3177 getF32Constant(DAG, 0x40348e95));
3178 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3179 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3180 getF32Constant(DAG, 0x3fdef31a));
3182 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3183 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3184 // For floating-point precision of 18:
3192 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3194 // error 0.0000023660568, which is better than 18 bits
3195 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3196 getF32Constant(DAG, 0xbc91e5ac));
3197 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3198 getF32Constant(DAG, 0x3e4350aa));
3199 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3200 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3201 getF32Constant(DAG, 0x3f60d3e3));
3202 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3203 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3204 getF32Constant(DAG, 0x4011cdf0));
3205 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3206 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3207 getF32Constant(DAG, 0x406cfd1c));
3208 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3209 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3210 getF32Constant(DAG, 0x408797cb));
3211 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3212 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3213 getF32Constant(DAG, 0x4006dcab));
3215 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3218 // No special expansion.
3219 result = DAG.getNode(ISD::FLOG,
3220 getValue(I.getOperand(1)).getValueType(),
3221 getValue(I.getOperand(1)));
3224 setValue(&I, result);
3227 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3228 /// limited-precision mode.
3230 SelectionDAGLowering::visitLog2(CallInst &I) {
3233 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3234 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3235 SDValue Op = getValue(I.getOperand(1));
3236 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3238 // Get the exponent.
3239 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI);
3241 // Get the significand and build it into a floating-point number with
3243 SDValue X = GetSignificand(DAG, Op1);
3245 // Different possible minimax approximations of significand in
3246 // floating-point for various degrees of accuracy over [1,2].
3247 if (LimitFloatPrecision <= 6) {
3248 // For floating-point precision of 6:
3250 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3252 // error 0.0049451742, which is more than 7 bits
3253 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3254 getF32Constant(DAG, 0xbeb08fe0));
3255 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3256 getF32Constant(DAG, 0x40019463));
3257 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3258 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3259 getF32Constant(DAG, 0x3fd6633d));
3261 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3262 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3263 // For floating-point precision of 12:
3269 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3271 // error 0.0000876136000, which is better than 13 bits
3272 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3273 getF32Constant(DAG, 0xbda7262e));
3274 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3275 getF32Constant(DAG, 0x3f25280b));
3276 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3277 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3278 getF32Constant(DAG, 0x4007b923));
3279 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3280 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3281 getF32Constant(DAG, 0x40823e2f));
3282 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3283 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3284 getF32Constant(DAG, 0x4020d29c));
3286 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3287 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3288 // For floating-point precision of 18:
3297 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3299 // error 0.0000018516, which is better than 18 bits
3300 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3301 getF32Constant(DAG, 0xbcd2769e));
3302 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3303 getF32Constant(DAG, 0x3e8ce0b9));
3304 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3305 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3306 getF32Constant(DAG, 0x3fa22ae7));
3307 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3308 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3309 getF32Constant(DAG, 0x40525723));
3310 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3311 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3312 getF32Constant(DAG, 0x40aaf200));
3313 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3314 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3315 getF32Constant(DAG, 0x40c39dad));
3316 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3317 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3318 getF32Constant(DAG, 0x4042902c));
3320 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3323 // No special expansion.
3324 result = DAG.getNode(ISD::FLOG2,
3325 getValue(I.getOperand(1)).getValueType(),
3326 getValue(I.getOperand(1)));
3329 setValue(&I, result);
3332 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3333 /// limited-precision mode.
3335 SelectionDAGLowering::visitLog10(CallInst &I) {
3338 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3339 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3340 SDValue Op = getValue(I.getOperand(1));
3341 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3343 // Scale the exponent by log10(2) [0.30102999f].
3344 SDValue Exp = GetExponent(DAG, Op1, TLI);
3345 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
3346 getF32Constant(DAG, 0x3e9a209a));
3348 // Get the significand and build it into a floating-point number with
3350 SDValue X = GetSignificand(DAG, Op1);
3352 if (LimitFloatPrecision <= 6) {
3353 // For floating-point precision of 6:
3355 // Log10ofMantissa =
3357 // (0.60948995f - 0.10380950f * x) * x;
3359 // error 0.0014886165, which is 6 bits
3360 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3361 getF32Constant(DAG, 0xbdd49a13));
3362 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3363 getF32Constant(DAG, 0x3f1c0789));
3364 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3365 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3366 getF32Constant(DAG, 0x3f011300));
3368 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3369 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3370 // For floating-point precision of 12:
3372 // Log10ofMantissa =
3375 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3377 // error 0.00019228036, which is better than 12 bits
3378 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3379 getF32Constant(DAG, 0x3d431f31));
3380 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3381 getF32Constant(DAG, 0x3ea21fb2));
3382 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3383 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3384 getF32Constant(DAG, 0x3f6ae232));
3385 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3386 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3387 getF32Constant(DAG, 0x3f25f7c3));
3389 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3390 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3391 // For floating-point precision of 18:
3393 // Log10ofMantissa =
3398 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3400 // error 0.0000037995730, which is better than 18 bits
3401 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3402 getF32Constant(DAG, 0x3c5d51ce));
3403 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3404 getF32Constant(DAG, 0x3e00685a));
3405 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3406 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3407 getF32Constant(DAG, 0x3efb6798));
3408 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3409 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3410 getF32Constant(DAG, 0x3f88d192));
3411 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3412 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3413 getF32Constant(DAG, 0x3fc4316c));
3414 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3415 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
3416 getF32Constant(DAG, 0x3f57ce70));
3418 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3421 // No special expansion.
3422 result = DAG.getNode(ISD::FLOG10,
3423 getValue(I.getOperand(1)).getValueType(),
3424 getValue(I.getOperand(1)));
3427 setValue(&I, result);
3430 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3431 /// limited-precision mode.
3433 SelectionDAGLowering::visitExp2(CallInst &I) {
3436 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3437 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3438 SDValue Op = getValue(I.getOperand(1));
3440 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3442 // FractionalPartOfX = x - (float)IntegerPartOfX;
3443 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3444 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3446 // IntegerPartOfX <<= 23;
3447 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3448 DAG.getConstant(23, TLI.getShiftAmountTy()));
3450 if (LimitFloatPrecision <= 6) {
3451 // For floating-point precision of 6:
3453 // TwoToFractionalPartOfX =
3455 // (0.735607626f + 0.252464424f * x) * x;
3457 // error 0.0144103317, which is 6 bits
3458 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3459 getF32Constant(DAG, 0x3e814304));
3460 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3461 getF32Constant(DAG, 0x3f3c50c8));
3462 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3463 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3464 getF32Constant(DAG, 0x3f7f5e7e));
3465 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3466 SDValue TwoToFractionalPartOfX =
3467 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3469 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3470 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3471 // For floating-point precision of 12:
3473 // TwoToFractionalPartOfX =
3476 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3478 // error 0.000107046256, which is 13 to 14 bits
3479 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3480 getF32Constant(DAG, 0x3da235e3));
3481 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3482 getF32Constant(DAG, 0x3e65b8f3));
3483 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3484 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3485 getF32Constant(DAG, 0x3f324b07));
3486 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3487 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3488 getF32Constant(DAG, 0x3f7ff8fd));
3489 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3490 SDValue TwoToFractionalPartOfX =
3491 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3493 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3494 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3495 // For floating-point precision of 18:
3497 // TwoToFractionalPartOfX =
3501 // (0.554906021e-1f +
3502 // (0.961591928e-2f +
3503 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3504 // error 2.47208000*10^(-7), which is better than 18 bits
3505 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3506 getF32Constant(DAG, 0x3924b03e));
3507 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3508 getF32Constant(DAG, 0x3ab24b87));
3509 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3510 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3511 getF32Constant(DAG, 0x3c1d8c17));
3512 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3513 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3514 getF32Constant(DAG, 0x3d634a1d));
3515 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3516 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3517 getF32Constant(DAG, 0x3e75fe14));
3518 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3519 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3520 getF32Constant(DAG, 0x3f317234));
3521 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3522 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3523 getF32Constant(DAG, 0x3f800000));
3524 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3525 SDValue TwoToFractionalPartOfX =
3526 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3528 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3531 // No special expansion.
3532 result = DAG.getNode(ISD::FEXP2,
3533 getValue(I.getOperand(1)).getValueType(),
3534 getValue(I.getOperand(1)));
3537 setValue(&I, result);
3540 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3541 /// limited-precision mode with x == 10.0f.
3543 SelectionDAGLowering::visitPow(CallInst &I) {
3545 Value *Val = I.getOperand(1);
3546 bool IsExp10 = false;
3548 if (getValue(Val).getValueType() == MVT::f32 &&
3549 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3550 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3551 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3552 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3554 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3559 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3560 SDValue Op = getValue(I.getOperand(2));
3562 // Put the exponent in the right bit position for later addition to the
3565 // #define LOG2OF10 3.3219281f
3566 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3567 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
3568 getF32Constant(DAG, 0x40549a78));
3569 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3571 // FractionalPartOfX = x - (float)IntegerPartOfX;
3572 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3573 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3575 // IntegerPartOfX <<= 23;
3576 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3577 DAG.getConstant(23, TLI.getShiftAmountTy()));
3579 if (LimitFloatPrecision <= 6) {
3580 // For floating-point precision of 6:
3582 // twoToFractionalPartOfX =
3584 // (0.735607626f + 0.252464424f * x) * x;
3586 // error 0.0144103317, which is 6 bits
3587 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3588 getF32Constant(DAG, 0x3e814304));
3589 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3590 getF32Constant(DAG, 0x3f3c50c8));
3591 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3592 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3593 getF32Constant(DAG, 0x3f7f5e7e));
3594 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3595 SDValue TwoToFractionalPartOfX =
3596 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3598 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3599 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3600 // For floating-point precision of 12:
3602 // TwoToFractionalPartOfX =
3605 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3607 // error 0.000107046256, which is 13 to 14 bits
3608 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3609 getF32Constant(DAG, 0x3da235e3));
3610 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3611 getF32Constant(DAG, 0x3e65b8f3));
3612 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3613 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3614 getF32Constant(DAG, 0x3f324b07));
3615 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3616 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3617 getF32Constant(DAG, 0x3f7ff8fd));
3618 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3619 SDValue TwoToFractionalPartOfX =
3620 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3622 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3623 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3624 // For floating-point precision of 18:
3626 // TwoToFractionalPartOfX =
3630 // (0.554906021e-1f +
3631 // (0.961591928e-2f +
3632 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3633 // error 2.47208000*10^(-7), which is better than 18 bits
3634 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3635 getF32Constant(DAG, 0x3924b03e));
3636 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3637 getF32Constant(DAG, 0x3ab24b87));
3638 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3639 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3640 getF32Constant(DAG, 0x3c1d8c17));
3641 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3642 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3643 getF32Constant(DAG, 0x3d634a1d));
3644 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3645 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3646 getF32Constant(DAG, 0x3e75fe14));
3647 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3648 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3649 getF32Constant(DAG, 0x3f317234));
3650 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3651 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3652 getF32Constant(DAG, 0x3f800000));
3653 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3654 SDValue TwoToFractionalPartOfX =
3655 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3657 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3660 // No special expansion.
3661 result = DAG.getNode(ISD::FPOW,
3662 getValue(I.getOperand(1)).getValueType(),
3663 getValue(I.getOperand(1)),
3664 getValue(I.getOperand(2)));
3667 setValue(&I, result);
3670 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3671 /// we want to emit this as a call to a named external function, return the name
3672 /// otherwise lower it and return null.
3674 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3675 switch (Intrinsic) {
3677 // By default, turn this into a target intrinsic node.
3678 visitTargetIntrinsic(I, Intrinsic);
3680 case Intrinsic::vastart: visitVAStart(I); return 0;
3681 case Intrinsic::vaend: visitVAEnd(I); return 0;
3682 case Intrinsic::vacopy: visitVACopy(I); return 0;
3683 case Intrinsic::returnaddress:
3684 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3685 getValue(I.getOperand(1))));
3687 case Intrinsic::frameaddress:
3688 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3689 getValue(I.getOperand(1))));
3691 case Intrinsic::setjmp:
3692 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3694 case Intrinsic::longjmp:
3695 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3697 case Intrinsic::memcpy: {
3698 SDValue Op1 = getValue(I.getOperand(1));
3699 SDValue Op2 = getValue(I.getOperand(2));
3700 SDValue Op3 = getValue(I.getOperand(3));
3701 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3702 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3703 I.getOperand(1), 0, I.getOperand(2), 0));
3706 case Intrinsic::memset: {
3707 SDValue Op1 = getValue(I.getOperand(1));
3708 SDValue Op2 = getValue(I.getOperand(2));
3709 SDValue Op3 = getValue(I.getOperand(3));
3710 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3711 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3712 I.getOperand(1), 0));
3715 case Intrinsic::memmove: {
3716 SDValue Op1 = getValue(I.getOperand(1));
3717 SDValue Op2 = getValue(I.getOperand(2));
3718 SDValue Op3 = getValue(I.getOperand(3));
3719 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3721 // If the source and destination are known to not be aliases, we can
3722 // lower memmove as memcpy.
3723 uint64_t Size = -1ULL;
3724 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3725 Size = C->getZExtValue();
3726 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3727 AliasAnalysis::NoAlias) {
3728 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3729 I.getOperand(1), 0, I.getOperand(2), 0));
3733 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3734 I.getOperand(1), 0, I.getOperand(2), 0));
3737 case Intrinsic::dbg_stoppoint: {
3738 DwarfWriter *DW = DAG.getDwarfWriter();
3739 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3740 if (DW && DW->ValidDebugInfo(SPI.getContext()))
3741 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3747 case Intrinsic::dbg_region_start: {
3748 DwarfWriter *DW = DAG.getDwarfWriter();
3749 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3750 if (DW && DW->ValidDebugInfo(RSI.getContext())) {
3752 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
3753 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3758 case Intrinsic::dbg_region_end: {
3759 DwarfWriter *DW = DAG.getDwarfWriter();
3760 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3761 if (DW && DW->ValidDebugInfo(REI.getContext())) {
3763 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
3764 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3769 case Intrinsic::dbg_func_start: {
3770 DwarfWriter *DW = DAG.getDwarfWriter();
3772 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3773 Value *SP = FSI.getSubprogram();
3774 if (SP && DW->ValidDebugInfo(SP)) {
3775 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3776 // what (most?) gdb expects.
3777 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3778 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
3779 unsigned SrcFile = DW->RecordSource(CompileUnit.getDirectory(),
3780 CompileUnit.getFilename());
3781 // Record the source line but does not create a label for the normal
3782 // function start. It will be emitted at asm emission time. However,
3783 // create a label if this is a beginning of inlined function.
3785 DW->RecordSourceLine(Subprogram.getLineNumber(), 0, SrcFile);
3786 if (DW->getRecordSourceLineCount() != 1)
3787 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3792 case Intrinsic::dbg_declare: {
3793 DwarfWriter *DW = DAG.getDwarfWriter();
3794 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3795 Value *Variable = DI.getVariable();
3796 if (DW && DW->ValidDebugInfo(Variable))
3797 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3798 getValue(DI.getAddress()), getValue(Variable)));
3802 case Intrinsic::eh_exception: {
3803 if (!CurMBB->isLandingPad()) {
3804 // FIXME: Mark exception register as live in. Hack for PR1508.
3805 unsigned Reg = TLI.getExceptionAddressRegister();
3806 if (Reg) CurMBB->addLiveIn(Reg);
3808 // Insert the EXCEPTIONADDR instruction.
3809 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3811 Ops[0] = DAG.getRoot();
3812 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3814 DAG.setRoot(Op.getValue(1));
3818 case Intrinsic::eh_selector_i32:
3819 case Intrinsic::eh_selector_i64: {
3820 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3821 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3822 MVT::i32 : MVT::i64);
3825 if (CurMBB->isLandingPad())
3826 AddCatchInfo(I, MMI, CurMBB);
3829 FuncInfo.CatchInfoLost.insert(&I);
3831 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3832 unsigned Reg = TLI.getExceptionSelectorRegister();
3833 if (Reg) CurMBB->addLiveIn(Reg);
3836 // Insert the EHSELECTION instruction.
3837 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3839 Ops[0] = getValue(I.getOperand(1));
3841 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3843 DAG.setRoot(Op.getValue(1));
3845 setValue(&I, DAG.getConstant(0, VT));
3851 case Intrinsic::eh_typeid_for_i32:
3852 case Intrinsic::eh_typeid_for_i64: {
3853 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3854 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3855 MVT::i32 : MVT::i64);
3858 // Find the type id for the given typeinfo.
3859 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3861 unsigned TypeID = MMI->getTypeIDFor(GV);
3862 setValue(&I, DAG.getConstant(TypeID, VT));
3864 // Return something different to eh_selector.
3865 setValue(&I, DAG.getConstant(1, VT));
3871 case Intrinsic::eh_return_i32:
3872 case Intrinsic::eh_return_i64:
3873 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3874 MMI->setCallsEHReturn(true);
3875 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3878 getValue(I.getOperand(1)),
3879 getValue(I.getOperand(2))));
3881 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3885 case Intrinsic::eh_unwind_init:
3886 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3887 MMI->setCallsUnwindInit(true);
3892 case Intrinsic::eh_dwarf_cfa: {
3893 MVT VT = getValue(I.getOperand(1)).getValueType();
3895 if (VT.bitsGT(TLI.getPointerTy()))
3896 CfaArg = DAG.getNode(ISD::TRUNCATE,
3897 TLI.getPointerTy(), getValue(I.getOperand(1)));
3899 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3900 TLI.getPointerTy(), getValue(I.getOperand(1)));
3902 SDValue Offset = DAG.getNode(ISD::ADD,
3904 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3905 TLI.getPointerTy()),
3907 setValue(&I, DAG.getNode(ISD::ADD,
3909 DAG.getNode(ISD::FRAMEADDR,
3912 TLI.getPointerTy())),
3917 case Intrinsic::convertff:
3918 case Intrinsic::convertfsi:
3919 case Intrinsic::convertfui:
3920 case Intrinsic::convertsif:
3921 case Intrinsic::convertuif:
3922 case Intrinsic::convertss:
3923 case Intrinsic::convertsu:
3924 case Intrinsic::convertus:
3925 case Intrinsic::convertuu: {
3926 ISD::CvtCode Code = ISD::CVT_INVALID;
3927 switch (Intrinsic) {
3928 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3929 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3930 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3931 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3932 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3933 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3934 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3935 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3936 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3938 MVT DestVT = TLI.getValueType(I.getType());
3939 Value* Op1 = I.getOperand(1);
3940 setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
3941 DAG.getValueType(DestVT),
3942 DAG.getValueType(getValue(Op1).getValueType()),
3943 getValue(I.getOperand(2)),
3944 getValue(I.getOperand(3)),
3949 case Intrinsic::sqrt:
3950 setValue(&I, DAG.getNode(ISD::FSQRT,
3951 getValue(I.getOperand(1)).getValueType(),
3952 getValue(I.getOperand(1))));
3954 case Intrinsic::powi:
3955 setValue(&I, DAG.getNode(ISD::FPOWI,
3956 getValue(I.getOperand(1)).getValueType(),
3957 getValue(I.getOperand(1)),
3958 getValue(I.getOperand(2))));
3960 case Intrinsic::sin:
3961 setValue(&I, DAG.getNode(ISD::FSIN,
3962 getValue(I.getOperand(1)).getValueType(),
3963 getValue(I.getOperand(1))));
3965 case Intrinsic::cos:
3966 setValue(&I, DAG.getNode(ISD::FCOS,
3967 getValue(I.getOperand(1)).getValueType(),
3968 getValue(I.getOperand(1))));
3970 case Intrinsic::log:
3973 case Intrinsic::log2:
3976 case Intrinsic::log10:
3979 case Intrinsic::exp:
3982 case Intrinsic::exp2:
3985 case Intrinsic::pow:
3988 case Intrinsic::pcmarker: {
3989 SDValue Tmp = getValue(I.getOperand(1));
3990 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3993 case Intrinsic::readcyclecounter: {
3994 SDValue Op = getRoot();
3995 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3996 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3999 DAG.setRoot(Tmp.getValue(1));
4002 case Intrinsic::part_select: {
4003 // Currently not implemented: just abort
4004 assert(0 && "part_select intrinsic not implemented");
4007 case Intrinsic::part_set: {
4008 // Currently not implemented: just abort
4009 assert(0 && "part_set intrinsic not implemented");
4012 case Intrinsic::bswap:
4013 setValue(&I, DAG.getNode(ISD::BSWAP,
4014 getValue(I.getOperand(1)).getValueType(),
4015 getValue(I.getOperand(1))));
4017 case Intrinsic::cttz: {
4018 SDValue Arg = getValue(I.getOperand(1));
4019 MVT Ty = Arg.getValueType();
4020 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
4021 setValue(&I, result);
4024 case Intrinsic::ctlz: {
4025 SDValue Arg = getValue(I.getOperand(1));
4026 MVT Ty = Arg.getValueType();
4027 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
4028 setValue(&I, result);
4031 case Intrinsic::ctpop: {
4032 SDValue Arg = getValue(I.getOperand(1));
4033 MVT Ty = Arg.getValueType();
4034 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
4035 setValue(&I, result);
4038 case Intrinsic::stacksave: {
4039 SDValue Op = getRoot();
4040 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
4041 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4043 DAG.setRoot(Tmp.getValue(1));
4046 case Intrinsic::stackrestore: {
4047 SDValue Tmp = getValue(I.getOperand(1));
4048 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
4051 case Intrinsic::stackprotector: {
4052 // Emit code into the DAG to store the stack guard onto the stack.
4053 MachineFunction &MF = DAG.getMachineFunction();
4054 MachineFrameInfo *MFI = MF.getFrameInfo();
4055 MVT PtrTy = TLI.getPointerTy();
4057 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4058 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4060 int FI = FuncInfo.StaticAllocaMap[Slot];
4061 MFI->setStackProtectorIndex(FI);
4063 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4065 // Store the stack protector onto the stack.
4066 SDValue Result = DAG.getStore(getRoot(), Src, FIN,
4067 PseudoSourceValue::getFixedStack(FI),
4069 setValue(&I, Result);
4070 DAG.setRoot(Result);
4073 case Intrinsic::var_annotation:
4074 // Discard annotate attributes
4077 case Intrinsic::init_trampoline: {
4078 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4082 Ops[1] = getValue(I.getOperand(1));
4083 Ops[2] = getValue(I.getOperand(2));
4084 Ops[3] = getValue(I.getOperand(3));
4085 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4086 Ops[5] = DAG.getSrcValue(F);
4088 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
4089 DAG.getNodeValueTypes(TLI.getPointerTy(),
4094 DAG.setRoot(Tmp.getValue(1));
4098 case Intrinsic::gcroot:
4100 Value *Alloca = I.getOperand(1);
4101 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4103 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4104 GFI->addStackRoot(FI->getIndex(), TypeMap);
4108 case Intrinsic::gcread:
4109 case Intrinsic::gcwrite:
4110 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4113 case Intrinsic::flt_rounds: {
4114 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
4118 case Intrinsic::trap: {
4119 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
4123 case Intrinsic::uadd_with_overflow:
4124 return implVisitAluOverflow(I, ISD::UADDO);
4125 case Intrinsic::sadd_with_overflow:
4126 return implVisitAluOverflow(I, ISD::SADDO);
4127 case Intrinsic::usub_with_overflow:
4128 return implVisitAluOverflow(I, ISD::USUBO);
4129 case Intrinsic::ssub_with_overflow:
4130 return implVisitAluOverflow(I, ISD::SSUBO);
4131 case Intrinsic::umul_with_overflow:
4132 return implVisitAluOverflow(I, ISD::UMULO);
4133 case Intrinsic::smul_with_overflow:
4134 return implVisitAluOverflow(I, ISD::SMULO);
4136 case Intrinsic::prefetch: {
4139 Ops[1] = getValue(I.getOperand(1));
4140 Ops[2] = getValue(I.getOperand(2));
4141 Ops[3] = getValue(I.getOperand(3));
4142 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
4146 case Intrinsic::memory_barrier: {
4149 for (int x = 1; x < 6; ++x)
4150 Ops[x] = getValue(I.getOperand(x));
4152 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
4155 case Intrinsic::atomic_cmp_swap: {
4156 SDValue Root = getRoot();
4158 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP,
4159 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4161 getValue(I.getOperand(1)),
4162 getValue(I.getOperand(2)),
4163 getValue(I.getOperand(3)),
4166 DAG.setRoot(L.getValue(1));
4169 case Intrinsic::atomic_load_add:
4170 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4171 case Intrinsic::atomic_load_sub:
4172 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4173 case Intrinsic::atomic_load_or:
4174 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4175 case Intrinsic::atomic_load_xor:
4176 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4177 case Intrinsic::atomic_load_and:
4178 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4179 case Intrinsic::atomic_load_nand:
4180 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4181 case Intrinsic::atomic_load_max:
4182 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4183 case Intrinsic::atomic_load_min:
4184 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4185 case Intrinsic::atomic_load_umin:
4186 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4187 case Intrinsic::atomic_load_umax:
4188 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4189 case Intrinsic::atomic_swap:
4190 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4195 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4197 MachineBasicBlock *LandingPad) {
4198 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4199 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4200 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4201 unsigned BeginLabel = 0, EndLabel = 0;
4203 TargetLowering::ArgListTy Args;
4204 TargetLowering::ArgListEntry Entry;
4205 Args.reserve(CS.arg_size());
4206 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4208 SDValue ArgNode = getValue(*i);
4209 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4211 unsigned attrInd = i - CS.arg_begin() + 1;
4212 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4213 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4214 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4215 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4216 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4217 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4218 Entry.Alignment = CS.getParamAlignment(attrInd);
4219 Args.push_back(Entry);
4222 if (LandingPad && MMI) {
4223 // Insert a label before the invoke call to mark the try range. This can be
4224 // used to detect deletion of the invoke via the MachineModuleInfo.
4225 BeginLabel = MMI->NextLabelID();
4226 // Both PendingLoads and PendingExports must be flushed here;
4227 // this call might not return.
4229 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4232 std::pair<SDValue,SDValue> Result =
4233 TLI.LowerCallTo(getRoot(), CS.getType(),
4234 CS.paramHasAttr(0, Attribute::SExt),
4235 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4236 CS.paramHasAttr(0, Attribute::InReg),
4237 CS.getCallingConv(),
4238 IsTailCall && PerformTailCallOpt,
4240 if (CS.getType() != Type::VoidTy)
4241 setValue(CS.getInstruction(), Result.first);
4242 DAG.setRoot(Result.second);
4244 if (LandingPad && MMI) {
4245 // Insert a label at the end of the invoke call to mark the try range. This
4246 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4247 EndLabel = MMI->NextLabelID();
4248 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4250 // Inform MachineModuleInfo of range.
4251 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4256 void SelectionDAGLowering::visitCall(CallInst &I) {
4257 const char *RenameFn = 0;
4258 if (Function *F = I.getCalledFunction()) {
4259 if (F->isDeclaration()) {
4260 if (unsigned IID = F->getIntrinsicID()) {
4261 RenameFn = visitIntrinsicCall(I, IID);
4267 // Check for well-known libc/libm calls. If the function is internal, it
4268 // can't be a library call.
4269 unsigned NameLen = F->getNameLen();
4270 if (!F->hasLocalLinkage() && NameLen) {
4271 const char *NameStr = F->getNameStart();
4272 if (NameStr[0] == 'c' &&
4273 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4274 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4275 if (I.getNumOperands() == 3 && // Basic sanity checks.
4276 I.getOperand(1)->getType()->isFloatingPoint() &&
4277 I.getType() == I.getOperand(1)->getType() &&
4278 I.getType() == I.getOperand(2)->getType()) {
4279 SDValue LHS = getValue(I.getOperand(1));
4280 SDValue RHS = getValue(I.getOperand(2));
4281 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4285 } else if (NameStr[0] == 'f' &&
4286 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4287 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4288 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4289 if (I.getNumOperands() == 2 && // Basic sanity checks.
4290 I.getOperand(1)->getType()->isFloatingPoint() &&
4291 I.getType() == I.getOperand(1)->getType()) {
4292 SDValue Tmp = getValue(I.getOperand(1));
4293 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4296 } else if (NameStr[0] == 's' &&
4297 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4298 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4299 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4300 if (I.getNumOperands() == 2 && // Basic sanity checks.
4301 I.getOperand(1)->getType()->isFloatingPoint() &&
4302 I.getType() == I.getOperand(1)->getType()) {
4303 SDValue Tmp = getValue(I.getOperand(1));
4304 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4307 } else if (NameStr[0] == 'c' &&
4308 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4309 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4310 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4311 if (I.getNumOperands() == 2 && // Basic sanity checks.
4312 I.getOperand(1)->getType()->isFloatingPoint() &&
4313 I.getType() == I.getOperand(1)->getType()) {
4314 SDValue Tmp = getValue(I.getOperand(1));
4315 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4320 } else if (isa<InlineAsm>(I.getOperand(0))) {
4327 Callee = getValue(I.getOperand(0));
4329 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4331 LowerCallTo(&I, Callee, I.isTailCall());
4335 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4336 /// this value and returns the result as a ValueVT value. This uses
4337 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4338 /// If the Flag pointer is NULL, no flag is used.
4339 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4341 SDValue *Flag) const {
4342 // Assemble the legal parts into the final values.
4343 SmallVector<SDValue, 4> Values(ValueVTs.size());
4344 SmallVector<SDValue, 8> Parts;
4345 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4346 // Copy the legal parts from the registers.
4347 MVT ValueVT = ValueVTs[Value];
4348 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4349 MVT RegisterVT = RegVTs[Value];
4351 Parts.resize(NumRegs);
4352 for (unsigned i = 0; i != NumRegs; ++i) {
4355 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4357 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4358 *Flag = P.getValue(2);
4360 Chain = P.getValue(1);
4362 // If the source register was virtual and if we know something about it,
4363 // add an assert node.
4364 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4365 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4366 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4367 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4368 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4369 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4371 unsigned RegSize = RegisterVT.getSizeInBits();
4372 unsigned NumSignBits = LOI.NumSignBits;
4373 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4375 // FIXME: We capture more information than the dag can represent. For
4376 // now, just use the tightest assertzext/assertsext possible.
4378 MVT FromVT(MVT::Other);
4379 if (NumSignBits == RegSize)
4380 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4381 else if (NumZeroBits >= RegSize-1)
4382 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4383 else if (NumSignBits > RegSize-8)
4384 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4385 else if (NumZeroBits >= RegSize-9)
4386 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4387 else if (NumSignBits > RegSize-16)
4388 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4389 else if (NumZeroBits >= RegSize-17)
4390 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4391 else if (NumSignBits > RegSize-32)
4392 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4393 else if (NumZeroBits >= RegSize-33)
4394 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4396 if (FromVT != MVT::Other) {
4397 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4398 RegisterVT, P, DAG.getValueType(FromVT));
4407 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4413 return DAG.getNode(ISD::MERGE_VALUES,
4414 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4415 &Values[0], ValueVTs.size());
4418 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4419 /// specified value into the registers specified by this object. This uses
4420 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4421 /// If the Flag pointer is NULL, no flag is used.
4422 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4423 SDValue &Chain, SDValue *Flag) const {
4424 // Get the list of the values's legal parts.
4425 unsigned NumRegs = Regs.size();
4426 SmallVector<SDValue, 8> Parts(NumRegs);
4427 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4428 MVT ValueVT = ValueVTs[Value];
4429 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4430 MVT RegisterVT = RegVTs[Value];
4432 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4433 &Parts[Part], NumParts, RegisterVT);
4437 // Copy the parts into the registers.
4438 SmallVector<SDValue, 8> Chains(NumRegs);
4439 for (unsigned i = 0; i != NumRegs; ++i) {
4442 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4444 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4445 *Flag = Part.getValue(1);
4447 Chains[i] = Part.getValue(0);
4450 if (NumRegs == 1 || Flag)
4451 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4452 // flagged to it. That is the CopyToReg nodes and the user are considered
4453 // a single scheduling unit. If we create a TokenFactor and return it as
4454 // chain, then the TokenFactor is both a predecessor (operand) of the
4455 // user as well as a successor (the TF operands are flagged to the user).
4456 // c1, f1 = CopyToReg
4457 // c2, f2 = CopyToReg
4458 // c3 = TokenFactor c1, c2
4461 Chain = Chains[NumRegs-1];
4463 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4466 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4467 /// operand list. This adds the code marker and includes the number of
4468 /// values added into it.
4469 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4470 std::vector<SDValue> &Ops) const {
4471 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4472 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4473 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4474 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4475 MVT RegisterVT = RegVTs[Value];
4476 for (unsigned i = 0; i != NumRegs; ++i) {
4477 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4478 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4483 /// isAllocatableRegister - If the specified register is safe to allocate,
4484 /// i.e. it isn't a stack pointer or some other special register, return the
4485 /// register class for the register. Otherwise, return null.
4486 static const TargetRegisterClass *
4487 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4488 const TargetLowering &TLI,
4489 const TargetRegisterInfo *TRI) {
4490 MVT FoundVT = MVT::Other;
4491 const TargetRegisterClass *FoundRC = 0;
4492 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4493 E = TRI->regclass_end(); RCI != E; ++RCI) {
4494 MVT ThisVT = MVT::Other;
4496 const TargetRegisterClass *RC = *RCI;
4497 // If none of the the value types for this register class are valid, we
4498 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4499 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4501 if (TLI.isTypeLegal(*I)) {
4502 // If we have already found this register in a different register class,
4503 // choose the one with the largest VT specified. For example, on
4504 // PowerPC, we favor f64 register classes over f32.
4505 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4512 if (ThisVT == MVT::Other) continue;
4514 // NOTE: This isn't ideal. In particular, this might allocate the
4515 // frame pointer in functions that need it (due to them not being taken
4516 // out of allocation, because a variable sized allocation hasn't been seen
4517 // yet). This is a slight code pessimization, but should still work.
4518 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4519 E = RC->allocation_order_end(MF); I != E; ++I)
4521 // We found a matching register class. Keep looking at others in case
4522 // we find one with larger registers that this physreg is also in.
4533 /// AsmOperandInfo - This contains information for each constraint that we are
4535 struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4536 public TargetLowering::AsmOperandInfo {
4537 /// CallOperand - If this is the result output operand or a clobber
4538 /// this is null, otherwise it is the incoming operand to the CallInst.
4539 /// This gets modified as the asm is processed.
4540 SDValue CallOperand;
4542 /// AssignedRegs - If this is a register or register class operand, this
4543 /// contains the set of register corresponding to the operand.
4544 RegsForValue AssignedRegs;
4546 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4547 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4550 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4551 /// busy in OutputRegs/InputRegs.
4552 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4553 std::set<unsigned> &OutputRegs,
4554 std::set<unsigned> &InputRegs,
4555 const TargetRegisterInfo &TRI) const {
4557 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4558 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4561 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4562 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4566 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4567 /// corresponds to. If there is no Value* for this operand, it returns
4569 MVT getCallOperandValMVT(const TargetLowering &TLI,
4570 const TargetData *TD) const {
4571 if (CallOperandVal == 0) return MVT::Other;
4573 if (isa<BasicBlock>(CallOperandVal))
4574 return TLI.getPointerTy();
4576 const llvm::Type *OpTy = CallOperandVal->getType();
4578 // If this is an indirect operand, the operand is a pointer to the
4581 OpTy = cast<PointerType>(OpTy)->getElementType();
4583 // If OpTy is not a single value, it may be a struct/union that we
4584 // can tile with integers.
4585 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4586 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4595 OpTy = IntegerType::get(BitSize);
4600 return TLI.getValueType(OpTy, true);
4604 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4606 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4607 const TargetRegisterInfo &TRI) {
4608 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4610 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4611 for (; *Aliases; ++Aliases)
4612 Regs.insert(*Aliases);
4615 } // end llvm namespace.
4618 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4619 /// specified operand. We prefer to assign virtual registers, to allow the
4620 /// register allocator handle the assignment process. However, if the asm uses
4621 /// features that we can't model on machineinstrs, we have SDISel do the
4622 /// allocation. This produces generally horrible, but correct, code.
4624 /// OpInfo describes the operand.
4625 /// Input and OutputRegs are the set of already allocated physical registers.
4627 void SelectionDAGLowering::
4628 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4629 std::set<unsigned> &OutputRegs,
4630 std::set<unsigned> &InputRegs) {
4631 // Compute whether this value requires an input register, an output register,
4633 bool isOutReg = false;
4634 bool isInReg = false;
4635 switch (OpInfo.Type) {
4636 case InlineAsm::isOutput:
4639 // If there is an input constraint that matches this, we need to reserve
4640 // the input register so no other inputs allocate to it.
4641 isInReg = OpInfo.hasMatchingInput();
4643 case InlineAsm::isInput:
4647 case InlineAsm::isClobber:
4654 MachineFunction &MF = DAG.getMachineFunction();
4655 SmallVector<unsigned, 4> Regs;
4657 // If this is a constraint for a single physreg, or a constraint for a
4658 // register class, find it.
4659 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4660 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4661 OpInfo.ConstraintVT);
4663 unsigned NumRegs = 1;
4664 if (OpInfo.ConstraintVT != MVT::Other) {
4665 // If this is a FP input in an integer register (or visa versa) insert a bit
4666 // cast of the input value. More generally, handle any case where the input
4667 // value disagrees with the register class we plan to stick this in.
4668 if (OpInfo.Type == InlineAsm::isInput &&
4669 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4670 // Try to convert to the first MVT that the reg class contains. If the
4671 // types are identical size, use a bitcast to convert (e.g. two differing
4673 MVT RegVT = *PhysReg.second->vt_begin();
4674 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4675 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4676 OpInfo.CallOperand);
4677 OpInfo.ConstraintVT = RegVT;
4678 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4679 // If the input is a FP value and we want it in FP registers, do a
4680 // bitcast to the corresponding integer type. This turns an f64 value
4681 // into i64, which can be passed with two i32 values on a 32-bit
4683 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4684 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4685 OpInfo.CallOperand);
4686 OpInfo.ConstraintVT = RegVT;
4690 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4694 MVT ValueVT = OpInfo.ConstraintVT;
4696 // If this is a constraint for a specific physical register, like {r17},
4698 if (PhysReg.first) {
4699 if (OpInfo.ConstraintVT == MVT::Other)
4700 ValueVT = *PhysReg.second->vt_begin();
4702 // Get the actual register value type. This is important, because the user
4703 // may have asked for (e.g.) the AX register in i32 type. We need to
4704 // remember that AX is actually i16 to get the right extension.
4705 RegVT = *PhysReg.second->vt_begin();
4707 // This is a explicit reference to a physical register.
4708 Regs.push_back(PhysReg.first);
4710 // If this is an expanded reference, add the rest of the regs to Regs.
4712 TargetRegisterClass::iterator I = PhysReg.second->begin();
4713 for (; *I != PhysReg.first; ++I)
4714 assert(I != PhysReg.second->end() && "Didn't find reg!");
4716 // Already added the first reg.
4718 for (; NumRegs; --NumRegs, ++I) {
4719 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4723 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4724 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4725 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4729 // Otherwise, if this was a reference to an LLVM register class, create vregs
4730 // for this reference.
4731 std::vector<unsigned> RegClassRegs;
4732 const TargetRegisterClass *RC = PhysReg.second;
4734 // If this is a tied register, our regalloc doesn't know how to maintain
4735 // the constraint, so we have to pick a register to pin the input/output to.
4736 // If it isn't a matched constraint, go ahead and create vreg and let the
4737 // regalloc do its thing.
4738 if (!OpInfo.hasMatchingInput()) {
4739 RegVT = *PhysReg.second->vt_begin();
4740 if (OpInfo.ConstraintVT == MVT::Other)
4743 // Create the appropriate number of virtual registers.
4744 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4745 for (; NumRegs; --NumRegs)
4746 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4748 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4752 // Otherwise, we can't allocate it. Let the code below figure out how to
4753 // maintain these constraints.
4754 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4757 // This is a reference to a register class that doesn't directly correspond
4758 // to an LLVM register class. Allocate NumRegs consecutive, available,
4759 // registers from the class.
4760 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4761 OpInfo.ConstraintVT);
4764 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4765 unsigned NumAllocated = 0;
4766 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4767 unsigned Reg = RegClassRegs[i];
4768 // See if this register is available.
4769 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4770 (isInReg && InputRegs.count(Reg))) { // Already used.
4771 // Make sure we find consecutive registers.
4776 // Check to see if this register is allocatable (i.e. don't give out the
4779 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4780 if (!RC) { // Couldn't allocate this register.
4781 // Reset NumAllocated to make sure we return consecutive registers.
4787 // Okay, this register is good, we can use it.
4790 // If we allocated enough consecutive registers, succeed.
4791 if (NumAllocated == NumRegs) {
4792 unsigned RegStart = (i-NumAllocated)+1;
4793 unsigned RegEnd = i+1;
4794 // Mark all of the allocated registers used.
4795 for (unsigned i = RegStart; i != RegEnd; ++i)
4796 Regs.push_back(RegClassRegs[i]);
4798 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4799 OpInfo.ConstraintVT);
4800 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4805 // Otherwise, we couldn't allocate enough registers for this.
4808 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4809 /// processed uses a memory 'm' constraint.
4811 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4812 const TargetLowering &TLI) {
4813 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4814 InlineAsm::ConstraintInfo &CI = CInfos[i];
4815 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4816 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4817 if (CType == TargetLowering::C_Memory)
4825 /// visitInlineAsm - Handle a call to an InlineAsm object.
4827 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4828 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4830 /// ConstraintOperands - Information about all of the constraints.
4831 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4833 SDValue Chain = getRoot();
4836 std::set<unsigned> OutputRegs, InputRegs;
4838 // Do a prepass over the constraints, canonicalizing them, and building up the
4839 // ConstraintOperands list.
4840 std::vector<InlineAsm::ConstraintInfo>
4841 ConstraintInfos = IA->ParseConstraints();
4843 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
4845 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4846 unsigned ResNo = 0; // ResNo - The result number of the next output.
4847 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4848 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4849 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4851 MVT OpVT = MVT::Other;
4853 // Compute the value type for each operand.
4854 switch (OpInfo.Type) {
4855 case InlineAsm::isOutput:
4856 // Indirect outputs just consume an argument.
4857 if (OpInfo.isIndirect) {
4858 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4862 // The return value of the call is this value. As such, there is no
4863 // corresponding argument.
4864 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4865 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4866 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4868 assert(ResNo == 0 && "Asm only has one result!");
4869 OpVT = TLI.getValueType(CS.getType());
4873 case InlineAsm::isInput:
4874 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4876 case InlineAsm::isClobber:
4881 // If this is an input or an indirect output, process the call argument.
4882 // BasicBlocks are labels, currently appearing only in asm's.
4883 if (OpInfo.CallOperandVal) {
4884 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
4885 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4887 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4890 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
4893 OpInfo.ConstraintVT = OpVT;
4896 // Second pass over the constraints: compute which constraint option to use
4897 // and assign registers to constraints that want a specific physreg.
4898 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4899 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4901 // If this is an output operand with a matching input operand, look up the
4902 // matching input. If their types mismatch, e.g. one is an integer, the
4903 // other is floating point, or their sizes are different, flag it as an
4905 if (OpInfo.hasMatchingInput()) {
4906 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4907 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4908 if ((OpInfo.ConstraintVT.isInteger() !=
4909 Input.ConstraintVT.isInteger()) ||
4910 (OpInfo.ConstraintVT.getSizeInBits() !=
4911 Input.ConstraintVT.getSizeInBits())) {
4912 cerr << "Unsupported asm: input constraint with a matching output "
4913 << "constraint of incompatible type!\n";
4916 Input.ConstraintVT = OpInfo.ConstraintVT;
4920 // Compute the constraint code and ConstraintType to use.
4921 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
4923 // If this is a memory input, and if the operand is not indirect, do what we
4924 // need to to provide an address for the memory input.
4925 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4926 !OpInfo.isIndirect) {
4927 assert(OpInfo.Type == InlineAsm::isInput &&
4928 "Can only indirectify direct input operands!");
4930 // Memory operands really want the address of the value. If we don't have
4931 // an indirect input, put it in the constpool if we can, otherwise spill
4932 // it to a stack slot.
4934 // If the operand is a float, integer, or vector constant, spill to a
4935 // constant pool entry to get its address.
4936 Value *OpVal = OpInfo.CallOperandVal;
4937 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4938 isa<ConstantVector>(OpVal)) {
4939 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4940 TLI.getPointerTy());
4942 // Otherwise, create a stack slot and emit a store to it before the
4944 const Type *Ty = OpVal->getType();
4945 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
4946 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4947 MachineFunction &MF = DAG.getMachineFunction();
4948 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4949 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4950 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4951 OpInfo.CallOperand = StackSlot;
4954 // There is no longer a Value* corresponding to this operand.
4955 OpInfo.CallOperandVal = 0;
4956 // It is now an indirect operand.
4957 OpInfo.isIndirect = true;
4960 // If this constraint is for a specific register, allocate it before
4962 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4963 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4965 ConstraintInfos.clear();
4968 // Second pass - Loop over all of the operands, assigning virtual or physregs
4969 // to register class operands.
4970 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4971 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4973 // C_Register operands have already been allocated, Other/Memory don't need
4975 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4976 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4979 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4980 std::vector<SDValue> AsmNodeOperands;
4981 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4982 AsmNodeOperands.push_back(
4983 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4986 // Loop over all of the inputs, copying the operand values into the
4987 // appropriate registers and processing the output regs.
4988 RegsForValue RetValRegs;
4990 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4991 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4993 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4994 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4996 switch (OpInfo.Type) {
4997 case InlineAsm::isOutput: {
4998 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4999 OpInfo.ConstraintType != TargetLowering::C_Register) {
5000 // Memory output, or 'other' output (e.g. 'X' constraint).
5001 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5003 // Add information to the INLINEASM node to know about this output.
5004 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5005 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5006 TLI.getPointerTy()));
5007 AsmNodeOperands.push_back(OpInfo.CallOperand);
5011 // Otherwise, this is a register or register class output.
5013 // Copy the output from the appropriate register. Find a register that
5015 if (OpInfo.AssignedRegs.Regs.empty()) {
5016 cerr << "Couldn't allocate output reg for constraint '"
5017 << OpInfo.ConstraintCode << "'!\n";
5021 // If this is an indirect operand, store through the pointer after the
5023 if (OpInfo.isIndirect) {
5024 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5025 OpInfo.CallOperandVal));
5027 // This is the result value of the call.
5028 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5029 // Concatenate this output onto the outputs list.
5030 RetValRegs.append(OpInfo.AssignedRegs);
5033 // Add information to the INLINEASM node to know that this register is
5035 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5036 6 /* EARLYCLOBBER REGDEF */ :
5038 DAG, AsmNodeOperands);
5041 case InlineAsm::isInput: {
5042 SDValue InOperandVal = OpInfo.CallOperand;
5044 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5045 // If this is required to match an output register we have already set,
5046 // just use its register.
5047 unsigned OperandNo = OpInfo.getMatchedOperand();
5049 // Scan until we find the definition we already emitted of this operand.
5050 // When we find it, create a RegsForValue operand.
5051 unsigned CurOp = 2; // The first operand.
5052 for (; OperandNo; --OperandNo) {
5053 // Advance to the next operand.
5055 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5056 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
5057 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5058 (NumOps & 7) == 4 /*MEM*/) &&
5059 "Skipped past definitions?");
5060 CurOp += (NumOps>>3)+1;
5064 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5065 if ((NumOps & 7) == 2 /*REGDEF*/
5066 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5067 // Add NumOps>>3 registers to MatchedRegs.
5068 RegsForValue MatchedRegs;
5069 MatchedRegs.TLI = &TLI;
5070 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5071 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5072 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5074 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5075 MatchedRegs.Regs.push_back(Reg);
5078 // Use the produced MatchedRegs object to
5079 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5080 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
5083 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
5084 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
5085 // Add information to the INLINEASM node to know about this input.
5086 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
5087 TLI.getPointerTy()));
5088 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5093 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5094 assert(!OpInfo.isIndirect &&
5095 "Don't know how to handle indirect other inputs yet!");
5097 std::vector<SDValue> Ops;
5098 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5099 hasMemory, Ops, DAG);
5101 cerr << "Invalid operand for inline asm constraint '"
5102 << OpInfo.ConstraintCode << "'!\n";
5106 // Add information to the INLINEASM node to know about this input.
5107 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5108 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5109 TLI.getPointerTy()));
5110 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5112 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5113 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5114 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5115 "Memory operands expect pointer values");
5117 // Add information to the INLINEASM node to know about this input.
5118 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5119 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5120 TLI.getPointerTy()));
5121 AsmNodeOperands.push_back(InOperandVal);
5125 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5126 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5127 "Unknown constraint type!");
5128 assert(!OpInfo.isIndirect &&
5129 "Don't know how to handle indirect register inputs yet!");
5131 // Copy the input into the appropriate registers.
5132 if (OpInfo.AssignedRegs.Regs.empty()) {
5133 cerr << "Couldn't allocate output reg for constraint '"
5134 << OpInfo.ConstraintCode << "'!\n";
5138 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5140 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5141 DAG, AsmNodeOperands);
5144 case InlineAsm::isClobber: {
5145 // Add the clobbered value to the operand list, so that the register
5146 // allocator is aware that the physreg got clobbered.
5147 if (!OpInfo.AssignedRegs.Regs.empty())
5148 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5149 DAG, AsmNodeOperands);
5155 // Finish up input operands.
5156 AsmNodeOperands[0] = Chain;
5157 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5159 Chain = DAG.getNode(ISD::INLINEASM,
5160 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5161 &AsmNodeOperands[0], AsmNodeOperands.size());
5162 Flag = Chain.getValue(1);
5164 // If this asm returns a register value, copy the result from that register
5165 // and set it as the value of the call.
5166 if (!RetValRegs.Regs.empty()) {
5167 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
5169 // FIXME: Why don't we do this for inline asms with MRVs?
5170 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5171 MVT ResultType = TLI.getValueType(CS.getType());
5173 // If any of the results of the inline asm is a vector, it may have the
5174 // wrong width/num elts. This can happen for register classes that can
5175 // contain multiple different value types. The preg or vreg allocated may
5176 // not have the same VT as was expected. Convert it to the right type
5177 // with bit_convert.
5178 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5179 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
5181 } else if (ResultType != Val.getValueType() &&
5182 ResultType.isInteger() && Val.getValueType().isInteger()) {
5183 // If a result value was tied to an input value, the computed result may
5184 // have a wider width than the expected result. Extract the relevant
5186 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
5189 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5192 setValue(CS.getInstruction(), Val);
5195 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5197 // Process indirect outputs, first output all of the flagged copies out of
5199 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5200 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5201 Value *Ptr = IndirectStoresToEmit[i].second;
5202 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5203 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5206 // Emit the non-flagged stores from the physregs.
5207 SmallVector<SDValue, 8> OutChains;
5208 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5209 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5210 getValue(StoresToEmit[i].second),
5211 StoresToEmit[i].second, 0));
5212 if (!OutChains.empty())
5213 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5214 &OutChains[0], OutChains.size());
5219 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5220 SDValue Src = getValue(I.getOperand(0));
5222 MVT IntPtr = TLI.getPointerTy();
5224 if (IntPtr.bitsLT(Src.getValueType()))
5225 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5226 else if (IntPtr.bitsGT(Src.getValueType()))
5227 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5229 // Scale the source by the type size.
5230 uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
5231 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5232 Src, DAG.getIntPtrConstant(ElementSize));
5234 TargetLowering::ArgListTy Args;
5235 TargetLowering::ArgListEntry Entry;
5237 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5238 Args.push_back(Entry);
5240 std::pair<SDValue,SDValue> Result =
5241 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5242 CallingConv::C, PerformTailCallOpt,
5243 DAG.getExternalSymbol("malloc", IntPtr),
5245 setValue(&I, Result.first); // Pointers always fit in registers
5246 DAG.setRoot(Result.second);
5249 void SelectionDAGLowering::visitFree(FreeInst &I) {
5250 TargetLowering::ArgListTy Args;
5251 TargetLowering::ArgListEntry Entry;
5252 Entry.Node = getValue(I.getOperand(0));
5253 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5254 Args.push_back(Entry);
5255 MVT IntPtr = TLI.getPointerTy();
5256 std::pair<SDValue,SDValue> Result =
5257 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5258 CallingConv::C, PerformTailCallOpt,
5259 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
5260 DAG.setRoot(Result.second);
5263 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5264 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5265 getValue(I.getOperand(1)),
5266 DAG.getSrcValue(I.getOperand(1))));
5269 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5270 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5271 getValue(I.getOperand(0)),
5272 DAG.getSrcValue(I.getOperand(0)));
5274 DAG.setRoot(V.getValue(1));
5277 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5278 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5279 getValue(I.getOperand(1)),
5280 DAG.getSrcValue(I.getOperand(1))));
5283 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5284 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5285 getValue(I.getOperand(1)),
5286 getValue(I.getOperand(2)),
5287 DAG.getSrcValue(I.getOperand(1)),
5288 DAG.getSrcValue(I.getOperand(2))));
5291 /// TargetLowering::LowerArguments - This is the default LowerArguments
5292 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5293 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5294 /// integrated into SDISel.
5295 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5296 SmallVectorImpl<SDValue> &ArgValues) {
5297 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5298 SmallVector<SDValue, 3+16> Ops;
5299 Ops.push_back(DAG.getRoot());
5300 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5301 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5303 // Add one result value for each formal argument.
5304 SmallVector<MVT, 16> RetVals;
5306 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5308 SmallVector<MVT, 4> ValueVTs;
5309 ComputeValueVTs(*this, I->getType(), ValueVTs);
5310 for (unsigned Value = 0, NumValues = ValueVTs.size();
5311 Value != NumValues; ++Value) {
5312 MVT VT = ValueVTs[Value];
5313 const Type *ArgTy = VT.getTypeForMVT();
5314 ISD::ArgFlagsTy Flags;
5315 unsigned OriginalAlignment =
5316 getTargetData()->getABITypeAlignment(ArgTy);
5318 if (F.paramHasAttr(j, Attribute::ZExt))
5320 if (F.paramHasAttr(j, Attribute::SExt))
5322 if (F.paramHasAttr(j, Attribute::InReg))
5324 if (F.paramHasAttr(j, Attribute::StructRet))
5326 if (F.paramHasAttr(j, Attribute::ByVal)) {
5328 const PointerType *Ty = cast<PointerType>(I->getType());
5329 const Type *ElementTy = Ty->getElementType();
5330 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5331 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
5332 // For ByVal, alignment should be passed from FE. BE will guess if
5333 // this info is not there but there are cases it cannot get right.
5334 if (F.getParamAlignment(j))
5335 FrameAlign = F.getParamAlignment(j);
5336 Flags.setByValAlign(FrameAlign);
5337 Flags.setByValSize(FrameSize);
5339 if (F.paramHasAttr(j, Attribute::Nest))
5341 Flags.setOrigAlign(OriginalAlignment);
5343 MVT RegisterVT = getRegisterType(VT);
5344 unsigned NumRegs = getNumRegisters(VT);
5345 for (unsigned i = 0; i != NumRegs; ++i) {
5346 RetVals.push_back(RegisterVT);
5347 ISD::ArgFlagsTy MyFlags = Flags;
5348 if (NumRegs > 1 && i == 0)
5350 // if it isn't first piece, alignment must be 1
5352 MyFlags.setOrigAlign(1);
5353 Ops.push_back(DAG.getArgFlags(MyFlags));
5358 RetVals.push_back(MVT::Other);
5361 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5362 DAG.getVTList(&RetVals[0], RetVals.size()),
5363 &Ops[0], Ops.size()).getNode();
5365 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5366 // allows exposing the loads that may be part of the argument access to the
5367 // first DAGCombiner pass.
5368 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5370 // The number of results should match up, except that the lowered one may have
5371 // an extra flag result.
5372 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5373 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5374 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5375 && "Lowering produced unexpected number of results!");
5377 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5378 if (Result != TmpRes.getNode() && Result->use_empty()) {
5379 HandleSDNode Dummy(DAG.getRoot());
5380 DAG.RemoveDeadNode(Result);
5383 Result = TmpRes.getNode();
5385 unsigned NumArgRegs = Result->getNumValues() - 1;
5386 DAG.setRoot(SDValue(Result, NumArgRegs));
5388 // Set up the return result vector.
5391 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5393 SmallVector<MVT, 4> ValueVTs;
5394 ComputeValueVTs(*this, I->getType(), ValueVTs);
5395 for (unsigned Value = 0, NumValues = ValueVTs.size();
5396 Value != NumValues; ++Value) {
5397 MVT VT = ValueVTs[Value];
5398 MVT PartVT = getRegisterType(VT);
5400 unsigned NumParts = getNumRegisters(VT);
5401 SmallVector<SDValue, 4> Parts(NumParts);
5402 for (unsigned j = 0; j != NumParts; ++j)
5403 Parts[j] = SDValue(Result, i++);
5405 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5406 if (F.paramHasAttr(Idx, Attribute::SExt))
5407 AssertOp = ISD::AssertSext;
5408 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5409 AssertOp = ISD::AssertZext;
5411 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5415 assert(i == NumArgRegs && "Argument register count mismatch!");
5419 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5420 /// implementation, which just inserts an ISD::CALL node, which is later custom
5421 /// lowered by the target to something concrete. FIXME: When all targets are
5422 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5423 std::pair<SDValue, SDValue>
5424 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5425 bool RetSExt, bool RetZExt, bool isVarArg,
5427 unsigned CallingConv, bool isTailCall,
5429 ArgListTy &Args, SelectionDAG &DAG) {
5430 assert((!isTailCall || PerformTailCallOpt) &&
5431 "isTailCall set when tail-call optimizations are disabled!");
5433 SmallVector<SDValue, 32> Ops;
5434 Ops.push_back(Chain); // Op#0 - Chain
5435 Ops.push_back(Callee);
5437 // Handle all of the outgoing arguments.
5438 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5439 SmallVector<MVT, 4> ValueVTs;
5440 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5441 for (unsigned Value = 0, NumValues = ValueVTs.size();
5442 Value != NumValues; ++Value) {
5443 MVT VT = ValueVTs[Value];
5444 const Type *ArgTy = VT.getTypeForMVT();
5445 SDValue Op = SDValue(Args[i].Node.getNode(),
5446 Args[i].Node.getResNo() + Value);
5447 ISD::ArgFlagsTy Flags;
5448 unsigned OriginalAlignment =
5449 getTargetData()->getABITypeAlignment(ArgTy);
5455 if (Args[i].isInReg)
5459 if (Args[i].isByVal) {
5461 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5462 const Type *ElementTy = Ty->getElementType();
5463 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5464 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
5465 // For ByVal, alignment should come from FE. BE will guess if this
5466 // info is not there but there are cases it cannot get right.
5467 if (Args[i].Alignment)
5468 FrameAlign = Args[i].Alignment;
5469 Flags.setByValAlign(FrameAlign);
5470 Flags.setByValSize(FrameSize);
5474 Flags.setOrigAlign(OriginalAlignment);
5476 MVT PartVT = getRegisterType(VT);
5477 unsigned NumParts = getNumRegisters(VT);
5478 SmallVector<SDValue, 4> Parts(NumParts);
5479 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5482 ExtendKind = ISD::SIGN_EXTEND;
5483 else if (Args[i].isZExt)
5484 ExtendKind = ISD::ZERO_EXTEND;
5486 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5488 for (unsigned i = 0; i != NumParts; ++i) {
5489 // if it isn't first piece, alignment must be 1
5490 ISD::ArgFlagsTy MyFlags = Flags;
5491 if (NumParts > 1 && i == 0)
5494 MyFlags.setOrigAlign(1);
5496 Ops.push_back(Parts[i]);
5497 Ops.push_back(DAG.getArgFlags(MyFlags));
5502 // Figure out the result value types. We start by making a list of
5503 // the potentially illegal return value types.
5504 SmallVector<MVT, 4> LoweredRetTys;
5505 SmallVector<MVT, 4> RetTys;
5506 ComputeValueVTs(*this, RetTy, RetTys);
5508 // Then we translate that to a list of legal types.
5509 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5511 MVT RegisterVT = getRegisterType(VT);
5512 unsigned NumRegs = getNumRegisters(VT);
5513 for (unsigned i = 0; i != NumRegs; ++i)
5514 LoweredRetTys.push_back(RegisterVT);
5517 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5519 // Create the CALL node.
5520 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
5521 DAG.getVTList(&LoweredRetTys[0],
5522 LoweredRetTys.size()),
5525 Chain = Res.getValue(LoweredRetTys.size() - 1);
5527 // Gather up the call result into a single value.
5528 if (RetTy != Type::VoidTy && !RetTys.empty()) {
5529 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5532 AssertOp = ISD::AssertSext;
5534 AssertOp = ISD::AssertZext;
5536 SmallVector<SDValue, 4> ReturnValues;
5538 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5540 MVT RegisterVT = getRegisterType(VT);
5541 unsigned NumRegs = getNumRegisters(VT);
5542 unsigned RegNoEnd = NumRegs + RegNo;
5543 SmallVector<SDValue, 4> Results;
5544 for (; RegNo != RegNoEnd; ++RegNo)
5545 Results.push_back(Res.getValue(RegNo));
5546 SDValue ReturnValue =
5547 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5549 ReturnValues.push_back(ReturnValue);
5551 Res = DAG.getNode(ISD::MERGE_VALUES,
5552 DAG.getVTList(&RetTys[0], RetTys.size()),
5553 &ReturnValues[0], ReturnValues.size());
5556 return std::make_pair(Res, Chain);
5559 void TargetLowering::LowerOperationWrapper(SDNode *N,
5560 SmallVectorImpl<SDValue> &Results,
5561 SelectionDAG &DAG) {
5562 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5564 Results.push_back(Res);
5567 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5568 assert(0 && "LowerOperation not implemented for this target!");
5574 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5575 SDValue Op = getValue(V);
5576 assert((Op.getOpcode() != ISD::CopyFromReg ||
5577 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5578 "Copy from a reg to the same reg!");
5579 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5581 RegsForValue RFV(TLI, Reg, V->getType());
5582 SDValue Chain = DAG.getEntryNode();
5583 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5584 PendingExports.push_back(Chain);
5587 #include "llvm/CodeGen/SelectionDAGISel.h"
5589 void SelectionDAGISel::
5590 LowerArguments(BasicBlock *LLVMBB) {
5591 // If this is the entry block, emit arguments.
5592 Function &F = *LLVMBB->getParent();
5593 SDValue OldRoot = SDL->DAG.getRoot();
5594 SmallVector<SDValue, 16> Args;
5595 TLI.LowerArguments(F, SDL->DAG, Args);
5598 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5600 SmallVector<MVT, 4> ValueVTs;
5601 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5602 unsigned NumValues = ValueVTs.size();
5603 if (!AI->use_empty()) {
5604 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5605 // If this argument is live outside of the entry block, insert a copy from
5606 // whereever we got it to the vreg that other BB's will reference it as.
5607 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5608 if (VMI != FuncInfo->ValueMap.end()) {
5609 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5615 // Finally, if the target has anything special to do, allow it to do so.
5616 // FIXME: this should insert code into the DAG!
5617 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5620 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5621 /// ensure constants are generated when needed. Remember the virtual registers
5622 /// that need to be added to the Machine PHI nodes as input. We cannot just
5623 /// directly add them, because expansion might result in multiple MBB's for one
5624 /// BB. As such, the start of the BB might correspond to a different MBB than
5628 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5629 TerminatorInst *TI = LLVMBB->getTerminator();
5631 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5633 // Check successor nodes' PHI nodes that expect a constant to be available
5635 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5636 BasicBlock *SuccBB = TI->getSuccessor(succ);
5637 if (!isa<PHINode>(SuccBB->begin())) continue;
5638 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5640 // If this terminator has multiple identical successors (common for
5641 // switches), only handle each succ once.
5642 if (!SuccsHandled.insert(SuccMBB)) continue;
5644 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5647 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5648 // nodes and Machine PHI nodes, but the incoming operands have not been
5650 for (BasicBlock::iterator I = SuccBB->begin();
5651 (PN = dyn_cast<PHINode>(I)); ++I) {
5652 // Ignore dead phi's.
5653 if (PN->use_empty()) continue;
5656 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5658 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5659 unsigned &RegOut = SDL->ConstantsOut[C];
5661 RegOut = FuncInfo->CreateRegForValue(C);
5662 SDL->CopyValueToVirtualRegister(C, RegOut);
5666 Reg = FuncInfo->ValueMap[PHIOp];
5668 assert(isa<AllocaInst>(PHIOp) &&
5669 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5670 "Didn't codegen value into a register!??");
5671 Reg = FuncInfo->CreateRegForValue(PHIOp);
5672 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5676 // Remember that this register needs to added to the machine PHI node as
5677 // the input for this MBB.
5678 SmallVector<MVT, 4> ValueVTs;
5679 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5680 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5681 MVT VT = ValueVTs[vti];
5682 unsigned NumRegisters = TLI.getNumRegisters(VT);
5683 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5684 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5685 Reg += NumRegisters;
5689 SDL->ConstantsOut.clear();
5692 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5693 /// supports legal types, and it emits MachineInstrs directly instead of
5694 /// creating SelectionDAG nodes.
5697 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5699 TerminatorInst *TI = LLVMBB->getTerminator();
5701 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5702 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5704 // Check successor nodes' PHI nodes that expect a constant to be available
5706 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5707 BasicBlock *SuccBB = TI->getSuccessor(succ);
5708 if (!isa<PHINode>(SuccBB->begin())) continue;
5709 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5711 // If this terminator has multiple identical successors (common for
5712 // switches), only handle each succ once.
5713 if (!SuccsHandled.insert(SuccMBB)) continue;
5715 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5718 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5719 // nodes and Machine PHI nodes, but the incoming operands have not been
5721 for (BasicBlock::iterator I = SuccBB->begin();
5722 (PN = dyn_cast<PHINode>(I)); ++I) {
5723 // Ignore dead phi's.
5724 if (PN->use_empty()) continue;
5726 // Only handle legal types. Two interesting things to note here. First,
5727 // by bailing out early, we may leave behind some dead instructions,
5728 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5729 // own moves. Second, this check is necessary becuase FastISel doesn't
5730 // use CreateRegForValue to create registers, so it always creates
5731 // exactly one register for each non-void instruction.
5732 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5733 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5736 VT = TLI.getTypeToTransformTo(VT);
5738 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5743 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5745 unsigned Reg = F->getRegForValue(PHIOp);
5747 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5750 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));