#include "llvm/Transforms/Scalar/InferAddressSpaces.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <cassert>
#include <iterator>
#include <limits>
#include <utility>
#include <vector>
#define DEBUG_TYPE "infer-address-spaces"
using namespace llvm;
static cl::opt<bool> AssumeDefaultIsFlatAddressSpace(
"assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden,
cl::desc("The default address space is assumed as the flat address space. "
"This is mainly for test purpose."));
static const unsigned UninitializedAddressSpace =
std::numeric_limits<unsigned>::max();
namespace {
using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>;
using PredicatedAddrSpaceMapTy =
DenseMap<std::pair<const Value *, const Value *>, unsigned>;
using PostorderStackTy = llvm::SmallVector<PointerIntPair<Value *, 1, bool>, 4>;
class InferAddressSpaces : public FunctionPass {
unsigned FlatAddrSpace = 0;
public:
static char ID;
InferAddressSpaces() :
FunctionPass(ID), FlatAddrSpace(UninitializedAddressSpace) {}
InferAddressSpaces(unsigned AS) : FunctionPass(ID), FlatAddrSpace(AS) {}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<TargetTransformInfoWrapperPass>();
}
bool runOnFunction(Function &F) override;
};
class InferAddressSpacesImpl {
AssumptionCache &AC;
const DominatorTree *DT = nullptr;
const TargetTransformInfo *TTI = nullptr;
const DataLayout *DL = nullptr;
unsigned FlatAddrSpace = 0;
bool updateAddressSpace(const Value &V,
ValueToAddrSpaceMapTy &InferredAddrSpace,
PredicatedAddrSpaceMapTy &PredicatedAS) const;
void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
ValueToAddrSpaceMapTy &InferredAddrSpace,
PredicatedAddrSpaceMapTy &PredicatedAS) const;
bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const;
Value *cloneInstructionWithNewAddressSpace(
Instruction *I, unsigned NewAddrSpace,
const ValueToValueMapTy &ValueWithNewAddrSpace,
const PredicatedAddrSpaceMapTy &PredicatedAS,
SmallVectorImpl<const Use *> *UndefUsesToFix) const;
bool
rewriteWithNewAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
const ValueToAddrSpaceMapTy &InferredAddrSpace,
const PredicatedAddrSpaceMapTy &PredicatedAS,
Function *F) const;
void appendsFlatAddressExpressionToPostorderStack(
Value *V, PostorderStackTy &PostorderStack,
DenseSet<Value *> &Visited) const;
bool rewriteIntrinsicOperands(IntrinsicInst *II,
Value *OldV, Value *NewV) const;
void collectRewritableIntrinsicOperands(IntrinsicInst *II,
PostorderStackTy &PostorderStack,
DenseSet<Value *> &Visited) const;
std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const;
Value *cloneValueWithNewAddressSpace(
Value *V, unsigned NewAddrSpace,
const ValueToValueMapTy &ValueWithNewAddrSpace,
const PredicatedAddrSpaceMapTy &PredicatedAS,
SmallVectorImpl<const Use *> *UndefUsesToFix) const;
unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const;
unsigned getPredicatedAddrSpace(const Value &V, Value *Opnd) const;
public:
InferAddressSpacesImpl(AssumptionCache &AC, const DominatorTree *DT,
const TargetTransformInfo *TTI, unsigned FlatAddrSpace)
: AC(AC), DT(DT), TTI(TTI), FlatAddrSpace(FlatAddrSpace) {}
bool run(Function &F);
};
}
char InferAddressSpaces::ID = 0;
INITIALIZE_PASS_BEGIN(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
false, false)
static bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL,
const TargetTransformInfo *TTI) {
assert(I2P->getOpcode() == Instruction::IntToPtr);
auto *P2I = dyn_cast<Operator>(I2P->getOperand(0));
if (!P2I || P2I->getOpcode() != Instruction::PtrToInt)
return false;
unsigned P2IOp0AS = P2I->getOperand(0)->getType()->getPointerAddressSpace();
unsigned I2PAS = I2P->getType()->getPointerAddressSpace();
return CastInst::isNoopCast(Instruction::CastOps(I2P->getOpcode()),
I2P->getOperand(0)->getType(), I2P->getType(),
DL) &&
CastInst::isNoopCast(Instruction::CastOps(P2I->getOpcode()),
P2I->getOperand(0)->getType(), P2I->getType(),
DL) &&
(P2IOp0AS == I2PAS || TTI->isNoopAddrSpaceCast(P2IOp0AS, I2PAS));
}
static bool isAddressExpression(const Value &V, const DataLayout &DL,
const TargetTransformInfo *TTI) {
const Operator *Op = dyn_cast<Operator>(&V);
if (!Op)
return false;
switch (Op->getOpcode()) {
case Instruction::PHI:
assert(Op->getType()->isPointerTy());
return true;
case Instruction::BitCast:
case Instruction::AddrSpaceCast:
case Instruction::GetElementPtr:
return true;
case Instruction::Select:
return Op->getType()->isPointerTy();
case Instruction::Call: {
const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&V);
return II && II->getIntrinsicID() == Intrinsic::ptrmask;
}
case Instruction::IntToPtr:
return isNoopPtrIntCastPair(Op, DL, TTI);
default:
return TTI->getAssumedAddrSpace(&V) != UninitializedAddressSpace;
}
}
static SmallVector<Value *, 2>
getPointerOperands(const Value &V, const DataLayout &DL,
const TargetTransformInfo *TTI) {
const Operator &Op = cast<Operator>(V);
switch (Op.getOpcode()) {
case Instruction::PHI: {
auto IncomingValues = cast<PHINode>(Op).incoming_values();
return {IncomingValues.begin(), IncomingValues.end()};
}
case Instruction::BitCast:
case Instruction::AddrSpaceCast:
case Instruction::GetElementPtr:
return {Op.getOperand(0)};
case Instruction::Select:
return {Op.getOperand(1), Op.getOperand(2)};
case Instruction::Call: {
const IntrinsicInst &II = cast<IntrinsicInst>(Op);
assert(II.getIntrinsicID() == Intrinsic::ptrmask &&
"unexpected intrinsic call");
return {II.getArgOperand(0)};
}
case Instruction::IntToPtr: {
assert(isNoopPtrIntCastPair(&Op, DL, TTI));
auto *P2I = cast<Operator>(Op.getOperand(0));
return {P2I->getOperand(0)};
}
default:
llvm_unreachable("Unexpected instruction type.");
}
}
bool InferAddressSpacesImpl::rewriteIntrinsicOperands(IntrinsicInst *II,
Value *OldV,
Value *NewV) const {
Module *M = II->getParent()->getParent()->getParent();
switch (II->getIntrinsicID()) {
case Intrinsic::objectsize: {
Type *DestTy = II->getType();
Type *SrcTy = NewV->getType();
Function *NewDecl =
Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
II->setArgOperand(0, NewV);
II->setCalledFunction(NewDecl);
return true;
}
case Intrinsic::ptrmask:
return false;
default: {
Value *Rewrite = TTI->rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
if (!Rewrite)
return false;
if (Rewrite != II)
II->replaceAllUsesWith(Rewrite);
return true;
}
}
}
void InferAddressSpacesImpl::collectRewritableIntrinsicOperands(
IntrinsicInst *II, PostorderStackTy &PostorderStack,
DenseSet<Value *> &Visited) const {
auto IID = II->getIntrinsicID();
switch (IID) {
case Intrinsic::ptrmask:
case Intrinsic::objectsize:
appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
PostorderStack, Visited);
break;
default:
SmallVector<int, 2> OpIndexes;
if (TTI->collectFlatAddressOperands(OpIndexes, IID)) {
for (int Idx : OpIndexes) {
appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(Idx),
PostorderStack, Visited);
}
}
break;
}
}
void InferAddressSpacesImpl::appendsFlatAddressExpressionToPostorderStack(
Value *V, PostorderStackTy &PostorderStack,
DenseSet<Value *> &Visited) const {
assert(V->getType()->isPointerTy());
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
PostorderStack.emplace_back(CE, false);
return;
}
if (V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
isAddressExpression(*V, *DL, TTI)) {
if (Visited.insert(V).second) {
PostorderStack.emplace_back(V, false);
Operator *Op = cast<Operator>(V);
for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) {
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) {
if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
PostorderStack.emplace_back(CE, false);
}
}
}
}
}
std::vector<WeakTrackingVH>
InferAddressSpacesImpl::collectFlatAddressExpressions(Function &F) const {
PostorderStackTy PostorderStack;
DenseSet<Value *> Visited;
auto PushPtrOperand = [&](Value *Ptr) {
appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack,
Visited);
};
for (Instruction &I : instructions(F)) {
if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
if (!GEP->getType()->isVectorTy())
PushPtrOperand(GEP->getPointerOperand());
} else if (auto *LI = dyn_cast<LoadInst>(&I))
PushPtrOperand(LI->getPointerOperand());
else if (auto *SI = dyn_cast<StoreInst>(&I))
PushPtrOperand(SI->getPointerOperand());
else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
PushPtrOperand(RMW->getPointerOperand());
else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
PushPtrOperand(CmpX->getPointerOperand());
else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
PushPtrOperand(MI->getRawDest());
if (auto *MTI = dyn_cast<MemTransferInst>(MI))
PushPtrOperand(MTI->getRawSource());
} else if (auto *II = dyn_cast<IntrinsicInst>(&I))
collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
if (Cmp->getOperand(0)->getType()->isPointerTy()) {
PushPtrOperand(Cmp->getOperand(0));
PushPtrOperand(Cmp->getOperand(1));
}
} else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) {
if (!ASC->getType()->isVectorTy())
PushPtrOperand(ASC->getPointerOperand());
} else if (auto *I2P = dyn_cast<IntToPtrInst>(&I)) {
if (isNoopPtrIntCastPair(cast<Operator>(I2P), *DL, TTI))
PushPtrOperand(
cast<Operator>(I2P->getOperand(0))->getOperand(0));
}
}
std::vector<WeakTrackingVH> Postorder; while (!PostorderStack.empty()) {
Value *TopVal = PostorderStack.back().getPointer();
if (PostorderStack.back().getInt()) {
if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace)
Postorder.push_back(TopVal);
PostorderStack.pop_back();
continue;
}
PostorderStack.back().setInt(true);
if (TTI->getAssumedAddrSpace(TopVal) == UninitializedAddressSpace) {
for (Value *PtrOperand : getPointerOperands(*TopVal, *DL, TTI)) {
appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
Visited);
}
}
}
return Postorder;
}
static Value *operandWithNewAddressSpaceOrCreateUndef(
const Use &OperandUse, unsigned NewAddrSpace,
const ValueToValueMapTy &ValueWithNewAddrSpace,
const PredicatedAddrSpaceMapTy &PredicatedAS,
SmallVectorImpl<const Use *> *UndefUsesToFix) {
Value *Operand = OperandUse.get();
Type *NewPtrTy = PointerType::getWithSamePointeeType(
cast<PointerType>(Operand->getType()), NewAddrSpace);
if (Constant *C = dyn_cast<Constant>(Operand))
return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
return NewOperand;
Instruction *Inst = cast<Instruction>(OperandUse.getUser());
auto I = PredicatedAS.find(std::make_pair(Inst, Operand));
if (I != PredicatedAS.end()) {
unsigned NewAS = I->second;
Type *NewPtrTy = PointerType::getWithSamePointeeType(
cast<PointerType>(Operand->getType()), NewAS);
auto *NewI = new AddrSpaceCastInst(Operand, NewPtrTy);
NewI->insertBefore(Inst);
return NewI;
}
UndefUsesToFix->push_back(&OperandUse);
return UndefValue::get(NewPtrTy);
}
Value *InferAddressSpacesImpl::cloneInstructionWithNewAddressSpace(
Instruction *I, unsigned NewAddrSpace,
const ValueToValueMapTy &ValueWithNewAddrSpace,
const PredicatedAddrSpaceMapTy &PredicatedAS,
SmallVectorImpl<const Use *> *UndefUsesToFix) const {
Type *NewPtrType = PointerType::getWithSamePointeeType(
cast<PointerType>(I->getType()), NewAddrSpace);
if (I->getOpcode() == Instruction::AddrSpaceCast) {
Value *Src = I->getOperand(0);
assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
if (Src->getType() != NewPtrType)
return new BitCastInst(Src, NewPtrType);
return Src;
}
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
assert(II->getIntrinsicID() == Intrinsic::ptrmask);
Value *NewPtr = operandWithNewAddressSpaceOrCreateUndef(
II->getArgOperandUse(0), NewAddrSpace, ValueWithNewAddrSpace,
PredicatedAS, UndefUsesToFix);
Value *Rewrite =
TTI->rewriteIntrinsicWithAddressSpace(II, II->getArgOperand(0), NewPtr);
if (Rewrite) {
assert(Rewrite != II && "cannot modify this pointer operation in place");
return Rewrite;
}
return nullptr;
}
unsigned AS = TTI->getAssumedAddrSpace(I);
if (AS != UninitializedAddressSpace) {
Type *NewPtrTy = PointerType::getWithSamePointeeType(
cast<PointerType>(I->getType()), AS);
auto *NewI = new AddrSpaceCastInst(I, NewPtrTy);
NewI->insertAfter(I);
return NewI;
}
SmallVector<Value *, 4> NewPointerOperands;
for (const Use &OperandUse : I->operands()) {
if (!OperandUse.get()->getType()->isPointerTy())
NewPointerOperands.push_back(nullptr);
else
NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef(
OperandUse, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS,
UndefUsesToFix));
}
switch (I->getOpcode()) {
case Instruction::BitCast:
return new BitCastInst(NewPointerOperands[0], NewPtrType);
case Instruction::PHI: {
assert(I->getType()->isPointerTy());
PHINode *PHI = cast<PHINode>(I);
PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
NewPHI->addIncoming(NewPointerOperands[OperandNo],
PHI->getIncomingBlock(Index));
}
return NewPHI;
}
case Instruction::GetElementPtr: {
GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
GEP->getSourceElementType(), NewPointerOperands[0],
SmallVector<Value *, 4>(GEP->indices()));
NewGEP->setIsInBounds(GEP->isInBounds());
return NewGEP;
}
case Instruction::Select:
assert(I->getType()->isPointerTy());
return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
NewPointerOperands[2], "", nullptr, I);
case Instruction::IntToPtr: {
assert(isNoopPtrIntCastPair(cast<Operator>(I), *DL, TTI));
Value *Src = cast<Operator>(I->getOperand(0))->getOperand(0);
if (Src->getType() == NewPtrType)
return Src;
return CastInst::CreatePointerBitCastOrAddrSpaceCast(Src, NewPtrType);
}
default:
llvm_unreachable("Unexpected opcode");
}
}
static Value *cloneConstantExprWithNewAddressSpace(
ConstantExpr *CE, unsigned NewAddrSpace,
const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL,
const TargetTransformInfo *TTI) {
Type *TargetType = CE->getType()->isPointerTy()
? PointerType::getWithSamePointeeType(
cast<PointerType>(CE->getType()), NewAddrSpace)
: CE->getType();
if (CE->getOpcode() == Instruction::AddrSpaceCast) {
assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
NewAddrSpace);
return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
}
if (CE->getOpcode() == Instruction::BitCast) {
if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0)))
return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType);
return ConstantExpr::getAddrSpaceCast(CE, TargetType);
}
if (CE->getOpcode() == Instruction::Select) {
Constant *Src0 = CE->getOperand(1);
Constant *Src1 = CE->getOperand(2);
if (Src0->getType()->getPointerAddressSpace() ==
Src1->getType()->getPointerAddressSpace()) {
return ConstantExpr::getSelect(
CE->getOperand(0), ConstantExpr::getAddrSpaceCast(Src0, TargetType),
ConstantExpr::getAddrSpaceCast(Src1, TargetType));
}
}
if (CE->getOpcode() == Instruction::IntToPtr) {
assert(isNoopPtrIntCastPair(cast<Operator>(CE), *DL, TTI));
Constant *Src = cast<ConstantExpr>(CE->getOperand(0))->getOperand(0);
assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
return ConstantExpr::getBitCast(Src, TargetType);
}
bool IsNew = false;
SmallVector<Constant *, 4> NewOperands;
for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
Constant *Operand = CE->getOperand(Index);
if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
IsNew = true;
NewOperands.push_back(cast<Constant>(NewOperand));
continue;
}
if (auto *CExpr = dyn_cast<ConstantExpr>(Operand))
if (Value *NewOperand = cloneConstantExprWithNewAddressSpace(
CExpr, NewAddrSpace, ValueWithNewAddrSpace, DL, TTI)) {
IsNew = true;
NewOperands.push_back(cast<Constant>(NewOperand));
continue;
}
NewOperands.push_back(Operand);
}
if (!IsNew)
return nullptr;
if (CE->getOpcode() == Instruction::GetElementPtr) {
return CE->getWithOperands(NewOperands, TargetType, false,
cast<GEPOperator>(CE)->getSourceElementType());
}
return CE->getWithOperands(NewOperands, TargetType);
}
Value *InferAddressSpacesImpl::cloneValueWithNewAddressSpace(
Value *V, unsigned NewAddrSpace,
const ValueToValueMapTy &ValueWithNewAddrSpace,
const PredicatedAddrSpaceMapTy &PredicatedAS,
SmallVectorImpl<const Use *> *UndefUsesToFix) const {
assert(V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
isAddressExpression(*V, *DL, TTI));
if (Instruction *I = dyn_cast<Instruction>(V)) {
Value *NewV = cloneInstructionWithNewAddressSpace(
I, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, UndefUsesToFix);
if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) {
if (NewI->getParent() == nullptr) {
NewI->insertBefore(I);
NewI->takeName(I);
}
}
return NewV;
}
return cloneConstantExprWithNewAddressSpace(
cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace, DL, TTI);
}
unsigned InferAddressSpacesImpl::joinAddressSpaces(unsigned AS1,
unsigned AS2) const {
if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
return FlatAddrSpace;
if (AS1 == UninitializedAddressSpace)
return AS2;
if (AS2 == UninitializedAddressSpace)
return AS1;
return (AS1 == AS2) ? AS1 : FlatAddrSpace;
}
bool InferAddressSpacesImpl::run(Function &F) {
DL = &F.getParent()->getDataLayout();
if (AssumeDefaultIsFlatAddressSpace)
FlatAddrSpace = 0;
if (FlatAddrSpace == UninitializedAddressSpace) {
FlatAddrSpace = TTI->getFlatAddressSpace();
if (FlatAddrSpace == UninitializedAddressSpace)
return false;
}
std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F);
ValueToAddrSpaceMapTy InferredAddrSpace;
PredicatedAddrSpaceMapTy PredicatedAS;
inferAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS);
return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS,
&F);
}
void InferAddressSpacesImpl::inferAddressSpaces(
ArrayRef<WeakTrackingVH> Postorder,
ValueToAddrSpaceMapTy &InferredAddrSpace,
PredicatedAddrSpaceMapTy &PredicatedAS) const {
SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
for (Value *V : Postorder)
InferredAddrSpace[V] = UninitializedAddressSpace;
while (!Worklist.empty()) {
Value *V = Worklist.pop_back_val();
if (!updateAddressSpace(*V, InferredAddrSpace, PredicatedAS))
continue;
for (Value *User : V->users()) {
if (Worklist.count(User))
continue;
auto Pos = InferredAddrSpace.find(User);
if (Pos == InferredAddrSpace.end())
continue;
if (Pos->second == FlatAddrSpace)
continue;
Worklist.insert(User);
}
}
}
unsigned InferAddressSpacesImpl::getPredicatedAddrSpace(const Value &V,
Value *Opnd) const {
const Instruction *I = dyn_cast<Instruction>(&V);
if (!I)
return UninitializedAddressSpace;
Opnd = Opnd->stripInBoundsOffsets();
for (auto &AssumeVH : AC.assumptionsFor(Opnd)) {
if (!AssumeVH)
continue;
CallInst *CI = cast<CallInst>(AssumeVH);
if (!isValidAssumeForContext(CI, I, DT))
continue;
const Value *Ptr;
unsigned AS;
std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(CI->getArgOperand(0));
if (Ptr)
return AS;
}
return UninitializedAddressSpace;
}
bool InferAddressSpacesImpl::updateAddressSpace(
const Value &V, ValueToAddrSpaceMapTy &InferredAddrSpace,
PredicatedAddrSpaceMapTy &PredicatedAS) const {
assert(InferredAddrSpace.count(&V));
LLVM_DEBUG(dbgs() << "Updating the address space of\n " << V << '\n');
unsigned NewAS = UninitializedAddressSpace;
const Operator &Op = cast<Operator>(V);
if (Op.getOpcode() == Instruction::Select) {
Value *Src0 = Op.getOperand(1);
Value *Src1 = Op.getOperand(2);
auto I = InferredAddrSpace.find(Src0);
unsigned Src0AS = (I != InferredAddrSpace.end()) ?
I->second : Src0->getType()->getPointerAddressSpace();
auto J = InferredAddrSpace.find(Src1);
unsigned Src1AS = (J != InferredAddrSpace.end()) ?
J->second : Src1->getType()->getPointerAddressSpace();
auto *C0 = dyn_cast<Constant>(Src0);
auto *C1 = dyn_cast<Constant>(Src1);
if ((C1 && Src0AS == UninitializedAddressSpace) ||
(C0 && Src1AS == UninitializedAddressSpace))
return false;
if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
NewAS = Src1AS;
else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
NewAS = Src0AS;
else
NewAS = joinAddressSpaces(Src0AS, Src1AS);
} else {
unsigned AS = TTI->getAssumedAddrSpace(&V);
if (AS != UninitializedAddressSpace) {
NewAS = AS;
} else {
for (Value *PtrOperand : getPointerOperands(V, *DL, TTI)) {
auto I = InferredAddrSpace.find(PtrOperand);
unsigned OperandAS;
if (I == InferredAddrSpace.end()) {
OperandAS = PtrOperand->getType()->getPointerAddressSpace();
if (OperandAS == FlatAddrSpace) {
unsigned AS = getPredicatedAddrSpace(V, PtrOperand);
if (AS != UninitializedAddressSpace) {
LLVM_DEBUG(dbgs()
<< " deduce operand AS from the predicate addrspace "
<< AS << '\n');
OperandAS = AS;
PredicatedAS[std::make_pair(&V, PtrOperand)] = OperandAS;
}
}
} else
OperandAS = I->second;
NewAS = joinAddressSpaces(NewAS, OperandAS);
if (NewAS == FlatAddrSpace)
break;
}
}
}
unsigned OldAS = InferredAddrSpace.lookup(&V);
assert(OldAS != FlatAddrSpace);
if (OldAS == NewAS)
return false;
LLVM_DEBUG(dbgs() << " to " << NewAS << '\n');
InferredAddrSpace[&V] = NewAS;
return true;
}
static bool isSimplePointerUseValidToReplace(const TargetTransformInfo &TTI,
Use &U, unsigned AddrSpace) {
User *Inst = U.getUser();
unsigned OpNo = U.getOperandNo();
bool VolatileIsAllowed = false;
if (auto *I = dyn_cast<Instruction>(Inst))
VolatileIsAllowed = TTI.hasVolatileVariant(I, AddrSpace);
if (auto *LI = dyn_cast<LoadInst>(Inst))
return OpNo == LoadInst::getPointerOperandIndex() &&
(VolatileIsAllowed || !LI->isVolatile());
if (auto *SI = dyn_cast<StoreInst>(Inst))
return OpNo == StoreInst::getPointerOperandIndex() &&
(VolatileIsAllowed || !SI->isVolatile());
if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
return OpNo == AtomicRMWInst::getPointerOperandIndex() &&
(VolatileIsAllowed || !RMW->isVolatile());
if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst))
return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() &&
(VolatileIsAllowed || !CmpX->isVolatile());
return false;
}
static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV,
Value *NewV) {
IRBuilder<> B(MI);
MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa);
MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope);
MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias);
if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
B.CreateMemSet(NewV, MSI->getValue(), MSI->getLength(), MSI->getDestAlign(),
false, TBAA, ScopeMD, NoAliasMD);
} else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
Value *Src = MTI->getRawSource();
Value *Dest = MTI->getRawDest();
if (Src == OldV)
Src = NewV;
if (Dest == OldV)
Dest = NewV;
if (isa<MemCpyInlineInst>(MTI)) {
MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
B.CreateMemCpyInline(Dest, MTI->getDestAlign(), Src,
MTI->getSourceAlign(), MTI->getLength(),
false, TBAA, TBAAStruct, ScopeMD, NoAliasMD);
} else if (isa<MemCpyInst>(MTI)) {
MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
B.CreateMemCpy(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
MTI->getLength(),
false, TBAA, TBAAStruct, ScopeMD, NoAliasMD);
} else {
assert(isa<MemMoveInst>(MTI));
B.CreateMemMove(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
MTI->getLength(),
false, TBAA, ScopeMD, NoAliasMD);
}
} else
llvm_unreachable("unhandled MemIntrinsic");
MI->eraseFromParent();
return true;
}
bool InferAddressSpacesImpl::isSafeToCastConstAddrSpace(Constant *C,
unsigned NewAS) const {
assert(NewAS != UninitializedAddressSpace);
unsigned SrcAS = C->getType()->getPointerAddressSpace();
if (SrcAS == NewAS || isa<UndefValue>(C))
return true;
if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
return false;
if (isa<ConstantPointerNull>(C))
return true;
if (auto *Op = dyn_cast<Operator>(C)) {
if (Op->getOpcode() == Instruction::AddrSpaceCast)
return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS);
if (Op->getOpcode() == Instruction::IntToPtr &&
Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
return true;
}
return false;
}
static Value::use_iterator skipToNextUser(Value::use_iterator I,
Value::use_iterator End) {
User *CurUser = I->getUser();
++I;
while (I != End && I->getUser() == CurUser)
++I;
return I;
}
bool InferAddressSpacesImpl::rewriteWithNewAddressSpaces(
ArrayRef<WeakTrackingVH> Postorder,
const ValueToAddrSpaceMapTy &InferredAddrSpace,
const PredicatedAddrSpaceMapTy &PredicatedAS, Function *F) const {
ValueToValueMapTy ValueWithNewAddrSpace;
SmallVector<const Use *, 32> UndefUsesToFix;
for (Value* V : Postorder) {
unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
if (NewAddrSpace == UninitializedAddressSpace)
continue;
if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
Value *New =
cloneValueWithNewAddressSpace(V, NewAddrSpace, ValueWithNewAddrSpace,
PredicatedAS, &UndefUsesToFix);
if (New)
ValueWithNewAddrSpace[V] = New;
}
}
if (ValueWithNewAddrSpace.empty())
return false;
for (const Use *UndefUse : UndefUsesToFix) {
User *V = UndefUse->getUser();
User *NewV = cast_or_null<User>(ValueWithNewAddrSpace.lookup(V));
if (!NewV)
continue;
unsigned OperandNo = UndefUse->getOperandNo();
assert(isa<UndefValue>(NewV->getOperand(OperandNo)));
NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get()));
}
SmallVector<Instruction *, 16> DeadInstructions;
for (const WeakTrackingVH &WVH : Postorder) {
assert(WVH && "value was unexpectedly deleted");
Value *V = WVH;
Value *NewV = ValueWithNewAddrSpace.lookup(V);
if (NewV == nullptr)
continue;
LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n with\n "
<< *NewV << '\n');
if (Constant *C = dyn_cast<Constant>(V)) {
Constant *Replace = ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
C->getType());
if (C != Replace) {
LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace
<< ": " << *Replace << '\n');
C->replaceAllUsesWith(Replace);
V = Replace;
}
}
Value::use_iterator I, E, Next;
for (I = V->use_begin(), E = V->use_end(); I != E; ) {
Use &U = *I;
I = skipToNextUser(I, E);
if (isSimplePointerUseValidToReplace(
*TTI, U, V->getType()->getPointerAddressSpace())) {
U.set(NewV);
continue;
}
User *CurUser = U.getUser();
if (CurUser == NewV)
continue;
if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
continue;
}
if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
if (rewriteIntrinsicOperands(II, V, NewV))
continue;
}
if (isa<Instruction>(CurUser)) {
if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
unsigned NewAS = NewV->getType()->getPointerAddressSpace();
int SrcIdx = U.getOperandNo();
int OtherIdx = (SrcIdx == 0) ? 1 : 0;
Value *OtherSrc = Cmp->getOperand(OtherIdx);
if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
Cmp->setOperand(OtherIdx, OtherNewV);
Cmp->setOperand(SrcIdx, NewV);
continue;
}
}
if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
Cmp->setOperand(SrcIdx, NewV);
Cmp->setOperand(OtherIdx,
ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType()));
continue;
}
}
}
if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) {
unsigned NewAS = NewV->getType()->getPointerAddressSpace();
if (ASC->getDestAddressSpace() == NewAS) {
if (!cast<PointerType>(ASC->getType())
->hasSameElementTypeAs(
cast<PointerType>(NewV->getType()))) {
BasicBlock::iterator InsertPos;
if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
InsertPos = std::next(NewVInst->getIterator());
else if (Instruction *VInst = dyn_cast<Instruction>(V))
InsertPos = std::next(VInst->getIterator());
else
InsertPos = ASC->getIterator();
NewV = CastInst::Create(Instruction::BitCast, NewV,
ASC->getType(), "", &*InsertPos);
}
ASC->replaceAllUsesWith(NewV);
DeadInstructions.push_back(ASC);
continue;
}
}
if (Instruction *VInst = dyn_cast<Instruction>(V)) {
if (U == V && isa<AddrSpaceCastInst>(V))
continue;
BasicBlock::iterator InsertPos;
if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
InsertPos = std::next(NewVInst->getIterator());
else
InsertPos = std::next(VInst->getIterator());
while (isa<PHINode>(InsertPos))
++InsertPos;
U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
} else {
U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
V->getType()));
}
}
}
if (V->use_empty()) {
if (Instruction *I = dyn_cast<Instruction>(V))
DeadInstructions.push_back(I);
}
}
for (Instruction *I : DeadInstructions)
RecursivelyDeleteTriviallyDeadInstructions(I);
return true;
}
bool InferAddressSpaces::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
return InferAddressSpacesImpl(
getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), DT,
&getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
FlatAddrSpace)
.run(F);
}
FunctionPass *llvm::createInferAddressSpacesPass(unsigned AddressSpace) {
return new InferAddressSpaces(AddressSpace);
}
InferAddressSpacesPass::InferAddressSpacesPass()
: FlatAddrSpace(UninitializedAddressSpace) {}
InferAddressSpacesPass::InferAddressSpacesPass(unsigned AddressSpace)
: FlatAddrSpace(AddressSpace) {}
PreservedAnalyses InferAddressSpacesPass::run(Function &F,
FunctionAnalysisManager &AM) {
bool Changed =
InferAddressSpacesImpl(AM.getResult<AssumptionAnalysis>(F),
AM.getCachedResult<DominatorTreeAnalysis>(F),
&AM.getResult<TargetIRAnalysis>(F), FlatAddrSpace)
.run(F);
if (Changed) {
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
PA.preserve<DominatorTreeAnalysis>();
return PA;
}
return PreservedAnalyses::all();
}