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/ParameterAttributes.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/SelectionDAG.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetFrameInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/MathExtras.h"
52 /// LimitFloatPrecision - Generate low-precision inline sequences for
53 /// some float libcalls (6, 8 or 12 bits).
54 static unsigned LimitFloatPrecision;
56 static cl::opt<unsigned, true>
57 LimitFPPrecision("limit-float-precision",
58 cl::desc("Generate low-precision inline sequences "
59 "for some float libcalls"),
60 cl::location(LimitFloatPrecision),
63 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
64 /// insertvalue or extractvalue indices that identify a member, return
65 /// the linearized index of the start of the member.
67 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
68 const unsigned *Indices,
69 const unsigned *IndicesEnd,
70 unsigned CurIndex = 0) {
71 // Base case: We're done.
72 if (Indices && Indices == IndicesEnd)
75 // Given a struct type, recursively traverse the elements.
76 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
77 for (StructType::element_iterator EB = STy->element_begin(),
79 EE = STy->element_end();
81 if (Indices && *Indices == unsigned(EI - EB))
82 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
83 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
86 // Given an array type, recursively traverse the elements.
87 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
88 const Type *EltTy = ATy->getElementType();
89 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
90 if (Indices && *Indices == i)
91 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
92 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
95 // We haven't found the type we're looking for, so keep searching.
99 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
100 /// MVTs that represent all the individual underlying
101 /// non-aggregate types that comprise it.
103 /// If Offsets is non-null, it points to a vector to be filled in
104 /// with the in-memory offsets of each of the individual values.
106 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
107 SmallVectorImpl<MVT> &ValueVTs,
108 SmallVectorImpl<uint64_t> *Offsets = 0,
109 uint64_t StartingOffset = 0) {
110 // Given a struct type, recursively traverse the elements.
111 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
112 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
113 for (StructType::element_iterator EB = STy->element_begin(),
115 EE = STy->element_end();
117 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
118 StartingOffset + SL->getElementOffset(EI - EB));
121 // Given an array type, recursively traverse the elements.
122 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
123 const Type *EltTy = ATy->getElementType();
124 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
125 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
126 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
127 StartingOffset + i * EltSize);
130 // Base case: we can get an MVT for this LLVM IR type.
131 ValueVTs.push_back(TLI.getValueType(Ty));
133 Offsets->push_back(StartingOffset);
137 /// RegsForValue - This struct represents the registers (physical or virtual)
138 /// that a particular set of values is assigned, and the type information about
139 /// the value. The most common situation is to represent one value at a time,
140 /// but struct or array values are handled element-wise as multiple values.
141 /// The splitting of aggregates is performed recursively, so that we never
142 /// have aggregate-typed registers. The values at this point do not necessarily
143 /// have legal types, so each value may require one or more registers of some
146 struct VISIBILITY_HIDDEN RegsForValue {
147 /// TLI - The TargetLowering object.
149 const TargetLowering *TLI;
151 /// ValueVTs - The value types of the values, which may not be legal, and
152 /// may need be promoted or synthesized from one or more registers.
154 SmallVector<MVT, 4> ValueVTs;
156 /// RegVTs - The value types of the registers. This is the same size as
157 /// ValueVTs and it records, for each value, what the type of the assigned
158 /// register or registers are. (Individual values are never synthesized
159 /// from more than one type of register.)
161 /// With virtual registers, the contents of RegVTs is redundant with TLI's
162 /// getRegisterType member function, however when with physical registers
163 /// it is necessary to have a separate record of the types.
165 SmallVector<MVT, 4> RegVTs;
167 /// Regs - This list holds the registers assigned to the values.
168 /// Each legal or promoted value requires one register, and each
169 /// expanded value requires multiple registers.
171 SmallVector<unsigned, 4> Regs;
173 RegsForValue() : TLI(0) {}
175 RegsForValue(const TargetLowering &tli,
176 const SmallVector<unsigned, 4> ®s,
177 MVT regvt, MVT valuevt)
178 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
179 RegsForValue(const TargetLowering &tli,
180 const SmallVector<unsigned, 4> ®s,
181 const SmallVector<MVT, 4> ®vts,
182 const SmallVector<MVT, 4> &valuevts)
183 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
184 RegsForValue(const TargetLowering &tli,
185 unsigned Reg, const Type *Ty) : TLI(&tli) {
186 ComputeValueVTs(tli, Ty, ValueVTs);
188 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
189 MVT ValueVT = ValueVTs[Value];
190 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
191 MVT RegisterVT = TLI->getRegisterType(ValueVT);
192 for (unsigned i = 0; i != NumRegs; ++i)
193 Regs.push_back(Reg + i);
194 RegVTs.push_back(RegisterVT);
199 /// append - Add the specified values to this one.
200 void append(const RegsForValue &RHS) {
202 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
203 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
204 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
208 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
209 /// this value and returns the result as a ValueVTs value. This uses
210 /// Chain/Flag as the input and updates them for the output Chain/Flag.
211 /// If the Flag pointer is NULL, no flag is used.
212 SDValue getCopyFromRegs(SelectionDAG &DAG,
213 SDValue &Chain, SDValue *Flag) const;
215 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
216 /// specified value into the registers specified by this object. 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 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
220 SDValue &Chain, SDValue *Flag) const;
222 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
223 /// operand list. This adds the code marker and includes the number of
224 /// values added into it.
225 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
226 std::vector<SDValue> &Ops) const;
230 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
231 /// PHI nodes or outside of the basic block that defines it, or used by a
232 /// switch or atomic instruction, which may expand to multiple basic blocks.
233 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
234 if (isa<PHINode>(I)) return true;
235 BasicBlock *BB = I->getParent();
236 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
237 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
238 // FIXME: Remove switchinst special case.
239 isa<SwitchInst>(*UI))
244 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
245 /// entry block, return true. This includes arguments used by switches, since
246 /// the switch may expand into multiple basic blocks.
247 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
248 // With FastISel active, we may be splitting blocks, so force creation
249 // of virtual registers for all non-dead arguments.
251 return A->use_empty();
253 BasicBlock *Entry = A->getParent()->begin();
254 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
255 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
256 return false; // Use not in entry block.
260 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
264 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
265 bool EnableFastISel) {
268 RegInfo = &MF->getRegInfo();
270 // Create a vreg for each argument register that is not dead and is used
271 // outside of the entry block for the function.
272 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
274 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
275 InitializeRegForValue(AI);
277 // Initialize the mapping of values to registers. This is only set up for
278 // instruction values that are used outside of the block that defines
280 Function::iterator BB = Fn->begin(), EB = Fn->end();
281 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
282 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
283 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
284 const Type *Ty = AI->getAllocatedType();
285 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
287 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
290 TySize *= CUI->getZExtValue(); // Get total allocated size.
291 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
292 StaticAllocaMap[AI] =
293 MF->getFrameInfo()->CreateStackObject(TySize, Align);
296 for (; BB != EB; ++BB)
297 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
298 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
299 if (!isa<AllocaInst>(I) ||
300 !StaticAllocaMap.count(cast<AllocaInst>(I)))
301 InitializeRegForValue(I);
303 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
304 // also creates the initial PHI MachineInstrs, though none of the input
305 // operands are populated.
306 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
307 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
311 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
314 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
315 if (PN->use_empty()) continue;
317 unsigned PHIReg = ValueMap[PN];
318 assert(PHIReg && "PHI node does not have an assigned virtual register!");
320 SmallVector<MVT, 4> ValueVTs;
321 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
322 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
323 MVT VT = ValueVTs[vti];
324 unsigned NumRegisters = TLI.getNumRegisters(VT);
325 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
326 for (unsigned i = 0; i != NumRegisters; ++i)
327 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
328 PHIReg += NumRegisters;
334 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
335 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
338 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
339 /// the correctly promoted or expanded types. Assign these registers
340 /// consecutive vreg numbers and return the first assigned number.
342 /// In the case that the given value has struct or array type, this function
343 /// will assign registers for each member or element.
345 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
346 SmallVector<MVT, 4> ValueVTs;
347 ComputeValueVTs(TLI, V->getType(), ValueVTs);
349 unsigned FirstReg = 0;
350 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
351 MVT ValueVT = ValueVTs[Value];
352 MVT RegisterVT = TLI.getRegisterType(ValueVT);
354 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
355 for (unsigned i = 0; i != NumRegs; ++i) {
356 unsigned R = MakeReg(RegisterVT);
357 if (!FirstReg) FirstReg = R;
363 /// getCopyFromParts - Create a value that contains the specified legal parts
364 /// combined into the value they represent. If the parts combine to a type
365 /// larger then ValueVT then AssertOp can be used to specify whether the extra
366 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
367 /// (ISD::AssertSext).
368 static SDValue getCopyFromParts(SelectionDAG &DAG,
369 const SDValue *Parts,
373 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
374 assert(NumParts > 0 && "No parts to assemble!");
375 TargetLowering &TLI = DAG.getTargetLoweringInfo();
376 SDValue Val = Parts[0];
379 // Assemble the value from multiple parts.
380 if (!ValueVT.isVector()) {
381 unsigned PartBits = PartVT.getSizeInBits();
382 unsigned ValueBits = ValueVT.getSizeInBits();
384 // Assemble the power of 2 part.
385 unsigned RoundParts = NumParts & (NumParts - 1) ?
386 1 << Log2_32(NumParts) : NumParts;
387 unsigned RoundBits = PartBits * RoundParts;
388 MVT RoundVT = RoundBits == ValueBits ?
389 ValueVT : MVT::getIntegerVT(RoundBits);
392 if (RoundParts > 2) {
393 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
394 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
395 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
401 if (TLI.isBigEndian())
403 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
405 if (RoundParts < NumParts) {
406 // Assemble the trailing non-power-of-2 part.
407 unsigned OddParts = NumParts - RoundParts;
408 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
409 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
411 // Combine the round and odd parts.
413 if (TLI.isBigEndian())
415 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
416 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
417 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
418 DAG.getConstant(Lo.getValueType().getSizeInBits(),
419 TLI.getShiftAmountTy()));
420 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
421 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
424 // Handle a multi-element vector.
425 MVT IntermediateVT, RegisterVT;
426 unsigned NumIntermediates;
428 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
430 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
431 NumParts = NumRegs; // Silence a compiler warning.
432 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
433 assert(RegisterVT == Parts[0].getValueType() &&
434 "Part type doesn't match part!");
436 // Assemble the parts into intermediate operands.
437 SmallVector<SDValue, 8> Ops(NumIntermediates);
438 if (NumIntermediates == NumParts) {
439 // If the register was not expanded, truncate or copy the value,
441 for (unsigned i = 0; i != NumParts; ++i)
442 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
443 PartVT, IntermediateVT);
444 } else if (NumParts > 0) {
445 // If the intermediate type was expanded, build the intermediate operands
447 assert(NumParts % NumIntermediates == 0 &&
448 "Must expand into a divisible number of parts!");
449 unsigned Factor = NumParts / NumIntermediates;
450 for (unsigned i = 0; i != NumIntermediates; ++i)
451 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
452 PartVT, IntermediateVT);
455 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
457 Val = DAG.getNode(IntermediateVT.isVector() ?
458 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
459 ValueVT, &Ops[0], NumIntermediates);
463 // There is now one part, held in Val. Correct it to match ValueVT.
464 PartVT = Val.getValueType();
466 if (PartVT == ValueVT)
469 if (PartVT.isVector()) {
470 assert(ValueVT.isVector() && "Unknown vector conversion!");
471 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
474 if (ValueVT.isVector()) {
475 assert(ValueVT.getVectorElementType() == PartVT &&
476 ValueVT.getVectorNumElements() == 1 &&
477 "Only trivial scalar-to-vector conversions should get here!");
478 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
481 if (PartVT.isInteger() &&
482 ValueVT.isInteger()) {
483 if (ValueVT.bitsLT(PartVT)) {
484 // For a truncate, see if we have any information to
485 // indicate whether the truncated bits will always be
486 // zero or sign-extension.
487 if (AssertOp != ISD::DELETED_NODE)
488 Val = DAG.getNode(AssertOp, PartVT, Val,
489 DAG.getValueType(ValueVT));
490 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
492 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
496 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
497 if (ValueVT.bitsLT(Val.getValueType()))
498 // FP_ROUND's are always exact here.
499 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
500 DAG.getIntPtrConstant(1));
501 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
504 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
505 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
507 assert(0 && "Unknown mismatch!");
511 /// getCopyToParts - Create a series of nodes that contain the specified value
512 /// split into legal parts. If the parts contain more bits than Val, then, for
513 /// integers, ExtendKind can be used to specify how to generate the extra bits.
514 static void getCopyToParts(SelectionDAG &DAG,
519 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
520 TargetLowering &TLI = DAG.getTargetLoweringInfo();
521 MVT PtrVT = TLI.getPointerTy();
522 MVT ValueVT = Val.getValueType();
523 unsigned PartBits = PartVT.getSizeInBits();
524 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
529 if (!ValueVT.isVector()) {
530 if (PartVT == ValueVT) {
531 assert(NumParts == 1 && "No-op copy with multiple parts!");
536 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
537 // If the parts cover more bits than the value has, promote the value.
538 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
539 assert(NumParts == 1 && "Do not know what to promote to!");
540 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
541 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
542 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
543 Val = DAG.getNode(ExtendKind, ValueVT, Val);
545 assert(0 && "Unknown mismatch!");
547 } else if (PartBits == ValueVT.getSizeInBits()) {
548 // Different types of the same size.
549 assert(NumParts == 1 && PartVT != ValueVT);
550 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
551 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
552 // If the parts cover less bits than value has, truncate the value.
553 if (PartVT.isInteger() && ValueVT.isInteger()) {
554 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
555 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
557 assert(0 && "Unknown mismatch!");
561 // The value may have changed - recompute ValueVT.
562 ValueVT = Val.getValueType();
563 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
564 "Failed to tile the value with PartVT!");
567 assert(PartVT == ValueVT && "Type conversion failed!");
572 // Expand the value into multiple parts.
573 if (NumParts & (NumParts - 1)) {
574 // The number of parts is not a power of 2. Split off and copy the tail.
575 assert(PartVT.isInteger() && ValueVT.isInteger() &&
576 "Do not know what to expand to!");
577 unsigned RoundParts = 1 << Log2_32(NumParts);
578 unsigned RoundBits = RoundParts * PartBits;
579 unsigned OddParts = NumParts - RoundParts;
580 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
581 DAG.getConstant(RoundBits,
582 TLI.getShiftAmountTy()));
583 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
584 if (TLI.isBigEndian())
585 // The odd parts were reversed by getCopyToParts - unreverse them.
586 std::reverse(Parts + RoundParts, Parts + NumParts);
587 NumParts = RoundParts;
588 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
589 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
592 // The number of parts is a power of 2. Repeatedly bisect the value using
594 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
595 MVT::getIntegerVT(ValueVT.getSizeInBits()),
597 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
598 for (unsigned i = 0; i < NumParts; i += StepSize) {
599 unsigned ThisBits = StepSize * PartBits / 2;
600 MVT ThisVT = MVT::getIntegerVT (ThisBits);
601 SDValue &Part0 = Parts[i];
602 SDValue &Part1 = Parts[i+StepSize/2];
604 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
605 DAG.getConstant(1, PtrVT));
606 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
607 DAG.getConstant(0, PtrVT));
609 if (ThisBits == PartBits && ThisVT != PartVT) {
610 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
611 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
616 if (TLI.isBigEndian())
617 std::reverse(Parts, Parts + NumParts);
624 if (PartVT != ValueVT) {
625 if (PartVT.isVector()) {
626 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
628 assert(ValueVT.getVectorElementType() == PartVT &&
629 ValueVT.getVectorNumElements() == 1 &&
630 "Only trivial vector-to-scalar conversions should get here!");
631 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
632 DAG.getConstant(0, PtrVT));
640 // Handle a multi-element vector.
641 MVT IntermediateVT, RegisterVT;
642 unsigned NumIntermediates;
644 DAG.getTargetLoweringInfo()
645 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
647 unsigned NumElements = ValueVT.getVectorNumElements();
649 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
650 NumParts = NumRegs; // Silence a compiler warning.
651 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
653 // Split the vector into intermediate operands.
654 SmallVector<SDValue, 8> Ops(NumIntermediates);
655 for (unsigned i = 0; i != NumIntermediates; ++i)
656 if (IntermediateVT.isVector())
657 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
659 DAG.getConstant(i * (NumElements / NumIntermediates),
662 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
664 DAG.getConstant(i, PtrVT));
666 // Split the intermediate operands into legal parts.
667 if (NumParts == NumIntermediates) {
668 // If the register was not expanded, promote or copy the value,
670 for (unsigned i = 0; i != NumParts; ++i)
671 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
672 } else if (NumParts > 0) {
673 // If the intermediate type was expanded, split each the value into
675 assert(NumParts % NumIntermediates == 0 &&
676 "Must expand into a divisible number of parts!");
677 unsigned Factor = NumParts / NumIntermediates;
678 for (unsigned i = 0; i != NumIntermediates; ++i)
679 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
684 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
687 TD = DAG.getTarget().getTargetData();
690 /// clear - Clear out the curret SelectionDAG and the associated
691 /// state and prepare this SelectionDAGLowering object to be used
692 /// for a new block. This doesn't clear out information about
693 /// additional blocks that are needed to complete switch lowering
694 /// or PHI node updating; that information is cleared out as it is
696 void SelectionDAGLowering::clear() {
698 PendingLoads.clear();
699 PendingExports.clear();
703 /// getRoot - Return the current virtual root of the Selection DAG,
704 /// flushing any PendingLoad items. This must be done before emitting
705 /// a store or any other node that may need to be ordered after any
706 /// prior load instructions.
708 SDValue SelectionDAGLowering::getRoot() {
709 if (PendingLoads.empty())
710 return DAG.getRoot();
712 if (PendingLoads.size() == 1) {
713 SDValue Root = PendingLoads[0];
715 PendingLoads.clear();
719 // Otherwise, we have to make a token factor node.
720 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
721 &PendingLoads[0], PendingLoads.size());
722 PendingLoads.clear();
727 /// getControlRoot - Similar to getRoot, but instead of flushing all the
728 /// PendingLoad items, flush all the PendingExports items. It is necessary
729 /// to do this before emitting a terminator instruction.
731 SDValue SelectionDAGLowering::getControlRoot() {
732 SDValue Root = DAG.getRoot();
734 if (PendingExports.empty())
737 // Turn all of the CopyToReg chains into one factored node.
738 if (Root.getOpcode() != ISD::EntryToken) {
739 unsigned i = 0, e = PendingExports.size();
740 for (; i != e; ++i) {
741 assert(PendingExports[i].getNode()->getNumOperands() > 1);
742 if (PendingExports[i].getNode()->getOperand(0) == Root)
743 break; // Don't add the root if we already indirectly depend on it.
747 PendingExports.push_back(Root);
750 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
752 PendingExports.size());
753 PendingExports.clear();
758 void SelectionDAGLowering::visit(Instruction &I) {
759 visit(I.getOpcode(), I);
762 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
763 // Note: this doesn't use InstVisitor, because it has to work with
764 // ConstantExpr's in addition to instructions.
766 default: assert(0 && "Unknown instruction type encountered!");
768 // Build the switch statement using the Instruction.def file.
769 #define HANDLE_INST(NUM, OPCODE, CLASS) \
770 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
771 #include "llvm/Instruction.def"
775 void SelectionDAGLowering::visitAdd(User &I) {
776 if (I.getType()->isFPOrFPVector())
777 visitBinary(I, ISD::FADD);
779 visitBinary(I, ISD::ADD);
782 void SelectionDAGLowering::visitMul(User &I) {
783 if (I.getType()->isFPOrFPVector())
784 visitBinary(I, ISD::FMUL);
786 visitBinary(I, ISD::MUL);
789 SDValue SelectionDAGLowering::getValue(const Value *V) {
790 SDValue &N = NodeMap[V];
791 if (N.getNode()) return N;
793 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
794 MVT VT = TLI.getValueType(V->getType(), true);
796 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
797 return N = DAG.getConstant(CI->getValue(), VT);
799 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
800 return N = DAG.getGlobalAddress(GV, VT);
802 if (isa<ConstantPointerNull>(C))
803 return N = DAG.getConstant(0, TLI.getPointerTy());
805 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
806 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
808 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
809 !V->getType()->isAggregateType())
810 return N = DAG.getNode(ISD::UNDEF, VT);
812 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
813 visit(CE->getOpcode(), *CE);
814 SDValue N1 = NodeMap[V];
815 assert(N1.getNode() && "visit didn't populate the ValueMap!");
819 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
820 SmallVector<SDValue, 4> Constants;
821 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
823 SDNode *Val = getValue(*OI).getNode();
824 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
825 Constants.push_back(SDValue(Val, i));
827 return DAG.getMergeValues(&Constants[0], Constants.size());
830 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
831 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
832 "Unknown struct or array constant!");
834 SmallVector<MVT, 4> ValueVTs;
835 ComputeValueVTs(TLI, C->getType(), ValueVTs);
836 unsigned NumElts = ValueVTs.size();
838 return SDValue(); // empty struct
839 SmallVector<SDValue, 4> Constants(NumElts);
840 for (unsigned i = 0; i != NumElts; ++i) {
841 MVT EltVT = ValueVTs[i];
842 if (isa<UndefValue>(C))
843 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
844 else if (EltVT.isFloatingPoint())
845 Constants[i] = DAG.getConstantFP(0, EltVT);
847 Constants[i] = DAG.getConstant(0, EltVT);
849 return DAG.getMergeValues(&Constants[0], NumElts);
852 const VectorType *VecTy = cast<VectorType>(V->getType());
853 unsigned NumElements = VecTy->getNumElements();
855 // Now that we know the number and type of the elements, get that number of
856 // elements into the Ops array based on what kind of constant it is.
857 SmallVector<SDValue, 16> Ops;
858 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
859 for (unsigned i = 0; i != NumElements; ++i)
860 Ops.push_back(getValue(CP->getOperand(i)));
862 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
863 "Unknown vector constant!");
864 MVT EltVT = TLI.getValueType(VecTy->getElementType());
867 if (isa<UndefValue>(C))
868 Op = DAG.getNode(ISD::UNDEF, EltVT);
869 else if (EltVT.isFloatingPoint())
870 Op = DAG.getConstantFP(0, EltVT);
872 Op = DAG.getConstant(0, EltVT);
873 Ops.assign(NumElements, Op);
876 // Create a BUILD_VECTOR node.
877 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
880 // If this is a static alloca, generate it as the frameindex instead of
882 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
883 DenseMap<const AllocaInst*, int>::iterator SI =
884 FuncInfo.StaticAllocaMap.find(AI);
885 if (SI != FuncInfo.StaticAllocaMap.end())
886 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
889 unsigned InReg = FuncInfo.ValueMap[V];
890 assert(InReg && "Value not in map!");
892 RegsForValue RFV(TLI, InReg, V->getType());
893 SDValue Chain = DAG.getEntryNode();
894 return RFV.getCopyFromRegs(DAG, Chain, NULL);
898 void SelectionDAGLowering::visitRet(ReturnInst &I) {
899 if (I.getNumOperands() == 0) {
900 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
904 SmallVector<SDValue, 8> NewValues;
905 NewValues.push_back(getControlRoot());
906 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
907 SDValue RetOp = getValue(I.getOperand(i));
909 SmallVector<MVT, 4> ValueVTs;
910 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
911 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
912 MVT VT = ValueVTs[j];
914 // FIXME: C calling convention requires the return type to be promoted to
915 // at least 32-bit. But this is not necessary for non-C calling conventions.
916 if (VT.isInteger()) {
917 MVT MinVT = TLI.getRegisterType(MVT::i32);
918 if (VT.bitsLT(MinVT))
922 unsigned NumParts = TLI.getNumRegisters(VT);
923 MVT PartVT = TLI.getRegisterType(VT);
924 SmallVector<SDValue, 4> Parts(NumParts);
925 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
927 const Function *F = I.getParent()->getParent();
928 if (F->paramHasAttr(0, ParamAttr::SExt))
929 ExtendKind = ISD::SIGN_EXTEND;
930 else if (F->paramHasAttr(0, ParamAttr::ZExt))
931 ExtendKind = ISD::ZERO_EXTEND;
933 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
934 &Parts[0], NumParts, PartVT, ExtendKind);
936 for (unsigned i = 0; i < NumParts; ++i) {
937 NewValues.push_back(Parts[i]);
938 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
942 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
943 &NewValues[0], NewValues.size()));
946 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
947 /// the current basic block, add it to ValueMap now so that we'll get a
949 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
950 // No need to export constants.
951 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
954 if (FuncInfo.isExportedInst(V)) return;
956 unsigned Reg = FuncInfo.InitializeRegForValue(V);
957 CopyValueToVirtualRegister(V, Reg);
960 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
961 const BasicBlock *FromBB) {
962 // The operands of the setcc have to be in this block. We don't know
963 // how to export them from some other block.
964 if (Instruction *VI = dyn_cast<Instruction>(V)) {
965 // Can export from current BB.
966 if (VI->getParent() == FromBB)
969 // Is already exported, noop.
970 return FuncInfo.isExportedInst(V);
973 // If this is an argument, we can export it if the BB is the entry block or
974 // if it is already exported.
975 if (isa<Argument>(V)) {
976 if (FromBB == &FromBB->getParent()->getEntryBlock())
979 // Otherwise, can only export this if it is already exported.
980 return FuncInfo.isExportedInst(V);
983 // Otherwise, constants can always be exported.
987 static bool InBlock(const Value *V, const BasicBlock *BB) {
988 if (const Instruction *I = dyn_cast<Instruction>(V))
989 return I->getParent() == BB;
993 /// FindMergedConditions - If Cond is an expression like
994 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
995 MachineBasicBlock *TBB,
996 MachineBasicBlock *FBB,
997 MachineBasicBlock *CurBB,
999 // If this node is not part of the or/and tree, emit it as a branch.
1000 Instruction *BOp = dyn_cast<Instruction>(Cond);
1002 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1003 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1004 BOp->getParent() != CurBB->getBasicBlock() ||
1005 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1006 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1007 const BasicBlock *BB = CurBB->getBasicBlock();
1009 // If the leaf of the tree is a comparison, merge the condition into
1011 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1012 // The operands of the cmp have to be in this block. We don't know
1013 // how to export them from some other block. If this is the first block
1014 // of the sequence, no exporting is needed.
1016 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1017 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1018 BOp = cast<Instruction>(Cond);
1019 ISD::CondCode Condition;
1020 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1021 switch (IC->getPredicate()) {
1022 default: assert(0 && "Unknown icmp predicate opcode!");
1023 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1024 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1025 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1026 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1027 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1028 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1029 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1030 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1031 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1032 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1034 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1035 ISD::CondCode FPC, FOC;
1036 switch (FC->getPredicate()) {
1037 default: assert(0 && "Unknown fcmp predicate opcode!");
1038 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1039 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1040 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1041 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1042 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1043 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1044 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1045 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1046 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1047 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1048 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1049 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1050 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1051 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1052 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1053 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1055 if (FiniteOnlyFPMath())
1060 Condition = ISD::SETEQ; // silence warning.
1061 assert(0 && "Unknown compare instruction");
1064 CaseBlock CB(Condition, BOp->getOperand(0),
1065 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1066 SwitchCases.push_back(CB);
1070 // Create a CaseBlock record representing this branch.
1071 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1072 NULL, TBB, FBB, CurBB);
1073 SwitchCases.push_back(CB);
1078 // Create TmpBB after CurBB.
1079 MachineFunction::iterator BBI = CurBB;
1080 MachineFunction &MF = DAG.getMachineFunction();
1081 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1082 CurBB->getParent()->insert(++BBI, TmpBB);
1084 if (Opc == Instruction::Or) {
1085 // Codegen X | Y as:
1093 // Emit the LHS condition.
1094 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1096 // Emit the RHS condition into TmpBB.
1097 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1099 assert(Opc == Instruction::And && "Unknown merge op!");
1100 // Codegen X & Y as:
1107 // This requires creation of TmpBB after CurBB.
1109 // Emit the LHS condition.
1110 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1112 // Emit the RHS condition into TmpBB.
1113 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1117 /// If the set of cases should be emitted as a series of branches, return true.
1118 /// If we should emit this as a bunch of and/or'd together conditions, return
1121 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1122 if (Cases.size() != 2) return true;
1124 // If this is two comparisons of the same values or'd or and'd together, they
1125 // will get folded into a single comparison, so don't emit two blocks.
1126 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1127 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1128 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1129 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1136 void SelectionDAGLowering::visitBr(BranchInst &I) {
1137 // Update machine-CFG edges.
1138 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1140 // Figure out which block is immediately after the current one.
1141 MachineBasicBlock *NextBlock = 0;
1142 MachineFunction::iterator BBI = CurMBB;
1143 if (++BBI != CurMBB->getParent()->end())
1146 if (I.isUnconditional()) {
1147 // Update machine-CFG edges.
1148 CurMBB->addSuccessor(Succ0MBB);
1150 // If this is not a fall-through branch, emit the branch.
1151 if (Succ0MBB != NextBlock)
1152 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1153 DAG.getBasicBlock(Succ0MBB)));
1157 // If this condition is one of the special cases we handle, do special stuff
1159 Value *CondVal = I.getCondition();
1160 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1162 // If this is a series of conditions that are or'd or and'd together, emit
1163 // this as a sequence of branches instead of setcc's with and/or operations.
1164 // For example, instead of something like:
1177 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1178 if (BOp->hasOneUse() &&
1179 (BOp->getOpcode() == Instruction::And ||
1180 BOp->getOpcode() == Instruction::Or)) {
1181 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1182 // If the compares in later blocks need to use values not currently
1183 // exported from this block, export them now. This block should always
1184 // be the first entry.
1185 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1187 // Allow some cases to be rejected.
1188 if (ShouldEmitAsBranches(SwitchCases)) {
1189 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1190 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1191 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1194 // Emit the branch for this block.
1195 visitSwitchCase(SwitchCases[0]);
1196 SwitchCases.erase(SwitchCases.begin());
1200 // Okay, we decided not to do this, remove any inserted MBB's and clear
1202 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1203 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1205 SwitchCases.clear();
1209 // Create a CaseBlock record representing this branch.
1210 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1211 NULL, Succ0MBB, Succ1MBB, CurMBB);
1212 // Use visitSwitchCase to actually insert the fast branch sequence for this
1214 visitSwitchCase(CB);
1217 /// visitSwitchCase - Emits the necessary code to represent a single node in
1218 /// the binary search tree resulting from lowering a switch instruction.
1219 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1221 SDValue CondLHS = getValue(CB.CmpLHS);
1223 // Build the setcc now.
1224 if (CB.CmpMHS == NULL) {
1225 // Fold "(X == true)" to X and "(X == false)" to !X to
1226 // handle common cases produced by branch lowering.
1227 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1229 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1230 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1231 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1233 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1235 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1237 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1238 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1240 SDValue CmpOp = getValue(CB.CmpMHS);
1241 MVT VT = CmpOp.getValueType();
1243 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1244 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1246 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1247 Cond = DAG.getSetCC(MVT::i1, SUB,
1248 DAG.getConstant(High-Low, VT), ISD::SETULE);
1252 // Update successor info
1253 CurMBB->addSuccessor(CB.TrueBB);
1254 CurMBB->addSuccessor(CB.FalseBB);
1256 // Set NextBlock to be the MBB immediately after the current one, if any.
1257 // This is used to avoid emitting unnecessary branches to the next block.
1258 MachineBasicBlock *NextBlock = 0;
1259 MachineFunction::iterator BBI = CurMBB;
1260 if (++BBI != CurMBB->getParent()->end())
1263 // If the lhs block is the next block, invert the condition so that we can
1264 // fall through to the lhs instead of the rhs block.
1265 if (CB.TrueBB == NextBlock) {
1266 std::swap(CB.TrueBB, CB.FalseBB);
1267 SDValue True = DAG.getConstant(1, Cond.getValueType());
1268 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1270 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1271 DAG.getBasicBlock(CB.TrueBB));
1273 // If the branch was constant folded, fix up the CFG.
1274 if (BrCond.getOpcode() == ISD::BR) {
1275 CurMBB->removeSuccessor(CB.FalseBB);
1276 DAG.setRoot(BrCond);
1278 // Otherwise, go ahead and insert the false branch.
1279 if (BrCond == getControlRoot())
1280 CurMBB->removeSuccessor(CB.TrueBB);
1282 if (CB.FalseBB == NextBlock)
1283 DAG.setRoot(BrCond);
1285 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1286 DAG.getBasicBlock(CB.FalseBB)));
1290 /// visitJumpTable - Emit JumpTable node in the current MBB
1291 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1292 // Emit the code for the jump table
1293 assert(JT.Reg != -1U && "Should lower JT Header first!");
1294 MVT PTy = TLI.getPointerTy();
1295 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1296 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1297 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1302 /// visitJumpTableHeader - This function emits necessary code to produce index
1303 /// in the JumpTable from switch case.
1304 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1305 JumpTableHeader &JTH) {
1306 // Subtract the lowest switch case value from the value being switched on
1307 // and conditional branch to default mbb if the result is greater than the
1308 // difference between smallest and largest cases.
1309 SDValue SwitchOp = getValue(JTH.SValue);
1310 MVT VT = SwitchOp.getValueType();
1311 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1312 DAG.getConstant(JTH.First, VT));
1314 // The SDNode we just created, which holds the value being switched on
1315 // minus the the smallest case value, needs to be copied to a virtual
1316 // register so it can be used as an index into the jump table in a
1317 // subsequent basic block. This value may be smaller or larger than the
1318 // target's pointer type, and therefore require extension or truncating.
1319 if (VT.bitsGT(TLI.getPointerTy()))
1320 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1322 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1324 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1325 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1326 JT.Reg = JumpTableReg;
1328 // Emit the range check for the jump table, and branch to the default
1329 // block for the switch statement if the value being switched on exceeds
1330 // the largest case in the switch.
1331 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1332 DAG.getConstant(JTH.Last-JTH.First,VT),
1335 // Set NextBlock to be the MBB immediately after the current one, if any.
1336 // This is used to avoid emitting unnecessary branches to the next block.
1337 MachineBasicBlock *NextBlock = 0;
1338 MachineFunction::iterator BBI = CurMBB;
1339 if (++BBI != CurMBB->getParent()->end())
1342 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1343 DAG.getBasicBlock(JT.Default));
1345 if (JT.MBB == NextBlock)
1346 DAG.setRoot(BrCond);
1348 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1349 DAG.getBasicBlock(JT.MBB)));
1354 /// visitBitTestHeader - This function emits necessary code to produce value
1355 /// suitable for "bit tests"
1356 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1357 // Subtract the minimum value
1358 SDValue SwitchOp = getValue(B.SValue);
1359 MVT VT = SwitchOp.getValueType();
1360 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1361 DAG.getConstant(B.First, VT));
1364 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1365 DAG.getConstant(B.Range, VT),
1369 if (VT.bitsGT(TLI.getShiftAmountTy()))
1370 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1372 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1374 // Make desired shift
1375 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1376 DAG.getConstant(1, TLI.getPointerTy()),
1379 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1380 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1383 // Set NextBlock to be the MBB immediately after the current one, if any.
1384 // This is used to avoid emitting unnecessary branches to the next block.
1385 MachineBasicBlock *NextBlock = 0;
1386 MachineFunction::iterator BBI = CurMBB;
1387 if (++BBI != CurMBB->getParent()->end())
1390 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1392 CurMBB->addSuccessor(B.Default);
1393 CurMBB->addSuccessor(MBB);
1395 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1396 DAG.getBasicBlock(B.Default));
1398 if (MBB == NextBlock)
1399 DAG.setRoot(BrRange);
1401 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1402 DAG.getBasicBlock(MBB)));
1407 /// visitBitTestCase - this function produces one "bit test"
1408 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1411 // Emit bit tests and jumps
1412 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1413 TLI.getPointerTy());
1415 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1416 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1417 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1418 DAG.getConstant(0, TLI.getPointerTy()),
1421 CurMBB->addSuccessor(B.TargetBB);
1422 CurMBB->addSuccessor(NextMBB);
1424 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1425 AndCmp, DAG.getBasicBlock(B.TargetBB));
1427 // Set NextBlock to be the MBB immediately after the current one, if any.
1428 // This is used to avoid emitting unnecessary branches to the next block.
1429 MachineBasicBlock *NextBlock = 0;
1430 MachineFunction::iterator BBI = CurMBB;
1431 if (++BBI != CurMBB->getParent()->end())
1434 if (NextMBB == NextBlock)
1437 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1438 DAG.getBasicBlock(NextMBB)));
1443 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1444 // Retrieve successors.
1445 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1446 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1448 if (isa<InlineAsm>(I.getCalledValue()))
1451 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1453 // If the value of the invoke is used outside of its defining block, make it
1454 // available as a virtual register.
1455 if (!I.use_empty()) {
1456 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1457 if (VMI != FuncInfo.ValueMap.end())
1458 CopyValueToVirtualRegister(&I, VMI->second);
1461 // Update successor info
1462 CurMBB->addSuccessor(Return);
1463 CurMBB->addSuccessor(LandingPad);
1465 // Drop into normal successor.
1466 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1467 DAG.getBasicBlock(Return)));
1470 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1473 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1474 /// small case ranges).
1475 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1476 CaseRecVector& WorkList,
1478 MachineBasicBlock* Default) {
1479 Case& BackCase = *(CR.Range.second-1);
1481 // Size is the number of Cases represented by this range.
1482 unsigned Size = CR.Range.second - CR.Range.first;
1486 // Get the MachineFunction which holds the current MBB. This is used when
1487 // inserting any additional MBBs necessary to represent the switch.
1488 MachineFunction *CurMF = CurMBB->getParent();
1490 // Figure out which block is immediately after the current one.
1491 MachineBasicBlock *NextBlock = 0;
1492 MachineFunction::iterator BBI = CR.CaseBB;
1494 if (++BBI != CurMBB->getParent()->end())
1497 // TODO: If any two of the cases has the same destination, and if one value
1498 // is the same as the other, but has one bit unset that the other has set,
1499 // use bit manipulation to do two compares at once. For example:
1500 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1502 // Rearrange the case blocks so that the last one falls through if possible.
1503 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1504 // The last case block won't fall through into 'NextBlock' if we emit the
1505 // branches in this order. See if rearranging a case value would help.
1506 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1507 if (I->BB == NextBlock) {
1508 std::swap(*I, BackCase);
1514 // Create a CaseBlock record representing a conditional branch to
1515 // the Case's target mbb if the value being switched on SV is equal
1517 MachineBasicBlock *CurBlock = CR.CaseBB;
1518 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1519 MachineBasicBlock *FallThrough;
1521 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1522 CurMF->insert(BBI, FallThrough);
1524 // If the last case doesn't match, go to the default block.
1525 FallThrough = Default;
1528 Value *RHS, *LHS, *MHS;
1530 if (I->High == I->Low) {
1531 // This is just small small case range :) containing exactly 1 case
1533 LHS = SV; RHS = I->High; MHS = NULL;
1536 LHS = I->Low; MHS = SV; RHS = I->High;
1538 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1540 // If emitting the first comparison, just call visitSwitchCase to emit the
1541 // code into the current block. Otherwise, push the CaseBlock onto the
1542 // vector to be later processed by SDISel, and insert the node's MBB
1543 // before the next MBB.
1544 if (CurBlock == CurMBB)
1545 visitSwitchCase(CB);
1547 SwitchCases.push_back(CB);
1549 CurBlock = FallThrough;
1555 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1556 return !DisableJumpTables &&
1557 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1558 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1561 /// handleJTSwitchCase - Emit jumptable for current switch case range
1562 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1563 CaseRecVector& WorkList,
1565 MachineBasicBlock* Default) {
1566 Case& FrontCase = *CR.Range.first;
1567 Case& BackCase = *(CR.Range.second-1);
1569 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1570 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1573 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1577 if (!areJTsAllowed(TLI) || TSize <= 3)
1580 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1584 DOUT << "Lowering jump table\n"
1585 << "First entry: " << First << ". Last entry: " << Last << "\n"
1586 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1588 // Get the MachineFunction which holds the current MBB. This is used when
1589 // inserting any additional MBBs necessary to represent the switch.
1590 MachineFunction *CurMF = CurMBB->getParent();
1592 // Figure out which block is immediately after the current one.
1593 MachineBasicBlock *NextBlock = 0;
1594 MachineFunction::iterator BBI = CR.CaseBB;
1596 if (++BBI != CurMBB->getParent()->end())
1599 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1601 // Create a new basic block to hold the code for loading the address
1602 // of the jump table, and jumping to it. Update successor information;
1603 // we will either branch to the default case for the switch, or the jump
1605 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1606 CurMF->insert(BBI, JumpTableBB);
1607 CR.CaseBB->addSuccessor(Default);
1608 CR.CaseBB->addSuccessor(JumpTableBB);
1610 // Build a vector of destination BBs, corresponding to each target
1611 // of the jump table. If the value of the jump table slot corresponds to
1612 // a case statement, push the case's BB onto the vector, otherwise, push
1614 std::vector<MachineBasicBlock*> DestBBs;
1615 int64_t TEI = First;
1616 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1617 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1618 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1620 if ((Low <= TEI) && (TEI <= High)) {
1621 DestBBs.push_back(I->BB);
1625 DestBBs.push_back(Default);
1629 // Update successor info. Add one edge to each unique successor.
1630 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1631 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1632 E = DestBBs.end(); I != E; ++I) {
1633 if (!SuccsHandled[(*I)->getNumber()]) {
1634 SuccsHandled[(*I)->getNumber()] = true;
1635 JumpTableBB->addSuccessor(*I);
1639 // Create a jump table index for this jump table, or return an existing
1641 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1643 // Set the jump table information so that we can codegen it as a second
1644 // MachineBasicBlock
1645 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1646 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1647 if (CR.CaseBB == CurMBB)
1648 visitJumpTableHeader(JT, JTH);
1650 JTCases.push_back(JumpTableBlock(JTH, JT));
1655 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1657 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1658 CaseRecVector& WorkList,
1660 MachineBasicBlock* Default) {
1661 // Get the MachineFunction which holds the current MBB. This is used when
1662 // inserting any additional MBBs necessary to represent the switch.
1663 MachineFunction *CurMF = CurMBB->getParent();
1665 // Figure out which block is immediately after the current one.
1666 MachineBasicBlock *NextBlock = 0;
1667 MachineFunction::iterator BBI = CR.CaseBB;
1669 if (++BBI != CurMBB->getParent()->end())
1672 Case& FrontCase = *CR.Range.first;
1673 Case& BackCase = *(CR.Range.second-1);
1674 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1676 // Size is the number of Cases represented by this range.
1677 unsigned Size = CR.Range.second - CR.Range.first;
1679 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1680 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1682 CaseItr Pivot = CR.Range.first + Size/2;
1684 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1685 // (heuristically) allow us to emit JumpTable's later.
1687 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1691 uint64_t LSize = FrontCase.size();
1692 uint64_t RSize = TSize-LSize;
1693 DOUT << "Selecting best pivot: \n"
1694 << "First: " << First << ", Last: " << Last <<"\n"
1695 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1696 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1698 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1699 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1700 assert((RBegin-LEnd>=1) && "Invalid case distance");
1701 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1702 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1703 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1704 // Should always split in some non-trivial place
1706 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1707 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1708 << "Metric: " << Metric << "\n";
1709 if (FMetric < Metric) {
1712 DOUT << "Current metric set to: " << FMetric << "\n";
1718 if (areJTsAllowed(TLI)) {
1719 // If our case is dense we *really* should handle it earlier!
1720 assert((FMetric > 0) && "Should handle dense range earlier!");
1722 Pivot = CR.Range.first + Size/2;
1725 CaseRange LHSR(CR.Range.first, Pivot);
1726 CaseRange RHSR(Pivot, CR.Range.second);
1727 Constant *C = Pivot->Low;
1728 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1730 // We know that we branch to the LHS if the Value being switched on is
1731 // less than the Pivot value, C. We use this to optimize our binary
1732 // tree a bit, by recognizing that if SV is greater than or equal to the
1733 // LHS's Case Value, and that Case Value is exactly one less than the
1734 // Pivot's Value, then we can branch directly to the LHS's Target,
1735 // rather than creating a leaf node for it.
1736 if ((LHSR.second - LHSR.first) == 1 &&
1737 LHSR.first->High == CR.GE &&
1738 cast<ConstantInt>(C)->getSExtValue() ==
1739 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1740 TrueBB = LHSR.first->BB;
1742 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1743 CurMF->insert(BBI, TrueBB);
1744 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1747 // Similar to the optimization above, if the Value being switched on is
1748 // known to be less than the Constant CR.LT, and the current Case Value
1749 // is CR.LT - 1, then we can branch directly to the target block for
1750 // the current Case Value, rather than emitting a RHS leaf node for it.
1751 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1752 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1753 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1754 FalseBB = RHSR.first->BB;
1756 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1757 CurMF->insert(BBI, FalseBB);
1758 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1761 // Create a CaseBlock record representing a conditional branch to
1762 // the LHS node if the value being switched on SV is less than C.
1763 // Otherwise, branch to LHS.
1764 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1766 if (CR.CaseBB == CurMBB)
1767 visitSwitchCase(CB);
1769 SwitchCases.push_back(CB);
1774 /// handleBitTestsSwitchCase - if current case range has few destination and
1775 /// range span less, than machine word bitwidth, encode case range into series
1776 /// of masks and emit bit tests with these masks.
1777 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1778 CaseRecVector& WorkList,
1780 MachineBasicBlock* Default){
1781 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1783 Case& FrontCase = *CR.Range.first;
1784 Case& BackCase = *(CR.Range.second-1);
1786 // Get the MachineFunction which holds the current MBB. This is used when
1787 // inserting any additional MBBs necessary to represent the switch.
1788 MachineFunction *CurMF = CurMBB->getParent();
1790 unsigned numCmps = 0;
1791 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1793 // Single case counts one, case range - two.
1794 if (I->Low == I->High)
1800 // Count unique destinations
1801 SmallSet<MachineBasicBlock*, 4> Dests;
1802 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1803 Dests.insert(I->BB);
1804 if (Dests.size() > 3)
1805 // Don't bother the code below, if there are too much unique destinations
1808 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1809 << "Total number of comparisons: " << numCmps << "\n";
1811 // Compute span of values.
1812 Constant* minValue = FrontCase.Low;
1813 Constant* maxValue = BackCase.High;
1814 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1815 cast<ConstantInt>(minValue)->getSExtValue();
1816 DOUT << "Compare range: " << range << "\n"
1817 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1818 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1820 if (range>=IntPtrBits ||
1821 (!(Dests.size() == 1 && numCmps >= 3) &&
1822 !(Dests.size() == 2 && numCmps >= 5) &&
1823 !(Dests.size() >= 3 && numCmps >= 6)))
1826 DOUT << "Emitting bit tests\n";
1827 int64_t lowBound = 0;
1829 // Optimize the case where all the case values fit in a
1830 // word without having to subtract minValue. In this case,
1831 // we can optimize away the subtraction.
1832 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1833 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1834 range = cast<ConstantInt>(maxValue)->getSExtValue();
1836 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1839 CaseBitsVector CasesBits;
1840 unsigned i, count = 0;
1842 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1843 MachineBasicBlock* Dest = I->BB;
1844 for (i = 0; i < count; ++i)
1845 if (Dest == CasesBits[i].BB)
1849 assert((count < 3) && "Too much destinations to test!");
1850 CasesBits.push_back(CaseBits(0, Dest, 0));
1854 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1855 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1857 for (uint64_t j = lo; j <= hi; j++) {
1858 CasesBits[i].Mask |= 1ULL << j;
1859 CasesBits[i].Bits++;
1863 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1867 // Figure out which block is immediately after the current one.
1868 MachineFunction::iterator BBI = CR.CaseBB;
1871 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1874 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1875 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1876 << ", BB: " << CasesBits[i].BB << "\n";
1878 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1879 CurMF->insert(BBI, CaseBB);
1880 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1885 BitTestBlock BTB(lowBound, range, SV,
1886 -1U, (CR.CaseBB == CurMBB),
1887 CR.CaseBB, Default, BTC);
1889 if (CR.CaseBB == CurMBB)
1890 visitBitTestHeader(BTB);
1892 BitTestCases.push_back(BTB);
1898 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1899 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1900 const SwitchInst& SI) {
1901 unsigned numCmps = 0;
1903 // Start with "simple" cases
1904 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1905 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1906 Cases.push_back(Case(SI.getSuccessorValue(i),
1907 SI.getSuccessorValue(i),
1910 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1912 // Merge case into clusters
1913 if (Cases.size()>=2)
1914 // Must recompute end() each iteration because it may be
1915 // invalidated by erase if we hold on to it
1916 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1917 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1918 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1919 MachineBasicBlock* nextBB = J->BB;
1920 MachineBasicBlock* currentBB = I->BB;
1922 // If the two neighboring cases go to the same destination, merge them
1923 // into a single case.
1924 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1932 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1933 if (I->Low != I->High)
1934 // A range counts double, since it requires two compares.
1941 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1942 // Figure out which block is immediately after the current one.
1943 MachineBasicBlock *NextBlock = 0;
1944 MachineFunction::iterator BBI = CurMBB;
1946 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1948 // If there is only the default destination, branch to it if it is not the
1949 // next basic block. Otherwise, just fall through.
1950 if (SI.getNumOperands() == 2) {
1951 // Update machine-CFG edges.
1953 // If this is not a fall-through branch, emit the branch.
1954 CurMBB->addSuccessor(Default);
1955 if (Default != NextBlock)
1956 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1957 DAG.getBasicBlock(Default)));
1962 // If there are any non-default case statements, create a vector of Cases
1963 // representing each one, and sort the vector so that we can efficiently
1964 // create a binary search tree from them.
1966 unsigned numCmps = Clusterify(Cases, SI);
1967 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1968 << ". Total compares: " << numCmps << "\n";
1970 // Get the Value to be switched on and default basic blocks, which will be
1971 // inserted into CaseBlock records, representing basic blocks in the binary
1973 Value *SV = SI.getOperand(0);
1975 // Push the initial CaseRec onto the worklist
1976 CaseRecVector WorkList;
1977 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1979 while (!WorkList.empty()) {
1980 // Grab a record representing a case range to process off the worklist
1981 CaseRec CR = WorkList.back();
1982 WorkList.pop_back();
1984 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1987 // If the range has few cases (two or less) emit a series of specific
1989 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1992 // If the switch has more than 5 blocks, and at least 40% dense, and the
1993 // target supports indirect branches, then emit a jump table rather than
1994 // lowering the switch to a binary tree of conditional branches.
1995 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1998 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1999 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2000 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2005 void SelectionDAGLowering::visitSub(User &I) {
2006 // -0.0 - X --> fneg
2007 const Type *Ty = I.getType();
2008 if (isa<VectorType>(Ty)) {
2009 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2010 const VectorType *DestTy = cast<VectorType>(I.getType());
2011 const Type *ElTy = DestTy->getElementType();
2012 if (ElTy->isFloatingPoint()) {
2013 unsigned VL = DestTy->getNumElements();
2014 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2015 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2017 SDValue Op2 = getValue(I.getOperand(1));
2018 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2024 if (Ty->isFloatingPoint()) {
2025 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2026 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2027 SDValue Op2 = getValue(I.getOperand(1));
2028 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2033 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2036 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2037 SDValue Op1 = getValue(I.getOperand(0));
2038 SDValue Op2 = getValue(I.getOperand(1));
2040 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2043 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2044 SDValue Op1 = getValue(I.getOperand(0));
2045 SDValue Op2 = getValue(I.getOperand(1));
2046 if (!isa<VectorType>(I.getType())) {
2047 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2048 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2049 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2050 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2053 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2056 void SelectionDAGLowering::visitICmp(User &I) {
2057 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2058 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2059 predicate = IC->getPredicate();
2060 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2061 predicate = ICmpInst::Predicate(IC->getPredicate());
2062 SDValue Op1 = getValue(I.getOperand(0));
2063 SDValue Op2 = getValue(I.getOperand(1));
2064 ISD::CondCode Opcode;
2065 switch (predicate) {
2066 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2067 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2068 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2069 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2070 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2071 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2072 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2073 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2074 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2075 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2077 assert(!"Invalid ICmp predicate value");
2078 Opcode = ISD::SETEQ;
2081 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2084 void SelectionDAGLowering::visitFCmp(User &I) {
2085 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2086 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2087 predicate = FC->getPredicate();
2088 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2089 predicate = FCmpInst::Predicate(FC->getPredicate());
2090 SDValue Op1 = getValue(I.getOperand(0));
2091 SDValue Op2 = getValue(I.getOperand(1));
2092 ISD::CondCode Condition, FOC, FPC;
2093 switch (predicate) {
2094 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2095 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2096 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2097 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2098 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2099 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2100 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2101 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2102 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2103 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2104 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2105 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2106 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2107 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2108 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2109 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2111 assert(!"Invalid FCmp predicate value");
2112 FOC = FPC = ISD::SETFALSE;
2115 if (FiniteOnlyFPMath())
2119 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2122 void SelectionDAGLowering::visitVICmp(User &I) {
2123 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2124 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2125 predicate = IC->getPredicate();
2126 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2127 predicate = ICmpInst::Predicate(IC->getPredicate());
2128 SDValue Op1 = getValue(I.getOperand(0));
2129 SDValue Op2 = getValue(I.getOperand(1));
2130 ISD::CondCode Opcode;
2131 switch (predicate) {
2132 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2133 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2134 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2135 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2136 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2137 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2138 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2139 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2140 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2141 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2143 assert(!"Invalid ICmp predicate value");
2144 Opcode = ISD::SETEQ;
2147 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2150 void SelectionDAGLowering::visitVFCmp(User &I) {
2151 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2152 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2153 predicate = FC->getPredicate();
2154 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2155 predicate = FCmpInst::Predicate(FC->getPredicate());
2156 SDValue Op1 = getValue(I.getOperand(0));
2157 SDValue Op2 = getValue(I.getOperand(1));
2158 ISD::CondCode Condition, FOC, FPC;
2159 switch (predicate) {
2160 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2161 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2162 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2163 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2164 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2165 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2166 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2167 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2168 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2169 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2170 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2171 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2172 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2173 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2174 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2175 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2177 assert(!"Invalid VFCmp predicate value");
2178 FOC = FPC = ISD::SETFALSE;
2181 if (FiniteOnlyFPMath())
2186 MVT DestVT = TLI.getValueType(I.getType());
2188 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2191 void SelectionDAGLowering::visitSelect(User &I) {
2192 SDValue Cond = getValue(I.getOperand(0));
2193 SDValue TrueVal = getValue(I.getOperand(1));
2194 SDValue FalseVal = getValue(I.getOperand(2));
2195 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2196 TrueVal, FalseVal));
2200 void SelectionDAGLowering::visitTrunc(User &I) {
2201 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2202 SDValue N = getValue(I.getOperand(0));
2203 MVT DestVT = TLI.getValueType(I.getType());
2204 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2207 void SelectionDAGLowering::visitZExt(User &I) {
2208 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2209 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2210 SDValue N = getValue(I.getOperand(0));
2211 MVT DestVT = TLI.getValueType(I.getType());
2212 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2215 void SelectionDAGLowering::visitSExt(User &I) {
2216 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2217 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2218 SDValue N = getValue(I.getOperand(0));
2219 MVT DestVT = TLI.getValueType(I.getType());
2220 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2223 void SelectionDAGLowering::visitFPTrunc(User &I) {
2224 // FPTrunc is never a no-op cast, no need to check
2225 SDValue N = getValue(I.getOperand(0));
2226 MVT DestVT = TLI.getValueType(I.getType());
2227 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2230 void SelectionDAGLowering::visitFPExt(User &I){
2231 // FPTrunc is never a no-op cast, no need to check
2232 SDValue N = getValue(I.getOperand(0));
2233 MVT DestVT = TLI.getValueType(I.getType());
2234 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2237 void SelectionDAGLowering::visitFPToUI(User &I) {
2238 // FPToUI is never a no-op cast, no need to check
2239 SDValue N = getValue(I.getOperand(0));
2240 MVT DestVT = TLI.getValueType(I.getType());
2241 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2244 void SelectionDAGLowering::visitFPToSI(User &I) {
2245 // FPToSI is never a no-op cast, no need to check
2246 SDValue N = getValue(I.getOperand(0));
2247 MVT DestVT = TLI.getValueType(I.getType());
2248 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2251 void SelectionDAGLowering::visitUIToFP(User &I) {
2252 // UIToFP is never a no-op cast, no need to check
2253 SDValue N = getValue(I.getOperand(0));
2254 MVT DestVT = TLI.getValueType(I.getType());
2255 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2258 void SelectionDAGLowering::visitSIToFP(User &I){
2259 // UIToFP is never a no-op cast, no need to check
2260 SDValue N = getValue(I.getOperand(0));
2261 MVT DestVT = TLI.getValueType(I.getType());
2262 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2265 void SelectionDAGLowering::visitPtrToInt(User &I) {
2266 // What to do depends on the size of the integer and the size of the pointer.
2267 // We can either truncate, zero extend, or no-op, accordingly.
2268 SDValue N = getValue(I.getOperand(0));
2269 MVT SrcVT = N.getValueType();
2270 MVT DestVT = TLI.getValueType(I.getType());
2272 if (DestVT.bitsLT(SrcVT))
2273 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2275 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2276 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2277 setValue(&I, Result);
2280 void SelectionDAGLowering::visitIntToPtr(User &I) {
2281 // What to do depends on the size of the integer and the size of the pointer.
2282 // We can either truncate, zero extend, or no-op, accordingly.
2283 SDValue N = getValue(I.getOperand(0));
2284 MVT SrcVT = N.getValueType();
2285 MVT DestVT = TLI.getValueType(I.getType());
2286 if (DestVT.bitsLT(SrcVT))
2287 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2289 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2290 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2293 void SelectionDAGLowering::visitBitCast(User &I) {
2294 SDValue N = getValue(I.getOperand(0));
2295 MVT DestVT = TLI.getValueType(I.getType());
2297 // BitCast assures us that source and destination are the same size so this
2298 // is either a BIT_CONVERT or a no-op.
2299 if (DestVT != N.getValueType())
2300 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2302 setValue(&I, N); // noop cast.
2305 void SelectionDAGLowering::visitInsertElement(User &I) {
2306 SDValue InVec = getValue(I.getOperand(0));
2307 SDValue InVal = getValue(I.getOperand(1));
2308 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2309 getValue(I.getOperand(2)));
2311 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2312 TLI.getValueType(I.getType()),
2313 InVec, InVal, InIdx));
2316 void SelectionDAGLowering::visitExtractElement(User &I) {
2317 SDValue InVec = getValue(I.getOperand(0));
2318 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2319 getValue(I.getOperand(1)));
2320 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2321 TLI.getValueType(I.getType()), InVec, InIdx));
2324 void SelectionDAGLowering::visitShuffleVector(User &I) {
2325 SDValue V1 = getValue(I.getOperand(0));
2326 SDValue V2 = getValue(I.getOperand(1));
2327 SDValue Mask = getValue(I.getOperand(2));
2329 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2330 TLI.getValueType(I.getType()),
2334 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2335 const Value *Op0 = I.getOperand(0);
2336 const Value *Op1 = I.getOperand(1);
2337 const Type *AggTy = I.getType();
2338 const Type *ValTy = Op1->getType();
2339 bool IntoUndef = isa<UndefValue>(Op0);
2340 bool FromUndef = isa<UndefValue>(Op1);
2342 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2343 I.idx_begin(), I.idx_end());
2345 SmallVector<MVT, 4> AggValueVTs;
2346 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2347 SmallVector<MVT, 4> ValValueVTs;
2348 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2350 unsigned NumAggValues = AggValueVTs.size();
2351 unsigned NumValValues = ValValueVTs.size();
2352 SmallVector<SDValue, 4> Values(NumAggValues);
2354 SDValue Agg = getValue(Op0);
2355 SDValue Val = getValue(Op1);
2357 // Copy the beginning value(s) from the original aggregate.
2358 for (; i != LinearIndex; ++i)
2359 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2360 SDValue(Agg.getNode(), Agg.getResNo() + i);
2361 // Copy values from the inserted value(s).
2362 for (; i != LinearIndex + NumValValues; ++i)
2363 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2364 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2365 // Copy remaining value(s) from the original aggregate.
2366 for (; i != NumAggValues; ++i)
2367 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2368 SDValue(Agg.getNode(), Agg.getResNo() + i);
2370 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2371 &Values[0], NumAggValues));
2374 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2375 const Value *Op0 = I.getOperand(0);
2376 const Type *AggTy = Op0->getType();
2377 const Type *ValTy = I.getType();
2378 bool OutOfUndef = isa<UndefValue>(Op0);
2380 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2381 I.idx_begin(), I.idx_end());
2383 SmallVector<MVT, 4> ValValueVTs;
2384 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2386 unsigned NumValValues = ValValueVTs.size();
2387 SmallVector<SDValue, 4> Values(NumValValues);
2389 SDValue Agg = getValue(Op0);
2390 // Copy out the selected value(s).
2391 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2392 Values[i - LinearIndex] =
2393 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2394 SDValue(Agg.getNode(), Agg.getResNo() + i);
2396 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2397 &Values[0], NumValValues));
2401 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2402 SDValue N = getValue(I.getOperand(0));
2403 const Type *Ty = I.getOperand(0)->getType();
2405 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2408 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2409 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2412 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2413 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2414 DAG.getIntPtrConstant(Offset));
2416 Ty = StTy->getElementType(Field);
2418 Ty = cast<SequentialType>(Ty)->getElementType();
2420 // If this is a constant subscript, handle it quickly.
2421 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2422 if (CI->getZExtValue() == 0) continue;
2424 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2425 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2426 DAG.getIntPtrConstant(Offs));
2430 // N = N + Idx * ElementSize;
2431 uint64_t ElementSize = TD->getABITypeSize(Ty);
2432 SDValue IdxN = getValue(Idx);
2434 // If the index is smaller or larger than intptr_t, truncate or extend
2436 if (IdxN.getValueType().bitsLT(N.getValueType()))
2437 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2438 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2439 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2441 // If this is a multiply by a power of two, turn it into a shl
2442 // immediately. This is a very common case.
2443 if (ElementSize != 1) {
2444 if (isPowerOf2_64(ElementSize)) {
2445 unsigned Amt = Log2_64(ElementSize);
2446 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2447 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2449 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2450 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2454 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2460 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2461 // If this is a fixed sized alloca in the entry block of the function,
2462 // allocate it statically on the stack.
2463 if (FuncInfo.StaticAllocaMap.count(&I))
2464 return; // getValue will auto-populate this.
2466 const Type *Ty = I.getAllocatedType();
2467 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2469 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2472 SDValue AllocSize = getValue(I.getArraySize());
2473 MVT IntPtr = TLI.getPointerTy();
2474 if (IntPtr.bitsLT(AllocSize.getValueType()))
2475 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2476 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2477 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2479 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2480 DAG.getIntPtrConstant(TySize));
2482 // Handle alignment. If the requested alignment is less than or equal to
2483 // the stack alignment, ignore it. If the size is greater than or equal to
2484 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2485 unsigned StackAlign =
2486 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2487 if (Align <= StackAlign)
2490 // Round the size of the allocation up to the stack alignment size
2491 // by add SA-1 to the size.
2492 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2493 DAG.getIntPtrConstant(StackAlign-1));
2494 // Mask out the low bits for alignment purposes.
2495 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2496 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2498 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2499 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2501 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2503 DAG.setRoot(DSA.getValue(1));
2505 // Inform the Frame Information that we have just allocated a variable-sized
2507 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2510 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2511 const Value *SV = I.getOperand(0);
2512 SDValue Ptr = getValue(SV);
2514 const Type *Ty = I.getType();
2515 bool isVolatile = I.isVolatile();
2516 unsigned Alignment = I.getAlignment();
2518 SmallVector<MVT, 4> ValueVTs;
2519 SmallVector<uint64_t, 4> Offsets;
2520 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2521 unsigned NumValues = ValueVTs.size();
2526 bool ConstantMemory = false;
2528 // Serialize volatile loads with other side effects.
2530 else if (AA->pointsToConstantMemory(SV)) {
2531 // Do not serialize (non-volatile) loads of constant memory with anything.
2532 Root = DAG.getEntryNode();
2533 ConstantMemory = true;
2535 // Do not serialize non-volatile loads against each other.
2536 Root = DAG.getRoot();
2539 SmallVector<SDValue, 4> Values(NumValues);
2540 SmallVector<SDValue, 4> Chains(NumValues);
2541 MVT PtrVT = Ptr.getValueType();
2542 for (unsigned i = 0; i != NumValues; ++i) {
2543 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2544 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2545 DAG.getConstant(Offsets[i], PtrVT)),
2547 isVolatile, Alignment);
2549 Chains[i] = L.getValue(1);
2552 if (!ConstantMemory) {
2553 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2554 &Chains[0], NumValues);
2558 PendingLoads.push_back(Chain);
2561 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2562 &Values[0], NumValues));
2566 void SelectionDAGLowering::visitStore(StoreInst &I) {
2567 Value *SrcV = I.getOperand(0);
2568 Value *PtrV = I.getOperand(1);
2570 SmallVector<MVT, 4> ValueVTs;
2571 SmallVector<uint64_t, 4> Offsets;
2572 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2573 unsigned NumValues = ValueVTs.size();
2577 // Get the lowered operands. Note that we do this after
2578 // checking if NumResults is zero, because with zero results
2579 // the operands won't have values in the map.
2580 SDValue Src = getValue(SrcV);
2581 SDValue Ptr = getValue(PtrV);
2583 SDValue Root = getRoot();
2584 SmallVector<SDValue, 4> Chains(NumValues);
2585 MVT PtrVT = Ptr.getValueType();
2586 bool isVolatile = I.isVolatile();
2587 unsigned Alignment = I.getAlignment();
2588 for (unsigned i = 0; i != NumValues; ++i)
2589 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2590 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2591 DAG.getConstant(Offsets[i], PtrVT)),
2593 isVolatile, Alignment);
2595 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2598 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2600 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2601 unsigned Intrinsic) {
2602 bool HasChain = !I.doesNotAccessMemory();
2603 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2605 // Build the operand list.
2606 SmallVector<SDValue, 8> Ops;
2607 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2609 // We don't need to serialize loads against other loads.
2610 Ops.push_back(DAG.getRoot());
2612 Ops.push_back(getRoot());
2616 // Add the intrinsic ID as an integer operand.
2617 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2619 // Add all operands of the call to the operand list.
2620 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2621 SDValue Op = getValue(I.getOperand(i));
2622 assert(TLI.isTypeLegal(Op.getValueType()) &&
2623 "Intrinsic uses a non-legal type?");
2627 std::vector<MVT> VTs;
2628 if (I.getType() != Type::VoidTy) {
2629 MVT VT = TLI.getValueType(I.getType());
2630 if (VT.isVector()) {
2631 const VectorType *DestTy = cast<VectorType>(I.getType());
2632 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2634 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2635 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2638 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2642 VTs.push_back(MVT::Other);
2644 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2649 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2650 &Ops[0], Ops.size());
2651 else if (I.getType() != Type::VoidTy)
2652 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2653 &Ops[0], Ops.size());
2655 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2656 &Ops[0], Ops.size());
2659 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2661 PendingLoads.push_back(Chain);
2665 if (I.getType() != Type::VoidTy) {
2666 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2667 MVT VT = TLI.getValueType(PTy);
2668 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2670 setValue(&I, Result);
2674 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2675 static GlobalVariable *ExtractTypeInfo(Value *V) {
2676 V = V->stripPointerCasts();
2677 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2678 assert ((GV || isa<ConstantPointerNull>(V)) &&
2679 "TypeInfo must be a global variable or NULL");
2685 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2686 /// call, and add them to the specified machine basic block.
2687 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2688 MachineBasicBlock *MBB) {
2689 // Inform the MachineModuleInfo of the personality for this landing pad.
2690 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2691 assert(CE->getOpcode() == Instruction::BitCast &&
2692 isa<Function>(CE->getOperand(0)) &&
2693 "Personality should be a function");
2694 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2696 // Gather all the type infos for this landing pad and pass them along to
2697 // MachineModuleInfo.
2698 std::vector<GlobalVariable *> TyInfo;
2699 unsigned N = I.getNumOperands();
2701 for (unsigned i = N - 1; i > 2; --i) {
2702 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2703 unsigned FilterLength = CI->getZExtValue();
2704 unsigned FirstCatch = i + FilterLength + !FilterLength;
2705 assert (FirstCatch <= N && "Invalid filter length");
2707 if (FirstCatch < N) {
2708 TyInfo.reserve(N - FirstCatch);
2709 for (unsigned j = FirstCatch; j < N; ++j)
2710 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2711 MMI->addCatchTypeInfo(MBB, TyInfo);
2715 if (!FilterLength) {
2717 MMI->addCleanup(MBB);
2720 TyInfo.reserve(FilterLength - 1);
2721 for (unsigned j = i + 1; j < FirstCatch; ++j)
2722 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2723 MMI->addFilterTypeInfo(MBB, TyInfo);
2732 TyInfo.reserve(N - 3);
2733 for (unsigned j = 3; j < N; ++j)
2734 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2735 MMI->addCatchTypeInfo(MBB, TyInfo);
2741 /// Inlined utility function to implement binary input atomic intrinsics for
2742 /// visitIntrinsicCall: I is a call instruction
2743 /// Op is the associated NodeType for I
2745 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2746 SDValue Root = getRoot();
2747 SDValue L = DAG.getAtomic(Op, Root,
2748 getValue(I.getOperand(1)),
2749 getValue(I.getOperand(2)),
2752 DAG.setRoot(L.getValue(1));
2756 /// visitExp - lower an exp intrinsic. Handles the special sequences
2757 /// for limited-precision mode.
2760 SelectionDAGLowering::visitExp(CallInst &I) {
2762 // No special expansion.
2763 result = DAG.getNode(ISD::FEXP,
2764 getValue(I.getOperand(1)).getValueType(),
2765 getValue(I.getOperand(1)));
2766 setValue(&I, result);
2769 /// visitLog - lower a log intrinsic. Handles the special sequences
2770 /// for limited-precision mode.
2773 SelectionDAGLowering::visitLog(CallInst &I) {
2775 // No special expansion.
2776 result = DAG.getNode(ISD::FLOG,
2777 getValue(I.getOperand(1)).getValueType(),
2778 getValue(I.getOperand(1)));
2779 setValue(&I, result);
2782 /// visitLog2 - lower a log2 intrinsic. Handles the special sequences
2783 /// for limited-precision mode.
2786 SelectionDAGLowering::visitLog2(CallInst &I) {
2788 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2789 LimitFloatPrecision>0 && LimitFloatPrecision<=12) {
2790 SDValue operand = getValue(I.getOperand(1));
2791 SDValue operand1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, operand);
2792 SDValue t0 = DAG.getNode(ISD::SRL, MVT::i32, operand1,
2793 DAG.getConstant(23, MVT::i32));
2794 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, t0,
2795 DAG.getConstant(255, MVT::i32));
2796 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2797 DAG.getConstant(127, MVT::i32));
2798 SDValue t3 = DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
2799 SDValue t4 = DAG.getNode(ISD::OR, MVT::i32, operand1,
2800 DAG.getConstant(1065353216, MVT::i32));
2801 SDValue t5 = DAG.getNode(ISD::AND, MVT::i32, t4,
2802 DAG.getConstant(1073741823, MVT::i32));
2803 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t5);
2804 SDValue t7 = DAG.getNode(ISD::FMUL, MVT::f32, t6,
2805 DAG.getConstantFP(APFloat(
2806 APInt(32, 0xbda7262e)), MVT::f32));
2807 SDValue t8 = DAG.getNode(ISD::FADD, MVT::f32, t7,
2808 DAG.getConstantFP(APFloat(
2809 APInt(32, 0x3f25280b)), MVT::f32));
2810 SDValue t9 = DAG.getNode(ISD::FMUL, MVT::f32, t8, t6);
2811 SDValue t10 = DAG.getNode(ISD::FSUB, MVT::f32, t9,
2812 DAG.getConstantFP(APFloat(
2813 APInt(32, 0x4007b923)), MVT::f32));
2814 SDValue t11 = DAG.getNode(ISD::FMUL, MVT::f32, t10, t6);
2815 SDValue t12 = DAG.getNode(ISD::FADD, MVT::f32, t11,
2816 DAG.getConstantFP(APFloat(
2817 APInt(32, 0x40823e2f)), MVT::f32));
2818 SDValue t13 = DAG.getNode(ISD::FMUL, MVT::f32, t12, t6);
2819 SDValue t14 = DAG.getNode(ISD::FSUB, MVT::f32, t13,
2820 DAG.getConstantFP(APFloat(
2821 APInt(32, 0x4020d29c)), MVT::f32));
2822 result = DAG.getNode(ISD::FADD, MVT::f32, t3, t14);
2824 // No special expansion.
2825 result = DAG.getNode(ISD::FLOG2,
2826 getValue(I.getOperand(1)).getValueType(),
2827 getValue(I.getOperand(1)));
2829 setValue(&I, result);
2832 /// visitLog10 - lower a log10 intrinsic. Handles the special sequences
2833 /// for limited-precision mode.
2836 SelectionDAGLowering::visitLog10(CallInst &I) {
2838 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2839 LimitFloatPrecision>0 && LimitFloatPrecision<=12) {
2840 SDValue operand = getValue(I.getOperand(1));
2841 SDValue operand1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, operand);
2842 SDValue t0 = DAG.getNode(ISD::SRL, MVT::i32, operand1,
2843 DAG.getConstant(23, MVT::i32));
2844 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, t0,
2845 DAG.getConstant(255, MVT::i32));
2846 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2847 DAG.getConstant(127, MVT::i32));
2848 SDValue t3 = DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
2849 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3,
2850 DAG.getConstantFP(APFloat(
2851 APInt(32, 0x3e9a209a)), MVT::f32));
2852 SDValue t5 = DAG.getNode(ISD::OR, MVT::i32, operand1,
2853 DAG.getConstant(1065353216, MVT::i32));
2854 SDValue t6 = DAG.getNode(ISD::AND, MVT::i32, t5,
2855 DAG.getConstant(1073741823, MVT::i32));
2856 SDValue t7 = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
2857 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7,
2858 DAG.getConstantFP(APFloat(
2859 APInt(32, 0x3d431f31)), MVT::f32));
2860 SDValue t9 = DAG.getNode(ISD::FSUB, MVT::f32, t8,
2861 DAG.getConstantFP(APFloat(
2862 APInt(32, 0x3ea21fb2)), MVT::f32));
2863 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, t7);
2864 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
2865 DAG.getConstantFP(APFloat(
2866 APInt(32, 0x3f6ae232)), MVT::f32));
2867 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, t7);
2868 SDValue t13 = DAG.getNode(ISD::FSUB, MVT::f32, t12,
2869 DAG.getConstantFP(APFloat(
2870 APInt(32, 0x3f25f7c3)), MVT::f32));
2871 result = DAG.getNode(ISD::FADD, MVT::f32, t4, t13);
2873 // No special expansion.
2874 result = DAG.getNode(ISD::FLOG10,
2875 getValue(I.getOperand(1)).getValueType(),
2876 getValue(I.getOperand(1)));
2878 setValue(&I, result);
2881 /// visitExp2 - lower an exp2 intrinsic. Handles the special sequences
2882 /// for limited-precision mode.
2885 SelectionDAGLowering::visitExp2(CallInst &I) {
2887 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2888 LimitFloatPrecision>0 && LimitFloatPrecision<=12) {
2889 SDValue operand = getValue(I.getOperand(1));
2890 SDValue t0 = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, operand);
2891 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, t0);
2892 SDValue t2 = DAG.getNode(ISD::FSUB, MVT::f32, operand, t1);
2893 SDValue t3 = DAG.getNode(ISD::SHL, MVT::i32, t0,
2894 DAG.getConstant(23, MVT::i32));
2895 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t2,
2896 DAG.getConstantFP(APFloat(
2897 APInt(32, 0x3da235e3)), MVT::f32));
2898 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2899 DAG.getConstantFP(APFloat(
2900 APInt(32, 0x3e65b8f3)), MVT::f32));
2901 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, t2);
2902 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
2903 DAG.getConstantFP(APFloat(
2904 APInt(32, 0x3f324b07)), MVT::f32));
2905 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, t2);
2906 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
2907 DAG.getConstantFP(APFloat(
2908 APInt(32, 0x3f7ff8fd)), MVT::f32));
2909 SDValue t10 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t9);
2910 SDValue t11 = DAG.getNode(ISD::ADD, MVT::i32, t10, t3);
2911 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t11);
2913 // No special expansion.
2914 result = DAG.getNode(ISD::FEXP2,
2915 getValue(I.getOperand(1)).getValueType(),
2916 getValue(I.getOperand(1)));
2918 setValue(&I, result);
2921 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2922 /// we want to emit this as a call to a named external function, return the name
2923 /// otherwise lower it and return null.
2925 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2926 switch (Intrinsic) {
2928 // By default, turn this into a target intrinsic node.
2929 visitTargetIntrinsic(I, Intrinsic);
2931 case Intrinsic::vastart: visitVAStart(I); return 0;
2932 case Intrinsic::vaend: visitVAEnd(I); return 0;
2933 case Intrinsic::vacopy: visitVACopy(I); return 0;
2934 case Intrinsic::returnaddress:
2935 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2936 getValue(I.getOperand(1))));
2938 case Intrinsic::frameaddress:
2939 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2940 getValue(I.getOperand(1))));
2942 case Intrinsic::setjmp:
2943 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2945 case Intrinsic::longjmp:
2946 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2948 case Intrinsic::memcpy_i32:
2949 case Intrinsic::memcpy_i64: {
2950 SDValue Op1 = getValue(I.getOperand(1));
2951 SDValue Op2 = getValue(I.getOperand(2));
2952 SDValue Op3 = getValue(I.getOperand(3));
2953 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2954 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2955 I.getOperand(1), 0, I.getOperand(2), 0));
2958 case Intrinsic::memset_i32:
2959 case Intrinsic::memset_i64: {
2960 SDValue Op1 = getValue(I.getOperand(1));
2961 SDValue Op2 = getValue(I.getOperand(2));
2962 SDValue Op3 = getValue(I.getOperand(3));
2963 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2964 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2965 I.getOperand(1), 0));
2968 case Intrinsic::memmove_i32:
2969 case Intrinsic::memmove_i64: {
2970 SDValue Op1 = getValue(I.getOperand(1));
2971 SDValue Op2 = getValue(I.getOperand(2));
2972 SDValue Op3 = getValue(I.getOperand(3));
2973 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2975 // If the source and destination are known to not be aliases, we can
2976 // lower memmove as memcpy.
2977 uint64_t Size = -1ULL;
2978 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2979 Size = C->getValue();
2980 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2981 AliasAnalysis::NoAlias) {
2982 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2983 I.getOperand(1), 0, I.getOperand(2), 0));
2987 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2988 I.getOperand(1), 0, I.getOperand(2), 0));
2991 case Intrinsic::dbg_stoppoint: {
2992 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2993 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2994 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2995 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2996 assert(DD && "Not a debug information descriptor");
2997 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3000 cast<CompileUnitDesc>(DD)));
3005 case Intrinsic::dbg_region_start: {
3006 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3007 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3008 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3009 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3010 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3015 case Intrinsic::dbg_region_end: {
3016 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3017 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3018 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3019 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3020 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3025 case Intrinsic::dbg_func_start: {
3026 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3028 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3029 Value *SP = FSI.getSubprogram();
3030 if (SP && MMI->Verify(SP)) {
3031 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3032 // what (most?) gdb expects.
3033 DebugInfoDesc *DD = MMI->getDescFor(SP);
3034 assert(DD && "Not a debug information descriptor");
3035 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3036 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3037 unsigned SrcFile = MMI->RecordSource(CompileUnit);
3038 // Record the source line but does create a label. It will be emitted
3039 // at asm emission time.
3040 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3045 case Intrinsic::dbg_declare: {
3046 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3047 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3048 Value *Variable = DI.getVariable();
3049 if (MMI && Variable && MMI->Verify(Variable))
3050 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3051 getValue(DI.getAddress()), getValue(Variable)));
3055 case Intrinsic::eh_exception: {
3056 if (!CurMBB->isLandingPad()) {
3057 // FIXME: Mark exception register as live in. Hack for PR1508.
3058 unsigned Reg = TLI.getExceptionAddressRegister();
3059 if (Reg) CurMBB->addLiveIn(Reg);
3061 // Insert the EXCEPTIONADDR instruction.
3062 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3064 Ops[0] = DAG.getRoot();
3065 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3067 DAG.setRoot(Op.getValue(1));
3071 case Intrinsic::eh_selector_i32:
3072 case Intrinsic::eh_selector_i64: {
3073 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3074 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3075 MVT::i32 : MVT::i64);
3078 if (CurMBB->isLandingPad())
3079 AddCatchInfo(I, MMI, CurMBB);
3082 FuncInfo.CatchInfoLost.insert(&I);
3084 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3085 unsigned Reg = TLI.getExceptionSelectorRegister();
3086 if (Reg) CurMBB->addLiveIn(Reg);
3089 // Insert the EHSELECTION instruction.
3090 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3092 Ops[0] = getValue(I.getOperand(1));
3094 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3096 DAG.setRoot(Op.getValue(1));
3098 setValue(&I, DAG.getConstant(0, VT));
3104 case Intrinsic::eh_typeid_for_i32:
3105 case Intrinsic::eh_typeid_for_i64: {
3106 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3107 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3108 MVT::i32 : MVT::i64);
3111 // Find the type id for the given typeinfo.
3112 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3114 unsigned TypeID = MMI->getTypeIDFor(GV);
3115 setValue(&I, DAG.getConstant(TypeID, VT));
3117 // Return something different to eh_selector.
3118 setValue(&I, DAG.getConstant(1, VT));
3124 case Intrinsic::eh_return: {
3125 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3128 MMI->setCallsEHReturn(true);
3129 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3132 getValue(I.getOperand(1)),
3133 getValue(I.getOperand(2))));
3135 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3141 case Intrinsic::eh_unwind_init: {
3142 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3143 MMI->setCallsUnwindInit(true);
3149 case Intrinsic::eh_dwarf_cfa: {
3150 MVT VT = getValue(I.getOperand(1)).getValueType();
3152 if (VT.bitsGT(TLI.getPointerTy()))
3153 CfaArg = DAG.getNode(ISD::TRUNCATE,
3154 TLI.getPointerTy(), getValue(I.getOperand(1)));
3156 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3157 TLI.getPointerTy(), getValue(I.getOperand(1)));
3159 SDValue Offset = DAG.getNode(ISD::ADD,
3161 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3162 TLI.getPointerTy()),
3164 setValue(&I, DAG.getNode(ISD::ADD,
3166 DAG.getNode(ISD::FRAMEADDR,
3169 TLI.getPointerTy())),
3174 case Intrinsic::sqrt:
3175 setValue(&I, DAG.getNode(ISD::FSQRT,
3176 getValue(I.getOperand(1)).getValueType(),
3177 getValue(I.getOperand(1))));
3179 case Intrinsic::powi:
3180 setValue(&I, DAG.getNode(ISD::FPOWI,
3181 getValue(I.getOperand(1)).getValueType(),
3182 getValue(I.getOperand(1)),
3183 getValue(I.getOperand(2))));
3185 case Intrinsic::sin:
3186 setValue(&I, DAG.getNode(ISD::FSIN,
3187 getValue(I.getOperand(1)).getValueType(),
3188 getValue(I.getOperand(1))));
3190 case Intrinsic::cos:
3191 setValue(&I, DAG.getNode(ISD::FCOS,
3192 getValue(I.getOperand(1)).getValueType(),
3193 getValue(I.getOperand(1))));
3195 case Intrinsic::log:
3198 case Intrinsic::log2:
3201 case Intrinsic::log10:
3204 case Intrinsic::exp:
3207 case Intrinsic::exp2:
3210 case Intrinsic::pow:
3211 setValue(&I, DAG.getNode(ISD::FPOW,
3212 getValue(I.getOperand(1)).getValueType(),
3213 getValue(I.getOperand(1)),
3214 getValue(I.getOperand(2))));
3216 case Intrinsic::pcmarker: {
3217 SDValue Tmp = getValue(I.getOperand(1));
3218 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3221 case Intrinsic::readcyclecounter: {
3222 SDValue Op = getRoot();
3223 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3224 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3227 DAG.setRoot(Tmp.getValue(1));
3230 case Intrinsic::part_select: {
3231 // Currently not implemented: just abort
3232 assert(0 && "part_select intrinsic not implemented");
3235 case Intrinsic::part_set: {
3236 // Currently not implemented: just abort
3237 assert(0 && "part_set intrinsic not implemented");
3240 case Intrinsic::bswap:
3241 setValue(&I, DAG.getNode(ISD::BSWAP,
3242 getValue(I.getOperand(1)).getValueType(),
3243 getValue(I.getOperand(1))));
3245 case Intrinsic::cttz: {
3246 SDValue Arg = getValue(I.getOperand(1));
3247 MVT Ty = Arg.getValueType();
3248 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3249 setValue(&I, result);
3252 case Intrinsic::ctlz: {
3253 SDValue Arg = getValue(I.getOperand(1));
3254 MVT Ty = Arg.getValueType();
3255 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3256 setValue(&I, result);
3259 case Intrinsic::ctpop: {
3260 SDValue Arg = getValue(I.getOperand(1));
3261 MVT Ty = Arg.getValueType();
3262 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3263 setValue(&I, result);
3266 case Intrinsic::stacksave: {
3267 SDValue Op = getRoot();
3268 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3269 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3271 DAG.setRoot(Tmp.getValue(1));
3274 case Intrinsic::stackrestore: {
3275 SDValue Tmp = getValue(I.getOperand(1));
3276 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3279 case Intrinsic::var_annotation:
3280 // Discard annotate attributes
3283 case Intrinsic::init_trampoline: {
3284 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3288 Ops[1] = getValue(I.getOperand(1));
3289 Ops[2] = getValue(I.getOperand(2));
3290 Ops[3] = getValue(I.getOperand(3));
3291 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3292 Ops[5] = DAG.getSrcValue(F);
3294 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3295 DAG.getNodeValueTypes(TLI.getPointerTy(),
3300 DAG.setRoot(Tmp.getValue(1));
3304 case Intrinsic::gcroot:
3306 Value *Alloca = I.getOperand(1);
3307 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3309 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
3310 GFI->addStackRoot(FI->getIndex(), TypeMap);
3314 case Intrinsic::gcread:
3315 case Intrinsic::gcwrite:
3316 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3319 case Intrinsic::flt_rounds: {
3320 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3324 case Intrinsic::trap: {
3325 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3328 case Intrinsic::prefetch: {
3331 Ops[1] = getValue(I.getOperand(1));
3332 Ops[2] = getValue(I.getOperand(2));
3333 Ops[3] = getValue(I.getOperand(3));
3334 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3338 case Intrinsic::memory_barrier: {
3341 for (int x = 1; x < 6; ++x)
3342 Ops[x] = getValue(I.getOperand(x));
3344 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3347 case Intrinsic::atomic_cmp_swap: {
3348 SDValue Root = getRoot();
3350 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3352 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root,
3353 getValue(I.getOperand(1)),
3354 getValue(I.getOperand(2)),
3355 getValue(I.getOperand(3)),
3359 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root,
3360 getValue(I.getOperand(1)),
3361 getValue(I.getOperand(2)),
3362 getValue(I.getOperand(3)),
3366 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root,
3367 getValue(I.getOperand(1)),
3368 getValue(I.getOperand(2)),
3369 getValue(I.getOperand(3)),
3373 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root,
3374 getValue(I.getOperand(1)),
3375 getValue(I.getOperand(2)),
3376 getValue(I.getOperand(3)),
3380 assert(0 && "Invalid atomic type");
3384 DAG.setRoot(L.getValue(1));
3387 case Intrinsic::atomic_load_add:
3388 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3390 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3392 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3394 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3396 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3398 assert(0 && "Invalid atomic type");
3401 case Intrinsic::atomic_load_sub:
3402 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3404 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3406 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3408 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3410 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3412 assert(0 && "Invalid atomic type");
3415 case Intrinsic::atomic_load_or:
3416 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3418 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3420 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3422 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3424 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3426 assert(0 && "Invalid atomic type");
3429 case Intrinsic::atomic_load_xor:
3430 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3432 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3434 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3436 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3438 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3440 assert(0 && "Invalid atomic type");
3443 case Intrinsic::atomic_load_and:
3444 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3446 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3448 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3450 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3452 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3454 assert(0 && "Invalid atomic type");
3457 case Intrinsic::atomic_load_nand:
3458 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3460 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
3462 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
3464 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
3466 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
3468 assert(0 && "Invalid atomic type");
3471 case Intrinsic::atomic_load_max:
3472 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3474 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
3476 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
3478 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
3480 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
3482 assert(0 && "Invalid atomic type");
3485 case Intrinsic::atomic_load_min:
3486 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3488 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
3490 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
3492 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
3494 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
3496 assert(0 && "Invalid atomic type");
3499 case Intrinsic::atomic_load_umin:
3500 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3502 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
3504 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
3506 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
3508 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
3510 assert(0 && "Invalid atomic type");
3513 case Intrinsic::atomic_load_umax:
3514 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3516 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
3518 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
3520 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
3522 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
3524 assert(0 && "Invalid atomic type");
3527 case Intrinsic::atomic_swap:
3528 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3530 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
3532 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
3534 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
3536 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
3538 assert(0 && "Invalid atomic type");
3545 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
3547 MachineBasicBlock *LandingPad) {
3548 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3549 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3550 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3551 unsigned BeginLabel = 0, EndLabel = 0;
3553 TargetLowering::ArgListTy Args;
3554 TargetLowering::ArgListEntry Entry;
3555 Args.reserve(CS.arg_size());
3556 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3558 SDValue ArgNode = getValue(*i);
3559 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3561 unsigned attrInd = i - CS.arg_begin() + 1;
3562 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3563 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3564 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3565 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3566 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3567 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3568 Entry.Alignment = CS.getParamAlignment(attrInd);
3569 Args.push_back(Entry);
3572 if (LandingPad && MMI) {
3573 // Insert a label before the invoke call to mark the try range. This can be
3574 // used to detect deletion of the invoke via the MachineModuleInfo.
3575 BeginLabel = MMI->NextLabelID();
3576 // Both PendingLoads and PendingExports must be flushed here;
3577 // this call might not return.
3579 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
3582 std::pair<SDValue,SDValue> Result =
3583 TLI.LowerCallTo(getRoot(), CS.getType(),
3584 CS.paramHasAttr(0, ParamAttr::SExt),
3585 CS.paramHasAttr(0, ParamAttr::ZExt),
3586 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3588 if (CS.getType() != Type::VoidTy)
3589 setValue(CS.getInstruction(), Result.first);
3590 DAG.setRoot(Result.second);
3592 if (LandingPad && MMI) {
3593 // Insert a label at the end of the invoke call to mark the try range. This
3594 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3595 EndLabel = MMI->NextLabelID();
3596 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
3598 // Inform MachineModuleInfo of range.
3599 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3604 void SelectionDAGLowering::visitCall(CallInst &I) {
3605 const char *RenameFn = 0;
3606 if (Function *F = I.getCalledFunction()) {
3607 if (F->isDeclaration()) {
3608 if (unsigned IID = F->getIntrinsicID()) {
3609 RenameFn = visitIntrinsicCall(I, IID);
3615 // Check for well-known libc/libm calls. If the function is internal, it
3616 // can't be a library call.
3617 unsigned NameLen = F->getNameLen();
3618 if (!F->hasInternalLinkage() && NameLen) {
3619 const char *NameStr = F->getNameStart();
3620 if (NameStr[0] == 'c' &&
3621 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3622 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3623 if (I.getNumOperands() == 3 && // Basic sanity checks.
3624 I.getOperand(1)->getType()->isFloatingPoint() &&
3625 I.getType() == I.getOperand(1)->getType() &&
3626 I.getType() == I.getOperand(2)->getType()) {
3627 SDValue LHS = getValue(I.getOperand(1));
3628 SDValue RHS = getValue(I.getOperand(2));
3629 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3633 } else if (NameStr[0] == 'f' &&
3634 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3635 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3636 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3637 if (I.getNumOperands() == 2 && // Basic sanity checks.
3638 I.getOperand(1)->getType()->isFloatingPoint() &&
3639 I.getType() == I.getOperand(1)->getType()) {
3640 SDValue Tmp = getValue(I.getOperand(1));
3641 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3644 } else if (NameStr[0] == 's' &&
3645 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3646 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3647 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3648 if (I.getNumOperands() == 2 && // Basic sanity checks.
3649 I.getOperand(1)->getType()->isFloatingPoint() &&
3650 I.getType() == I.getOperand(1)->getType()) {
3651 SDValue Tmp = getValue(I.getOperand(1));
3652 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3655 } else if (NameStr[0] == 'c' &&
3656 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3657 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3658 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3659 if (I.getNumOperands() == 2 && // Basic sanity checks.
3660 I.getOperand(1)->getType()->isFloatingPoint() &&
3661 I.getType() == I.getOperand(1)->getType()) {
3662 SDValue Tmp = getValue(I.getOperand(1));
3663 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3668 } else if (isa<InlineAsm>(I.getOperand(0))) {
3675 Callee = getValue(I.getOperand(0));
3677 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3679 LowerCallTo(&I, Callee, I.isTailCall());
3683 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3684 /// this value and returns the result as a ValueVT value. This uses
3685 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3686 /// If the Flag pointer is NULL, no flag is used.
3687 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3689 SDValue *Flag) const {
3690 // Assemble the legal parts into the final values.
3691 SmallVector<SDValue, 4> Values(ValueVTs.size());
3692 SmallVector<SDValue, 8> Parts;
3693 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3694 // Copy the legal parts from the registers.
3695 MVT ValueVT = ValueVTs[Value];
3696 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3697 MVT RegisterVT = RegVTs[Value];
3699 Parts.resize(NumRegs);
3700 for (unsigned i = 0; i != NumRegs; ++i) {
3703 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3705 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3706 *Flag = P.getValue(2);
3708 Chain = P.getValue(1);
3710 // If the source register was virtual and if we know something about it,
3711 // add an assert node.
3712 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3713 RegisterVT.isInteger() && !RegisterVT.isVector()) {
3714 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3715 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3716 if (FLI.LiveOutRegInfo.size() > SlotNo) {
3717 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3719 unsigned RegSize = RegisterVT.getSizeInBits();
3720 unsigned NumSignBits = LOI.NumSignBits;
3721 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3723 // FIXME: We capture more information than the dag can represent. For
3724 // now, just use the tightest assertzext/assertsext possible.
3726 MVT FromVT(MVT::Other);
3727 if (NumSignBits == RegSize)
3728 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
3729 else if (NumZeroBits >= RegSize-1)
3730 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
3731 else if (NumSignBits > RegSize-8)
3732 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
3733 else if (NumZeroBits >= RegSize-9)
3734 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
3735 else if (NumSignBits > RegSize-16)
3736 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
3737 else if (NumZeroBits >= RegSize-17)
3738 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
3739 else if (NumSignBits > RegSize-32)
3740 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
3741 else if (NumZeroBits >= RegSize-33)
3742 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
3744 if (FromVT != MVT::Other) {
3745 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3746 RegisterVT, P, DAG.getValueType(FromVT));
3755 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
3761 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3762 &Values[0], ValueVTs.size());
3765 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3766 /// specified value into the registers specified by this object. This uses
3767 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3768 /// If the Flag pointer is NULL, no flag is used.
3769 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
3770 SDValue &Chain, SDValue *Flag) const {
3771 // Get the list of the values's legal parts.
3772 unsigned NumRegs = Regs.size();
3773 SmallVector<SDValue, 8> Parts(NumRegs);
3774 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3775 MVT ValueVT = ValueVTs[Value];
3776 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3777 MVT RegisterVT = RegVTs[Value];
3779 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
3780 &Parts[Part], NumParts, RegisterVT);
3784 // Copy the parts into the registers.
3785 SmallVector<SDValue, 8> Chains(NumRegs);
3786 for (unsigned i = 0; i != NumRegs; ++i) {
3789 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3791 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3792 *Flag = Part.getValue(1);
3794 Chains[i] = Part.getValue(0);
3797 if (NumRegs == 1 || Flag)
3798 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3799 // flagged to it. That is the CopyToReg nodes and the user are considered
3800 // a single scheduling unit. If we create a TokenFactor and return it as
3801 // chain, then the TokenFactor is both a predecessor (operand) of the
3802 // user as well as a successor (the TF operands are flagged to the user).
3803 // c1, f1 = CopyToReg
3804 // c2, f2 = CopyToReg
3805 // c3 = TokenFactor c1, c2
3808 Chain = Chains[NumRegs-1];
3810 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3813 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3814 /// operand list. This adds the code marker and includes the number of
3815 /// values added into it.
3816 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3817 std::vector<SDValue> &Ops) const {
3818 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3819 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3820 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3821 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3822 MVT RegisterVT = RegVTs[Value];
3823 for (unsigned i = 0; i != NumRegs; ++i)
3824 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3828 /// isAllocatableRegister - If the specified register is safe to allocate,
3829 /// i.e. it isn't a stack pointer or some other special register, return the
3830 /// register class for the register. Otherwise, return null.
3831 static const TargetRegisterClass *
3832 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3833 const TargetLowering &TLI,
3834 const TargetRegisterInfo *TRI) {
3835 MVT FoundVT = MVT::Other;
3836 const TargetRegisterClass *FoundRC = 0;
3837 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3838 E = TRI->regclass_end(); RCI != E; ++RCI) {
3839 MVT ThisVT = MVT::Other;
3841 const TargetRegisterClass *RC = *RCI;
3842 // If none of the the value types for this register class are valid, we
3843 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3844 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3846 if (TLI.isTypeLegal(*I)) {
3847 // If we have already found this register in a different register class,
3848 // choose the one with the largest VT specified. For example, on
3849 // PowerPC, we favor f64 register classes over f32.
3850 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
3857 if (ThisVT == MVT::Other) continue;
3859 // NOTE: This isn't ideal. In particular, this might allocate the
3860 // frame pointer in functions that need it (due to them not being taken
3861 // out of allocation, because a variable sized allocation hasn't been seen
3862 // yet). This is a slight code pessimization, but should still work.
3863 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3864 E = RC->allocation_order_end(MF); I != E; ++I)
3866 // We found a matching register class. Keep looking at others in case
3867 // we find one with larger registers that this physreg is also in.
3878 /// AsmOperandInfo - This contains information for each constraint that we are
3880 struct VISIBILITY_HIDDEN SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3881 /// CallOperand - If this is the result output operand or a clobber
3882 /// this is null, otherwise it is the incoming operand to the CallInst.
3883 /// This gets modified as the asm is processed.
3884 SDValue CallOperand;
3886 /// AssignedRegs - If this is a register or register class operand, this
3887 /// contains the set of register corresponding to the operand.
3888 RegsForValue AssignedRegs;
3890 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3891 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3894 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3895 /// busy in OutputRegs/InputRegs.
3896 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3897 std::set<unsigned> &OutputRegs,
3898 std::set<unsigned> &InputRegs,
3899 const TargetRegisterInfo &TRI) const {
3901 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3902 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3905 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3906 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3911 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3913 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3914 const TargetRegisterInfo &TRI) {
3915 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3917 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3918 for (; *Aliases; ++Aliases)
3919 Regs.insert(*Aliases);
3922 } // end llvm namespace.
3925 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3926 /// specified operand. We prefer to assign virtual registers, to allow the
3927 /// register allocator handle the assignment process. However, if the asm uses
3928 /// features that we can't model on machineinstrs, we have SDISel do the
3929 /// allocation. This produces generally horrible, but correct, code.
3931 /// OpInfo describes the operand.
3932 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3933 /// or any explicitly clobbered registers.
3934 /// Input and OutputRegs are the set of already allocated physical registers.
3936 void SelectionDAGLowering::
3937 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3938 std::set<unsigned> &OutputRegs,
3939 std::set<unsigned> &InputRegs) {
3940 // Compute whether this value requires an input register, an output register,
3942 bool isOutReg = false;
3943 bool isInReg = false;
3944 switch (OpInfo.Type) {
3945 case InlineAsm::isOutput:
3948 // If this is an early-clobber output, or if there is an input
3949 // constraint that matches this, we need to reserve the input register
3950 // so no other inputs allocate to it.
3951 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3953 case InlineAsm::isInput:
3957 case InlineAsm::isClobber:
3964 MachineFunction &MF = DAG.getMachineFunction();
3965 SmallVector<unsigned, 4> Regs;
3967 // If this is a constraint for a single physreg, or a constraint for a
3968 // register class, find it.
3969 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3970 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3971 OpInfo.ConstraintVT);
3973 unsigned NumRegs = 1;
3974 if (OpInfo.ConstraintVT != MVT::Other)
3975 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3977 MVT ValueVT = OpInfo.ConstraintVT;
3980 // If this is a constraint for a specific physical register, like {r17},
3982 if (PhysReg.first) {
3983 if (OpInfo.ConstraintVT == MVT::Other)
3984 ValueVT = *PhysReg.second->vt_begin();
3986 // Get the actual register value type. This is important, because the user
3987 // may have asked for (e.g.) the AX register in i32 type. We need to
3988 // remember that AX is actually i16 to get the right extension.
3989 RegVT = *PhysReg.second->vt_begin();
3991 // This is a explicit reference to a physical register.
3992 Regs.push_back(PhysReg.first);
3994 // If this is an expanded reference, add the rest of the regs to Regs.
3996 TargetRegisterClass::iterator I = PhysReg.second->begin();
3997 for (; *I != PhysReg.first; ++I)
3998 assert(I != PhysReg.second->end() && "Didn't find reg!");
4000 // Already added the first reg.
4002 for (; NumRegs; --NumRegs, ++I) {
4003 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4007 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4008 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4009 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4013 // Otherwise, if this was a reference to an LLVM register class, create vregs
4014 // for this reference.
4015 std::vector<unsigned> RegClassRegs;
4016 const TargetRegisterClass *RC = PhysReg.second;
4018 // If this is an early clobber or tied register, our regalloc doesn't know
4019 // how to maintain the constraint. If it isn't, go ahead and create vreg
4020 // and let the regalloc do the right thing.
4021 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4022 // If there is some other early clobber and this is an input register,
4023 // then we are forced to pre-allocate the input reg so it doesn't
4024 // conflict with the earlyclobber.
4025 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
4026 RegVT = *PhysReg.second->vt_begin();
4028 if (OpInfo.ConstraintVT == MVT::Other)
4031 // Create the appropriate number of virtual registers.
4032 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4033 for (; NumRegs; --NumRegs)
4034 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4036 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4040 // Otherwise, we can't allocate it. Let the code below figure out how to
4041 // maintain these constraints.
4042 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4045 // This is a reference to a register class that doesn't directly correspond
4046 // to an LLVM register class. Allocate NumRegs consecutive, available,
4047 // registers from the class.
4048 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4049 OpInfo.ConstraintVT);
4052 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4053 unsigned NumAllocated = 0;
4054 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4055 unsigned Reg = RegClassRegs[i];
4056 // See if this register is available.
4057 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4058 (isInReg && InputRegs.count(Reg))) { // Already used.
4059 // Make sure we find consecutive registers.
4064 // Check to see if this register is allocatable (i.e. don't give out the
4067 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4068 if (!RC) { // Couldn't allocate this register.
4069 // Reset NumAllocated to make sure we return consecutive registers.
4075 // Okay, this register is good, we can use it.
4078 // If we allocated enough consecutive registers, succeed.
4079 if (NumAllocated == NumRegs) {
4080 unsigned RegStart = (i-NumAllocated)+1;
4081 unsigned RegEnd = i+1;
4082 // Mark all of the allocated registers used.
4083 for (unsigned i = RegStart; i != RegEnd; ++i)
4084 Regs.push_back(RegClassRegs[i]);
4086 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4087 OpInfo.ConstraintVT);
4088 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4093 // Otherwise, we couldn't allocate enough registers for this.
4097 /// visitInlineAsm - Handle a call to an InlineAsm object.
4099 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4100 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4102 /// ConstraintOperands - Information about all of the constraints.
4103 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4105 SDValue Chain = getRoot();
4108 std::set<unsigned> OutputRegs, InputRegs;
4110 // Do a prepass over the constraints, canonicalizing them, and building up the
4111 // ConstraintOperands list.
4112 std::vector<InlineAsm::ConstraintInfo>
4113 ConstraintInfos = IA->ParseConstraints();
4115 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4116 // constraint. If so, we can't let the register allocator allocate any input
4117 // registers, because it will not know to avoid the earlyclobbered output reg.
4118 bool SawEarlyClobber = false;
4120 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4121 unsigned ResNo = 0; // ResNo - The result number of the next output.
4122 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4123 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4124 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4126 MVT OpVT = MVT::Other;
4128 // Compute the value type for each operand.
4129 switch (OpInfo.Type) {
4130 case InlineAsm::isOutput:
4131 // Indirect outputs just consume an argument.
4132 if (OpInfo.isIndirect) {
4133 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4136 // The return value of the call is this value. As such, there is no
4137 // corresponding argument.
4138 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4139 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4140 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4142 assert(ResNo == 0 && "Asm only has one result!");
4143 OpVT = TLI.getValueType(CS.getType());
4147 case InlineAsm::isInput:
4148 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4150 case InlineAsm::isClobber:
4155 // If this is an input or an indirect output, process the call argument.
4156 // BasicBlocks are labels, currently appearing only in asm's.
4157 if (OpInfo.CallOperandVal) {
4158 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4159 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4161 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4162 const Type *OpTy = OpInfo.CallOperandVal->getType();
4163 // If this is an indirect operand, the operand is a pointer to the
4165 if (OpInfo.isIndirect)
4166 OpTy = cast<PointerType>(OpTy)->getElementType();
4168 // If OpTy is not a single value, it may be a struct/union that we
4169 // can tile with integers.
4170 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4171 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4179 OpTy = IntegerType::get(BitSize);
4184 OpVT = TLI.getValueType(OpTy, true);
4188 OpInfo.ConstraintVT = OpVT;
4190 // Compute the constraint code and ConstraintType to use.
4191 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
4193 // Keep track of whether we see an earlyclobber.
4194 SawEarlyClobber |= OpInfo.isEarlyClobber;
4196 // If we see a clobber of a register, it is an early clobber.
4197 if (!SawEarlyClobber &&
4198 OpInfo.Type == InlineAsm::isClobber &&
4199 OpInfo.ConstraintType == TargetLowering::C_Register) {
4200 // Note that we want to ignore things that we don't track here, like
4201 // dirflag, fpsr, flags, etc.
4202 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4203 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4204 OpInfo.ConstraintVT);
4205 if (PhysReg.first || PhysReg.second) {
4206 // This is a register we know of.
4207 SawEarlyClobber = true;
4211 // If this is a memory input, and if the operand is not indirect, do what we
4212 // need to to provide an address for the memory input.
4213 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4214 !OpInfo.isIndirect) {
4215 assert(OpInfo.Type == InlineAsm::isInput &&
4216 "Can only indirectify direct input operands!");
4218 // Memory operands really want the address of the value. If we don't have
4219 // an indirect input, put it in the constpool if we can, otherwise spill
4220 // it to a stack slot.
4222 // If the operand is a float, integer, or vector constant, spill to a
4223 // constant pool entry to get its address.
4224 Value *OpVal = OpInfo.CallOperandVal;
4225 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4226 isa<ConstantVector>(OpVal)) {
4227 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4228 TLI.getPointerTy());
4230 // Otherwise, create a stack slot and emit a store to it before the
4232 const Type *Ty = OpVal->getType();
4233 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4234 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4235 MachineFunction &MF = DAG.getMachineFunction();
4236 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4237 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4238 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4239 OpInfo.CallOperand = StackSlot;
4242 // There is no longer a Value* corresponding to this operand.
4243 OpInfo.CallOperandVal = 0;
4244 // It is now an indirect operand.
4245 OpInfo.isIndirect = true;
4248 // If this constraint is for a specific register, allocate it before
4250 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4251 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4253 ConstraintInfos.clear();
4256 // Second pass - Loop over all of the operands, assigning virtual or physregs
4257 // to registerclass operands.
4258 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4259 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4261 // C_Register operands have already been allocated, Other/Memory don't need
4263 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4264 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4267 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4268 std::vector<SDValue> AsmNodeOperands;
4269 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4270 AsmNodeOperands.push_back(
4271 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4274 // Loop over all of the inputs, copying the operand values into the
4275 // appropriate registers and processing the output regs.
4276 RegsForValue RetValRegs;
4278 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4279 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4281 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4282 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4284 switch (OpInfo.Type) {
4285 case InlineAsm::isOutput: {
4286 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4287 OpInfo.ConstraintType != TargetLowering::C_Register) {
4288 // Memory output, or 'other' output (e.g. 'X' constraint).
4289 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4291 // Add information to the INLINEASM node to know about this output.
4292 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4293 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4294 TLI.getPointerTy()));
4295 AsmNodeOperands.push_back(OpInfo.CallOperand);
4299 // Otherwise, this is a register or register class output.
4301 // Copy the output from the appropriate register. Find a register that
4303 if (OpInfo.AssignedRegs.Regs.empty()) {
4304 cerr << "Couldn't allocate output reg for constraint '"
4305 << OpInfo.ConstraintCode << "'!\n";
4309 // If this is an indirect operand, store through the pointer after the
4311 if (OpInfo.isIndirect) {
4312 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4313 OpInfo.CallOperandVal));
4315 // This is the result value of the call.
4316 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4317 // Concatenate this output onto the outputs list.
4318 RetValRegs.append(OpInfo.AssignedRegs);
4321 // Add information to the INLINEASM node to know that this register is
4323 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4327 case InlineAsm::isInput: {
4328 SDValue InOperandVal = OpInfo.CallOperand;
4330 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
4331 // If this is required to match an output register we have already set,
4332 // just use its register.
4333 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4335 // Scan until we find the definition we already emitted of this operand.
4336 // When we find it, create a RegsForValue operand.
4337 unsigned CurOp = 2; // The first operand.
4338 for (; OperandNo; --OperandNo) {
4339 // Advance to the next operand.
4341 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4342 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4343 (NumOps & 7) == 4 /*MEM*/) &&
4344 "Skipped past definitions?");
4345 CurOp += (NumOps>>3)+1;
4349 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4350 if ((NumOps & 7) == 2 /*REGDEF*/) {
4351 // Add NumOps>>3 registers to MatchedRegs.
4352 RegsForValue MatchedRegs;
4353 MatchedRegs.TLI = &TLI;
4354 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4355 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4356 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4358 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4359 MatchedRegs.Regs.push_back(Reg);
4362 // Use the produced MatchedRegs object to
4363 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4364 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4367 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4368 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4369 // Add information to the INLINEASM node to know about this input.
4370 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4371 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4372 TLI.getPointerTy()));
4373 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4378 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4379 assert(!OpInfo.isIndirect &&
4380 "Don't know how to handle indirect other inputs yet!");
4382 std::vector<SDValue> Ops;
4383 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4386 cerr << "Invalid operand for inline asm constraint '"
4387 << OpInfo.ConstraintCode << "'!\n";
4391 // Add information to the INLINEASM node to know about this input.
4392 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4393 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4394 TLI.getPointerTy()));
4395 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4397 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4398 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4399 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4400 "Memory operands expect pointer values");
4402 // Add information to the INLINEASM node to know about this input.
4403 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4404 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4405 TLI.getPointerTy()));
4406 AsmNodeOperands.push_back(InOperandVal);
4410 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4411 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4412 "Unknown constraint type!");
4413 assert(!OpInfo.isIndirect &&
4414 "Don't know how to handle indirect register inputs yet!");
4416 // Copy the input into the appropriate registers.
4417 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4418 "Couldn't allocate input reg!");
4420 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4422 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4426 case InlineAsm::isClobber: {
4427 // Add the clobbered value to the operand list, so that the register
4428 // allocator is aware that the physreg got clobbered.
4429 if (!OpInfo.AssignedRegs.Regs.empty())
4430 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4437 // Finish up input operands.
4438 AsmNodeOperands[0] = Chain;
4439 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
4441 Chain = DAG.getNode(ISD::INLINEASM,
4442 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4443 &AsmNodeOperands[0], AsmNodeOperands.size());
4444 Flag = Chain.getValue(1);
4446 // If this asm returns a register value, copy the result from that register
4447 // and set it as the value of the call.
4448 if (!RetValRegs.Regs.empty()) {
4449 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4451 // If any of the results of the inline asm is a vector, it may have the
4452 // wrong width/num elts. This can happen for register classes that can
4453 // contain multiple different value types. The preg or vreg allocated may
4454 // not have the same VT as was expected. Convert it to the right type with
4456 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4457 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4458 if (Val.getNode()->getValueType(i).isVector())
4459 Val = DAG.getNode(ISD::BIT_CONVERT,
4460 TLI.getValueType(ResSTy->getElementType(i)), Val);
4463 if (Val.getValueType().isVector())
4464 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4468 setValue(CS.getInstruction(), Val);
4471 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
4473 // Process indirect outputs, first output all of the flagged copies out of
4475 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4476 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4477 Value *Ptr = IndirectStoresToEmit[i].second;
4478 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4479 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4482 // Emit the non-flagged stores from the physregs.
4483 SmallVector<SDValue, 8> OutChains;
4484 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4485 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4486 getValue(StoresToEmit[i].second),
4487 StoresToEmit[i].second, 0));
4488 if (!OutChains.empty())
4489 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4490 &OutChains[0], OutChains.size());
4495 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4496 SDValue Src = getValue(I.getOperand(0));
4498 MVT IntPtr = TLI.getPointerTy();
4500 if (IntPtr.bitsLT(Src.getValueType()))
4501 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4502 else if (IntPtr.bitsGT(Src.getValueType()))
4503 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4505 // Scale the source by the type size.
4506 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4507 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4508 Src, DAG.getIntPtrConstant(ElementSize));
4510 TargetLowering::ArgListTy Args;
4511 TargetLowering::ArgListEntry Entry;
4513 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4514 Args.push_back(Entry);
4516 std::pair<SDValue,SDValue> Result =
4517 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4518 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4519 setValue(&I, Result.first); // Pointers always fit in registers
4520 DAG.setRoot(Result.second);
4523 void SelectionDAGLowering::visitFree(FreeInst &I) {
4524 TargetLowering::ArgListTy Args;
4525 TargetLowering::ArgListEntry Entry;
4526 Entry.Node = getValue(I.getOperand(0));
4527 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4528 Args.push_back(Entry);
4529 MVT IntPtr = TLI.getPointerTy();
4530 std::pair<SDValue,SDValue> Result =
4531 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4532 CallingConv::C, true,
4533 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4534 DAG.setRoot(Result.second);
4537 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4538 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4539 getValue(I.getOperand(1)),
4540 DAG.getSrcValue(I.getOperand(1))));
4543 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4544 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4545 getValue(I.getOperand(0)),
4546 DAG.getSrcValue(I.getOperand(0)));
4548 DAG.setRoot(V.getValue(1));
4551 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4552 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4553 getValue(I.getOperand(1)),
4554 DAG.getSrcValue(I.getOperand(1))));
4557 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4558 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4559 getValue(I.getOperand(1)),
4560 getValue(I.getOperand(2)),
4561 DAG.getSrcValue(I.getOperand(1)),
4562 DAG.getSrcValue(I.getOperand(2))));
4565 /// TargetLowering::LowerArguments - This is the default LowerArguments
4566 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4567 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4568 /// integrated into SDISel.
4569 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
4570 SmallVectorImpl<SDValue> &ArgValues) {
4571 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4572 SmallVector<SDValue, 3+16> Ops;
4573 Ops.push_back(DAG.getRoot());
4574 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4575 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4577 // Add one result value for each formal argument.
4578 SmallVector<MVT, 16> RetVals;
4580 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4582 SmallVector<MVT, 4> ValueVTs;
4583 ComputeValueVTs(*this, I->getType(), ValueVTs);
4584 for (unsigned Value = 0, NumValues = ValueVTs.size();
4585 Value != NumValues; ++Value) {
4586 MVT VT = ValueVTs[Value];
4587 const Type *ArgTy = VT.getTypeForMVT();
4588 ISD::ArgFlagsTy Flags;
4589 unsigned OriginalAlignment =
4590 getTargetData()->getABITypeAlignment(ArgTy);
4592 if (F.paramHasAttr(j, ParamAttr::ZExt))
4594 if (F.paramHasAttr(j, ParamAttr::SExt))
4596 if (F.paramHasAttr(j, ParamAttr::InReg))
4598 if (F.paramHasAttr(j, ParamAttr::StructRet))
4600 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4602 const PointerType *Ty = cast<PointerType>(I->getType());
4603 const Type *ElementTy = Ty->getElementType();
4604 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4605 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4606 // For ByVal, alignment should be passed from FE. BE will guess if
4607 // this info is not there but there are cases it cannot get right.
4608 if (F.getParamAlignment(j))
4609 FrameAlign = F.getParamAlignment(j);
4610 Flags.setByValAlign(FrameAlign);
4611 Flags.setByValSize(FrameSize);
4613 if (F.paramHasAttr(j, ParamAttr::Nest))
4615 Flags.setOrigAlign(OriginalAlignment);
4617 MVT RegisterVT = getRegisterType(VT);
4618 unsigned NumRegs = getNumRegisters(VT);
4619 for (unsigned i = 0; i != NumRegs; ++i) {
4620 RetVals.push_back(RegisterVT);
4621 ISD::ArgFlagsTy MyFlags = Flags;
4622 if (NumRegs > 1 && i == 0)
4624 // if it isn't first piece, alignment must be 1
4626 MyFlags.setOrigAlign(1);
4627 Ops.push_back(DAG.getArgFlags(MyFlags));
4632 RetVals.push_back(MVT::Other);
4635 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4636 DAG.getVTList(&RetVals[0], RetVals.size()),
4637 &Ops[0], Ops.size()).getNode();
4639 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4640 // allows exposing the loads that may be part of the argument access to the
4641 // first DAGCombiner pass.
4642 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
4644 // The number of results should match up, except that the lowered one may have
4645 // an extra flag result.
4646 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
4647 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
4648 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4649 && "Lowering produced unexpected number of results!");
4651 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
4652 if (Result != TmpRes.getNode() && Result->use_empty()) {
4653 HandleSDNode Dummy(DAG.getRoot());
4654 DAG.RemoveDeadNode(Result);
4657 Result = TmpRes.getNode();
4659 unsigned NumArgRegs = Result->getNumValues() - 1;
4660 DAG.setRoot(SDValue(Result, NumArgRegs));
4662 // Set up the return result vector.
4665 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4667 SmallVector<MVT, 4> ValueVTs;
4668 ComputeValueVTs(*this, I->getType(), ValueVTs);
4669 for (unsigned Value = 0, NumValues = ValueVTs.size();
4670 Value != NumValues; ++Value) {
4671 MVT VT = ValueVTs[Value];
4672 MVT PartVT = getRegisterType(VT);
4674 unsigned NumParts = getNumRegisters(VT);
4675 SmallVector<SDValue, 4> Parts(NumParts);
4676 for (unsigned j = 0; j != NumParts; ++j)
4677 Parts[j] = SDValue(Result, i++);
4679 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4680 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4681 AssertOp = ISD::AssertSext;
4682 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4683 AssertOp = ISD::AssertZext;
4685 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4689 assert(i == NumArgRegs && "Argument register count mismatch!");
4693 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4694 /// implementation, which just inserts an ISD::CALL node, which is later custom
4695 /// lowered by the target to something concrete. FIXME: When all targets are
4696 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4697 std::pair<SDValue, SDValue>
4698 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
4699 bool RetSExt, bool RetZExt, bool isVarArg,
4700 unsigned CallingConv, bool isTailCall,
4702 ArgListTy &Args, SelectionDAG &DAG) {
4703 SmallVector<SDValue, 32> Ops;
4704 Ops.push_back(Chain); // Op#0 - Chain
4705 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4706 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4707 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4708 Ops.push_back(Callee);
4710 // Handle all of the outgoing arguments.
4711 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4712 SmallVector<MVT, 4> ValueVTs;
4713 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4714 for (unsigned Value = 0, NumValues = ValueVTs.size();
4715 Value != NumValues; ++Value) {
4716 MVT VT = ValueVTs[Value];
4717 const Type *ArgTy = VT.getTypeForMVT();
4718 SDValue Op = SDValue(Args[i].Node.getNode(), Args[i].Node.getResNo() + Value);
4719 ISD::ArgFlagsTy Flags;
4720 unsigned OriginalAlignment =
4721 getTargetData()->getABITypeAlignment(ArgTy);
4727 if (Args[i].isInReg)
4731 if (Args[i].isByVal) {
4733 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4734 const Type *ElementTy = Ty->getElementType();
4735 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4736 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4737 // For ByVal, alignment should come from FE. BE will guess if this
4738 // info is not there but there are cases it cannot get right.
4739 if (Args[i].Alignment)
4740 FrameAlign = Args[i].Alignment;
4741 Flags.setByValAlign(FrameAlign);
4742 Flags.setByValSize(FrameSize);
4746 Flags.setOrigAlign(OriginalAlignment);
4748 MVT PartVT = getRegisterType(VT);
4749 unsigned NumParts = getNumRegisters(VT);
4750 SmallVector<SDValue, 4> Parts(NumParts);
4751 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4754 ExtendKind = ISD::SIGN_EXTEND;
4755 else if (Args[i].isZExt)
4756 ExtendKind = ISD::ZERO_EXTEND;
4758 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4760 for (unsigned i = 0; i != NumParts; ++i) {
4761 // if it isn't first piece, alignment must be 1
4762 ISD::ArgFlagsTy MyFlags = Flags;
4763 if (NumParts > 1 && i == 0)
4766 MyFlags.setOrigAlign(1);
4768 Ops.push_back(Parts[i]);
4769 Ops.push_back(DAG.getArgFlags(MyFlags));
4774 // Figure out the result value types. We start by making a list of
4775 // the potentially illegal return value types.
4776 SmallVector<MVT, 4> LoweredRetTys;
4777 SmallVector<MVT, 4> RetTys;
4778 ComputeValueVTs(*this, RetTy, RetTys);
4780 // Then we translate that to a list of legal types.
4781 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4783 MVT RegisterVT = getRegisterType(VT);
4784 unsigned NumRegs = getNumRegisters(VT);
4785 for (unsigned i = 0; i != NumRegs; ++i)
4786 LoweredRetTys.push_back(RegisterVT);
4789 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4791 // Create the CALL node.
4792 SDValue Res = DAG.getNode(ISD::CALL,
4793 DAG.getVTList(&LoweredRetTys[0],
4794 LoweredRetTys.size()),
4795 &Ops[0], Ops.size());
4796 Chain = Res.getValue(LoweredRetTys.size() - 1);
4798 // Gather up the call result into a single value.
4799 if (RetTy != Type::VoidTy) {
4800 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4803 AssertOp = ISD::AssertSext;
4805 AssertOp = ISD::AssertZext;
4807 SmallVector<SDValue, 4> ReturnValues;
4809 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4811 MVT RegisterVT = getRegisterType(VT);
4812 unsigned NumRegs = getNumRegisters(VT);
4813 unsigned RegNoEnd = NumRegs + RegNo;
4814 SmallVector<SDValue, 4> Results;
4815 for (; RegNo != RegNoEnd; ++RegNo)
4816 Results.push_back(Res.getValue(RegNo));
4817 SDValue ReturnValue =
4818 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4820 ReturnValues.push_back(ReturnValue);
4822 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4823 &ReturnValues[0], ReturnValues.size());
4826 return std::make_pair(Res, Chain);
4829 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
4830 assert(0 && "LowerOperation not implemented for this target!");
4836 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4837 SDValue Op = getValue(V);
4838 assert((Op.getOpcode() != ISD::CopyFromReg ||
4839 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4840 "Copy from a reg to the same reg!");
4841 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4843 RegsForValue RFV(TLI, Reg, V->getType());
4844 SDValue Chain = DAG.getEntryNode();
4845 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4846 PendingExports.push_back(Chain);
4849 #include "llvm/CodeGen/SelectionDAGISel.h"
4851 void SelectionDAGISel::
4852 LowerArguments(BasicBlock *LLVMBB) {
4853 // If this is the entry block, emit arguments.
4854 Function &F = *LLVMBB->getParent();
4855 SDValue OldRoot = SDL->DAG.getRoot();
4856 SmallVector<SDValue, 16> Args;
4857 TLI.LowerArguments(F, SDL->DAG, Args);
4860 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4862 SmallVector<MVT, 4> ValueVTs;
4863 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4864 unsigned NumValues = ValueVTs.size();
4865 if (!AI->use_empty()) {
4866 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
4867 // If this argument is live outside of the entry block, insert a copy from
4868 // whereever we got it to the vreg that other BB's will reference it as.
4869 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
4870 if (VMI != FuncInfo->ValueMap.end()) {
4871 SDL->CopyValueToVirtualRegister(AI, VMI->second);
4877 // Finally, if the target has anything special to do, allow it to do so.
4878 // FIXME: this should insert code into the DAG!
4879 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
4882 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4883 /// ensure constants are generated when needed. Remember the virtual registers
4884 /// that need to be added to the Machine PHI nodes as input. We cannot just
4885 /// directly add them, because expansion might result in multiple MBB's for one
4886 /// BB. As such, the start of the BB might correspond to a different MBB than
4890 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
4891 TerminatorInst *TI = LLVMBB->getTerminator();
4893 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
4895 // Check successor nodes' PHI nodes that expect a constant to be available
4897 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4898 BasicBlock *SuccBB = TI->getSuccessor(succ);
4899 if (!isa<PHINode>(SuccBB->begin())) continue;
4900 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
4902 // If this terminator has multiple identical successors (common for
4903 // switches), only handle each succ once.
4904 if (!SuccsHandled.insert(SuccMBB)) continue;
4906 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4909 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4910 // nodes and Machine PHI nodes, but the incoming operands have not been
4912 for (BasicBlock::iterator I = SuccBB->begin();
4913 (PN = dyn_cast<PHINode>(I)); ++I) {
4914 // Ignore dead phi's.
4915 if (PN->use_empty()) continue;
4918 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4920 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4921 unsigned &RegOut = SDL->ConstantsOut[C];
4923 RegOut = FuncInfo->CreateRegForValue(C);
4924 SDL->CopyValueToVirtualRegister(C, RegOut);
4928 Reg = FuncInfo->ValueMap[PHIOp];
4930 assert(isa<AllocaInst>(PHIOp) &&
4931 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4932 "Didn't codegen value into a register!??");
4933 Reg = FuncInfo->CreateRegForValue(PHIOp);
4934 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
4938 // Remember that this register needs to added to the machine PHI node as
4939 // the input for this MBB.
4940 SmallVector<MVT, 4> ValueVTs;
4941 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
4942 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
4943 MVT VT = ValueVTs[vti];
4944 unsigned NumRegisters = TLI.getNumRegisters(VT);
4945 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4946 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4947 Reg += NumRegisters;
4951 SDL->ConstantsOut.clear();
4954 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
4955 /// supports legal types, and it emits MachineInstrs directly instead of
4956 /// creating SelectionDAG nodes.
4959 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
4961 TerminatorInst *TI = LLVMBB->getTerminator();
4963 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
4964 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
4966 // Check successor nodes' PHI nodes that expect a constant to be available
4968 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4969 BasicBlock *SuccBB = TI->getSuccessor(succ);
4970 if (!isa<PHINode>(SuccBB->begin())) continue;
4971 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
4973 // If this terminator has multiple identical successors (common for
4974 // switches), only handle each succ once.
4975 if (!SuccsHandled.insert(SuccMBB)) continue;
4977 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4980 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4981 // nodes and Machine PHI nodes, but the incoming operands have not been
4983 for (BasicBlock::iterator I = SuccBB->begin();
4984 (PN = dyn_cast<PHINode>(I)); ++I) {
4985 // Ignore dead phi's.
4986 if (PN->use_empty()) continue;
4988 // Only handle legal types. Two interesting things to note here. First,
4989 // by bailing out early, we may leave behind some dead instructions,
4990 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
4991 // own moves. Second, this check is necessary becuase FastISel doesn't
4992 // use CreateRegForValue to create registers, so it always creates
4993 // exactly one register for each non-void instruction.
4994 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
4995 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
4996 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5000 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5002 unsigned Reg = F->getRegForValue(PHIOp);
5004 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5007 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));