| //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===// |
| // |
| // The LLVM Compiler Infrastructure |
| // |
| // This file is distributed under the University of Illinois Open Source |
| // License. See LICENSE.TXT for details. |
| // |
| //===----------------------------------------------------------------------===// |
| // |
| // This implements routines for translating from LLVM IR into SelectionDAG IR. |
| // |
| //===----------------------------------------------------------------------===// |
| |
| #define DEBUG_TYPE "isel" |
| #include "SDNodeDbgValue.h" |
| #include "SelectionDAGBuilder.h" |
| #include "llvm/ADT/BitVector.h" |
| #include "llvm/ADT/PostOrderIterator.h" |
| #include "llvm/ADT/SmallSet.h" |
| #include "llvm/Analysis/AliasAnalysis.h" |
| #include "llvm/Analysis/ConstantFolding.h" |
| #include "llvm/Constants.h" |
| #include "llvm/CallingConv.h" |
| #include "llvm/DerivedTypes.h" |
| #include "llvm/Function.h" |
| #include "llvm/GlobalVariable.h" |
| #include "llvm/InlineAsm.h" |
| #include "llvm/Instructions.h" |
| #include "llvm/Intrinsics.h" |
| #include "llvm/IntrinsicInst.h" |
| #include "llvm/LLVMContext.h" |
| #include "llvm/Module.h" |
| #include "llvm/CodeGen/Analysis.h" |
| #include "llvm/CodeGen/FastISel.h" |
| #include "llvm/CodeGen/FunctionLoweringInfo.h" |
| #include "llvm/CodeGen/GCStrategy.h" |
| #include "llvm/CodeGen/GCMetadata.h" |
| #include "llvm/CodeGen/MachineFunction.h" |
| #include "llvm/CodeGen/MachineFrameInfo.h" |
| #include "llvm/CodeGen/MachineInstrBuilder.h" |
| #include "llvm/CodeGen/MachineJumpTableInfo.h" |
| #include "llvm/CodeGen/MachineModuleInfo.h" |
| #include "llvm/CodeGen/MachineRegisterInfo.h" |
| #include "llvm/CodeGen/SelectionDAG.h" |
| #include "llvm/Analysis/DebugInfo.h" |
| #include "llvm/Target/TargetData.h" |
| #include "llvm/Target/TargetFrameLowering.h" |
| #include "llvm/Target/TargetInstrInfo.h" |
| #include "llvm/Target/TargetIntrinsicInfo.h" |
| #include "llvm/Target/TargetLibraryInfo.h" |
| #include "llvm/Target/TargetLowering.h" |
| #include "llvm/Target/TargetOptions.h" |
| #include "llvm/Support/CommandLine.h" |
| #include "llvm/Support/Debug.h" |
| #include "llvm/Support/ErrorHandling.h" |
| #include "llvm/Support/MathExtras.h" |
| #include "llvm/Support/raw_ostream.h" |
| #include <algorithm> |
| using namespace llvm; |
| |
| /// LimitFloatPrecision - Generate low-precision inline sequences for |
| /// some float libcalls (6, 8 or 12 bits). |
| static unsigned LimitFloatPrecision; |
| |
| static cl::opt<unsigned, true> |
| LimitFPPrecision("limit-float-precision", |
| cl::desc("Generate low-precision inline sequences " |
| "for some float libcalls"), |
| cl::location(LimitFloatPrecision), |
| cl::init(0)); |
| |
| // Limit the width of DAG chains. This is important in general to prevent |
| // prevent DAG-based analysis from blowing up. For example, alias analysis and |
| // load clustering may not complete in reasonable time. It is difficult to |
| // recognize and avoid this situation within each individual analysis, and |
| // future analyses are likely to have the same behavior. Limiting DAG width is |
| // the safe approach, and will be especially important with global DAGs. |
| // |
| // MaxParallelChains default is arbitrarily high to avoid affecting |
| // optimization, but could be lowered to improve compile time. Any ld-ld-st-st |
| // sequence over this should have been converted to llvm.memcpy by the |
| // frontend. It easy to induce this behavior with .ll code such as: |
| // %buffer = alloca [4096 x i8] |
| // %data = load [4096 x i8]* %argPtr |
| // store [4096 x i8] %data, [4096 x i8]* %buffer |
| static const unsigned MaxParallelChains = 64; |
| |
| static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL, |
| const SDValue *Parts, unsigned NumParts, |
| EVT PartVT, EVT ValueVT); |
| |
| /// getCopyFromParts - Create a value that contains the specified legal parts |
| /// combined into the value they represent. If the parts combine to a type |
| /// larger then ValueVT then AssertOp can be used to specify whether the extra |
| /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT |
| /// (ISD::AssertSext). |
| static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc DL, |
| const SDValue *Parts, |
| unsigned NumParts, EVT PartVT, EVT ValueVT, |
| ISD::NodeType AssertOp = ISD::DELETED_NODE) { |
| if (ValueVT.isVector()) |
| return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT); |
| |
| assert(NumParts > 0 && "No parts to assemble!"); |
| const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| SDValue Val = Parts[0]; |
| |
| if (NumParts > 1) { |
| // Assemble the value from multiple parts. |
| if (ValueVT.isInteger()) { |
| unsigned PartBits = PartVT.getSizeInBits(); |
| unsigned ValueBits = ValueVT.getSizeInBits(); |
| |
| // Assemble the power of 2 part. |
| unsigned RoundParts = NumParts & (NumParts - 1) ? |
| 1 << Log2_32(NumParts) : NumParts; |
| unsigned RoundBits = PartBits * RoundParts; |
| EVT RoundVT = RoundBits == ValueBits ? |
| ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); |
| SDValue Lo, Hi; |
| |
| EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); |
| |
| if (RoundParts > 2) { |
| Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, |
| PartVT, HalfVT); |
| Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, |
| RoundParts / 2, PartVT, HalfVT); |
| } else { |
| Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); |
| Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); |
| } |
| |
| if (TLI.isBigEndian()) |
| std::swap(Lo, Hi); |
| |
| Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); |
| |
| if (RoundParts < NumParts) { |
| // Assemble the trailing non-power-of-2 part. |
| unsigned OddParts = NumParts - RoundParts; |
| EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); |
| Hi = getCopyFromParts(DAG, DL, |
| Parts + RoundParts, OddParts, PartVT, OddVT); |
| |
| // Combine the round and odd parts. |
| Lo = Val; |
| if (TLI.isBigEndian()) |
| std::swap(Lo, Hi); |
| EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); |
| Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); |
| Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, |
| DAG.getConstant(Lo.getValueType().getSizeInBits(), |
| TLI.getPointerTy())); |
| Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); |
| Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); |
| } |
| } else if (PartVT.isFloatingPoint()) { |
| // FP split into multiple FP parts (for ppcf128) |
| assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) && |
| "Unexpected split"); |
| SDValue Lo, Hi; |
| Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); |
| Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); |
| if (TLI.isBigEndian()) |
| std::swap(Lo, Hi); |
| Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); |
| } else { |
| // FP split into integer parts (soft fp) |
| assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && |
| !PartVT.isVector() && "Unexpected split"); |
| EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); |
| Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT); |
| } |
| } |
| |
| // There is now one part, held in Val. Correct it to match ValueVT. |
| PartVT = Val.getValueType(); |
| |
| if (PartVT == ValueVT) |
| return Val; |
| |
| if (PartVT.isInteger() && ValueVT.isInteger()) { |
| if (ValueVT.bitsLT(PartVT)) { |
| // For a truncate, see if we have any information to |
| // indicate whether the truncated bits will always be |
| // zero or sign-extension. |
| if (AssertOp != ISD::DELETED_NODE) |
| Val = DAG.getNode(AssertOp, DL, PartVT, Val, |
| DAG.getValueType(ValueVT)); |
| return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); |
| } |
| return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); |
| } |
| |
| if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { |
| // FP_ROUND's are always exact here. |
| if (ValueVT.bitsLT(Val.getValueType())) |
| return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, |
| DAG.getTargetConstant(1, TLI.getPointerTy())); |
| |
| return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); |
| } |
| |
| if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) |
| return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); |
| |
| llvm_unreachable("Unknown mismatch!"); |
| } |
| |
| /// getCopyFromParts - Create a value that contains the specified legal parts |
| /// combined into the value they represent. If the parts combine to a type |
| /// larger then ValueVT then AssertOp can be used to specify whether the extra |
| /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT |
| /// (ISD::AssertSext). |
| static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL, |
| const SDValue *Parts, unsigned NumParts, |
| EVT PartVT, EVT ValueVT) { |
| assert(ValueVT.isVector() && "Not a vector value"); |
| assert(NumParts > 0 && "No parts to assemble!"); |
| const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| SDValue Val = Parts[0]; |
| |
| // Handle a multi-element vector. |
| if (NumParts > 1) { |
| EVT IntermediateVT, RegisterVT; |
| unsigned NumIntermediates; |
| unsigned NumRegs = |
| TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, |
| NumIntermediates, RegisterVT); |
| assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); |
| NumParts = NumRegs; // Silence a compiler warning. |
| assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); |
| assert(RegisterVT == Parts[0].getValueType() && |
| "Part type doesn't match part!"); |
| |
| // Assemble the parts into intermediate operands. |
| SmallVector<SDValue, 8> Ops(NumIntermediates); |
| if (NumIntermediates == NumParts) { |
| // If the register was not expanded, truncate or copy the value, |
| // as appropriate. |
| for (unsigned i = 0; i != NumParts; ++i) |
| Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, |
| PartVT, IntermediateVT); |
| } else if (NumParts > 0) { |
| // If the intermediate type was expanded, build the intermediate |
| // operands from the parts. |
| assert(NumParts % NumIntermediates == 0 && |
| "Must expand into a divisible number of parts!"); |
| unsigned Factor = NumParts / NumIntermediates; |
| for (unsigned i = 0; i != NumIntermediates; ++i) |
| Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, |
| PartVT, IntermediateVT); |
| } |
| |
| // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the |
| // intermediate operands. |
| Val = DAG.getNode(IntermediateVT.isVector() ? |
| ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL, |
| ValueVT, &Ops[0], NumIntermediates); |
| } |
| |
| // There is now one part, held in Val. Correct it to match ValueVT. |
| PartVT = Val.getValueType(); |
| |
| if (PartVT == ValueVT) |
| return Val; |
| |
| if (PartVT.isVector()) { |
| // If the element type of the source/dest vectors are the same, but the |
| // parts vector has more elements than the value vector, then we have a |
| // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the |
| // elements we want. |
| if (PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { |
| assert(PartVT.getVectorNumElements() > ValueVT.getVectorNumElements() && |
| "Cannot narrow, it would be a lossy transformation"); |
| return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, |
| DAG.getIntPtrConstant(0)); |
| } |
| |
| // Vector/Vector bitcast. |
| if (ValueVT.getSizeInBits() == PartVT.getSizeInBits()) |
| return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); |
| |
| assert(PartVT.getVectorNumElements() == ValueVT.getVectorNumElements() && |
| "Cannot handle this kind of promotion"); |
| // Promoted vector extract |
| bool Smaller = ValueVT.bitsLE(PartVT); |
| return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), |
| DL, ValueVT, Val); |
| |
| } |
| |
| // Trivial bitcast if the types are the same size and the destination |
| // vector type is legal. |
| if (PartVT.getSizeInBits() == ValueVT.getSizeInBits() && |
| TLI.isTypeLegal(ValueVT)) |
| return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); |
| |
| // Handle cases such as i8 -> <1 x i1> |
| assert(ValueVT.getVectorNumElements() == 1 && |
| "Only trivial scalar-to-vector conversions should get here!"); |
| |
| if (ValueVT.getVectorNumElements() == 1 && |
| ValueVT.getVectorElementType() != PartVT) { |
| bool Smaller = ValueVT.bitsLE(PartVT); |
| Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), |
| DL, ValueVT.getScalarType(), Val); |
| } |
| |
| return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val); |
| } |
| |
| |
| |
| |
| static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc dl, |
| SDValue Val, SDValue *Parts, unsigned NumParts, |
| EVT PartVT); |
| |
| /// getCopyToParts - Create a series of nodes that contain the specified value |
| /// split into legal parts. If the parts contain more bits than Val, then, for |
| /// integers, ExtendKind can be used to specify how to generate the extra bits. |
| static void getCopyToParts(SelectionDAG &DAG, DebugLoc DL, |
| SDValue Val, SDValue *Parts, unsigned NumParts, |
| EVT PartVT, |
| ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { |
| EVT ValueVT = Val.getValueType(); |
| |
| // Handle the vector case separately. |
| if (ValueVT.isVector()) |
| return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT); |
| |
| const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| unsigned PartBits = PartVT.getSizeInBits(); |
| unsigned OrigNumParts = NumParts; |
| assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!"); |
| |
| if (NumParts == 0) |
| return; |
| |
| assert(!ValueVT.isVector() && "Vector case handled elsewhere"); |
| if (PartVT == ValueVT) { |
| assert(NumParts == 1 && "No-op copy with multiple parts!"); |
| Parts[0] = Val; |
| return; |
| } |
| |
| if (NumParts * PartBits > ValueVT.getSizeInBits()) { |
| // If the parts cover more bits than the value has, promote the value. |
| if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { |
| assert(NumParts == 1 && "Do not know what to promote to!"); |
| Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); |
| } else { |
| assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && |
| ValueVT.isInteger() && |
| "Unknown mismatch!"); |
| ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); |
| Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); |
| if (PartVT == MVT::x86mmx) |
| Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); |
| } |
| } else if (PartBits == ValueVT.getSizeInBits()) { |
| // Different types of the same size. |
| assert(NumParts == 1 && PartVT != ValueVT); |
| Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); |
| } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { |
| // If the parts cover less bits than value has, truncate the value. |
| assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && |
| ValueVT.isInteger() && |
| "Unknown mismatch!"); |
| ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); |
| Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); |
| if (PartVT == MVT::x86mmx) |
| Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); |
| } |
| |
| // The value may have changed - recompute ValueVT. |
| ValueVT = Val.getValueType(); |
| assert(NumParts * PartBits == ValueVT.getSizeInBits() && |
| "Failed to tile the value with PartVT!"); |
| |
| if (NumParts == 1) { |
| assert(PartVT == ValueVT && "Type conversion failed!"); |
| Parts[0] = Val; |
| return; |
| } |
| |
| // Expand the value into multiple parts. |
| if (NumParts & (NumParts - 1)) { |
| // The number of parts is not a power of 2. Split off and copy the tail. |
| assert(PartVT.isInteger() && ValueVT.isInteger() && |
| "Do not know what to expand to!"); |
| unsigned RoundParts = 1 << Log2_32(NumParts); |
| unsigned RoundBits = RoundParts * PartBits; |
| unsigned OddParts = NumParts - RoundParts; |
| SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, |
| DAG.getIntPtrConstant(RoundBits)); |
| getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT); |
| |
| if (TLI.isBigEndian()) |
| // The odd parts were reversed by getCopyToParts - unreverse them. |
| std::reverse(Parts + RoundParts, Parts + NumParts); |
| |
| NumParts = RoundParts; |
| ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); |
| Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); |
| } |
| |
| // The number of parts is a power of 2. Repeatedly bisect the value using |
| // EXTRACT_ELEMENT. |
| Parts[0] = DAG.getNode(ISD::BITCAST, DL, |
| EVT::getIntegerVT(*DAG.getContext(), |
| ValueVT.getSizeInBits()), |
| Val); |
| |
| for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { |
| for (unsigned i = 0; i < NumParts; i += StepSize) { |
| unsigned ThisBits = StepSize * PartBits / 2; |
| EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); |
| SDValue &Part0 = Parts[i]; |
| SDValue &Part1 = Parts[i+StepSize/2]; |
| |
| Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, |
| ThisVT, Part0, DAG.getIntPtrConstant(1)); |
| Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, |
| ThisVT, Part0, DAG.getIntPtrConstant(0)); |
| |
| if (ThisBits == PartBits && ThisVT != PartVT) { |
| Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); |
| Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); |
| } |
| } |
| } |
| |
| if (TLI.isBigEndian()) |
| std::reverse(Parts, Parts + OrigNumParts); |
| } |
| |
| |
| /// getCopyToPartsVector - Create a series of nodes that contain the specified |
| /// value split into legal parts. |
| static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc DL, |
| SDValue Val, SDValue *Parts, unsigned NumParts, |
| EVT PartVT) { |
| EVT ValueVT = Val.getValueType(); |
| assert(ValueVT.isVector() && "Not a vector"); |
| const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| |
| if (NumParts == 1) { |
| if (PartVT == ValueVT) { |
| // Nothing to do. |
| } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { |
| // Bitconvert vector->vector case. |
| Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); |
| } else if (PartVT.isVector() && |
| PartVT.getVectorElementType() == ValueVT.getVectorElementType() && |
| PartVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { |
| EVT ElementVT = PartVT.getVectorElementType(); |
| // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in |
| // undef elements. |
| SmallVector<SDValue, 16> Ops; |
| for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) |
| Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, |
| ElementVT, Val, DAG.getIntPtrConstant(i))); |
| |
| for (unsigned i = ValueVT.getVectorNumElements(), |
| e = PartVT.getVectorNumElements(); i != e; ++i) |
| Ops.push_back(DAG.getUNDEF(ElementVT)); |
| |
| Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size()); |
| |
| // FIXME: Use CONCAT for 2x -> 4x. |
| |
| //SDValue UndefElts = DAG.getUNDEF(VectorTy); |
| //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); |
| } else if (PartVT.isVector() && |
| PartVT.getVectorElementType().bitsGE( |
| ValueVT.getVectorElementType()) && |
| PartVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { |
| |
| // Promoted vector extract |
| bool Smaller = PartVT.bitsLE(ValueVT); |
| Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), |
| DL, PartVT, Val); |
| } else{ |
| // Vector -> scalar conversion. |
| assert(ValueVT.getVectorNumElements() == 1 && |
| "Only trivial vector-to-scalar conversions should get here!"); |
| Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, |
| PartVT, Val, DAG.getIntPtrConstant(0)); |
| |
| bool Smaller = ValueVT.bitsLE(PartVT); |
| Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), |
| DL, PartVT, Val); |
| } |
| |
| Parts[0] = Val; |
| return; |
| } |
| |
| // Handle a multi-element vector. |
| EVT IntermediateVT, RegisterVT; |
| unsigned NumIntermediates; |
| unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, |
| IntermediateVT, |
| NumIntermediates, RegisterVT); |
| unsigned NumElements = ValueVT.getVectorNumElements(); |
| |
| assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); |
| NumParts = NumRegs; // Silence a compiler warning. |
| assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); |
| |
| // Split the vector into intermediate operands. |
| SmallVector<SDValue, 8> Ops(NumIntermediates); |
| for (unsigned i = 0; i != NumIntermediates; ++i) { |
| if (IntermediateVT.isVector()) |
| Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, |
| IntermediateVT, Val, |
| DAG.getIntPtrConstant(i * (NumElements / NumIntermediates))); |
| else |
| Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, |
| IntermediateVT, Val, DAG.getIntPtrConstant(i)); |
| } |
| |
| // Split the intermediate operands into legal parts. |
| if (NumParts == NumIntermediates) { |
| // If the register was not expanded, promote or copy the value, |
| // as appropriate. |
| for (unsigned i = 0; i != NumParts; ++i) |
| getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT); |
| } else if (NumParts > 0) { |
| // If the intermediate type was expanded, split each the value into |
| // legal parts. |
| assert(NumParts % NumIntermediates == 0 && |
| "Must expand into a divisible number of parts!"); |
| unsigned Factor = NumParts / NumIntermediates; |
| for (unsigned i = 0; i != NumIntermediates; ++i) |
| getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT); |
| } |
| } |
| |
| |
| |
| |
| namespace { |
| /// RegsForValue - This struct represents the registers (physical or virtual) |
| /// that a particular set of values is assigned, and the type information |
| /// about the value. The most common situation is to represent one value at a |
| /// time, but struct or array values are handled element-wise as multiple |
| /// values. The splitting of aggregates is performed recursively, so that we |
| /// never have aggregate-typed registers. The values at this point do not |
| /// necessarily have legal types, so each value may require one or more |
| /// registers of some legal type. |
| /// |
| struct RegsForValue { |
| /// ValueVTs - The value types of the values, which may not be legal, and |
| /// may need be promoted or synthesized from one or more registers. |
| /// |
| SmallVector<EVT, 4> ValueVTs; |
| |
| /// RegVTs - The value types of the registers. This is the same size as |
| /// ValueVTs and it records, for each value, what the type of the assigned |
| /// register or registers are. (Individual values are never synthesized |
| /// from more than one type of register.) |
| /// |
| /// With virtual registers, the contents of RegVTs is redundant with TLI's |
| /// getRegisterType member function, however when with physical registers |
| /// it is necessary to have a separate record of the types. |
| /// |
| SmallVector<EVT, 4> RegVTs; |
| |
| /// Regs - This list holds the registers assigned to the values. |
| /// Each legal or promoted value requires one register, and each |
| /// expanded value requires multiple registers. |
| /// |
| SmallVector<unsigned, 4> Regs; |
| |
| RegsForValue() {} |
| |
| RegsForValue(const SmallVector<unsigned, 4> ®s, |
| EVT regvt, EVT valuevt) |
| : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {} |
| |
| RegsForValue(LLVMContext &Context, const TargetLowering &tli, |
| unsigned Reg, Type *Ty) { |
| ComputeValueVTs(tli, Ty, ValueVTs); |
| |
| for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { |
| EVT ValueVT = ValueVTs[Value]; |
| unsigned NumRegs = tli.getNumRegisters(Context, ValueVT); |
| EVT RegisterVT = tli.getRegisterType(Context, ValueVT); |
| for (unsigned i = 0; i != NumRegs; ++i) |
| Regs.push_back(Reg + i); |
| RegVTs.push_back(RegisterVT); |
| Reg += NumRegs; |
| } |
| } |
| |
| /// areValueTypesLegal - Return true if types of all the values are legal. |
| bool areValueTypesLegal(const TargetLowering &TLI) { |
| for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { |
| EVT RegisterVT = RegVTs[Value]; |
| if (!TLI.isTypeLegal(RegisterVT)) |
| return false; |
| } |
| return true; |
| } |
| |
| /// append - Add the specified values to this one. |
| void append(const RegsForValue &RHS) { |
| ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end()); |
| RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end()); |
| Regs.append(RHS.Regs.begin(), RHS.Regs.end()); |
| } |
| |
| /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from |
| /// this value and returns the result as a ValueVTs value. This uses |
| /// Chain/Flag as the input and updates them for the output Chain/Flag. |
| /// If the Flag pointer is NULL, no flag is used. |
| SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, |
| DebugLoc dl, |
| SDValue &Chain, SDValue *Flag) const; |
| |
| /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the |
| /// specified value into the registers specified by this object. This uses |
| /// Chain/Flag as the input and updates them for the output Chain/Flag. |
| /// If the Flag pointer is NULL, no flag is used. |
| void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, |
| SDValue &Chain, SDValue *Flag) const; |
| |
| /// AddInlineAsmOperands - Add this value to the specified inlineasm node |
| /// operand list. This adds the code marker, matching input operand index |
| /// (if applicable), and includes the number of values added into it. |
| void AddInlineAsmOperands(unsigned Kind, |
| bool HasMatching, unsigned MatchingIdx, |
| SelectionDAG &DAG, |
| std::vector<SDValue> &Ops) const; |
| }; |
| } |
| |
| /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from |
| /// this value and returns the result as a ValueVT value. This uses |
| /// Chain/Flag as the input and updates them for the output Chain/Flag. |
| /// If the Flag pointer is NULL, no flag is used. |
| SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, |
| FunctionLoweringInfo &FuncInfo, |
| DebugLoc dl, |
| SDValue &Chain, SDValue *Flag) const { |
| // A Value with type {} or [0 x %t] needs no registers. |
| if (ValueVTs.empty()) |
| return SDValue(); |
| |
| const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| |
| // Assemble the legal parts into the final values. |
| SmallVector<SDValue, 4> Values(ValueVTs.size()); |
| SmallVector<SDValue, 8> Parts; |
| for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { |
| // Copy the legal parts from the registers. |
| EVT ValueVT = ValueVTs[Value]; |
| unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT); |
| EVT RegisterVT = RegVTs[Value]; |
| |
| Parts.resize(NumRegs); |
| for (unsigned i = 0; i != NumRegs; ++i) { |
| SDValue P; |
| if (Flag == 0) { |
| P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); |
| } else { |
| P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); |
| *Flag = P.getValue(2); |
| } |
| |
| Chain = P.getValue(1); |
| Parts[i] = P; |
| |
| // If the source register was virtual and if we know something about it, |
| // add an assert node. |
| if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || |
| !RegisterVT.isInteger() || RegisterVT.isVector()) |
| continue; |
| |
| const FunctionLoweringInfo::LiveOutInfo *LOI = |
| FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); |
| if (!LOI) |
| continue; |
| |
| unsigned RegSize = RegisterVT.getSizeInBits(); |
| unsigned NumSignBits = LOI->NumSignBits; |
| unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes(); |
| |
| // FIXME: We capture more information than the dag can represent. For |
| // now, just use the tightest assertzext/assertsext possible. |
| bool isSExt = true; |
| EVT FromVT(MVT::Other); |
| if (NumSignBits == RegSize) |
| isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1 |
| else if (NumZeroBits >= RegSize-1) |
| isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1 |
| else if (NumSignBits > RegSize-8) |
| isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8 |
| else if (NumZeroBits >= RegSize-8) |
| isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8 |
| else if (NumSignBits > RegSize-16) |
| isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16 |
| else if (NumZeroBits >= RegSize-16) |
| isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16 |
| else if (NumSignBits > RegSize-32) |
| isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32 |
| else if (NumZeroBits >= RegSize-32) |
| isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32 |
| else |
| continue; |
| |
| // Add an assertion node. |
| assert(FromVT != MVT::Other); |
| Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, |
| RegisterVT, P, DAG.getValueType(FromVT)); |
| } |
| |
| Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), |
| NumRegs, RegisterVT, ValueVT); |
| Part += NumRegs; |
| Parts.clear(); |
| } |
| |
| return DAG.getNode(ISD::MERGE_VALUES, dl, |
| DAG.getVTList(&ValueVTs[0], ValueVTs.size()), |
| &Values[0], ValueVTs.size()); |
| } |
| |
| /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the |
| /// specified value into the registers specified by this object. This uses |
| /// Chain/Flag as the input and updates them for the output Chain/Flag. |
| /// If the Flag pointer is NULL, no flag is used. |
| void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, |
| SDValue &Chain, SDValue *Flag) const { |
| const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| |
| // Get the list of the values's legal parts. |
| unsigned NumRegs = Regs.size(); |
| SmallVector<SDValue, 8> Parts(NumRegs); |
| for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { |
| EVT ValueVT = ValueVTs[Value]; |
| unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT); |
| EVT RegisterVT = RegVTs[Value]; |
| |
| getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), |
| &Parts[Part], NumParts, RegisterVT); |
| Part += NumParts; |
| } |
| |
| // Copy the parts into the registers. |
| SmallVector<SDValue, 8> Chains(NumRegs); |
| for (unsigned i = 0; i != NumRegs; ++i) { |
| SDValue Part; |
| if (Flag == 0) { |
| Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); |
| } else { |
| Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); |
| *Flag = Part.getValue(1); |
| } |
| |
| Chains[i] = Part.getValue(0); |
| } |
| |
| if (NumRegs == 1 || Flag) |
| // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is |
| // flagged to it. That is the CopyToReg nodes and the user are considered |
| // a single scheduling unit. If we create a TokenFactor and return it as |
| // chain, then the TokenFactor is both a predecessor (operand) of the |
| // user as well as a successor (the TF operands are flagged to the user). |
| // c1, f1 = CopyToReg |
| // c2, f2 = CopyToReg |
| // c3 = TokenFactor c1, c2 |
| // ... |
| // = op c3, ..., f2 |
| Chain = Chains[NumRegs-1]; |
| else |
| Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs); |
| } |
| |
| /// AddInlineAsmOperands - Add this value to the specified inlineasm node |
| /// operand list. This adds the code marker and includes the number of |
| /// values added into it. |
| void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, |
| unsigned MatchingIdx, |
| SelectionDAG &DAG, |
| std::vector<SDValue> &Ops) const { |
| const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| |
| unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); |
| if (HasMatching) |
| Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); |
| else if (!Regs.empty() && |
| TargetRegisterInfo::isVirtualRegister(Regs.front())) { |
| // Put the register class of the virtual registers in the flag word. That |
| // way, later passes can recompute register class constraints for inline |
| // assembly as well as normal instructions. |
| // Don't do this for tied operands that can use the regclass information |
| // from the def. |
| const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); |
| const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); |
| Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); |
| } |
| |
| SDValue Res = DAG.getTargetConstant(Flag, MVT::i32); |
| Ops.push_back(Res); |
| |
| for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { |
| unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); |
| EVT RegisterVT = RegVTs[Value]; |
| for (unsigned i = 0; i != NumRegs; ++i) { |
| assert(Reg < Regs.size() && "Mismatch in # registers expected"); |
| Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT)); |
| } |
| } |
| } |
| |
| void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa, |
| const TargetLibraryInfo *li) { |
| AA = &aa; |
| GFI = gfi; |
| LibInfo = li; |
| TD = DAG.getTarget().getTargetData(); |
| LPadToCallSiteMap.clear(); |
| } |
| |
| /// clear - Clear out the current SelectionDAG and the associated |
| /// state and prepare this SelectionDAGBuilder object to be used |
| /// for a new block. This doesn't clear out information about |
| /// additional blocks that are needed to complete switch lowering |
| /// or PHI node updating; that information is cleared out as it is |
| /// consumed. |
| void SelectionDAGBuilder::clear() { |
| NodeMap.clear(); |
| UnusedArgNodeMap.clear(); |
| PendingLoads.clear(); |
| PendingExports.clear(); |
| CurDebugLoc = DebugLoc(); |
| HasTailCall = false; |
| } |
| |
| /// clearDanglingDebugInfo - Clear the dangling debug information |
| /// map. This function is seperated from the clear so that debug |
| /// information that is dangling in a basic block can be properly |
| /// resolved in a different basic block. This allows the |
| /// SelectionDAG to resolve dangling debug information attached |
| /// to PHI nodes. |
| void SelectionDAGBuilder::clearDanglingDebugInfo() { |
| DanglingDebugInfoMap.clear(); |
| } |
| |
| /// getRoot - Return the current virtual root of the Selection DAG, |
| /// flushing any PendingLoad items. This must be done before emitting |
| /// a store or any other node that may need to be ordered after any |
| /// prior load instructions. |
| /// |
| SDValue SelectionDAGBuilder::getRoot() { |
| if (PendingLoads.empty()) |
| return DAG.getRoot(); |
| |
| if (PendingLoads.size() == 1) { |
| SDValue Root = PendingLoads[0]; |
| DAG.setRoot(Root); |
| PendingLoads.clear(); |
| return Root; |
| } |
| |
| // Otherwise, we have to make a token factor node. |
| SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, |
| &PendingLoads[0], PendingLoads.size()); |
| PendingLoads.clear(); |
| DAG.setRoot(Root); |
| return Root; |
| } |
| |
| /// getControlRoot - Similar to getRoot, but instead of flushing all the |
| /// PendingLoad items, flush all the PendingExports items. It is necessary |
| /// to do this before emitting a terminator instruction. |
| /// |
| SDValue SelectionDAGBuilder::getControlRoot() { |
| SDValue Root = DAG.getRoot(); |
| |
| if (PendingExports.empty()) |
| return Root; |
| |
| // Turn all of the CopyToReg chains into one factored node. |
| if (Root.getOpcode() != ISD::EntryToken) { |
| unsigned i = 0, e = PendingExports.size(); |
| for (; i != e; ++i) { |
| assert(PendingExports[i].getNode()->getNumOperands() > 1); |
| if (PendingExports[i].getNode()->getOperand(0) == Root) |
| break; // Don't add the root if we already indirectly depend on it. |
| } |
| |
| if (i == e) |
| PendingExports.push_back(Root); |
| } |
| |
| Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, |
| &PendingExports[0], |
| PendingExports.size()); |
| PendingExports.clear(); |
| DAG.setRoot(Root); |
| return Root; |
| } |
| |
| void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) { |
| if (DAG.GetOrdering(Node) != 0) return; // Already has ordering. |
| DAG.AssignOrdering(Node, SDNodeOrder); |
| |
| for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) |
| AssignOrderingToNode(Node->getOperand(I).getNode()); |
| } |
| |
| void SelectionDAGBuilder::visit(const Instruction &I) { |
| // Set up outgoing PHI node register values before emitting the terminator. |
| if (isa<TerminatorInst>(&I)) |
| HandlePHINodesInSuccessorBlocks(I.getParent()); |
| |
| CurDebugLoc = I.getDebugLoc(); |
| |
| visit(I.getOpcode(), I); |
| |
| if (!isa<TerminatorInst>(&I) && !HasTailCall) |
| CopyToExportRegsIfNeeded(&I); |
| |
| CurDebugLoc = DebugLoc(); |
| } |
| |
| void SelectionDAGBuilder::visitPHI(const PHINode &) { |
| llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); |
| } |
| |
| void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { |
| // Note: this doesn't use InstVisitor, because it has to work with |
| // ConstantExpr's in addition to instructions. |
| switch (Opcode) { |
| default: llvm_unreachable("Unknown instruction type encountered!"); |
| // Build the switch statement using the Instruction.def file. |
| #define HANDLE_INST(NUM, OPCODE, CLASS) \ |
| case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break; |
| #include "llvm/Instruction.def" |
| } |
| |
| // Assign the ordering to the freshly created DAG nodes. |
| if (NodeMap.count(&I)) { |
| ++SDNodeOrder; |
| AssignOrderingToNode(getValue(&I).getNode()); |
| } |
| } |
| |
| // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, |
| // generate the debug data structures now that we've seen its definition. |
| void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, |
| SDValue Val) { |
| DanglingDebugInfo &DDI = DanglingDebugInfoMap[V]; |
| if (DDI.getDI()) { |
| const DbgValueInst *DI = DDI.getDI(); |
| DebugLoc dl = DDI.getdl(); |
| unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); |
| MDNode *Variable = DI->getVariable(); |
| uint64_t Offset = DI->getOffset(); |
| SDDbgValue *SDV; |
| if (Val.getNode()) { |
| if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) { |
| SDV = DAG.getDbgValue(Variable, Val.getNode(), |
| Val.getResNo(), Offset, dl, DbgSDNodeOrder); |
| DAG.AddDbgValue(SDV, Val.getNode(), false); |
| } |
| } else |
| DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); |
| DanglingDebugInfoMap[V] = DanglingDebugInfo(); |
| } |
| } |
| |
| /// getValue - Return an SDValue for the given Value. |
| SDValue SelectionDAGBuilder::getValue(const Value *V) { |
| // If we already have an SDValue for this value, use it. It's important |
| // to do this first, so that we don't create a CopyFromReg if we already |
| // have a regular SDValue. |
| SDValue &N = NodeMap[V]; |
| if (N.getNode()) return N; |
| |
| // If there's a virtual register allocated and initialized for this |
| // value, use it. |
| DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); |
| if (It != FuncInfo.ValueMap.end()) { |
| unsigned InReg = It->second; |
| RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType()); |
| SDValue Chain = DAG.getEntryNode(); |
| N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL); |
| resolveDanglingDebugInfo(V, N); |
| return N; |
| } |
| |
| // Otherwise create a new SDValue and remember it. |
| SDValue Val = getValueImpl(V); |
| NodeMap[V] = Val; |
| resolveDanglingDebugInfo(V, Val); |
| return Val; |
| } |
| |
| /// getNonRegisterValue - Return an SDValue for the given Value, but |
| /// don't look in FuncInfo.ValueMap for a virtual register. |
| SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { |
| // If we already have an SDValue for this value, use it. |
| SDValue &N = NodeMap[V]; |
| if (N.getNode()) return N; |
| |
| // Otherwise create a new SDValue and remember it. |
| SDValue Val = getValueImpl(V); |
| NodeMap[V] = Val; |
| resolveDanglingDebugInfo(V, Val); |
| return Val; |
| } |
| |
| /// getValueImpl - Helper function for getValue and getNonRegisterValue. |
| /// Create an SDValue for the given value. |
| SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { |
| if (const Constant *C = dyn_cast<Constant>(V)) { |
| EVT VT = TLI.getValueType(V->getType(), true); |
| |
| if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) |
| return DAG.getConstant(*CI, VT); |
| |
| if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) |
| return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT); |
| |
| if (isa<ConstantPointerNull>(C)) |
| return DAG.getConstant(0, TLI.getPointerTy()); |
| |
| if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) |
| return DAG.getConstantFP(*CFP, VT); |
| |
| if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) |
| return DAG.getUNDEF(VT); |
| |
| if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { |
| visit(CE->getOpcode(), *CE); |
| SDValue N1 = NodeMap[V]; |
| assert(N1.getNode() && "visit didn't populate the NodeMap!"); |
| return N1; |
| } |
| |
| if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { |
| SmallVector<SDValue, 4> Constants; |
| for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); |
| OI != OE; ++OI) { |
| SDNode *Val = getValue(*OI).getNode(); |
| // If the operand is an empty aggregate, there are no values. |
| if (!Val) continue; |
| // Add each leaf value from the operand to the Constants list |
| // to form a flattened list of all the values. |
| for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) |
| Constants.push_back(SDValue(Val, i)); |
| } |
| |
| return DAG.getMergeValues(&Constants[0], Constants.size(), |
| getCurDebugLoc()); |
| } |
| |
| if (const ConstantDataSequential *CDS = |
| dyn_cast<ConstantDataSequential>(C)) { |
| SmallVector<SDValue, 4> Ops; |
| for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { |
| SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); |
| // Add each leaf value from the operand to the Constants list |
| // to form a flattened list of all the values. |
| for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) |
| Ops.push_back(SDValue(Val, i)); |
| } |
| |
| if (isa<ArrayType>(CDS->getType())) |
| return DAG.getMergeValues(&Ops[0], Ops.size(), getCurDebugLoc()); |
| return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), |
| VT, &Ops[0], Ops.size()); |
| } |
| |
| if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { |
| assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && |
| "Unknown struct or array constant!"); |
| |
| SmallVector<EVT, 4> ValueVTs; |
| ComputeValueVTs(TLI, C->getType(), ValueVTs); |
| unsigned NumElts = ValueVTs.size(); |
| if (NumElts == 0) |
| return SDValue(); // empty struct |
| SmallVector<SDValue, 4> Constants(NumElts); |
| for (unsigned i = 0; i != NumElts; ++i) { |
| EVT EltVT = ValueVTs[i]; |
| if (isa<UndefValue>(C)) |
| Constants[i] = DAG.getUNDEF(EltVT); |
| else if (EltVT.isFloatingPoint()) |
| Constants[i] = DAG.getConstantFP(0, EltVT); |
| else |
| Constants[i] = DAG.getConstant(0, EltVT); |
| } |
| |
| return DAG.getMergeValues(&Constants[0], NumElts, |
| getCurDebugLoc()); |
| } |
| |
| if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) |
| return DAG.getBlockAddress(BA, VT); |
| |
| VectorType *VecTy = cast<VectorType>(V->getType()); |
| unsigned NumElements = VecTy->getNumElements(); |
| |
| // Now that we know the number and type of the elements, get that number of |
| // elements into the Ops array based on what kind of constant it is. |
| SmallVector<SDValue, 16> Ops; |
| if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { |
| for (unsigned i = 0; i != NumElements; ++i) |
| Ops.push_back(getValue(CV->getOperand(i))); |
| } else { |
| assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); |
| EVT EltVT = TLI.getValueType(VecTy->getElementType()); |
| |
| SDValue Op; |
| if (EltVT.isFloatingPoint()) |
| Op = DAG.getConstantFP(0, EltVT); |
| else |
| Op = DAG.getConstant(0, EltVT); |
| Ops.assign(NumElements, Op); |
| } |
| |
| // Create a BUILD_VECTOR node. |
| return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), |
| VT, &Ops[0], Ops.size()); |
| } |
| |
| // If this is a static alloca, generate it as the frameindex instead of |
| // computation. |
| if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { |
| DenseMap<const AllocaInst*, int>::iterator SI = |
| FuncInfo.StaticAllocaMap.find(AI); |
| if (SI != FuncInfo.StaticAllocaMap.end()) |
| return DAG.getFrameIndex(SI->second, TLI.getPointerTy()); |
| } |
| |
| // If this is an instruction which fast-isel has deferred, select it now. |
| if (const Instruction *Inst = dyn_cast<Instruction>(V)) { |
| unsigned InReg = FuncInfo.InitializeRegForValue(Inst); |
| RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType()); |
| SDValue Chain = DAG.getEntryNode(); |
| return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL); |
| } |
| |
| llvm_unreachable("Can't get register for value!"); |
| } |
| |
| void SelectionDAGBuilder::visitRet(const ReturnInst &I) { |
| SDValue Chain = getControlRoot(); |
| SmallVector<ISD::OutputArg, 8> Outs; |
| SmallVector<SDValue, 8> OutVals; |
| |
| if (!FuncInfo.CanLowerReturn) { |
| unsigned DemoteReg = FuncInfo.DemoteRegister; |
| const Function *F = I.getParent()->getParent(); |
| |
| // Emit a store of the return value through the virtual register. |
| // Leave Outs empty so that LowerReturn won't try to load return |
| // registers the usual way. |
| SmallVector<EVT, 1> PtrValueVTs; |
| ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()), |
| PtrValueVTs); |
| |
| SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]); |
| SDValue RetOp = getValue(I.getOperand(0)); |
| |
| SmallVector<EVT, 4> ValueVTs; |
| SmallVector<uint64_t, 4> Offsets; |
| ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets); |
| unsigned NumValues = ValueVTs.size(); |
| |
| SmallVector<SDValue, 4> Chains(NumValues); |
| for (unsigned i = 0; i != NumValues; ++i) { |
| SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), |
| RetPtr.getValueType(), RetPtr, |
| DAG.getIntPtrConstant(Offsets[i])); |
| Chains[i] = |
| DAG.getStore(Chain, getCurDebugLoc(), |
| SDValue(RetOp.getNode(), RetOp.getResNo() + i), |
| // FIXME: better loc info would be nice. |
| Add, MachinePointerInfo(), false, false, 0); |
| } |
| |
| Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), |
| MVT::Other, &Chains[0], NumValues); |
| } else if (I.getNumOperands() != 0) { |
| SmallVector<EVT, 4> ValueVTs; |
| ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs); |
| unsigned NumValues = ValueVTs.size(); |
| if (NumValues) { |
| SDValue RetOp = getValue(I.getOperand(0)); |
| for (unsigned j = 0, f = NumValues; j != f; ++j) { |
| EVT VT = ValueVTs[j]; |
| |
| ISD::NodeType ExtendKind = ISD::ANY_EXTEND; |
| |
| const Function *F = I.getParent()->getParent(); |
| if (F->paramHasAttr(0, Attribute::SExt)) |
| ExtendKind = ISD::SIGN_EXTEND; |
| else if (F->paramHasAttr(0, Attribute::ZExt)) |
| ExtendKind = ISD::ZERO_EXTEND; |
| |
| if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) |
| VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind); |
| |
| unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT); |
| EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT); |
| SmallVector<SDValue, 4> Parts(NumParts); |
| getCopyToParts(DAG, getCurDebugLoc(), |
| SDValue(RetOp.getNode(), RetOp.getResNo() + j), |
| &Parts[0], NumParts, PartVT, ExtendKind); |
| |
| // 'inreg' on function refers to return value |
| ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); |
| if (F->paramHasAttr(0, Attribute::InReg)) |
| Flags.setInReg(); |
| |
| // Propagate extension type if any |
| if (ExtendKind == ISD::SIGN_EXTEND) |
| Flags.setSExt(); |
| else if (ExtendKind == ISD::ZERO_EXTEND) |
| Flags.setZExt(); |
| |
| for (unsigned i = 0; i < NumParts; ++i) { |
| Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), |
| /*isfixed=*/true)); |
| OutVals.push_back(Parts[i]); |
| } |
| } |
| } |
| } |
| |
| bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); |
| CallingConv::ID CallConv = |
| DAG.getMachineFunction().getFunction()->getCallingConv(); |
| Chain = TLI.LowerReturn(Chain, CallConv, isVarArg, |
| Outs, OutVals, getCurDebugLoc(), DAG); |
| |
| // Verify that the target's LowerReturn behaved as expected. |
| assert(Chain.getNode() && Chain.getValueType() == MVT::Other && |
| "LowerReturn didn't return a valid chain!"); |
| |
| // Update the DAG with the new chain value resulting from return lowering. |
| DAG.setRoot(Chain); |
| } |
| |
| /// CopyToExportRegsIfNeeded - If the given value has virtual registers |
| /// created for it, emit nodes to copy the value into the virtual |
| /// registers. |
| void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { |
| // Skip empty types |
| if (V->getType()->isEmptyTy()) |
| return; |
| |
| DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); |
| if (VMI != FuncInfo.ValueMap.end()) { |
| assert(!V->use_empty() && "Unused value assigned virtual registers!"); |
| CopyValueToVirtualRegister(V, VMI->second); |
| } |
| } |
| |
| /// ExportFromCurrentBlock - If this condition isn't known to be exported from |
| /// the current basic block, add it to ValueMap now so that we'll get a |
| /// CopyTo/FromReg. |
| void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { |
| // No need to export constants. |
| if (!isa<Instruction>(V) && !isa<Argument>(V)) return; |
| |
| // Already exported? |
| if (FuncInfo.isExportedInst(V)) return; |
| |
| unsigned Reg = FuncInfo.InitializeRegForValue(V); |
| CopyValueToVirtualRegister(V, Reg); |
| } |
| |
| bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, |
| const BasicBlock *FromBB) { |
| // The operands of the setcc have to be in this block. We don't know |
| // how to export them from some other block. |
| if (const Instruction *VI = dyn_cast<Instruction>(V)) { |
| // Can export from current BB. |
| if (VI->getParent() == FromBB) |
| return true; |
| |
| // Is already exported, noop. |
| return FuncInfo.isExportedInst(V); |
| } |
| |
| // If this is an argument, we can export it if the BB is the entry block or |
| // if it is already exported. |
| if (isa<Argument>(V)) { |
| if (FromBB == &FromBB->getParent()->getEntryBlock()) |
| return true; |
| |
| // Otherwise, can only export this if it is already exported. |
| return FuncInfo.isExportedInst(V); |
| } |
| |
| // Otherwise, constants can always be exported. |
| return true; |
| } |
| |
| /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. |
| uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src, |
| const MachineBasicBlock *Dst) const { |
| BranchProbabilityInfo *BPI = FuncInfo.BPI; |
| if (!BPI) |
| return 0; |
| const BasicBlock *SrcBB = Src->getBasicBlock(); |
| const BasicBlock *DstBB = Dst->getBasicBlock(); |
| return BPI->getEdgeWeight(SrcBB, DstBB); |
| } |
| |
| void SelectionDAGBuilder:: |
| addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst, |
| uint32_t Weight /* = 0 */) { |
| if (!Weight) |
| Weight = getEdgeWeight(Src, Dst); |
| Src->addSuccessor(Dst, Weight); |
| } |
| |
| |
| static bool InBlock(const Value *V, const BasicBlock *BB) { |
| if (const Instruction *I = dyn_cast<Instruction>(V)) |
| return I->getParent() == BB; |
| return true; |
| } |
| |
| /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. |
| /// This function emits a branch and is used at the leaves of an OR or an |
| /// AND operator tree. |
| /// |
| void |
| SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, |
| MachineBasicBlock *TBB, |
| MachineBasicBlock *FBB, |
| MachineBasicBlock *CurBB, |
| MachineBasicBlock *SwitchBB) { |
| const BasicBlock *BB = CurBB->getBasicBlock(); |
| |
| // If the leaf of the tree is a comparison, merge the condition into |
| // the caseblock. |
| if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { |
| // The operands of the cmp have to be in this block. We don't know |
| // how to export them from some other block. If this is the first block |
| // of the sequence, no exporting is needed. |
| if (CurBB == SwitchBB || |
| (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && |
| isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { |
| ISD::CondCode Condition; |
| if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { |
| Condition = getICmpCondCode(IC->getPredicate()); |
| } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) { |
| Condition = getFCmpCondCode(FC->getPredicate()); |
| if (TM.Options.NoNaNsFPMath) |
| Condition = getFCmpCodeWithoutNaN(Condition); |
| } else { |
| Condition = ISD::SETEQ; // silence warning. |
| llvm_unreachable("Unknown compare instruction"); |
| } |
| |
| CaseBlock CB(Condition, BOp->getOperand(0), |
| BOp->getOperand(1), NULL, TBB, FBB, CurBB); |
| SwitchCases.push_back(CB); |
| return; |
| } |
| } |
| |
| // Create a CaseBlock record representing this branch. |
| CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()), |
| NULL, TBB, FBB, CurBB); |
| SwitchCases.push_back(CB); |
| } |
| |
| /// FindMergedConditions - If Cond is an expression like |
| void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, |
| MachineBasicBlock *TBB, |
| MachineBasicBlock *FBB, |
| MachineBasicBlock *CurBB, |
| MachineBasicBlock *SwitchBB, |
| unsigned Opc) { |
| // If this node is not part of the or/and tree, emit it as a branch. |
| const Instruction *BOp = dyn_cast<Instruction>(Cond); |
| if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || |
| (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || |
| BOp->getParent() != CurBB->getBasicBlock() || |
| !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || |
| !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { |
| EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB); |
| return; |
| } |
| |
| // Create TmpBB after CurBB. |
| MachineFunction::iterator BBI = CurBB; |
| MachineFunction &MF = DAG.getMachineFunction(); |
| MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); |
| CurBB->getParent()->insert(++BBI, TmpBB); |
| |
| if (Opc == Instruction::Or) { |
| // Codegen X | Y as: |
| // jmp_if_X TBB |
| // jmp TmpBB |
| // TmpBB: |
| // jmp_if_Y TBB |
| // jmp FBB |
| // |
| |
| // Emit the LHS condition. |
| FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc); |
| |
| // Emit the RHS condition into TmpBB. |
| FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc); |
| } else { |
| assert(Opc == Instruction::And && "Unknown merge op!"); |
| // Codegen X & Y as: |
| // jmp_if_X TmpBB |
| // jmp FBB |
| // TmpBB: |
| // jmp_if_Y TBB |
| // jmp FBB |
| // |
| // This requires creation of TmpBB after CurBB. |
| |
| // Emit the LHS condition. |
| FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc); |
| |
| // Emit the RHS condition into TmpBB. |
| FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc); |
| } |
| } |
| |
| /// If the set of cases should be emitted as a series of branches, return true. |
| /// If we should emit this as a bunch of and/or'd together conditions, return |
| /// false. |
| bool |
| SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){ |
| if (Cases.size() != 2) return true; |
| |
| // If this is two comparisons of the same values or'd or and'd together, they |
| // will get folded into a single comparison, so don't emit two blocks. |
| if ((Cases[0].CmpLHS == Cases[1].CmpLHS && |
| Cases[0].CmpRHS == Cases[1].CmpRHS) || |
| (Cases[0].CmpRHS == Cases[1].CmpLHS && |
| Cases[0].CmpLHS == Cases[1].CmpRHS)) { |
| return false; |
| } |
| |
| // Handle: (X != null) | (Y != null) --> (X|Y) != 0 |
| // Handle: (X == null) & (Y == null) --> (X|Y) == 0 |
| if (Cases[0].CmpRHS == Cases[1].CmpRHS && |
| Cases[0].CC == Cases[1].CC && |
| isa<Constant>(Cases[0].CmpRHS) && |
| cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { |
| if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) |
| return false; |
| if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) |
| return false; |
| } |
| |
| return true; |
| } |
| |
| void SelectionDAGBuilder::visitBr(const BranchInst &I) { |
| MachineBasicBlock *BrMBB = FuncInfo.MBB; |
| |
| // Update machine-CFG edges. |
| MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; |
| |
| // Figure out which block is immediately after the current one. |
| MachineBasicBlock *NextBlock = 0; |
| MachineFunction::iterator BBI = BrMBB; |
| if (++BBI != FuncInfo.MF->end()) |
| NextBlock = BBI; |
| |
| if (I.isUnconditional()) { |
| // Update machine-CFG edges. |
| BrMBB->addSuccessor(Succ0MBB); |
| |
| // If this is not a fall-through branch, emit the branch. |
| if (Succ0MBB != NextBlock) |
| DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), |
| MVT::Other, getControlRoot(), |
| DAG.getBasicBlock(Succ0MBB))); |
| |
| return; |
| } |
| |
| // If this condition is one of the special cases we handle, do special stuff |
| // now. |
| const Value *CondVal = I.getCondition(); |
| MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; |
| |
| // If this is a series of conditions that are or'd or and'd together, emit |
| // this as a sequence of branches instead of setcc's with and/or operations. |
| // As long as jumps are not expensive, this should improve performance. |
| // For example, instead of something like: |
| // cmp A, B |
| // C = seteq |
| // cmp D, E |
| // F = setle |
| // or C, F |
| // jnz foo |
| // Emit: |
| // cmp A, B |
| // je foo |
| // cmp D, E |
| // jle foo |
| // |
| if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { |
| if (!TLI.isJumpExpensive() && |
| BOp->hasOneUse() && |
| (BOp->getOpcode() == Instruction::And || |
| BOp->getOpcode() == Instruction::Or)) { |
| FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, |
| BOp->getOpcode()); |
| // If the compares in later blocks need to use values not currently |
| // exported from this block, export them now. This block should always |
| // be the first entry. |
| assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); |
| |
| // Allow some cases to be rejected. |
| if (ShouldEmitAsBranches(SwitchCases)) { |
| for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { |
| ExportFromCurrentBlock(SwitchCases[i].CmpLHS); |
| ExportFromCurrentBlock(SwitchCases[i].CmpRHS); |
| } |
| |
| // Emit the branch for this block. |
| visitSwitchCase(SwitchCases[0], BrMBB); |
| SwitchCases.erase(SwitchCases.begin()); |
| return; |
| } |
| |
| // Okay, we decided not to do this, remove any inserted MBB's and clear |
| // SwitchCases. |
| for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) |
| FuncInfo.MF->erase(SwitchCases[i].ThisBB); |
| |
| SwitchCases.clear(); |
| } |
| } |
| |
| // Create a CaseBlock record representing this branch. |
| CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), |
| NULL, Succ0MBB, Succ1MBB, BrMBB); |
| |
| // Use visitSwitchCase to actually insert the fast branch sequence for this |
| // cond branch. |
| visitSwitchCase(CB, BrMBB); |
| } |
| |
| /// visitSwitchCase - Emits the necessary code to represent a single node in |
| /// the binary search tree resulting from lowering a switch instruction. |
| void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, |
| MachineBasicBlock *SwitchBB) { |
| SDValue Cond; |
| SDValue CondLHS = getValue(CB.CmpLHS); |
| DebugLoc dl = getCurDebugLoc(); |
| |
| // Build the setcc now. |
| if (CB.CmpMHS == NULL) { |
| // Fold "(X == true)" to X and "(X == false)" to !X to |
| // handle common cases produced by branch lowering. |
| if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && |
| CB.CC == ISD::SETEQ) |
| Cond = CondLHS; |
| else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && |
| CB.CC == ISD::SETEQ) { |
| SDValue True = DAG.getConstant(1, CondLHS.getValueType()); |
| Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); |
| } else |
| Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); |
| } else { |
| assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); |
| |
| const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); |
| const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); |
| |
| SDValue CmpOp = getValue(CB.CmpMHS); |
| EVT VT = CmpOp.getValueType(); |
| |
| if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { |
| Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT), |
| ISD::SETLE); |
| } else { |
| SDValue SUB = DAG.getNode(ISD::SUB, dl, |
| VT, CmpOp, DAG.getConstant(Low, VT)); |
| Cond = DAG.getSetCC(dl, MVT::i1, SUB, |
| DAG.getConstant(High-Low, VT), ISD::SETULE); |
| } |
| } |
| |
| // Update successor info |
| addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight); |
| addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight); |
| |
| // Set NextBlock to be the MBB immediately after the current one, if any. |
| // This is used to avoid emitting unnecessary branches to the next block. |
| MachineBasicBlock *NextBlock = 0; |
| MachineFunction::iterator BBI = SwitchBB; |
| if (++BBI != FuncInfo.MF->end()) |
| NextBlock = BBI; |
| |
| // If the lhs block is the next block, invert the condition so that we can |
| // fall through to the lhs instead of the rhs block. |
| if (CB.TrueBB == NextBlock) { |
| std::swap(CB.TrueBB, CB.FalseBB); |
| SDValue True = DAG.getConstant(1, Cond.getValueType()); |
| Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); |
| } |
| |
| SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, |
| MVT::Other, getControlRoot(), Cond, |
| DAG.getBasicBlock(CB.TrueBB)); |
| |
| // Insert the false branch. Do this even if it's a fall through branch, |
| // this makes it easier to do DAG optimizations which require inverting |
| // the branch condition. |
| BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, |
| DAG.getBasicBlock(CB.FalseBB)); |
| |
| DAG.setRoot(BrCond); |
| } |
| |
| /// visitJumpTable - Emit JumpTable node in the current MBB |
| void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { |
| // Emit the code for the jump table |
| assert(JT.Reg != -1U && "Should lower JT Header first!"); |
| EVT PTy = TLI.getPointerTy(); |
| SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), |
| JT.Reg, PTy); |
| SDValue Table = DAG.getJumpTable(JT.JTI, PTy); |
| SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(), |
| MVT::Other, Index.getValue(1), |
| Table, Index); |
| DAG.setRoot(BrJumpTable); |
| } |
| |
| /// visitJumpTableHeader - This function emits necessary code to produce index |
| /// in the JumpTable from switch case. |
| void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, |
| JumpTableHeader &JTH, |
| MachineBasicBlock *SwitchBB) { |
| // Subtract the lowest switch case value from the value being switched on and |
| // conditional branch to default mbb if the result is greater than the |
| // difference between smallest and largest cases. |
| SDValue SwitchOp = getValue(JTH.SValue); |
| EVT VT = SwitchOp.getValueType(); |
| SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp, |
| DAG.getConstant(JTH.First, VT)); |
| |
| // The SDNode we just created, which holds the value being switched on minus |
| // the smallest case value, needs to be copied to a virtual register so it |
| // can be used as an index into the jump table in a subsequent basic block. |
| // This value may be smaller or larger than the target's pointer type, and |
| // therefore require extension or truncating. |
| SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy()); |
| |
| unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy()); |
| SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(), |
| JumpTableReg, SwitchOp); |
| JT.Reg = JumpTableReg; |
| |
| // Emit the range check for the jump table, and branch to the default block |
| // for the switch statement if the value being switched on exceeds the largest |
| // case in the switch. |
| SDValue CMP = DAG.getSetCC(getCurDebugLoc(), |
| TLI.getSetCCResultType(Sub.getValueType()), Sub, |
| DAG.getConstant(JTH.Last-JTH.First,VT), |
| ISD::SETUGT); |
| |
| // Set NextBlock to be the MBB immediately after the current one, if any. |
| // This is used to avoid emitting unnecessary branches to the next block. |
| MachineBasicBlock *NextBlock = 0; |
| MachineFunction::iterator BBI = SwitchBB; |
| |
| if (++BBI != FuncInfo.MF->end()) |
| NextBlock = BBI; |
| |
| SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), |
| MVT::Other, CopyTo, CMP, |
| DAG.getBasicBlock(JT.Default)); |
| |
| if (JT.MBB != NextBlock) |
| BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond, |
| DAG.getBasicBlock(JT.MBB)); |
| |
| DAG.setRoot(BrCond); |
| } |
| |
| /// visitBitTestHeader - This function emits necessary code to produce value |
| /// suitable for "bit tests" |
| void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, |
| MachineBasicBlock *SwitchBB) { |
| // Subtract the minimum value |
| SDValue SwitchOp = getValue(B.SValue); |
| EVT VT = SwitchOp.getValueType(); |
| SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp, |
| DAG.getConstant(B.First, VT)); |
| |
| // Check range |
| SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(), |
| TLI.getSetCCResultType(Sub.getValueType()), |
| Sub, DAG.getConstant(B.Range, VT), |
| ISD::SETUGT); |
| |
| // Determine the type of the test operands. |
| bool UsePtrType = false; |
| if (!TLI.isTypeLegal(VT)) |
| UsePtrType = true; |
| else { |
| for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) |
| if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { |
| // Switch table case range are encoded into series of masks. |
| // Just use pointer type, it's guaranteed to fit. |
| UsePtrType = true; |
| break; |
| } |
| } |
| if (UsePtrType) { |
| VT = TLI.getPointerTy(); |
| Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT); |
| } |
| |
| B.RegVT = VT; |
| B.Reg = FuncInfo.CreateReg(VT); |
| SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(), |
| B.Reg, Sub); |
| |
| // Set NextBlock to be the MBB immediately after the current one, if any. |
| // This is used to avoid emitting unnecessary branches to the next block. |
| MachineBasicBlock *NextBlock = 0; |
| MachineFunction::iterator BBI = SwitchBB; |
| if (++BBI != FuncInfo.MF->end()) |
| NextBlock = BBI; |
| |
| MachineBasicBlock* MBB = B.Cases[0].ThisBB; |
| |
| addSuccessorWithWeight(SwitchBB, B.Default); |
| addSuccessorWithWeight(SwitchBB, MBB); |
| |
| SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), |
| MVT::Other, CopyTo, RangeCmp, |
| DAG.getBasicBlock(B.Default)); |
| |
| if (MBB != NextBlock) |
| BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo, |
| DAG.getBasicBlock(MBB)); |
| |
| DAG.setRoot(BrRange); |
| } |
| |
| /// visitBitTestCase - this function produces one "bit test" |
| void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, |
| MachineBasicBlock* NextMBB, |
| unsigned Reg, |
| BitTestCase &B, |
| MachineBasicBlock *SwitchBB) { |
| EVT VT = BB.RegVT; |
| SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), |
| Reg, VT); |
| SDValue Cmp; |
| unsigned PopCount = CountPopulation_64(B.Mask); |
| if (PopCount == 1) { |
| // Testing for a single bit; just compare the shift count with what it |
| // would need to be to shift a 1 bit in that position. |
| Cmp = DAG.getSetCC(getCurDebugLoc(), |
| TLI.getSetCCResultType(VT), |
| ShiftOp, |
| DAG.getConstant(CountTrailingZeros_64(B.Mask), VT), |
| ISD::SETEQ); |
| } else if (PopCount == BB.Range) { |
| // There is only one zero bit in the range, test for it directly. |
| Cmp = DAG.getSetCC(getCurDebugLoc(), |
| TLI.getSetCCResultType(VT), |
| ShiftOp, |
| DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), |
| ISD::SETNE); |
| } else { |
| // Make desired shift |
| SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT, |
| DAG.getConstant(1, VT), ShiftOp); |
| |
| // Emit bit tests and jumps |
| SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(), |
| VT, SwitchVal, DAG.getConstant(B.Mask, VT)); |
| Cmp = DAG.getSetCC(getCurDebugLoc(), |
| TLI.getSetCCResultType(VT), |
| AndOp, DAG.getConstant(0, VT), |
| ISD::SETNE); |
| } |
| |
| addSuccessorWithWeight(SwitchBB, B.TargetBB); |
| addSuccessorWithWeight(SwitchBB, NextMBB); |
| |
| SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), |
| MVT::Other, getControlRoot(), |
| Cmp, DAG.getBasicBlock(B.TargetBB)); |
| |
| // Set NextBlock to be the MBB immediately after the current one, if any. |
| // This is used to avoid emitting unnecessary branches to the next block. |
| MachineBasicBlock *NextBlock = 0; |
| MachineFunction::iterator BBI = SwitchBB; |
| if (++BBI != FuncInfo.MF->end()) |
| NextBlock = BBI; |
| |
| if (NextMBB != NextBlock) |
| BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd, |
| DAG.getBasicBlock(NextMBB)); |
| |
| DAG.setRoot(BrAnd); |
| } |
| |
| void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { |
| MachineBasicBlock *InvokeMBB = FuncInfo.MBB; |
| |
| // Retrieve successors. |
| MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; |
| MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)]; |
| |
| const Value *Callee(I.getCalledValue()); |
| if (isa<InlineAsm>(Callee)) |
| visitInlineAsm(&I); |
| else |
| LowerCallTo(&I, getValue(Callee), false, LandingPad); |
| |
| // If the value of the invoke is used outside of its defining block, make it |
| // available as a virtual register. |
| CopyToExportRegsIfNeeded(&I); |
| |
| // Update successor info |
| addSuccessorWithWeight(InvokeMBB, Return); |
| addSuccessorWithWeight(InvokeMBB, LandingPad); |
| |
| // Drop into normal successor. |
| DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), |
| MVT::Other, getControlRoot(), |
| DAG.getBasicBlock(Return))); |
| } |
| |
| void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { |
| llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); |
| } |
| |
| void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { |
| assert(FuncInfo.MBB->isLandingPad() && |
| "Call to landingpad not in landing pad!"); |
| |
| MachineBasicBlock *MBB = FuncInfo.MBB; |
| MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); |
| AddLandingPadInfo(LP, MMI, MBB); |
| |
| // If there aren't registers to copy the values into (e.g., during SjLj |
| // exceptions), then don't bother to create these DAG nodes. |
| if (TLI.getExceptionPointerRegister() == 0 && |
| TLI.getExceptionSelectorRegister() == 0) |
| return; |
| |
| SmallVector<EVT, 2> ValueVTs; |
| ComputeValueVTs(TLI, LP.getType(), ValueVTs); |
| |
| // Insert the EXCEPTIONADDR instruction. |
| assert(FuncInfo.MBB->isLandingPad() && |
| "Call to eh.exception not in landing pad!"); |
| SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); |
| SDValue Ops[2]; |
| Ops[0] = DAG.getRoot(); |
| SDValue Op1 = DAG.getNode(ISD::EXCEPTIONADDR, getCurDebugLoc(), VTs, Ops, 1); |
| SDValue Chain = Op1.getValue(1); |
| |
| // Insert the EHSELECTION instruction. |
| VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); |
| Ops[0] = Op1; |
| Ops[1] = Chain; |
| SDValue Op2 = DAG.getNode(ISD::EHSELECTION, getCurDebugLoc(), VTs, Ops, 2); |
| Chain = Op2.getValue(1); |
| Op2 = DAG.getSExtOrTrunc(Op2, getCurDebugLoc(), MVT::i32); |
| |
| Ops[0] = Op1; |
| Ops[1] = Op2; |
| SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), |
| DAG.getVTList(&ValueVTs[0], ValueVTs.size()), |
| &Ops[0], 2); |
| |
| std::pair<SDValue, SDValue> RetPair = std::make_pair(Res, Chain); |
| setValue(&LP, RetPair.first); |
| DAG.setRoot(RetPair.second); |
| } |
| |
| /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for |
| /// small case ranges). |
| bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR, |
| CaseRecVector& WorkList, |
| const Value* SV, |
| MachineBasicBlock *Default, |
| MachineBasicBlock *SwitchBB) { |
| Case& BackCase = *(CR.Range.second-1); |
| |
| // Size is the number of Cases represented by this range. |
| size_t Size = CR.Range.second - CR.Range.first; |
| if (Size > 3) |
| return false; |
| |
| // Get the MachineFunction which holds the current MBB. This is used when |
| // inserting any additional MBBs necessary to represent the switch. |
| MachineFunction *CurMF = FuncInfo.MF; |
| |
| // Figure out which block is immediately after the current one. |
| MachineBasicBlock *NextBlock = 0; |
| MachineFunction::iterator BBI = CR.CaseBB; |
| |
| if (++BBI != FuncInfo.MF->end()) |
| NextBlock = BBI; |
| |
| // If any two of the cases has the same destination, and if one value |
| // is the same as the other, but has one bit unset that the other has set, |
| // use bit manipulation to do two compares at once. For example: |
| // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" |
| // TODO: This could be extended to merge any 2 cases in switches with 3 cases. |
| // TODO: Handle cases where CR.CaseBB != SwitchBB. |
| if (Size == 2 && CR.CaseBB == SwitchBB) { |
| Case &Small = *CR.Range.first; |
| Case &Big = *(CR.Range.second-1); |
| |
| if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) { |
| const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue(); |
| const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue(); |
| |
| // Check that there is only one bit different. |
| if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 && |
| (SmallValue | BigValue) == BigValue) { |
| // Isolate the common bit. |
| APInt CommonBit = BigValue & ~SmallValue; |
| assert((SmallValue | CommonBit) == BigValue && |
| CommonBit.countPopulation() == 1 && "Not a common bit?"); |
| |
| SDValue CondLHS = getValue(SV); |
| EVT VT = CondLHS.getValueType(); |
| DebugLoc DL = getCurDebugLoc(); |
| |
| SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, |
| DAG.getConstant(CommonBit, VT)); |
| SDValue Cond = DAG.getSetCC(DL, MVT::i1, |
| Or, DAG.getConstant(BigValue, VT), |
| ISD::SETEQ); |
| |
| // Update successor info. |
| addSuccessorWithWeight(SwitchBB, Small.BB); |
| addSuccessorWithWeight(SwitchBB, Default); |
| |
| // Insert the true branch. |
| SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other, |
| getControlRoot(), Cond, |
| DAG.getBasicBlock(Small.BB)); |
| |
| // Insert the false branch. |
| BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, |
| DAG.getBasicBlock(Default)); |
| |
| DAG.setRoot(BrCond); |
| return true; |
| } |
| } |
| } |
| |
| // Rearrange the case blocks so that the last one falls through if possible. |
| if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) { |
| // The last case block won't fall through into 'NextBlock' if we emit the |
| // branches in this order. See if rearranging a case value would help. |
| for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) { |
| if (I->BB == NextBlock) { |
| std::swap(*I, BackCase); |
| break; |
| } |
| } |
| } |
| |
| // Create a CaseBlock record representing a conditional branch to |
| // the Case's target mbb if the value being switched on SV is equal |
| // to C. |
| MachineBasicBlock *CurBlock = CR.CaseBB; |
| for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) { |
| MachineBasicBlock *FallThrough; |
| if (I != E-1) { |
| FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock()); |
| CurMF->insert(BBI, FallThrough); |
| |
| // Put SV in a virtual register to make it available from the new blocks. |
| ExportFromCurrentBlock(SV); |
| } else { |
| // If the last case doesn't match, go to the default block. |
| FallThrough = Default; |
| } |
| |
| const Value *RHS, *LHS, *MHS; |
| ISD::CondCode CC; |
| if (I->High == I->Low) { |
| // This is just small small case range :) containing exactly 1 case |
| CC = ISD::SETEQ; |
| LHS = SV; RHS = I->High; MHS = NULL; |
| } else { |
| CC = ISD::SETLE; |
| LHS = I->Low; MHS = SV; RHS = I->High; |
| } |
| |
| uint32_t ExtraWeight = I->ExtraWeight; |
| CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough, |
| /* me */ CurBlock, |
| /* trueweight */ ExtraWeight / 2, /* falseweight */ ExtraWeight / 2); |
| |
| // If emitting the first comparison, just call visitSwitchCase to emit the |
| // code into the current block. Otherwise, push the CaseBlock onto the |
| // vector to be later processed by SDISel, and insert the node's MBB |
| // before the next MBB. |
| if (CurBlock == SwitchBB) |
| visitSwitchCase(CB, SwitchBB); |
| else |
| SwitchCases.push_back(CB); |
| |
| CurBlock = FallThrough; |
| } |
| |
| return true; |
| } |
| |
| static inline bool areJTsAllowed(const TargetLowering &TLI) { |
| return !TLI.getTargetMachine().Options.DisableJumpTables && |
| (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) || |
| TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other)); |
| } |
| |
| static APInt ComputeRange(const APInt &First, const APInt &Last) { |
| uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1; |
| APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth); |
| return (LastExt - FirstExt + 1ULL); |
| } |
| |
| /// handleJTSwitchCase - Emit jumptable for current switch case range |
| bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR, |
| CaseRecVector &WorkList, |
| const Value *SV, |
| MachineBasicBlock *Default, |
| MachineBasicBlock *SwitchBB) { |
| Case& FrontCase = *CR.Range.first; |
| Case& BackCase = *(CR.Range.second-1); |
| |
| const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); |
| const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); |
| |
| APInt TSize(First.getBitWidth(), 0); |
| for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) |
| TSize += I->size(); |
| |
| if (!areJTsAllowed(TLI) || TSize.ult(4)) |
| return false; |
| |
| APInt Range = ComputeRange(First, Last); |
| // The density is TSize / Range. Require at least 40%. |
| // It should not be possible for IntTSize to saturate for sane code, but make |
| // sure we handle Range saturation correctly. |
| uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10); |
| uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10); |
| if (IntTSize * 10 < IntRange * 4) |
| return false; |
| |
| DEBUG(dbgs() << "Lowering jump table\n" |
| << "First entry: " << First << ". Last entry: " << Last << '\n' |
| << "Range: " << Range << ". Size: " << TSize << ".\n\n"); |
| |
| // Get the MachineFunction which holds the current MBB. This is used when |
| // inserting any additional MBBs necessary to represent the switch. |
| MachineFunction *CurMF = FuncInfo.MF; |
| |
| // Figure out which block is immediately after the current one. |
| MachineFunction::iterator BBI = CR.CaseBB; |
| ++BBI; |
| |
| const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); |
| |
| // Create a new basic block to hold the code for loading the address |
| // of the jump table, and jumping to it. Update successor information; |
| // we will either branch to the default case for the switch, or the jump |
| // table. |
| MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB); |
| CurMF->insert(BBI, JumpTableBB); |
| |
| addSuccessorWithWeight(CR.CaseBB, Default); |
| addSuccessorWithWeight(CR.CaseBB, JumpTableBB); |
| |
| // Build a vector of destination BBs, corresponding to each target |
| // of the jump table. If the value of the jump table slot corresponds to |
| // a case statement, push the case's BB onto the vector, otherwise, push |
| // the default BB. |
| std::vector<MachineBasicBlock*> DestBBs; |
| APInt TEI = First; |
| for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) { |
| const APInt &Low = cast<ConstantInt>(I->Low)->getValue(); |
| const APInt &High = cast<ConstantInt>(I->High)->getValue(); |
| |
| if (Low.sle(TEI) && TEI.sle(High)) { |
| DestBBs.push_back(I->BB); |
| if (TEI==High) |
| ++I; |
| } else { |
| DestBBs.push_back(Default); |
| } |
| } |
| |
| // Update successor info. Add one edge to each unique successor. |
| BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs()); |
| for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), |
| E = DestBBs.end(); I != E; ++I) { |
| if (!SuccsHandled[(*I)->getNumber()]) { |
| SuccsHandled[(*I)->getNumber()] = true; |
| addSuccessorWithWeight(JumpTableBB, *I); |
| } |
| } |
| |
| // Create a jump table index for this jump table. |
| unsigned JTEncoding = TLI.getJumpTableEncoding(); |
| unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding) |
| ->createJumpTableIndex(DestBBs); |
| |
| // Set the jump table information so that we can codegen it as a second |
| // MachineBasicBlock |
| JumpTable JT(-1U, JTI, JumpTableBB, Default); |
| JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB)); |
| if (CR.CaseBB == SwitchBB) |
| visitJumpTableHeader(JT, JTH, SwitchBB); |
| |
| JTCases.push_back(JumpTableBlock(JTH, JT)); |
| return true; |
| } |
| |
| /// handleBTSplitSwitchCase - emit comparison and split binary search tree into |
| /// 2 subtrees. |
| bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR, |
| CaseRecVector& WorkList, |
| const Value* SV, |
| MachineBasicBlock *Default, |
| MachineBasicBlock *SwitchBB) { |
| // Get the MachineFunction which holds the current MBB. This is used when |
| // inserting any additional MBBs necessary to represent the switch. |
| MachineFunction *CurMF = FuncInfo.MF; |
| |
| // Figure out which block is immediately after the current one. |
| MachineFunction::iterator BBI = CR.CaseBB; |
| ++BBI; |
| |
| Case& FrontCase = *CR.Range.first; |
| Case& BackCase = *(CR.Range.second-1); |
| const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); |
| |
| // Size is the number of Cases represented by this range. |
| unsigned Size = CR.Range.second - CR.Range.first; |
| |
| const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); |
| const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); |
| double FMetric = 0; |
| CaseItr Pivot = CR.Range.first + Size/2; |
| |
| // Select optimal pivot, maximizing sum density of LHS and RHS. This will |
| // (heuristically) allow us to emit JumpTable's later. |
| APInt TSize(First.getBitWidth(), 0); |
| for (CaseItr I = CR.Range.first, E = CR.Range.second; |
| I!=E; ++I) |
| TSize += I->size(); |
| |
| APInt LSize = FrontCase.size(); |
| APInt RSize = TSize-LSize; |
| DEBUG(dbgs() << "Selecting best pivot: \n" |
| << "First: " << First << ", Last: " << Last <<'\n' |
| << "LSize: " << LSize << ", RSize: " << RSize << '\n'); |
| for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second; |
| J!=E; ++I, ++J) { |
| const APInt &LEnd = cast<ConstantInt>(I->High)->getValue(); |
| const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue(); |
| APInt Range = ComputeRange(LEnd, RBegin); |
| assert((Range - 2ULL).isNonNegative() && |
| "Invalid case distance"); |
| // Use volatile double here to avoid excess precision issues on some hosts, |
| // e.g. that use 80-bit X87 registers. |
| volatile double LDensity = |
| (double)LSize.roundToDouble() / |
| (LEnd - First + 1ULL).roundToDouble(); |
| volatile double RDensity = |
| (double)RSize.roundToDouble() / |
| (Last - RBegin + 1ULL).roundToDouble(); |
| double Metric = Range.logBase2()*(LDensity+RDensity); |
| // Should always split in some non-trivial place |
| DEBUG(dbgs() <<"=>Step\n" |
| << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n' |
| << "LDensity: " << LDensity |
| << ", RDensity: " << RDensity << '\n' |
| << "Metric: " << Metric << '\n'); |
| if (FMetric < Metric) { |
| Pivot = J; |
| FMetric = Metric; |
| DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n'); |
| } |
| |
| LSize += J->size(); |
| RSize -= J->size(); |
| } |
| if (areJTsAllowed(TLI)) { |
| // If our case is dense we *really* should handle it earlier! |
| assert((FMetric > 0) && "Should handle dense range earlier!"); |
| } else { |
| Pivot = CR.Range.first + Size/2; |
| } |
| |
| CaseRange LHSR(CR.Range.first, Pivot); |
| CaseRange RHSR(Pivot, CR.Range.second); |
| const Constant *C = Pivot->Low; |
| MachineBasicBlock *FalseBB = 0, *TrueBB = 0; |
| |
| // We know that we branch to the LHS if the Value being switched on is |
| // less than the Pivot value, C. We use this to optimize our binary |
| // tree a bit, by recognizing that if SV is greater than or equal to the |
| // LHS's Case Value, and that Case Value is exactly one less than the |
| // Pivot's Value, then we can branch directly to the LHS's Target, |
| // rather than creating a leaf node for it. |
| if ((LHSR.second - LHSR.first) == 1 && |
| LHSR.first->High == CR.GE && |
| cast<ConstantInt>(C)->getValue() == |
| (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) { |
| TrueBB = LHSR.first->BB; |
| } else { |
| TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB); |
| CurMF->insert(BBI, TrueBB); |
| WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR)); |
| |
| // Put SV in a virtual register to make it available from the new blocks. |
| ExportFromCurrentBlock(SV); |
| } |
| |
| // Similar to the optimization above, if the Value being switched on is |
| // known to be less than the Constant CR.LT, and the current Case Value |
| // is CR.LT - 1, then we can branch directly to the target block for |
| // the current Case Value, rather than emitting a RHS leaf node for it. |
| if ((RHSR.second - RHSR.first) == 1 && CR.LT && |
| cast<ConstantInt>(RHSR.first->Low)->getValue() == |
| (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) { |
| FalseBB = RHSR.first->BB; |
| } else { |
| FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB); |
| CurMF->insert(BBI, FalseBB); |
| WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR)); |
| |
| // Put SV in a virtual register to make it available from the new blocks. |
| ExportFromCurrentBlock(SV); |
| } |
| |
| // Create a CaseBlock record representing a conditional branch to |
| // the LHS node if the value being switched on SV is less than C. |
| // Otherwise, branch to LHS. |
| CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB); |
| |
| if (CR.CaseBB == SwitchBB) |
| visitSwitchCase(CB, SwitchBB); |
| else |
| SwitchCases.push_back(CB); |
| |
| return true; |
| } |
| |
| /// handleBitTestsSwitchCase - if current case range has few destination and |
| /// range span less, than machine word bitwidth, encode case range into series |
| /// of masks and emit bit tests with these masks. |
| bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR, |
| CaseRecVector& WorkList, |
| const Value* SV, |
| MachineBasicBlock* Default, |
| MachineBasicBlock *SwitchBB){ |
| EVT PTy = TLI.getPointerTy(); |
| unsigned IntPtrBits = PTy.getSizeInBits(); |
| |
| Case& FrontCase = *CR.Range.first; |
| Case& BackCase = *(CR.Range.second-1); |
| |
| // Get the MachineFunction which holds the current MBB. This is used when |
| // inserting any additional MBBs necessary to represent the switch. |
| MachineFunction *CurMF = FuncInfo.MF; |
| |
| // If target does not have legal shift left, do not emit bit tests at all. |
| if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy())) |
| return false; |
| |
| size_t numCmps = 0; |
| for (CaseItr I = CR.Range.first, E = CR.Range.second; |
| I!=E; ++I) { |
| // Single case counts one, case range - two. |
| numCmps += (I->Low == I->High ? 1 : 2); |
| } |
| |
| // Count unique destinations |
| SmallSet<MachineBasicBlock*, 4> Dests; |
| for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { |
| Dests.insert(I->BB); |
| if (Dests.size() > 3) |
| // Don't bother the code below, if there are too much unique destinations |
| return false; |
| } |
| DEBUG(dbgs() << "Total number of unique destinations: " |
| << Dests.size() << '\n' |
| << "Total number of comparisons: " << numCmps << '\n'); |
| |
| // Compute span of values. |
| const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue(); |
| const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue(); |
| |