#include "llvm/ADT/SmallSet.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Constants.h"
+#include "llvm/Constants.h"
#include "llvm/CallingConv.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetIntrinsicInfo.h"
#include "llvm/Target/TargetLowering.h"
-#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Compiler.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>
// Given an array type, recursively traverse the elements.
if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
const Type *EltTy = ATy->getElementType();
- uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
+ uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
StartingOffset + i * EltSize);
return;
}
+ // Interpret void as zero return values.
+ if (Ty == Type::VoidTy)
+ return;
// Base case: we can get an MVT for this LLVM IR type.
ValueVTs.push_back(TLI.getValueType(Ty));
if (Offsets)
if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
const Type *Ty = AI->getAllocatedType();
- uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
+ uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
unsigned Align =
std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
AI->getAlignment());
switch (F->getIntrinsicID()) {
default: break;
case Intrinsic::dbg_stoppoint: {
- DwarfWriter *DW = DAG.getDwarfWriter();
DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
-
- if (DW && DW->ValidDebugInfo(SPI->getContext())) {
- DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
- std::string Dir, FN;
- unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
- CU.getFilename(FN));
- unsigned idx = MF->getOrCreateDebugLocID(SrcFile,
- SPI->getLine(),
- SPI->getColumn());
- DL = DebugLoc::get(idx);
- }
-
+ if (isValidDebugInfoIntrinsic(*SPI, CodeGenOpt::Default))
+ DL = ExtractDebugLocation(*SPI, MF->getDebugLocInfo());
break;
}
case Intrinsic::dbg_func_start: {
- DwarfWriter *DW = DAG.getDwarfWriter();
- if (DW) {
- DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
- Value *SP = FSI->getSubprogram();
-
- if (DW->ValidDebugInfo(SP)) {
- DISubprogram Subprogram(cast<GlobalVariable>(SP));
- DICompileUnit CU(Subprogram.getCompileUnit());
- std::string Dir, FN;
- unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
- CU.getFilename(FN));
- unsigned Line = Subprogram.getLineNumber();
- DL = DebugLoc::get(MF->getOrCreateDebugLocID(SrcFile, Line, 0));
- }
- }
-
+ DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
+ if (isValidDebugInfoIntrinsic(*FSI, CodeGenOpt::Default))
+ DL = ExtractDebugLocation(*FSI, MF->getDebugLocInfo());
break;
}
}
if (NumParts > 1) {
// Assemble the value from multiple parts.
- if (!ValueVT.isVector()) {
+ if (!ValueVT.isVector() && ValueVT.isInteger()) {
unsigned PartBits = PartVT.getSizeInBits();
unsigned ValueBits = ValueVT.getSizeInBits();
ValueVT : MVT::getIntegerVT(RoundBits);
SDValue Lo, Hi;
- MVT HalfVT = ValueVT.isInteger() ?
- MVT::getIntegerVT(RoundBits/2) :
- MVT::getFloatingPointVT(RoundBits/2);
+ MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
if (RoundParts > 2) {
Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
}
- } else {
+ } else if (ValueVT.isVector()) {
// Handle a multi-element vector.
MVT IntermediateVT, RegisterVT;
unsigned NumIntermediates;
Val = DAG.getNode(IntermediateVT.isVector() ?
ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
ValueVT, &Ops[0], NumIntermediates);
+ } else if (PartVT.isFloatingPoint()) {
+ // FP split into multiple FP parts (for ppcf128)
+ assert(ValueVT == MVT(MVT::ppcf128) && PartVT == MVT(MVT::f64) &&
+ "Unexpected split");
+ SDValue Lo, Hi;
+ Lo = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[0]);
+ Hi = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(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");
+ MVT IntVT = MVT::getIntegerVT(ValueVT.getSizeInBits());
+ Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
}
}
if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
- assert(0 && "Unknown mismatch!");
+ llvm_unreachable("Unknown mismatch!");
return SDValue();
}
ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
} else {
- assert(0 && "Unknown mismatch!");
+ llvm_unreachable("Unknown mismatch!");
}
} else if (PartBits == ValueVT.getSizeInBits()) {
// Different types of the same size.
ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
} else {
- assert(0 && "Unknown mismatch!");
+ llvm_unreachable("Unknown mismatch!");
}
}
PendingExports.clear();
DAG.clear();
CurDebugLoc = DebugLoc::getUnknownLoc();
+ HasTailCall = false;
}
/// getRoot - Return the current virtual root of the Selection DAG,
// Note: this doesn't use InstVisitor, because it has to work with
// ConstantExpr's in addition to instructions.
switch (Opcode) {
- default: assert(0 && "Unknown instruction type encountered!");
- abort();
+ 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:return visit##OPCODE((CLASS&)I);
}
}
-void SelectionDAGLowering::visitAdd(User &I) {
- if (I.getType()->isFPOrFPVector())
- visitBinary(I, ISD::FADD);
- else
- visitBinary(I, ISD::ADD);
-}
-
-void SelectionDAGLowering::visitMul(User &I) {
- if (I.getType()->isFPOrFPVector())
- visitBinary(I, ISD::FMUL);
- else
- visitBinary(I, ISD::MUL);
-}
-
SDValue SelectionDAGLowering::getValue(const Value *V) {
SDValue &N = NodeMap[V];
if (N.getNode()) return N;
if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
return N = DAG.getConstantFP(*CFP, VT);
- if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
- !V->getType()->isAggregateType())
+ if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
return N = DAG.getUNDEF(VT);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
for (unsigned i = 0; i != NumElements; ++i)
Ops.push_back(getValue(CP->getOperand(i)));
} else {
- assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
- "Unknown vector constant!");
+ assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
MVT EltVT = TLI.getValueType(VecTy->getElementType());
SDValue Op;
- if (isa<UndefValue>(C))
- Op = DAG.getUNDEF(EltVT);
- else if (EltVT.isFloatingPoint())
+ if (EltVT.isFloatingPoint())
Op = DAG.getConstantFP(0, EltVT);
else
Op = DAG.getConstant(0, EltVT);
void SelectionDAGLowering::visitRet(ReturnInst &I) {
- if (I.getNumOperands() == 0) {
- DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
- MVT::Other, getControlRoot()));
- return;
- }
-
- SmallVector<SDValue, 8> NewValues;
- NewValues.push_back(getControlRoot());
+ SDValue Chain = getControlRoot();
+ SmallVector<ISD::OutputArg, 8> Outs;
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
SmallVector<MVT, 4> ValueVTs;
ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
if (F->paramHasAttr(0, Attribute::InReg))
Flags.setInReg();
- for (unsigned i = 0; i < NumParts; ++i) {
- NewValues.push_back(Parts[i]);
- NewValues.push_back(DAG.getArgFlags(Flags));
- }
+
+ // Propagate extension type if any
+ if (F->paramHasAttr(0, Attribute::SExt))
+ Flags.setSExt();
+ else if (F->paramHasAttr(0, Attribute::ZExt))
+ Flags.setZExt();
+
+ for (unsigned i = 0; i < NumParts; ++i)
+ Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
}
}
- DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
- &NewValues[0], NewValues.size()));
+
+ bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
+ unsigned CallConv = DAG.getMachineFunction().getFunction()->getCallingConv();
+ Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
+ Outs, 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 SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
+ if (!V->use_empty()) {
+ DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
+ if (VMI != FuncInfo.ValueMap.end())
+ CopyValueToVirtualRegister(V, VMI->second);
+ }
}
/// ExportFromCurrentBlock - If this condition isn't known to be exported from
case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
default:
- assert(0 && "Invalid FCmp predicate opcode!");
+ llvm_unreachable("Invalid FCmp predicate opcode!");
FOC = FPC = ISD::SETFALSE;
break;
}
case ICmpInst::ICMP_SGT: return ISD::SETGT;
case ICmpInst::ICMP_UGT: return ISD::SETUGT;
default:
- assert(0 && "Invalid ICmp predicate opcode!");
+ llvm_unreachable("Invalid ICmp predicate opcode!");
return ISD::SETNE;
}
}
Condition = getFCmpCondCode(FC->getPredicate());
} else {
Condition = ISD::SETEQ; // silence warning.
- assert(0 && "Unknown compare instruction");
+ llvm_unreachable("Unknown compare instruction");
}
CaseBlock CB(Condition, BOp->getOperand(0),
}
// Create a CaseBlock record representing this branch.
- CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
+ CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
NULL, TBB, FBB, CurBB);
SwitchCases.push_back(CB);
}
}
// Create a CaseBlock record representing this branch.
- CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
+ CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
NULL, Succ0MBB, Succ1MBB, CurMBB);
// Use visitSwitchCase to actually insert the fast branch sequence for this
// cond branch.
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() && CB.CC == ISD::SETEQ)
+ if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
+ CB.CC == ISD::SETEQ)
Cond = CondLHS;
- else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
+ 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
// If the value of the invoke is used outside of its defining block, make it
// available as a virtual register.
- if (!I.use_empty()) {
- DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
- if (VMI != FuncInfo.ValueMap.end())
- CopyValueToVirtualRegister(&I, VMI->second);
- }
+ CopyToExportRegsIfNeeded(&I);
// Update successor info
CurMBB->addSuccessor(Return);
// inserting any additional MBBs necessary to represent the switch.
MachineFunction *CurMF = CurMBB->getParent();
+ // 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) {
}
-void SelectionDAGLowering::visitSub(User &I) {
+void SelectionDAGLowering::visitFSub(User &I) {
// -0.0 - X --> fneg
const Type *Ty = I.getType();
if (isa<VectorType>(Ty)) {
if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
const VectorType *DestTy = cast<VectorType>(I.getType());
const Type *ElTy = DestTy->getElementType();
- if (ElTy->isFloatingPoint()) {
- unsigned VL = DestTy->getNumElements();
- std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
- Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
- if (CV == CNZ) {
- SDValue Op2 = getValue(I.getOperand(1));
- setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
- Op2.getValueType(), Op2));
- return;
- }
- }
- }
- }
- if (Ty->isFloatingPoint()) {
- if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
- if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
+ unsigned VL = DestTy->getNumElements();
+ std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
+ Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
+ if (CV == CNZ) {
SDValue Op2 = getValue(I.getOperand(1));
setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Op2.getValueType(), Op2));
return;
}
+ }
}
+ if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
+ if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
+ SDValue Op2 = getValue(I.getOperand(1));
+ setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
+ Op2.getValueType(), Op2));
+ return;
+ }
- visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
+ visitBinary(I, ISD::FSUB);
}
void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
SDValue Op1 = getValue(I.getOperand(0));
SDValue Op2 = getValue(I.getOperand(1));
ISD::CondCode Opcode = getICmpCondCode(predicate);
- setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
+
+ MVT DestVT = TLI.getValueType(I.getType());
+ setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
}
void SelectionDAGLowering::visitFCmp(User &I) {
SDValue Op1 = getValue(I.getOperand(0));
SDValue Op2 = getValue(I.getOperand(1));
ISD::CondCode Condition = getFCmpCondCode(predicate);
- setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
-}
-
-void SelectionDAGLowering::visitVICmp(User &I) {
- ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
- if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
- predicate = IC->getPredicate();
- else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
- predicate = ICmpInst::Predicate(IC->getPredicate());
- SDValue Op1 = getValue(I.getOperand(0));
- SDValue Op2 = getValue(I.getOperand(1));
- ISD::CondCode Opcode = getICmpCondCode(predicate);
- setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
- Op1, Op2, Opcode));
-}
-
-void SelectionDAGLowering::visitVFCmp(User &I) {
- FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
- if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
- predicate = FC->getPredicate();
- else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
- predicate = FCmpInst::Predicate(FC->getPredicate());
- SDValue Op1 = getValue(I.getOperand(0));
- SDValue Op2 = getValue(I.getOperand(1));
- ISD::CondCode Condition = getFCmpCondCode(predicate);
MVT DestVT = TLI.getValueType(I.getType());
-
- setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
+ setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
}
void SelectionDAGLowering::visitSelect(User &I) {
// Utility for visitShuffleVector - Returns true if the mask is mask starting
// from SIndx and increasing to the element length (undefs are allowed).
-static bool SequentialMask(SDValue Mask, unsigned SIndx) {
- unsigned MaskNumElts = Mask.getNumOperands();
- for (unsigned i = 0; i != MaskNumElts; ++i) {
- if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
- unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
- if (Idx != i + SIndx)
- return false;
- }
- }
+static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
+ unsigned MaskNumElts = Mask.size();
+ for (unsigned i = 0; i != MaskNumElts; ++i)
+ if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
+ return false;
return true;
}
void SelectionDAGLowering::visitShuffleVector(User &I) {
+ SmallVector<int, 8> Mask;
SDValue Src1 = getValue(I.getOperand(0));
SDValue Src2 = getValue(I.getOperand(1));
- SDValue Mask = getValue(I.getOperand(2));
+ // Convert the ConstantVector mask operand into an array of ints, with -1
+ // representing undef values.
+ SmallVector<Constant*, 8> MaskElts;
+ cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
+ MaskElts);
+ unsigned MaskNumElts = MaskElts.size();
+ for (unsigned i = 0; i != MaskNumElts; ++i) {
+ if (isa<UndefValue>(MaskElts[i]))
+ Mask.push_back(-1);
+ else
+ Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
+ }
+
MVT VT = TLI.getValueType(I.getType());
MVT SrcVT = Src1.getValueType();
- int MaskNumElts = Mask.getNumOperands();
- int SrcNumElts = SrcVT.getVectorNumElements();
+ unsigned SrcNumElts = SrcVT.getVectorNumElements();
if (SrcNumElts == MaskNumElts) {
- setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
- VT, Src1, Src2, Mask));
+ setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
+ &Mask[0]));
return;
}
// Normalize the shuffle vector since mask and vector length don't match.
- MVT MaskEltVT = Mask.getValueType().getVectorElementType();
-
if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
// Mask is longer than the source vectors and is a multiple of the source
// vectors. We can use concatenate vector to make the mask and vectors
// Pad both vectors with undefs to make them the same length as the mask.
unsigned NumConcat = MaskNumElts / SrcNumElts;
+ bool Src1U = Src1.getOpcode() == ISD::UNDEF;
+ bool Src2U = Src2.getOpcode() == ISD::UNDEF;
SDValue UndefVal = DAG.getUNDEF(SrcVT);
- SDValue* MOps1 = new SDValue[NumConcat];
- SDValue* MOps2 = new SDValue[NumConcat];
+ SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
+ SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
MOps1[0] = Src1;
MOps2[0] = Src2;
- for (unsigned i = 1; i != NumConcat; ++i) {
- MOps1[i] = UndefVal;
- MOps2[i] = UndefVal;
- }
- Src1 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
- VT, MOps1, NumConcat);
- Src2 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
- VT, MOps2, NumConcat);
-
- delete [] MOps1;
- delete [] MOps2;
+
+ Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
+ getCurDebugLoc(), VT,
+ &MOps1[0], NumConcat);
+ Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
+ getCurDebugLoc(), VT,
+ &MOps2[0], NumConcat);
// Readjust mask for new input vector length.
- SmallVector<SDValue, 8> MappedOps;
- for (int i = 0; i != MaskNumElts; ++i) {
- if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
- MappedOps.push_back(Mask.getOperand(i));
- } else {
- int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
- if (Idx < SrcNumElts)
- MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
- else
- MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
- MaskEltVT));
- }
+ SmallVector<int, 8> MappedOps;
+ for (unsigned i = 0; i != MaskNumElts; ++i) {
+ int Idx = Mask[i];
+ if (Idx < (int)SrcNumElts)
+ MappedOps.push_back(Idx);
+ else
+ MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
}
- Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
- Mask.getValueType(),
- &MappedOps[0], MappedOps.size());
-
- setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
- VT, Src1, Src2, Mask));
+ setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
+ &MappedOps[0]));
return;
}
if (SrcNumElts > MaskNumElts) {
- // Resulting vector is shorter than the incoming vector.
- if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
- // Shuffle extracts 1st vector.
- setValue(&I, Src1);
- return;
- }
-
- if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
- // Shuffle extracts 2nd vector.
- setValue(&I, Src2);
- return;
- }
-
// Analyze the access pattern of the vector to see if we can extract
// two subvectors and do the shuffle. The analysis is done by calculating
// the range of elements the mask access on both vectors.
int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
int MaxRange[2] = {-1, -1};
- for (int i = 0; i != MaskNumElts; ++i) {
- SDValue Arg = Mask.getOperand(i);
- if (Arg.getOpcode() != ISD::UNDEF) {
- assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
- int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
- int Input = 0;
- if (Idx >= SrcNumElts) {
- Input = 1;
- Idx -= SrcNumElts;
- }
- if (Idx > MaxRange[Input])
- MaxRange[Input] = Idx;
- if (Idx < MinRange[Input])
- MinRange[Input] = Idx;
+ for (unsigned i = 0; i != MaskNumElts; ++i) {
+ int Idx = Mask[i];
+ int Input = 0;
+ if (Idx < 0)
+ continue;
+
+ if (Idx >= (int)SrcNumElts) {
+ Input = 1;
+ Idx -= SrcNumElts;
}
+ if (Idx > MaxRange[Input])
+ MaxRange[Input] = Idx;
+ if (Idx < MinRange[Input])
+ MinRange[Input] = Idx;
}
// Check if the access is smaller than the vector size and can we find
int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
int StartIdx[2]; // StartIdx to extract from
for (int Input=0; Input < 2; ++Input) {
- if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
+ if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
RangeUse[Input] = 0; // Unused
StartIdx[Input] = 0;
- } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
+ } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
// Fits within range but we should see if we can find a good
// start index that is a multiple of the mask length.
- if (MaxRange[Input] < MaskNumElts) {
+ if (MaxRange[Input] < (int)MaskNumElts) {
RangeUse[Input] = 1; // Extract from beginning of the vector
StartIdx[Input] = 0;
} else {
StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
- if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
+ if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
StartIdx[Input] + MaskNumElts < SrcNumElts)
RangeUse[Input] = 1; // Extract from a multiple of the mask length.
}
}
}
// Calculate new mask.
- SmallVector<SDValue, 8> MappedOps;
- for (int i = 0; i != MaskNumElts; ++i) {
- SDValue Arg = Mask.getOperand(i);
- if (Arg.getOpcode() == ISD::UNDEF) {
- MappedOps.push_back(Arg);
- } else {
- int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
- if (Idx < SrcNumElts)
- MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
- else {
- Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
- MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
- }
- }
+ SmallVector<int, 8> MappedOps;
+ for (unsigned i = 0; i != MaskNumElts; ++i) {
+ int Idx = Mask[i];
+ if (Idx < 0)
+ MappedOps.push_back(Idx);
+ else if (Idx < (int)SrcNumElts)
+ MappedOps.push_back(Idx - StartIdx[0]);
+ else
+ MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
}
- Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
- Mask.getValueType(),
- &MappedOps[0], MappedOps.size());
- setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
- VT, Src1, Src2, Mask));
+ setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
+ &MappedOps[0]));
return;
}
}
MVT EltVT = VT.getVectorElementType();
MVT PtrVT = TLI.getPointerTy();
SmallVector<SDValue,8> Ops;
- for (int i = 0; i != MaskNumElts; ++i) {
- SDValue Arg = Mask.getOperand(i);
- if (Arg.getOpcode() == ISD::UNDEF) {
+ for (unsigned i = 0; i != MaskNumElts; ++i) {
+ if (Mask[i] < 0) {
Ops.push_back(DAG.getUNDEF(EltVT));
} else {
- assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
- int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
- if (Idx < SrcNumElts)
+ int Idx = Mask[i];
+ if (Idx < (int)SrcNumElts)
Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
else
if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
if (CI->getZExtValue() == 0) continue;
uint64_t Offs =
- TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
+ TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
SDValue OffsVal;
unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
if (PtrBits < 64) {
}
// N = N + Idx * ElementSize;
- uint64_t ElementSize = TD->getTypePaddedSize(Ty);
+ uint64_t ElementSize = TD->getTypeAllocSize(Ty);
SDValue IdxN = getValue(Idx);
// If the index is smaller or larger than intptr_t, truncate or extend
return; // getValue will auto-populate this.
const Type *Ty = I.getAllocatedType();
- uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
+ uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
unsigned Align =
std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
I.getAlignment());
DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
- const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
- MVT::Other);
+ SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
- VTs, 2, Ops, 3);
+ VTs, Ops, 3);
setValue(&I, DSA);
DAG.setRoot(DSA.getValue(1));
Ops.push_back(Op);
}
- std::vector<MVT> VTs;
- if (I.getType() != Type::VoidTy) {
- MVT VT = TLI.getValueType(I.getType());
- if (VT.isVector()) {
- const VectorType *DestTy = cast<VectorType>(I.getType());
- MVT EltVT = TLI.getValueType(DestTy->getElementType());
-
- VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
- assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
- }
-
- assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
- VTs.push_back(VT);
+ SmallVector<MVT, 4> ValueVTs;
+ ComputeValueVTs(TLI, I.getType(), ValueVTs);
+#ifndef NDEBUG
+ for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
+ assert(TLI.isTypeLegal(ValueVTs[Val]) &&
+ "Intrinsic uses a non-legal type?");
}
+#endif // NDEBUG
if (HasChain)
- VTs.push_back(MVT::Other);
+ ValueVTs.push_back(MVT::Other);
- const MVT *VTList = DAG.getNodeValueTypes(VTs);
+ SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
// Create the node.
SDValue Result;
if (IsTgtIntrinsic) {
// This is target intrinsic that touches memory
Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
- VTList, VTs.size(),
- &Ops[0], Ops.size(),
+ VTs, &Ops[0], Ops.size(),
Info.memVT, Info.ptrVal, Info.offset,
Info.align, Info.vol,
Info.readMem, Info.writeMem);
}
else if (!HasChain)
Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
- VTList, VTs.size(),
- &Ops[0], Ops.size());
+ VTs, &Ops[0], Ops.size());
else if (I.getType() != Type::VoidTy)
Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
- VTList, VTs.size(),
- &Ops[0], Ops.size());
+ VTs, &Ops[0], Ops.size());
else
Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
- VTList, VTs.size(),
- &Ops[0], Ops.size());
+ VTs, &Ops[0], Ops.size());
if (HasChain) {
SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
SDValue Op1 = getValue(I.getOperand(1));
SDValue Op2 = getValue(I.getOperand(2));
- MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
- SDValue Ops[] = { Op1, Op2 };
-
- SDValue Result = DAG.getNode(Op, getCurDebugLoc(),
- DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
+ SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
+ SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
setValue(&I, Result);
return 0;
return 0;
}
case Intrinsic::dbg_stoppoint: {
- DwarfWriter *DW = DAG.getDwarfWriter();
DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
- if (DW && DW->ValidDebugInfo(SPI.getContext())) {
+ if (isValidDebugInfoIntrinsic(SPI, CodeGenOpt::Default)) {
MachineFunction &MF = DAG.getMachineFunction();
- if (Fast)
- DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
+ DebugLoc Loc = ExtractDebugLocation(SPI, MF.getDebugLocInfo());
+ setCurDebugLoc(Loc);
+
+ if (OptLevel == CodeGenOpt::None)
+ DAG.setRoot(DAG.getDbgStopPoint(Loc, getRoot(),
SPI.getLine(),
SPI.getColumn(),
SPI.getContext()));
- DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
- std::string Dir, FN;
- unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
- CU.getFilename(FN));
- unsigned idx = MF.getOrCreateDebugLocID(SrcFile,
- SPI.getLine(), SPI.getColumn());
- setCurDebugLoc(DebugLoc::get(idx));
}
return 0;
}
case Intrinsic::dbg_region_start: {
DwarfWriter *DW = DAG.getDwarfWriter();
DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
- if (DW && DW->ValidDebugInfo(RSI.getContext())) {
+ if (isValidDebugInfoIntrinsic(RSI, OptLevel) && DW
+ && DW->ShouldEmitDwarfDebug()) {
unsigned LabelID =
DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
- if (Fast)
- DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
- getRoot(), LabelID));
+ DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
+ getRoot(), LabelID));
}
-
return 0;
}
case Intrinsic::dbg_region_end: {
DwarfWriter *DW = DAG.getDwarfWriter();
DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
- if (DW && DW->ValidDebugInfo(REI.getContext())) {
- unsigned LabelID =
- DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
- if (Fast)
- DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
- getRoot(), LabelID));
- }
+ if (!isValidDebugInfoIntrinsic(REI, OptLevel) || !DW
+ || !DW->ShouldEmitDwarfDebug())
+ return 0;
+
+ MachineFunction &MF = DAG.getMachineFunction();
+ DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
+
+ if (isInlinedFnEnd(REI, MF.getFunction())) {
+ // This is end of inlined function. Debugging information for inlined
+ // function is not handled yet (only supported by FastISel).
+ if (OptLevel == CodeGenOpt::None) {
+ unsigned ID = DW->RecordInlinedFnEnd(Subprogram);
+ if (ID != 0)
+ // Returned ID is 0 if this is unbalanced "end of inlined
+ // scope". This could happen if optimizer eats dbg intrinsics or
+ // "beginning of inlined scope" is not recoginized due to missing
+ // location info. In such cases, do ignore this region.end.
+ DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
+ getRoot(), ID));
+ }
+ return 0;
+ }
+
+ unsigned LabelID =
+ DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
+ DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
+ getRoot(), LabelID));
return 0;
}
case Intrinsic::dbg_func_start: {
DwarfWriter *DW = DAG.getDwarfWriter();
- if (!DW) return 0;
DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
- Value *SP = FSI.getSubprogram();
- if (SP && DW->ValidDebugInfo(SP)) {
- // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
- // what (most?) gdb expects.
- MachineFunction &MF = DAG.getMachineFunction();
- DISubprogram Subprogram(cast<GlobalVariable>(SP));
- DICompileUnit CompileUnit = Subprogram.getCompileUnit();
- std::string Dir, FN;
- unsigned SrcFile = DW->getOrCreateSourceID(CompileUnit.getDirectory(Dir),
- CompileUnit.getFilename(FN));
-
- // Record the source line but does not create a label for the normal
- // function start. It will be emitted at asm emission time. However,
- // create a label if this is a beginning of inlined function.
- unsigned Line = Subprogram.getLineNumber();
-
- if (Fast) {
- unsigned LabelID = DW->RecordSourceLine(Line, 0, SrcFile);
- if (DW->getRecordSourceLineCount() != 1)
- DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
- getRoot(), LabelID));
- }
+ if (!isValidDebugInfoIntrinsic(FSI, CodeGenOpt::None))
+ return 0;
- setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
+ MachineFunction &MF = DAG.getMachineFunction();
+ // This is a beginning of an inlined function.
+ if (isInlinedFnStart(FSI, MF.getFunction())) {
+ if (OptLevel != CodeGenOpt::None)
+ // FIXME: Debugging informaation for inlined function is only
+ // supported at CodeGenOpt::Node.
+ return 0;
+
+ DebugLoc PrevLoc = CurDebugLoc;
+ // If llvm.dbg.func.start is seen in a new block before any
+ // llvm.dbg.stoppoint intrinsic then the location info is unknown.
+ // FIXME : Why DebugLoc is reset at the beginning of each block ?
+ if (PrevLoc.isUnknown())
+ return 0;
+
+ // Record the source line.
+ setCurDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
+
+ if (!DW || !DW->ShouldEmitDwarfDebug())
+ return 0;
+ DebugLocTuple PrevLocTpl = MF.getDebugLocTuple(PrevLoc);
+ DISubprogram SP(cast<GlobalVariable>(FSI.getSubprogram()));
+ DICompileUnit CU(PrevLocTpl.CompileUnit);
+ unsigned LabelID = DW->RecordInlinedFnStart(SP, CU,
+ PrevLocTpl.Line,
+ PrevLocTpl.Col);
+ DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
+ getRoot(), LabelID));
+ return 0;
}
+ // This is a beginning of a new function.
+ MF.setDefaultDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
+
+ if (!DW || !DW->ShouldEmitDwarfDebug())
+ return 0;
+ // llvm.dbg.func_start also defines beginning of function scope.
+ DW->RecordRegionStart(cast<GlobalVariable>(FSI.getSubprogram()));
return 0;
}
case Intrinsic::dbg_declare: {
- if (Fast) {
- DwarfWriter *DW = DAG.getDwarfWriter();
- DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
- Value *Variable = DI.getVariable();
- if (DW && DW->ValidDebugInfo(Variable))
- DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
- getValue(DI.getAddress()), getValue(Variable)));
- } else {
- // FIXME: Do something sensible here when we support debug declare.
- }
+ if (OptLevel != CodeGenOpt::None)
+ // FIXME: Variable debug info is not supported here.
+ return 0;
+
+ DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
+ if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
+ return 0;
+
+ Value *Variable = DI.getVariable();
+ DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
+ getValue(DI.getAddress()), getValue(Variable)));
return 0;
}
case Intrinsic::eh_exception: {
- if (!CurMBB->isLandingPad()) {
- // FIXME: Mark exception register as live in. Hack for PR1508.
- unsigned Reg = TLI.getExceptionAddressRegister();
- if (Reg) CurMBB->addLiveIn(Reg);
- }
// Insert the EXCEPTIONADDR instruction.
+ assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
SDValue Ops[1];
Ops[0] = DAG.getRoot();
case Intrinsic::readcyclecounter: {
SDValue Op = getRoot();
SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
- DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
- &Op, 1);
+ DAG.getVTList(MVT::i64, MVT::Other),
+ &Op, 1);
setValue(&I, Tmp);
DAG.setRoot(Tmp.getValue(1));
return 0;
}
- case Intrinsic::part_select: {
- // Currently not implemented: just abort
- assert(0 && "part_select intrinsic not implemented");
- abort();
- }
- case Intrinsic::part_set: {
- // Currently not implemented: just abort
- assert(0 && "part_set intrinsic not implemented");
- abort();
- }
case Intrinsic::bswap:
setValue(&I, DAG.getNode(ISD::BSWAP, dl,
getValue(I.getOperand(1)).getValueType(),
case Intrinsic::stacksave: {
SDValue Op = getRoot();
SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
- DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
+ DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
setValue(&I, Tmp);
DAG.setRoot(Tmp.getValue(1));
return 0;
Ops[5] = DAG.getSrcValue(F);
SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
- DAG.getNodeValueTypes(TLI.getPointerTy(),
- MVT::Other), 2,
- Ops, 6);
+ DAG.getVTList(TLI.getPointerTy(), MVT::Other),
+ Ops, 6);
setValue(&I, Tmp);
DAG.setRoot(Tmp.getValue(1));
case Intrinsic::gcread:
case Intrinsic::gcwrite:
- assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
+ llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
return 0;
case Intrinsic::flt_rounds: {
}
}
+/// Test if the given instruction is in a position to be optimized
+/// with a tail-call. This roughly means that it's in a block with
+/// a return and there's nothing that needs to be scheduled
+/// between it and the return.
+///
+/// This function only tests target-independent requirements.
+/// For target-dependent requirements, a target should override
+/// TargetLowering::IsEligibleForTailCallOptimization.
+///
+static bool
+isInTailCallPosition(const Instruction *I, Attributes RetAttr,
+ const TargetLowering &TLI) {
+ const BasicBlock *ExitBB = I->getParent();
+ const TerminatorInst *Term = ExitBB->getTerminator();
+ const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
+ const Function *F = ExitBB->getParent();
+
+ // The block must end in a return statement or an unreachable.
+ if (!Ret && !isa<UnreachableInst>(Term)) return false;
+
+ // If I will have a chain, make sure no other instruction that will have a
+ // chain interposes between I and the return.
+ if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
+ !I->isSafeToSpeculativelyExecute())
+ for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
+ --BBI) {
+ if (&*BBI == I)
+ break;
+ if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
+ !BBI->isSafeToSpeculativelyExecute())
+ return false;
+ }
+
+ // If the block ends with a void return or unreachable, it doesn't matter
+ // what the call's return type is.
+ if (!Ret || Ret->getNumOperands() == 0) return true;
+
+ // Conservatively require the attributes of the call to match those of
+ // the return.
+ if (F->getAttributes().getRetAttributes() != RetAttr)
+ return false;
+
+ // Otherwise, make sure the unmodified return value of I is the return value.
+ for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
+ U = dyn_cast<Instruction>(U->getOperand(0))) {
+ if (!U)
+ return false;
+ if (!U->hasOneUse())
+ return false;
+ if (U == I)
+ break;
+ // Check for a truly no-op truncate.
+ if (isa<TruncInst>(U) &&
+ TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
+ continue;
+ // Check for a truly no-op bitcast.
+ if (isa<BitCastInst>(U) &&
+ (U->getOperand(0)->getType() == U->getType() ||
+ (isa<PointerType>(U->getOperand(0)->getType()) &&
+ isa<PointerType>(U->getType()))))
+ continue;
+ // Otherwise it's not a true no-op.
+ return false;
+ }
+
+ return true;
+}
void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
- bool IsTailCall,
+ bool isTailCall,
MachineBasicBlock *LandingPad) {
const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
TargetLowering::ArgListTy Args;
TargetLowering::ArgListEntry Entry;
Args.reserve(CS.arg_size());
+ unsigned j = 1;
for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
- i != e; ++i) {
+ i != e; ++i, ++j) {
SDValue ArgNode = getValue(*i);
Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
getControlRoot(), BeginLabel));
}
+ // Check if target-independent constraints permit a tail call here.
+ // Target-dependent constraints are checked within TLI.LowerCallTo.
+ if (isTailCall &&
+ !isInTailCallPosition(CS.getInstruction(),
+ CS.getAttributes().getRetAttributes(),
+ TLI))
+ isTailCall = false;
+
std::pair<SDValue,SDValue> Result =
TLI.LowerCallTo(getRoot(), CS.getType(),
CS.paramHasAttr(0, Attribute::SExt),
CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
- CS.paramHasAttr(0, Attribute::InReg),
+ CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
CS.getCallingConv(),
- IsTailCall && PerformTailCallOpt,
+ isTailCall,
+ !CS.getInstruction()->use_empty(),
Callee, Args, DAG, getCurDebugLoc());
- if (CS.getType() != Type::VoidTy)
+ assert((isTailCall || Result.second.getNode()) &&
+ "Non-null chain expected with non-tail call!");
+ assert((Result.second.getNode() || !Result.first.getNode()) &&
+ "Null value expected with tail call!");
+ if (Result.first.getNode())
setValue(CS.getInstruction(), Result.first);
- DAG.setRoot(Result.second);
+ // As a special case, a null chain means that a tail call has
+ // been emitted and the DAG root is already updated.
+ if (Result.second.getNode())
+ DAG.setRoot(Result.second);
+ else
+ HasTailCall = true;
if (LandingPad && MMI) {
// Insert a label at the end of the invoke call to mark the try range. This
// Check for well-known libc/libm calls. If the function is internal, it
// can't be a library call.
- unsigned NameLen = F->getNameLen();
- if (!F->hasLocalLinkage() && NameLen) {
- const char *NameStr = F->getNameStart();
- if (NameStr[0] == 'c' &&
- ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
- (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
+ if (!F->hasLocalLinkage() && F->hasName()) {
+ StringRef Name = F->getName();
+ if (Name == "copysign" || Name == "copysignf") {
if (I.getNumOperands() == 3 && // Basic sanity checks.
I.getOperand(1)->getType()->isFloatingPoint() &&
I.getType() == I.getOperand(1)->getType() &&
LHS.getValueType(), LHS, RHS));
return;
}
- } else if (NameStr[0] == 'f' &&
- ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
- (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
- (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
+ } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
if (I.getNumOperands() == 2 && // Basic sanity checks.
I.getOperand(1)->getType()->isFloatingPoint() &&
I.getType() == I.getOperand(1)->getType()) {
Tmp.getValueType(), Tmp));
return;
}
- } else if (NameStr[0] == 's' &&
- ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
- (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
- (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
+ } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
if (I.getNumOperands() == 2 && // Basic sanity checks.
I.getOperand(1)->getType()->isFloatingPoint() &&
I.getType() == I.getOperand(1)->getType()) {
Tmp.getValueType(), Tmp));
return;
}
- } else if (NameStr[0] == 'c' &&
- ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
- (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
- (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
+ } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
if (I.getNumOperands() == 2 && // Basic sanity checks.
I.getOperand(1)->getType()->isFloatingPoint() &&
I.getType() == I.getOperand(1)->getType()) {
else
Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
- LowerCallTo(&I, Callee, I.isTailCall());
+ // Check if we can potentially perform a tail call. More detailed
+ // checking is be done within LowerCallTo, after more information
+ // about the call is known.
+ bool isTailCall = PerformTailCallOpt && I.isTailCall();
+
+ LowerCallTo(&I, Callee, isTailCall);
}
if (CType == TargetLowering::C_Memory)
return true;
}
+
+ // Indirect operand accesses access memory.
+ if (CI.isIndirect)
+ return true;
}
return false;
/// ConstraintOperands - Information about all of the constraints.
std::vector<SDISelAsmOperandInfo> ConstraintOperands;
- SDValue Chain = getRoot();
- SDValue Flag;
-
std::set<unsigned> OutputRegs, InputRegs;
// Do a prepass over the constraints, canonicalizing them, and building up the
ConstraintInfos = IA->ParseConstraints();
bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
+
+ SDValue Chain, Flag;
+
+ // We won't need to flush pending loads if this asm doesn't touch
+ // memory and is nonvolatile.
+ if (hasMemory || IA->hasSideEffects())
+ Chain = getRoot();
+ else
+ Chain = DAG.getRoot();
unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
unsigned ResNo = 0; // ResNo - The result number of the next output.
// If this is an input or an indirect output, process the call argument.
// BasicBlocks are labels, currently appearing only in asm's.
if (OpInfo.CallOperandVal) {
+ // Strip bitcasts, if any. This mostly comes up for functions.
+ OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
+
if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
} else {
Input.ConstraintVT.isInteger()) ||
(OpInfo.ConstraintVT.getSizeInBits() !=
Input.ConstraintVT.getSizeInBits())) {
- cerr << "Unsupported asm: input constraint with a matching output "
- << "constraint of incompatible type!\n";
- exit(1);
+ llvm_report_error("Unsupported asm: input constraint"
+ " with a matching output constraint of incompatible"
+ " type!");
}
Input.ConstraintVT = OpInfo.ConstraintVT;
}
// Otherwise, create a stack slot and emit a store to it before the
// asm.
const Type *Ty = OpVal->getType();
- uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
+ uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
MachineFunction &MF = DAG.getMachineFunction();
int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
// Copy the output from the appropriate register. Find a register that
// we can use.
if (OpInfo.AssignedRegs.Regs.empty()) {
- cerr << "Couldn't allocate output reg for constraint '"
- << OpInfo.ConstraintCode << "'!\n";
- exit(1);
+ llvm_report_error("Couldn't allocate output reg for"
+ " constraint '" + OpInfo.ConstraintCode + "'!");
}
// If this is an indirect operand, store through the pointer after the
if ((OpFlag & 7) == 2 /*REGDEF*/
|| (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
// Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
+ if (OpInfo.isIndirect) {
+ llvm_report_error("Don't know how to handle tied indirect "
+ "register inputs yet!");
+ }
RegsForValue MatchedRegs;
MatchedRegs.TLI = &TLI;
MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
hasMemory, Ops, DAG);
if (Ops.empty()) {
- cerr << "Invalid operand for inline asm constraint '"
- << OpInfo.ConstraintCode << "'!\n";
- exit(1);
+ llvm_report_error("Invalid operand for inline asm"
+ " constraint '" + OpInfo.ConstraintCode + "'!");
}
// Add information to the INLINEASM node to know about this input.
// Copy the input into the appropriate registers.
if (OpInfo.AssignedRegs.Regs.empty()) {
- cerr << "Couldn't allocate output reg for constraint '"
- << OpInfo.ConstraintCode << "'!\n";
- exit(1);
+ llvm_report_error("Couldn't allocate input reg for"
+ " constraint '"+ OpInfo.ConstraintCode +"'!");
}
OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
- DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
+ DAG.getVTList(MVT::Other, MVT::Flag),
&AsmNodeOperands[0], AsmNodeOperands.size());
Flag = Chain.getValue(1);
}
setValue(CS.getInstruction(), Val);
+ // Don't need to use this as a chain in this case.
+ if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
+ return;
}
std::vector<std::pair<SDValue, Value*> > StoresToEmit;
SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Chain, &Flag);
StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
+
}
// Emit the non-flagged stores from the physregs.
// i32-ness of the optimizer: we do not want to promote to i64 and then
// multiply on 64-bit targets.
// FIXME: Malloc inst should go away: PR715.
- uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
- if (ElementSize != 1)
+ uint64_t ElementSize = TD->getTypeAllocSize(I.getType()->getElementType());
+ if (ElementSize != 1) {
+ // Src is always 32-bits, make sure the constant fits.
+ assert(Src.getValueType() == MVT::i32);
+ ElementSize = (uint32_t)ElementSize;
Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
Src, DAG.getConstant(ElementSize, Src.getValueType()));
+ }
MVT IntPtr = TLI.getPointerTy();
Entry.Ty = TLI.getTargetData()->getIntPtrType();
Args.push_back(Entry);
+ bool isTailCall = PerformTailCallOpt &&
+ isInTailCallPosition(&I, Attribute::None, TLI);
std::pair<SDValue,SDValue> Result =
TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
- CallingConv::C, PerformTailCallOpt,
+ 0, CallingConv::C, isTailCall,
+ /*isReturnValueUsed=*/true,
DAG.getExternalSymbol("malloc", IntPtr),
Args, DAG, getCurDebugLoc());
- setValue(&I, Result.first); // Pointers always fit in registers
- DAG.setRoot(Result.second);
+ if (Result.first.getNode())
+ setValue(&I, Result.first); // Pointers always fit in registers
+ if (Result.second.getNode())
+ DAG.setRoot(Result.second);
}
void SelectionDAGLowering::visitFree(FreeInst &I) {
Entry.Ty = TLI.getTargetData()->getIntPtrType();
Args.push_back(Entry);
MVT IntPtr = TLI.getPointerTy();
+ bool isTailCall = PerformTailCallOpt &&
+ isInTailCallPosition(&I, Attribute::None, TLI);
std::pair<SDValue,SDValue> Result =
TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
- CallingConv::C, PerformTailCallOpt,
+ 0, CallingConv::C, isTailCall,
+ /*isReturnValueUsed=*/true,
DAG.getExternalSymbol("free", IntPtr), Args, DAG,
getCurDebugLoc());
- DAG.setRoot(Result.second);
+ if (Result.second.getNode())
+ DAG.setRoot(Result.second);
}
void SelectionDAGLowering::visitVAStart(CallInst &I) {
DAG.getSrcValue(I.getOperand(2))));
}
-/// TargetLowering::LowerArguments - This is the default LowerArguments
-/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
-/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
-/// integrated into SDISel.
-void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
- SmallVectorImpl<SDValue> &ArgValues,
- DebugLoc dl) {
- // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
- SmallVector<SDValue, 3+16> Ops;
- Ops.push_back(DAG.getRoot());
- Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
- Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
-
- // Add one result value for each formal argument.
- SmallVector<MVT, 16> RetVals;
- unsigned j = 1;
- for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
- I != E; ++I, ++j) {
- SmallVector<MVT, 4> ValueVTs;
- ComputeValueVTs(*this, I->getType(), ValueVTs);
- for (unsigned Value = 0, NumValues = ValueVTs.size();
- Value != NumValues; ++Value) {
- MVT VT = ValueVTs[Value];
- const Type *ArgTy = VT.getTypeForMVT();
- ISD::ArgFlagsTy Flags;
- unsigned OriginalAlignment =
- getTargetData()->getABITypeAlignment(ArgTy);
-
- if (F.paramHasAttr(j, Attribute::ZExt))
- Flags.setZExt();
- if (F.paramHasAttr(j, Attribute::SExt))
- Flags.setSExt();
- if (F.paramHasAttr(j, Attribute::InReg))
- Flags.setInReg();
- if (F.paramHasAttr(j, Attribute::StructRet))
- Flags.setSRet();
- if (F.paramHasAttr(j, Attribute::ByVal)) {
- Flags.setByVal();
- const PointerType *Ty = cast<PointerType>(I->getType());
- const Type *ElementTy = Ty->getElementType();
- unsigned FrameAlign = getByValTypeAlignment(ElementTy);
- unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
- // For ByVal, alignment should be passed from FE. BE will guess if
- // this info is not there but there are cases it cannot get right.
- if (F.getParamAlignment(j))
- FrameAlign = F.getParamAlignment(j);
- Flags.setByValAlign(FrameAlign);
- Flags.setByValSize(FrameSize);
- }
- if (F.paramHasAttr(j, Attribute::Nest))
- Flags.setNest();
- Flags.setOrigAlign(OriginalAlignment);
-
- MVT RegisterVT = getRegisterType(VT);
- unsigned NumRegs = getNumRegisters(VT);
- for (unsigned i = 0; i != NumRegs; ++i) {
- RetVals.push_back(RegisterVT);
- ISD::ArgFlagsTy MyFlags = Flags;
- if (NumRegs > 1 && i == 0)
- MyFlags.setSplit();
- // if it isn't first piece, alignment must be 1
- else if (i > 0)
- MyFlags.setOrigAlign(1);
- Ops.push_back(DAG.getArgFlags(MyFlags));
- }
- }
- }
-
- RetVals.push_back(MVT::Other);
-
- // Create the node.
- SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
- DAG.getVTList(&RetVals[0], RetVals.size()),
- &Ops[0], Ops.size()).getNode();
-
- // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
- // allows exposing the loads that may be part of the argument access to the
- // first DAGCombiner pass.
- SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
-
- // The number of results should match up, except that the lowered one may have
- // an extra flag result.
- assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
- (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
- TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
- && "Lowering produced unexpected number of results!");
-
- // The FORMAL_ARGUMENTS node itself is likely no longer needed.
- if (Result != TmpRes.getNode() && Result->use_empty()) {
- HandleSDNode Dummy(DAG.getRoot());
- DAG.RemoveDeadNode(Result);
- }
-
- Result = TmpRes.getNode();
-
- unsigned NumArgRegs = Result->getNumValues() - 1;
- DAG.setRoot(SDValue(Result, NumArgRegs));
-
- // Set up the return result vector.
- unsigned i = 0;
- unsigned Idx = 1;
- for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
- ++I, ++Idx) {
- SmallVector<MVT, 4> ValueVTs;
- ComputeValueVTs(*this, I->getType(), ValueVTs);
- for (unsigned Value = 0, NumValues = ValueVTs.size();
- Value != NumValues; ++Value) {
- MVT VT = ValueVTs[Value];
- MVT PartVT = getRegisterType(VT);
-
- unsigned NumParts = getNumRegisters(VT);
- SmallVector<SDValue, 4> Parts(NumParts);
- for (unsigned j = 0; j != NumParts; ++j)
- Parts[j] = SDValue(Result, i++);
-
- ISD::NodeType AssertOp = ISD::DELETED_NODE;
- if (F.paramHasAttr(Idx, Attribute::SExt))
- AssertOp = ISD::AssertSext;
- else if (F.paramHasAttr(Idx, Attribute::ZExt))
- AssertOp = ISD::AssertZext;
-
- ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
- PartVT, VT, AssertOp));
- }
- }
- assert(i == NumArgRegs && "Argument register count mismatch!");
-}
-
-
/// TargetLowering::LowerCallTo - This is the default LowerCallTo
-/// implementation, which just inserts an ISD::CALL node, which is later custom
-/// lowered by the target to something concrete. FIXME: When all targets are
-/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
+/// implementation, which just calls LowerCall.
+/// FIXME: When all targets are
+/// migrated to using LowerCall, this hook should be integrated into SDISel.
std::pair<SDValue, SDValue>
TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
bool RetSExt, bool RetZExt, bool isVarArg,
- bool isInreg,
- unsigned CallingConv, bool isTailCall,
+ bool isInreg, unsigned NumFixedArgs,
+ unsigned CallConv, bool isTailCall,
+ bool isReturnValueUsed,
SDValue Callee,
ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
+
assert((!isTailCall || PerformTailCallOpt) &&
"isTailCall set when tail-call optimizations are disabled!");
- SmallVector<SDValue, 32> Ops;
- Ops.push_back(Chain); // Op#0 - Chain
- Ops.push_back(Callee);
-
// Handle all of the outgoing arguments.
+ SmallVector<ISD::OutputArg, 32> Outs;
for (unsigned i = 0, e = Args.size(); i != e; ++i) {
SmallVector<MVT, 4> ValueVTs;
ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
const PointerType *Ty = cast<PointerType>(Args[i].Ty);
const Type *ElementTy = Ty->getElementType();
unsigned FrameAlign = getByValTypeAlignment(ElementTy);
- unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
+ unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
// For ByVal, alignment should come from FE. BE will guess if this
// info is not there but there are cases it cannot get right.
if (Args[i].Alignment)
getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
- for (unsigned i = 0; i != NumParts; ++i) {
+ for (unsigned j = 0; j != NumParts; ++j) {
// if it isn't first piece, alignment must be 1
- ISD::ArgFlagsTy MyFlags = Flags;
- if (NumParts > 1 && i == 0)
- MyFlags.setSplit();
- else if (i != 0)
- MyFlags.setOrigAlign(1);
-
- Ops.push_back(Parts[i]);
- Ops.push_back(DAG.getArgFlags(MyFlags));
+ ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
+ if (NumParts > 1 && j == 0)
+ MyFlags.Flags.setSplit();
+ else if (j != 0)
+ MyFlags.Flags.setOrigAlign(1);
+
+ Outs.push_back(MyFlags);
}
}
}
- // Figure out the result value types. We start by making a list of
- // the potentially illegal return value types.
- SmallVector<MVT, 4> LoweredRetTys;
+ // Handle the incoming return values from the call.
+ SmallVector<ISD::InputArg, 32> Ins;
SmallVector<MVT, 4> RetTys;
ComputeValueVTs(*this, RetTy, RetTys);
-
- // Then we translate that to a list of legal types.
for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
MVT VT = RetTys[I];
MVT RegisterVT = getRegisterType(VT);
unsigned NumRegs = getNumRegisters(VT);
- for (unsigned i = 0; i != NumRegs; ++i)
- LoweredRetTys.push_back(RegisterVT);
- }
-
- LoweredRetTys.push_back(MVT::Other); // Always has a chain.
-
- // Create the CALL node.
- SDValue Res = DAG.getCall(CallingConv, dl,
- isVarArg, isTailCall, isInreg,
- DAG.getVTList(&LoweredRetTys[0],
- LoweredRetTys.size()),
- &Ops[0], Ops.size()
- );
- Chain = Res.getValue(LoweredRetTys.size() - 1);
-
- // Gather up the call result into a single value.
- if (RetTy != Type::VoidTy && !RetTys.empty()) {
- ISD::NodeType AssertOp = ISD::DELETED_NODE;
-
- if (RetSExt)
- AssertOp = ISD::AssertSext;
- else if (RetZExt)
- AssertOp = ISD::AssertZext;
-
- SmallVector<SDValue, 4> ReturnValues;
- unsigned RegNo = 0;
- for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
- MVT VT = RetTys[I];
- MVT RegisterVT = getRegisterType(VT);
- unsigned NumRegs = getNumRegisters(VT);
- unsigned RegNoEnd = NumRegs + RegNo;
- SmallVector<SDValue, 4> Results;
- for (; RegNo != RegNoEnd; ++RegNo)
- Results.push_back(Res.getValue(RegNo));
- SDValue ReturnValue =
- getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
- AssertOp);
- ReturnValues.push_back(ReturnValue);
+ for (unsigned i = 0; i != NumRegs; ++i) {
+ ISD::InputArg MyFlags;
+ MyFlags.VT = RegisterVT;
+ MyFlags.Used = isReturnValueUsed;
+ if (RetSExt)
+ MyFlags.Flags.setSExt();
+ if (RetZExt)
+ MyFlags.Flags.setZExt();
+ if (isInreg)
+ MyFlags.Flags.setInReg();
+ Ins.push_back(MyFlags);
}
- Res = DAG.getNode(ISD::MERGE_VALUES, dl,
- DAG.getVTList(&RetTys[0], RetTys.size()),
- &ReturnValues[0], ReturnValues.size());
}
+ // Check if target-dependent constraints permit a tail call here.
+ // Target-independent constraints should be checked by the caller.
+ if (isTailCall &&
+ !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
+ isTailCall = false;
+
+ SmallVector<SDValue, 4> InVals;
+ Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
+ Outs, Ins, dl, DAG, InVals);
+
+ // Verify that the target's LowerCall behaved as expected.
+ assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
+ "LowerCall didn't return a valid chain!");
+ assert((!isTailCall || InVals.empty()) &&
+ "LowerCall emitted a return value for a tail call!");
+ assert((isTailCall || InVals.size() == Ins.size()) &&
+ "LowerCall didn't emit the correct number of values!");
+ DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
+ assert(InVals[i].getNode() &&
+ "LowerCall emitted a null value!");
+ assert(Ins[i].VT == InVals[i].getValueType() &&
+ "LowerCall emitted a value with the wrong type!");
+ });
+
+ // For a tail call, the return value is merely live-out and there aren't
+ // any nodes in the DAG representing it. Return a special value to
+ // indicate that a tail call has been emitted and no more Instructions
+ // should be processed in the current block.
+ if (isTailCall) {
+ DAG.setRoot(Chain);
+ return std::make_pair(SDValue(), SDValue());
+ }
+
+ // Collect the legal value parts into potentially illegal values
+ // that correspond to the original function's return values.
+ ISD::NodeType AssertOp = ISD::DELETED_NODE;
+ if (RetSExt)
+ AssertOp = ISD::AssertSext;
+ else if (RetZExt)
+ AssertOp = ISD::AssertZext;
+ SmallVector<SDValue, 4> ReturnValues;
+ unsigned CurReg = 0;
+ for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
+ MVT VT = RetTys[I];
+ MVT RegisterVT = getRegisterType(VT);
+ unsigned NumRegs = getNumRegisters(VT);
+
+ SDValue ReturnValue =
+ getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT,
+ AssertOp);
+ ReturnValues.push_back(ReturnValue);
+ CurReg += NumRegs;
+ }
+
+ // For a function returning void, there is no return value. We can't create
+ // such a node, so we just return a null return value in that case. In
+ // that case, nothing will actualy look at the value.
+ if (ReturnValues.empty())
+ return std::make_pair(SDValue(), Chain);
+
+ SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
+ DAG.getVTList(&RetTys[0], RetTys.size()),
+ &ReturnValues[0], ReturnValues.size());
+
return std::make_pair(Res, Chain);
}
}
SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
- assert(0 && "LowerOperation not implemented for this target!");
- abort();
+ llvm_unreachable("LowerOperation not implemented for this target!");
return SDValue();
}
LowerArguments(BasicBlock *LLVMBB) {
// If this is the entry block, emit arguments.
Function &F = *LLVMBB->getParent();
- SDValue OldRoot = SDL->DAG.getRoot();
- SmallVector<SDValue, 16> Args;
- TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
+ SelectionDAG &DAG = SDL->DAG;
+ SDValue OldRoot = DAG.getRoot();
+ DebugLoc dl = SDL->getCurDebugLoc();
+ const TargetData *TD = TLI.getTargetData();
- unsigned a = 0;
- for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
- AI != E; ++AI) {
+ // Set up the incoming argument description vector.
+ SmallVector<ISD::InputArg, 16> Ins;
+ unsigned Idx = 1;
+ for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
+ I != E; ++I, ++Idx) {
SmallVector<MVT, 4> ValueVTs;
- ComputeValueVTs(TLI, AI->getType(), ValueVTs);
+ ComputeValueVTs(TLI, I->getType(), ValueVTs);
+ bool isArgValueUsed = !I->use_empty();
+ for (unsigned Value = 0, NumValues = ValueVTs.size();
+ Value != NumValues; ++Value) {
+ MVT VT = ValueVTs[Value];
+ const Type *ArgTy = VT.getTypeForMVT();
+ ISD::ArgFlagsTy Flags;
+ unsigned OriginalAlignment =
+ TD->getABITypeAlignment(ArgTy);
+
+ if (F.paramHasAttr(Idx, Attribute::ZExt))
+ Flags.setZExt();
+ if (F.paramHasAttr(Idx, Attribute::SExt))
+ Flags.setSExt();
+ if (F.paramHasAttr(Idx, Attribute::InReg))
+ Flags.setInReg();
+ if (F.paramHasAttr(Idx, Attribute::StructRet))
+ Flags.setSRet();
+ if (F.paramHasAttr(Idx, Attribute::ByVal)) {
+ Flags.setByVal();
+ const PointerType *Ty = cast<PointerType>(I->getType());
+ const Type *ElementTy = Ty->getElementType();
+ unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
+ unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
+ // For ByVal, alignment should be passed from FE. BE will guess if
+ // this info is not there but there are cases it cannot get right.
+ if (F.getParamAlignment(Idx))
+ FrameAlign = F.getParamAlignment(Idx);
+ Flags.setByValAlign(FrameAlign);
+ Flags.setByValSize(FrameSize);
+ }
+ if (F.paramHasAttr(Idx, Attribute::Nest))
+ Flags.setNest();
+ Flags.setOrigAlign(OriginalAlignment);
+
+ MVT RegisterVT = TLI.getRegisterType(VT);
+ unsigned NumRegs = TLI.getNumRegisters(VT);
+ for (unsigned i = 0; i != NumRegs; ++i) {
+ ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
+ if (NumRegs > 1 && i == 0)
+ MyFlags.Flags.setSplit();
+ // if it isn't first piece, alignment must be 1
+ else if (i > 0)
+ MyFlags.Flags.setOrigAlign(1);
+ Ins.push_back(MyFlags);
+ }
+ }
+ }
+
+ // Call the target to set up the argument values.
+ SmallVector<SDValue, 8> InVals;
+ SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
+ F.isVarArg(), Ins,
+ dl, DAG, InVals);
+
+ // Verify that the target's LowerFormalArguments behaved as expected.
+ assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
+ "LowerFormalArguments didn't return a valid chain!");
+ assert(InVals.size() == Ins.size() &&
+ "LowerFormalArguments didn't emit the correct number of values!");
+ DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
+ assert(InVals[i].getNode() &&
+ "LowerFormalArguments emitted a null value!");
+ assert(Ins[i].VT == InVals[i].getValueType() &&
+ "LowerFormalArguments emitted a value with the wrong type!");
+ });
+
+ // Update the DAG with the new chain value resulting from argument lowering.
+ DAG.setRoot(NewRoot);
+
+ // Set up the argument values.
+ unsigned i = 0;
+ Idx = 1;
+ for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
+ ++I, ++Idx) {
+ SmallVector<SDValue, 4> ArgValues;
+ SmallVector<MVT, 4> ValueVTs;
+ ComputeValueVTs(TLI, I->getType(), ValueVTs);
unsigned NumValues = ValueVTs.size();
- if (!AI->use_empty()) {
- SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
- SDL->getCurDebugLoc()));
+ for (unsigned Value = 0; Value != NumValues; ++Value) {
+ MVT VT = ValueVTs[Value];
+ MVT PartVT = TLI.getRegisterType(VT);
+ unsigned NumParts = TLI.getNumRegisters(VT);
+
+ if (!I->use_empty()) {
+ ISD::NodeType AssertOp = ISD::DELETED_NODE;
+ if (F.paramHasAttr(Idx, Attribute::SExt))
+ AssertOp = ISD::AssertSext;
+ else if (F.paramHasAttr(Idx, Attribute::ZExt))
+ AssertOp = ISD::AssertZext;
+
+ ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
+ PartVT, VT, AssertOp));
+ }
+ i += NumParts;
+ }
+ if (!I->use_empty()) {
+ SDL->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues,
+ SDL->getCurDebugLoc()));
// If this argument is live outside of the entry block, insert a copy from
// whereever we got it to the vreg that other BB's will reference it as.
- DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
- if (VMI != FuncInfo->ValueMap.end()) {
- SDL->CopyValueToVirtualRegister(AI, VMI->second);
- }
+ SDL->CopyToExportRegsIfNeeded(I);
}
- a += NumValues;
}
+ assert(i == InVals.size() && "Argument register count mismatch!");
// Finally, if the target has anything special to do, allow it to do so.
// FIXME: this should insert code into the DAG!