[SROA] Run clang-format over the entire SROA pass as I wrote it before

much of the glory of clang-format, and now any time I touch it I risk
introducing formatting changes as part of a functional commit.

Also, clang-format is *way* better at formatting my code than I am.
Most of this is a huge improvement although I reverted a couple of
places where I hit a clang-format bug with lambdas that has been filed
but not (fully) fixed.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@224666 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Chandler Carruth
2014-12-20 02:39:18 +00:00
parent 795bfc9234
commit 93e03df3cf

View File

@@ -79,8 +79,8 @@ STATISTIC(NumVectorized, "Number of vectorized aggregates");
/// Hidden option to force the pass to not use DomTree and mem2reg, instead /// Hidden option to force the pass to not use DomTree and mem2reg, instead
/// forming SSA values through the SSAUpdater infrastructure. /// forming SSA values through the SSAUpdater infrastructure.
static cl::opt<bool> static cl::opt<bool> ForceSSAUpdater("force-ssa-updater", cl::init(false),
ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden); cl::Hidden);
/// Hidden option to enable randomly shuffling the slices to help uncover /// Hidden option to enable randomly shuffling the slices to help uncover
/// instability in their order. /// instability in their order.
@@ -89,15 +89,15 @@ static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
/// Hidden option to experiment with completely strict handling of inbounds /// Hidden option to experiment with completely strict handling of inbounds
/// GEPs. /// GEPs.
static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
cl::init(false), cl::Hidden); cl::Hidden);
namespace { namespace {
/// \brief A custom IRBuilder inserter which prefixes all names if they are /// \brief A custom IRBuilder inserter which prefixes all names if they are
/// preserved. /// preserved.
template <bool preserveNames = true> template <bool preserveNames = true>
class IRBuilderPrefixedInserter : class IRBuilderPrefixedInserter
public IRBuilderDefaultInserter<preserveNames> { : public IRBuilderDefaultInserter<preserveNames> {
std::string Prefix; std::string Prefix;
public: public:
@@ -113,19 +113,19 @@ protected:
// Specialization for not preserving the name is trivial. // Specialization for not preserving the name is trivial.
template <> template <>
class IRBuilderPrefixedInserter<false> : class IRBuilderPrefixedInserter<false>
public IRBuilderDefaultInserter<false> { : public IRBuilderDefaultInserter<false> {
public: public:
void SetNamePrefix(const Twine &P) {} void SetNamePrefix(const Twine &P) {}
}; };
/// \brief Provide a typedef for IRBuilder that drops names in release builds. /// \brief Provide a typedef for IRBuilder that drops names in release builds.
#ifndef NDEBUG #ifndef NDEBUG
typedef llvm::IRBuilder<true, ConstantFolder, typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
IRBuilderPrefixedInserter<true> > IRBuilderTy; IRBuilderTy;
#else #else
typedef llvm::IRBuilder<false, ConstantFolder, typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
IRBuilderPrefixedInserter<false> > IRBuilderTy; IRBuilderTy;
#endif #endif
} }
@@ -171,10 +171,14 @@ public:
/// decreasing. Thus the spanning range comes first in a cluster with the /// decreasing. Thus the spanning range comes first in a cluster with the
/// same start position. /// same start position.
bool operator<(const Slice &RHS) const { bool operator<(const Slice &RHS) const {
if (beginOffset() < RHS.beginOffset()) return true; if (beginOffset() < RHS.beginOffset())
if (beginOffset() > RHS.beginOffset()) return false; return true;
if (isSplittable() != RHS.isSplittable()) return !isSplittable(); if (beginOffset() > RHS.beginOffset())
if (endOffset() > RHS.endOffset()) return true; return false;
if (isSplittable() != RHS.isSplittable())
return !isSplittable();
if (endOffset() > RHS.endOffset())
return true;
return false; return false;
} }
@@ -198,9 +202,7 @@ public:
namespace llvm { namespace llvm {
template <typename T> struct isPodLike; template <typename T> struct isPodLike;
template <> struct isPodLike<Slice> { template <> struct isPodLike<Slice> { static const bool value = true; };
static const bool value = true;
};
} }
namespace { namespace {
@@ -421,7 +423,8 @@ private:
GEPOffset += GEPOffset +=
APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx)); APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
} else { } else {
// For array or vector indices, scale the index by the size of the type. // For array or vector indices, scale the index by the size of the
// type.
APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth()); APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
GEPOffset += Index * APInt(Offset.getBitWidth(), GEPOffset += Index * APInt(Offset.getBitWidth(),
DL.getTypeAllocSize(GTI.getIndexedType())); DL.getTypeAllocSize(GTI.getIndexedType()));
@@ -495,7 +498,6 @@ private:
handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile()); handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
} }
void visitMemSetInst(MemSetInst &II) { void visitMemSetInst(MemSetInst &II) {
assert(II.getRawDest() == *U && "Pointer use is not the destination?"); assert(II.getRawDest() == *U && "Pointer use is not the destination?");
ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
@@ -507,8 +509,7 @@ private:
if (!IsOffsetKnown) if (!IsOffsetKnown)
return PI.setAborted(&II); return PI.setAborted(&II);
insertUse(II, Offset, insertUse(II, Offset, Length ? Length->getLimitedValue()
Length ? Length->getLimitedValue()
: AllocSize - Offset.getLimitedValue(), : AllocSize - Offset.getLimitedValue(),
(bool)Length); (bool)Length);
} }
@@ -533,15 +534,15 @@ private:
// FIXME: Yet another place we really should bypass this when // FIXME: Yet another place we really should bypass this when
// instrumenting for ASan. // instrumenting for ASan.
if (Offset.uge(AllocSize)) { if (Offset.uge(AllocSize)) {
SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II); SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
MemTransferSliceMap.find(&II);
if (MTPI != MemTransferSliceMap.end()) if (MTPI != MemTransferSliceMap.end())
AS.Slices[MTPI->second].kill(); AS.Slices[MTPI->second].kill();
return markAsDead(II); return markAsDead(II);
} }
uint64_t RawOffset = Offset.getLimitedValue(); uint64_t RawOffset = Offset.getLimitedValue();
uint64_t Size = Length ? Length->getLimitedValue() uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
: AllocSize - RawOffset;
// Check for the special case where the same exact value is used for both // Check for the special case where the same exact value is used for both
// source and dest. // source and dest.
@@ -697,18 +698,12 @@ private:
insertUse(I, Offset, Size); insertUse(I, Offset, Size);
} }
void visitPHINode(PHINode &PN) { void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
visitPHINodeOrSelectInst(PN);
}
void visitSelectInst(SelectInst &SI) { void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
visitPHINodeOrSelectInst(SI);
}
/// \brief Disable SROA entirely if there are unhandled users of the alloca. /// \brief Disable SROA entirely if there are unhandled users of the alloca.
void visitInstruction(Instruction &I) { void visitInstruction(Instruction &I) { PI.setAborted(&I); }
PI.setAborted(&I);
}
}; };
AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI) AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
@@ -829,7 +824,8 @@ public:
DVIs.pop_back_val()->eraseFromParent(); DVIs.pop_back_val()->eraseFromParent();
} }
bool isInstInList(Instruction *I, bool
isInstInList(Instruction *I,
const SmallVectorImpl<Instruction *> &Insts) const override { const SmallVectorImpl<Instruction *> &Insts) const override {
Value *Ptr; Value *Ptr;
if (LoadInst *LI = dyn_cast<LoadInst>(I)) if (LoadInst *LI = dyn_cast<LoadInst>(I))
@@ -888,7 +884,6 @@ public:
}; };
} // end anon namespace } // end anon namespace
namespace { namespace {
/// \brief An optimization pass providing Scalar Replacement of Aggregates. /// \brief An optimization pass providing Scalar Replacement of Aggregates.
/// ///
@@ -960,8 +955,8 @@ class SROA : public FunctionPass {
public: public:
SROA(bool RequiresDomTree = true) SROA(bool RequiresDomTree = true)
: FunctionPass(ID), RequiresDomTree(RequiresDomTree), : FunctionPass(ID), RequiresDomTree(RequiresDomTree), C(nullptr),
C(nullptr), DL(nullptr), DT(nullptr) { DL(nullptr), DT(nullptr) {
initializeSROAPass(*PassRegistry::getPassRegistry()); initializeSROAPass(*PassRegistry::getPassRegistry());
} }
bool runOnFunction(Function &F) override; bool runOnFunction(Function &F) override;
@@ -992,12 +987,12 @@ FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
return new SROA(RequiresDomTree); return new SROA(RequiresDomTree);
} }
INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
false, false) false)
INITIALIZE_PASS_DEPENDENCY(AssumptionTracker) INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
false, false) false)
/// Walk the range of a partitioning looking for a common type to cover this /// Walk the range of a partitioning looking for a common type to cover this
/// sequence of slices. /// sequence of slices.
@@ -1068,8 +1063,7 @@ static Type *findCommonType(AllocaSlices::const_iterator B,
/// ///
/// FIXME: This should be hoisted into a generic utility, likely in /// FIXME: This should be hoisted into a generic utility, likely in
/// Transforms/Util/Local.h /// Transforms/Util/Local.h
static bool isSafePHIToSpeculate(PHINode &PN, static bool isSafePHIToSpeculate(PHINode &PN, const DataLayout *DL = nullptr) {
const DataLayout *DL = nullptr) {
// For now, we can only do this promotion if the load is in the same block // For now, we can only do this promotion if the load is in the same block
// as the PHI, and if there are no stores between the phi and load. // as the PHI, and if there are no stores between the phi and load.
// TODO: Allow recursive phi users. // TODO: Allow recursive phi users.
@@ -1329,7 +1323,8 @@ static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
SmallVectorImpl<Value *> &Indices, SmallVectorImpl<Value *> &Indices,
Twine NamePrefix) { Twine NamePrefix) {
if (Offset == 0) if (Offset == 0)
return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix); return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
NamePrefix);
// We can't recurse through pointer types. // We can't recurse through pointer types.
if (Ty->isPointerTy()) if (Ty->isPointerTy())
@@ -1437,8 +1432,7 @@ static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
/// a single GEP as possible, thus making each GEP more independent of the /// a single GEP as possible, thus making each GEP more independent of the
/// surrounding code. /// surrounding code.
static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
APInt Offset, Type *PointerTy, APInt Offset, Type *PointerTy, Twine NamePrefix) {
Twine NamePrefix) {
// Even though we don't look through PHI nodes, we could be called on an // Even though we don't look through PHI nodes, we could be called on an
// instruction in an unreachable block, which may be on a cycle. // instruction in an unreachable block, which may be on a cycle.
SmallPtrSet<Value *, 4> Visited; SmallPtrSet<Value *, 4> Visited;
@@ -1512,8 +1506,9 @@ static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Int8PtrOffset = Offset; Int8PtrOffset = Offset;
} }
OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr : OffsetPtr = Int8PtrOffset == 0
IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset), ? Int8Ptr
: IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
NamePrefix + "sroa_raw_idx"); NamePrefix + "sroa_raw_idx");
} }
Ptr = OffsetPtr; Ptr = OffsetPtr;
@@ -1695,8 +1690,8 @@ isVectorPromotionViableForSlice(const DataLayout &DL, uint64_t SliceBeginOffset,
/// don't want to do the rewrites unless we are confident that the result will /// don't want to do the rewrites unless we are confident that the result will
/// be promotable, so we have an early test here. /// be promotable, so we have an early test here.
static VectorType * static VectorType *
isVectorPromotionViable(const DataLayout &DL, isVectorPromotionViable(const DataLayout &DL, uint64_t SliceBeginOffset,
uint64_t SliceBeginOffset, uint64_t SliceEndOffset, uint64_t SliceEndOffset,
AllocaSlices::const_range Slices, AllocaSlices::const_range Slices,
ArrayRef<AllocaSlices::iterator> SplitUses) { ArrayRef<AllocaSlices::iterator> SplitUses) {
// Collect the candidate types for vector-based promotion. Also track whether // Collect the candidate types for vector-based promotion. Also track whether
@@ -1809,8 +1804,7 @@ isVectorPromotionViable(const DataLayout &DL,
static bool isIntegerWideningViableForSlice(const DataLayout &DL, static bool isIntegerWideningViableForSlice(const DataLayout &DL,
Type *AllocaTy, Type *AllocaTy,
uint64_t AllocBeginOffset, uint64_t AllocBeginOffset,
uint64_t Size, uint64_t Size, const Slice &S,
const Slice &S,
bool &WholeAllocaOp) { bool &WholeAllocaOp) {
uint64_t RelBegin = S.beginOffset() - AllocBeginOffset; uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
uint64_t RelEnd = S.endOffset() - AllocBeginOffset; uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
@@ -1978,9 +1972,8 @@ static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
return V; return V;
} }
static Value *extractVector(IRBuilderTy &IRB, Value *V, static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
unsigned BeginIndex, unsigned EndIndex, unsigned EndIndex, const Twine &Name) {
const Twine &Name) {
VectorType *VecTy = cast<VectorType>(V->getType()); VectorType *VecTy = cast<VectorType>(V->getType());
unsigned NumElements = EndIndex - BeginIndex; unsigned NumElements = EndIndex - BeginIndex;
assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
@@ -2000,8 +1993,7 @@ static Value *extractVector(IRBuilderTy &IRB, Value *V,
for (unsigned i = BeginIndex; i != EndIndex; ++i) for (unsigned i = BeginIndex; i != EndIndex; ++i)
Mask.push_back(IRB.getInt32(i)); Mask.push_back(IRB.getInt32(i));
V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
ConstantVector::get(Mask), ConstantVector::get(Mask), Name + ".extract");
Name + ".extract");
DEBUG(dbgs() << " shuffle: " << *V << "\n"); DEBUG(dbgs() << " shuffle: " << *V << "\n");
return V; return V;
} }
@@ -2040,8 +2032,7 @@ static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
else else
Mask.push_back(UndefValue::get(IRB.getInt32Ty())); Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
ConstantVector::get(Mask), ConstantVector::get(Mask), Name + ".expand");
Name + ".expand");
DEBUG(dbgs() << " shuffle: " << *V << "\n"); DEBUG(dbgs() << " shuffle: " << *V << "\n");
Mask.clear(); Mask.clear();
@@ -2221,7 +2212,8 @@ private:
); );
} }
/// \brief Compute suitable alignment to access this slice of the *new* alloca. /// \brief Compute suitable alignment to access this slice of the *new*
/// alloca.
/// ///
/// You can optionally pass a type to this routine and if that type's ABI /// You can optionally pass a type to this routine and if that type's ABI
/// alignment is itself suitable, this will return zero. /// alignment is itself suitable, this will return zero.
@@ -2229,7 +2221,8 @@ private:
unsigned NewAIAlign = NewAI.getAlignment(); unsigned NewAIAlign = NewAI.getAlignment();
if (!NewAIAlign) if (!NewAIAlign)
NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType()); NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset); unsigned Align =
MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align; return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
} }
@@ -2253,16 +2246,14 @@ private:
unsigned EndIndex = getIndex(NewEndOffset); unsigned EndIndex = getIndex(NewEndOffset);
assert(EndIndex > BeginIndex && "Empty vector!"); assert(EndIndex > BeginIndex && "Empty vector!");
Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
"load");
return extractVector(IRB, V, BeginIndex, EndIndex, "vec"); return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
} }
Value *rewriteIntegerLoad(LoadInst &LI) { Value *rewriteIntegerLoad(LoadInst &LI) {
assert(IntTy && "We cannot insert an integer to the alloca"); assert(IntTy && "We cannot insert an integer to the alloca");
assert(!LI.isVolatile()); assert(!LI.isVolatile());
Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
"load");
V = convertValue(DL, IRB, V, IntTy); V = convertValue(DL, IRB, V, IntTy);
assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset"); assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
@@ -2287,8 +2278,8 @@ private:
V = rewriteIntegerLoad(LI); V = rewriteIntegerLoad(LI);
} else if (NewBeginOffset == NewAllocaBeginOffset && } else if (NewBeginOffset == NewAllocaBeginOffset &&
canConvertValue(DL, NewAllocaTy, LI.getType())) { canConvertValue(DL, NewAllocaTy, LI.getType())) {
V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), LI.isVolatile(),
LI.isVolatile(), LI.getName()); LI.getName());
} else { } else {
Type *LTy = TargetTy->getPointerTo(); Type *LTy = TargetTy->getPointerTo();
V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy), V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
@@ -2313,10 +2304,9 @@ private:
// basis for the new value. This allows us to replace the uses of LI with // basis for the new value. This allows us to replace the uses of LI with
// the computed value, and then replace the placeholder with LI, leaving // the computed value, and then replace the placeholder with LI, leaving
// LI only used for this computation. // LI only used for this computation.
Value *Placeholder Value *Placeholder =
= new LoadInst(UndefValue::get(LI.getType()->getPointerTo())); new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset, V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset, "insert");
"insert");
LI.replaceAllUsesWith(V); LI.replaceAllUsesWith(V);
Placeholder->replaceAllUsesWith(&LI); Placeholder->replaceAllUsesWith(&LI);
delete Placeholder; delete Placeholder;
@@ -2337,15 +2327,14 @@ private:
assert(EndIndex > BeginIndex && "Empty vector!"); assert(EndIndex > BeginIndex && "Empty vector!");
unsigned NumElements = EndIndex - BeginIndex; unsigned NumElements = EndIndex - BeginIndex;
assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Type *SliceTy = Type *SliceTy = (NumElements == 1)
(NumElements == 1) ? ElementTy ? ElementTy
: VectorType::get(ElementTy, NumElements); : VectorType::get(ElementTy, NumElements);
if (V->getType() != SliceTy) if (V->getType() != SliceTy)
V = convertValue(DL, IRB, V, SliceTy); V = convertValue(DL, IRB, V, SliceTy);
// Mix in the existing elements. // Mix in the existing elements.
Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
"load");
V = insertVector(IRB, Old, V, BeginIndex, "vec"); V = insertVector(IRB, Old, V, BeginIndex, "vec");
} }
StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment()); StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
@@ -2360,13 +2349,12 @@ private:
assert(IntTy && "We cannot extract an integer from the alloca"); assert(IntTy && "We cannot extract an integer from the alloca");
assert(!SI.isVolatile()); assert(!SI.isVolatile());
if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) { if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), Value *Old =
"oldload"); IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Old = convertValue(DL, IRB, Old, IntTy); Old = convertValue(DL, IRB, Old, IntTy);
assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset"); assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
uint64_t Offset = BeginOffset - NewAllocaBeginOffset; uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
"insert");
} }
V = convertValue(DL, IRB, V, NewAllocaTy); V = convertValue(DL, IRB, V, NewAllocaTy);
StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment()); StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
@@ -2397,8 +2385,7 @@ private:
DL.getTypeStoreSizeInBits(V->getType()) && DL.getTypeStoreSizeInBits(V->getType()) &&
"Non-byte-multiple bit width"); "Non-byte-multiple bit width");
IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8); IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset, V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset, "extract");
"extract");
} }
if (VecTy) if (VecTy)
@@ -2443,11 +2430,11 @@ private:
return V; return V;
Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8); Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"), V = IRB.CreateMul(
IRB.CreateZExt(V, SplatIntTy, "zext"),
ConstantExpr::getUDiv( ConstantExpr::getUDiv(
Constant::getAllOnesValue(SplatIntTy), Constant::getAllOnesValue(SplatIntTy),
ConstantExpr::getZExt( ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
Constant::getAllOnesValue(V->getType()),
SplatIntTy)), SplatIntTy)),
"isplat"); "isplat");
return V; return V;
@@ -2486,8 +2473,7 @@ private:
// If this doesn't map cleanly onto the alloca type, and that type isn't // If this doesn't map cleanly onto the alloca type, and that type isn't
// a single value type, just emit a memset. // a single value type, just emit a memset.
if (!VecTy && !IntTy && if (!VecTy && !IntTy &&
(BeginOffset > NewAllocaBeginOffset || (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
EndOffset < NewAllocaEndOffset ||
SliceSize != DL.getTypeStoreSize(AllocaTy) || SliceSize != DL.getTypeStoreSize(AllocaTy) ||
!AllocaTy->isSingleValueType() || !AllocaTy->isSingleValueType() ||
!DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) || !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
@@ -2525,8 +2511,8 @@ private:
if (NumElements > 1) if (NumElements > 1)
Splat = getVectorSplat(Splat, NumElements); Splat = getVectorSplat(Splat, NumElements);
Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), Value *Old =
"oldload"); IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
V = insertVector(IRB, Old, Splat, BeginIndex, "vec"); V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
} else if (IntTy) { } else if (IntTy) {
// If this is a memset on an alloca where we can widen stores, insert the // If this is a memset on an alloca where we can widen stores, insert the
@@ -2538,8 +2524,8 @@ private:
if (IntTy && (BeginOffset != NewAllocaBeginOffset || if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
EndOffset != NewAllocaBeginOffset)) { EndOffset != NewAllocaBeginOffset)) {
Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), Value *Old =
"oldload"); IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Old = convertValue(DL, IRB, Old, IntTy); Old = convertValue(DL, IRB, Old, IntTy);
uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
V = insertInteger(DL, IRB, Old, V, Offset, "insert"); V = insertInteger(DL, IRB, Old, V, Offset, "insert");
@@ -2636,8 +2622,8 @@ private:
// Strip all inbounds GEPs and pointer casts to try to dig out any root // Strip all inbounds GEPs and pointer casts to try to dig out any root
// alloca that should be re-examined after rewriting this instruction. // alloca that should be re-examined after rewriting this instruction.
Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest(); Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
if (AllocaInst *AI if (AllocaInst *AI =
= dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) { dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
assert(AI != &OldAI && AI != &NewAI && assert(AI != &OldAI && AI != &NewAI &&
"Splittable transfers cannot reach the same alloca on both ends."); "Splittable transfers cannot reach the same alloca on both ends.");
Pass.Worklist.insert(AI); Pass.Worklist.insert(AI);
@@ -2676,8 +2662,8 @@ private:
unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0; unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0; unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
unsigned NumElements = EndIndex - BeginIndex; unsigned NumElements = EndIndex - BeginIndex;
IntegerType *SubIntTy IntegerType *SubIntTy =
= IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr; IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
// Reset the other pointer type to match the register type we're going to // Reset the other pointer type to match the register type we're going to
// use, but using the address space of the original other pointer. // use, but using the address space of the original other pointer.
@@ -2706,27 +2692,25 @@ private:
Value *Src; Value *Src;
if (VecTy && !IsWholeAlloca && !IsDest) { if (VecTy && !IsWholeAlloca && !IsDest) {
Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
"load");
Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec"); Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
} else if (IntTy && !IsWholeAlloca && !IsDest) { } else if (IntTy && !IsWholeAlloca && !IsDest) {
Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
"load");
Src = convertValue(DL, IRB, Src, IntTy); Src = convertValue(DL, IRB, Src, IntTy);
uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract"); Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
} else { } else {
Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), Src =
"copyload"); IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
} }
if (VecTy && !IsWholeAlloca && IsDest) { if (VecTy && !IsWholeAlloca && IsDest) {
Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), Value *Old =
"oldload"); IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Src = insertVector(IRB, Old, Src, BeginIndex, "vec"); Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
} else if (IntTy && !IsWholeAlloca && IsDest) { } else if (IntTy && !IsWholeAlloca && IsDest) {
Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), Value *Old =
"oldload"); IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Old = convertValue(DL, IRB, Old, IntTy); Old = convertValue(DL, IRB, Old, IntTy);
uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Src = insertInteger(DL, IRB, Old, Src, Offset, "insert"); Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
@@ -2749,8 +2733,8 @@ private:
// Record this instruction for deletion. // Record this instruction for deletion.
Pass.DeadInsts.insert(&II); Pass.DeadInsts.insert(&II);
ConstantInt *Size ConstantInt *Size =
= ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()), ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
NewEndOffset - NewBeginOffset); NewEndOffset - NewBeginOffset);
Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Value *New; Value *New;
@@ -2817,7 +2801,6 @@ private:
SelectUsers.insert(&SI); SelectUsers.insert(&SI);
return true; return true;
} }
}; };
} }
@@ -2872,8 +2855,7 @@ private:
bool visitInstruction(Instruction &I) { return false; } bool visitInstruction(Instruction &I) { return false; }
/// \brief Generic recursive split emission class. /// \brief Generic recursive split emission class.
template <typename Derived> template <typename Derived> class OpSplitter {
class OpSplitter {
protected: protected:
/// The builder used to form new instructions. /// The builder used to form new instructions.
IRBuilderTy IRB; IRBuilderTy IRB;
@@ -3072,8 +3054,8 @@ static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
/// when the size or offset cause either end of type-based partition to be off. /// when the size or offset cause either end of type-based partition to be off.
/// Also, this is a best-effort routine. It is reasonable to give up and not /// Also, this is a best-effort routine. It is reasonable to give up and not
/// return a type if necessary. /// return a type if necessary.
static Type *getTypePartition(const DataLayout &DL, Type *Ty, static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
uint64_t Offset, uint64_t Size) { uint64_t Size) {
if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size) if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
return stripAggregateTypeWrapping(DL, Ty); return stripAggregateTypeWrapping(DL, Ty);
if (Offset > DL.getTypeAllocSize(Ty) || if (Offset > DL.getTypeAllocSize(Ty) ||
@@ -3165,8 +3147,8 @@ static Type *getTypePartition(const DataLayout &DL, Type *Ty,
} }
// Try to build up a sub-structure. // Try to build up a sub-structure.
StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE), StructType *SubTy =
STy->isPacked()); StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
const StructLayout *SubSL = DL.getStructLayout(SubTy); const StructLayout *SubSL = DL.getStructLayout(SubTy);
if (Size != SubSL->getSizeInBytes()) if (Size != SubSL->getSizeInBytes())
return nullptr; // The sub-struct doesn't have quite the size needed. return nullptr; // The sub-struct doesn't have quite the size needed.
@@ -3227,8 +3209,7 @@ bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
// perform phi and select speculation. // perform phi and select speculation.
AllocaInst *NewAI; AllocaInst *NewAI;
if (SliceTy == AI.getAllocatedType()) { if (SliceTy == AI.getAllocatedType()) {
assert(BeginOffset == 0 && assert(BeginOffset == 0 && "Non-zero begin offset but same alloca type");
"Non-zero begin offset but same alloca type");
NewAI = &AI; NewAI = &AI;
// FIXME: We should be able to bail at this point with "nothing changed". // FIXME: We should be able to bail at this point with "nothing changed".
// FIXME: We might want to defer PHI speculation until after here. // FIXME: We might want to defer PHI speculation until after here.
@@ -3344,7 +3325,8 @@ removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
} }
size_t SplitUsesOldSize = SplitUses.size(); size_t SplitUsesOldSize = SplitUses.size();
SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(), SplitUses.erase(std::remove_if(
SplitUses.begin(), SplitUses.end(),
[Offset](const AllocaSlices::iterator &I) { [Offset](const AllocaSlices::iterator &I) {
return I->endOffset() <= Offset; return I->endOffset() <= Offset;
}), }),
@@ -3564,7 +3546,8 @@ bool SROA::runOnAlloca(AllocaInst &AI) {
/// ///
/// We also record the alloca instructions deleted here so that they aren't /// We also record the alloca instructions deleted here so that they aren't
/// subsequently handed to mem2reg to promote. /// subsequently handed to mem2reg to promote.
void SROA::deleteDeadInstructions(SmallPtrSetImpl<AllocaInst*> &DeletedAllocas) { void SROA::deleteDeadInstructions(
SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
while (!DeadInsts.empty()) { while (!DeadInsts.empty()) {
Instruction *I = DeadInsts.pop_back_val(); Instruction *I = DeadInsts.pop_back_val();
DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n"); DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
@@ -3714,9 +3697,7 @@ bool SROA::runOnFunction(Function &F) {
// Remove the deleted allocas from various lists so that we don't try to // Remove the deleted allocas from various lists so that we don't try to
// continue processing them. // continue processing them.
if (!DeletedAllocas.empty()) { if (!DeletedAllocas.empty()) {
auto IsInSet = [&](AllocaInst *AI) { auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
return DeletedAllocas.count(AI);
};
Worklist.remove_if(IsInSet); Worklist.remove_if(IsInSet);
PostPromotionWorklist.remove_if(IsInSet); PostPromotionWorklist.remove_if(IsInSet);
PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(), PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),