InferAddressSpaces.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  1. //===- InferAddressSpace.cpp - --------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // CUDA C/C++ includes memory space designation as variable type qualifers (such
  10. // as __global__ and __shared__). Knowing the space of a memory access allows
  11. // CUDA compilers to emit faster PTX loads and stores. For example, a load from
  12. // shared memory can be translated to `ld.shared` which is roughly 10% faster
  13. // than a generic `ld` on an NVIDIA Tesla K40c.
  14. //
  15. // Unfortunately, type qualifiers only apply to variable declarations, so CUDA
  16. // compilers must infer the memory space of an address expression from
  17. // type-qualified variables.
  18. //
  19. // LLVM IR uses non-zero (so-called) specific address spaces to represent memory
  20. // spaces (e.g. addrspace(3) means shared memory). The Clang frontend
  21. // places only type-qualified variables in specific address spaces, and then
  22. // conservatively `addrspacecast`s each type-qualified variable to addrspace(0)
  23. // (so-called the generic address space) for other instructions to use.
  24. //
  25. // For example, the Clang translates the following CUDA code
  26. // __shared__ float a[10];
  27. // float v = a[i];
  28. // to
  29. // %0 = addrspacecast [10 x float] addrspace(3)* @a to [10 x float]*
  30. // %1 = gep [10 x float], [10 x float]* %0, i64 0, i64 %i
  31. // %v = load float, float* %1 ; emits ld.f32
  32. // @a is in addrspace(3) since it's type-qualified, but its use from %1 is
  33. // redirected to %0 (the generic version of @a).
  34. //
  35. // The optimization implemented in this file propagates specific address spaces
  36. // from type-qualified variable declarations to its users. For example, it
  37. // optimizes the above IR to
  38. // %1 = gep [10 x float] addrspace(3)* @a, i64 0, i64 %i
  39. // %v = load float addrspace(3)* %1 ; emits ld.shared.f32
  40. // propagating the addrspace(3) from @a to %1. As the result, the NVPTX
  41. // codegen is able to emit ld.shared.f32 for %v.
  42. //
  43. // Address space inference works in two steps. First, it uses a data-flow
  44. // analysis to infer as many generic pointers as possible to point to only one
  45. // specific address space. In the above example, it can prove that %1 only
  46. // points to addrspace(3). This algorithm was published in
  47. // CUDA: Compiling and optimizing for a GPU platform
  48. // Chakrabarti, Grover, Aarts, Kong, Kudlur, Lin, Marathe, Murphy, Wang
  49. // ICCS 2012
  50. //
  51. // Then, address space inference replaces all refinable generic pointers with
  52. // equivalent specific pointers.
  53. //
  54. // The major challenge of implementing this optimization is handling PHINodes,
  55. // which may create loops in the data flow graph. This brings two complications.
  56. //
  57. // First, the data flow analysis in Step 1 needs to be circular. For example,
  58. // %generic.input = addrspacecast float addrspace(3)* %input to float*
  59. // loop:
  60. // %y = phi [ %generic.input, %y2 ]
  61. // %y2 = getelementptr %y, 1
  62. // %v = load %y2
  63. // br ..., label %loop, ...
  64. // proving %y specific requires proving both %generic.input and %y2 specific,
  65. // but proving %y2 specific circles back to %y. To address this complication,
  66. // the data flow analysis operates on a lattice:
  67. // uninitialized > specific address spaces > generic.
  68. // All address expressions (our implementation only considers phi, bitcast,
  69. // addrspacecast, and getelementptr) start with the uninitialized address space.
  70. // The monotone transfer function moves the address space of a pointer down a
  71. // lattice path from uninitialized to specific and then to generic. A join
  72. // operation of two different specific address spaces pushes the expression down
  73. // to the generic address space. The analysis completes once it reaches a fixed
  74. // point.
  75. //
  76. // Second, IR rewriting in Step 2 also needs to be circular. For example,
  77. // converting %y to addrspace(3) requires the compiler to know the converted
  78. // %y2, but converting %y2 needs the converted %y. To address this complication,
  79. // we break these cycles using "undef" placeholders. When converting an
  80. // instruction `I` to a new address space, if its operand `Op` is not converted
  81. // yet, we let `I` temporarily use `undef` and fix all the uses of undef later.
  82. // For instance, our algorithm first converts %y to
  83. // %y' = phi float addrspace(3)* [ %input, undef ]
  84. // Then, it converts %y2 to
  85. // %y2' = getelementptr %y', 1
  86. // Finally, it fixes the undef in %y' so that
  87. // %y' = phi float addrspace(3)* [ %input, %y2' ]
  88. //
  89. //===----------------------------------------------------------------------===//
  90. #include "llvm/Transforms/Scalar/InferAddressSpaces.h"
  91. #include "llvm/ADT/ArrayRef.h"
  92. #include "llvm/ADT/DenseMap.h"
  93. #include "llvm/ADT/DenseSet.h"
  94. #include "llvm/ADT/SetVector.h"
  95. #include "llvm/ADT/SmallVector.h"
  96. #include "llvm/Analysis/AssumptionCache.h"
  97. #include "llvm/Analysis/TargetTransformInfo.h"
  98. #include "llvm/Analysis/ValueTracking.h"
  99. #include "llvm/IR/BasicBlock.h"
  100. #include "llvm/IR/Constant.h"
  101. #include "llvm/IR/Constants.h"
  102. #include "llvm/IR/Dominators.h"
  103. #include "llvm/IR/Function.h"
  104. #include "llvm/IR/IRBuilder.h"
  105. #include "llvm/IR/InstIterator.h"
  106. #include "llvm/IR/Instruction.h"
  107. #include "llvm/IR/Instructions.h"
  108. #include "llvm/IR/IntrinsicInst.h"
  109. #include "llvm/IR/Intrinsics.h"
  110. #include "llvm/IR/LLVMContext.h"
  111. #include "llvm/IR/Operator.h"
  112. #include "llvm/IR/PassManager.h"
  113. #include "llvm/IR/Type.h"
  114. #include "llvm/IR/Use.h"
  115. #include "llvm/IR/User.h"
  116. #include "llvm/IR/Value.h"
  117. #include "llvm/IR/ValueHandle.h"
  118. #include "llvm/InitializePasses.h"
  119. #include "llvm/Pass.h"
  120. #include "llvm/Support/Casting.h"
  121. #include "llvm/Support/CommandLine.h"
  122. #include "llvm/Support/Compiler.h"
  123. #include "llvm/Support/Debug.h"
  124. #include "llvm/Support/ErrorHandling.h"
  125. #include "llvm/Support/raw_ostream.h"
  126. #include "llvm/Transforms/Scalar.h"
  127. #include "llvm/Transforms/Utils/Local.h"
  128. #include "llvm/Transforms/Utils/ValueMapper.h"
  129. #include <cassert>
  130. #include <iterator>
  131. #include <limits>
  132. #include <utility>
  133. #include <vector>
  134. #define DEBUG_TYPE "infer-address-spaces"
  135. using namespace llvm;
  136. static cl::opt<bool> AssumeDefaultIsFlatAddressSpace(
  137. "assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden,
  138. cl::desc("The default address space is assumed as the flat address space. "
  139. "This is mainly for test purpose."));
  140. static const unsigned UninitializedAddressSpace =
  141. std::numeric_limits<unsigned>::max();
  142. namespace {
  143. using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>;
  144. // Different from ValueToAddrSpaceMapTy, where a new addrspace is inferred on
  145. // the *def* of a value, PredicatedAddrSpaceMapTy is map where a new
  146. // addrspace is inferred on the *use* of a pointer. This map is introduced to
  147. // infer addrspace from the addrspace predicate assumption built from assume
  148. // intrinsic. In that scenario, only specific uses (under valid assumption
  149. // context) could be inferred with a new addrspace.
  150. using PredicatedAddrSpaceMapTy =
  151. DenseMap<std::pair<const Value *, const Value *>, unsigned>;
  152. using PostorderStackTy = llvm::SmallVector<PointerIntPair<Value *, 1, bool>, 4>;
  153. class InferAddressSpaces : public FunctionPass {
  154. unsigned FlatAddrSpace = 0;
  155. public:
  156. static char ID;
  157. InferAddressSpaces() :
  158. FunctionPass(ID), FlatAddrSpace(UninitializedAddressSpace) {}
  159. InferAddressSpaces(unsigned AS) : FunctionPass(ID), FlatAddrSpace(AS) {}
  160. void getAnalysisUsage(AnalysisUsage &AU) const override {
  161. AU.setPreservesCFG();
  162. AU.addPreserved<DominatorTreeWrapperPass>();
  163. AU.addRequired<AssumptionCacheTracker>();
  164. AU.addRequired<TargetTransformInfoWrapperPass>();
  165. }
  166. bool runOnFunction(Function &F) override;
  167. };
  168. class InferAddressSpacesImpl {
  169. AssumptionCache &AC;
  170. const DominatorTree *DT = nullptr;
  171. const TargetTransformInfo *TTI = nullptr;
  172. const DataLayout *DL = nullptr;
  173. /// Target specific address space which uses of should be replaced if
  174. /// possible.
  175. unsigned FlatAddrSpace = 0;
  176. // Try to update the address space of V. If V is updated, returns true and
  177. // false otherwise.
  178. bool updateAddressSpace(const Value &V,
  179. ValueToAddrSpaceMapTy &InferredAddrSpace,
  180. PredicatedAddrSpaceMapTy &PredicatedAS) const;
  181. // Tries to infer the specific address space of each address expression in
  182. // Postorder.
  183. void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
  184. ValueToAddrSpaceMapTy &InferredAddrSpace,
  185. PredicatedAddrSpaceMapTy &PredicatedAS) const;
  186. bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const;
  187. Value *cloneInstructionWithNewAddressSpace(
  188. Instruction *I, unsigned NewAddrSpace,
  189. const ValueToValueMapTy &ValueWithNewAddrSpace,
  190. const PredicatedAddrSpaceMapTy &PredicatedAS,
  191. SmallVectorImpl<const Use *> *UndefUsesToFix) const;
  192. // Changes the flat address expressions in function F to point to specific
  193. // address spaces if InferredAddrSpace says so. Postorder is the postorder of
  194. // all flat expressions in the use-def graph of function F.
  195. bool
  196. rewriteWithNewAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
  197. const ValueToAddrSpaceMapTy &InferredAddrSpace,
  198. const PredicatedAddrSpaceMapTy &PredicatedAS,
  199. Function *F) const;
  200. void appendsFlatAddressExpressionToPostorderStack(
  201. Value *V, PostorderStackTy &PostorderStack,
  202. DenseSet<Value *> &Visited) const;
  203. bool rewriteIntrinsicOperands(IntrinsicInst *II,
  204. Value *OldV, Value *NewV) const;
  205. void collectRewritableIntrinsicOperands(IntrinsicInst *II,
  206. PostorderStackTy &PostorderStack,
  207. DenseSet<Value *> &Visited) const;
  208. std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const;
  209. Value *cloneValueWithNewAddressSpace(
  210. Value *V, unsigned NewAddrSpace,
  211. const ValueToValueMapTy &ValueWithNewAddrSpace,
  212. const PredicatedAddrSpaceMapTy &PredicatedAS,
  213. SmallVectorImpl<const Use *> *UndefUsesToFix) const;
  214. unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const;
  215. unsigned getPredicatedAddrSpace(const Value &V, Value *Opnd) const;
  216. public:
  217. InferAddressSpacesImpl(AssumptionCache &AC, const DominatorTree *DT,
  218. const TargetTransformInfo *TTI, unsigned FlatAddrSpace)
  219. : AC(AC), DT(DT), TTI(TTI), FlatAddrSpace(FlatAddrSpace) {}
  220. bool run(Function &F);
  221. };
  222. } // end anonymous namespace
  223. char InferAddressSpaces::ID = 0;
  224. INITIALIZE_PASS_BEGIN(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
  225. false, false)
  226. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  227. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  228. INITIALIZE_PASS_END(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
  229. false, false)
  230. // Check whether that's no-op pointer bicast using a pair of
  231. // `ptrtoint`/`inttoptr` due to the missing no-op pointer bitcast over
  232. // different address spaces.
  233. static bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL,
  234. const TargetTransformInfo *TTI) {
  235. assert(I2P->getOpcode() == Instruction::IntToPtr);
  236. auto *P2I = dyn_cast<Operator>(I2P->getOperand(0));
  237. if (!P2I || P2I->getOpcode() != Instruction::PtrToInt)
  238. return false;
  239. // Check it's really safe to treat that pair of `ptrtoint`/`inttoptr` as a
  240. // no-op cast. Besides checking both of them are no-op casts, as the
  241. // reinterpreted pointer may be used in other pointer arithmetic, we also
  242. // need to double-check that through the target-specific hook. That ensures
  243. // the underlying target also agrees that's a no-op address space cast and
  244. // pointer bits are preserved.
  245. // The current IR spec doesn't have clear rules on address space casts,
  246. // especially a clear definition for pointer bits in non-default address
  247. // spaces. It would be undefined if that pointer is dereferenced after an
  248. // invalid reinterpret cast. Also, due to the unclearness for the meaning of
  249. // bits in non-default address spaces in the current spec, the pointer
  250. // arithmetic may also be undefined after invalid pointer reinterpret cast.
  251. // However, as we confirm through the target hooks that it's a no-op
  252. // addrspacecast, it doesn't matter since the bits should be the same.
  253. unsigned P2IOp0AS = P2I->getOperand(0)->getType()->getPointerAddressSpace();
  254. unsigned I2PAS = I2P->getType()->getPointerAddressSpace();
  255. return CastInst::isNoopCast(Instruction::CastOps(I2P->getOpcode()),
  256. I2P->getOperand(0)->getType(), I2P->getType(),
  257. DL) &&
  258. CastInst::isNoopCast(Instruction::CastOps(P2I->getOpcode()),
  259. P2I->getOperand(0)->getType(), P2I->getType(),
  260. DL) &&
  261. (P2IOp0AS == I2PAS || TTI->isNoopAddrSpaceCast(P2IOp0AS, I2PAS));
  262. }
  263. // Returns true if V is an address expression.
  264. // TODO: Currently, we consider only phi, bitcast, addrspacecast, and
  265. // getelementptr operators.
  266. static bool isAddressExpression(const Value &V, const DataLayout &DL,
  267. const TargetTransformInfo *TTI) {
  268. const Operator *Op = dyn_cast<Operator>(&V);
  269. if (!Op)
  270. return false;
  271. switch (Op->getOpcode()) {
  272. case Instruction::PHI:
  273. assert(Op->getType()->isPointerTy());
  274. return true;
  275. case Instruction::BitCast:
  276. case Instruction::AddrSpaceCast:
  277. case Instruction::GetElementPtr:
  278. return true;
  279. case Instruction::Select:
  280. return Op->getType()->isPointerTy();
  281. case Instruction::Call: {
  282. const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&V);
  283. return II && II->getIntrinsicID() == Intrinsic::ptrmask;
  284. }
  285. case Instruction::IntToPtr:
  286. return isNoopPtrIntCastPair(Op, DL, TTI);
  287. default:
  288. // That value is an address expression if it has an assumed address space.
  289. return TTI->getAssumedAddrSpace(&V) != UninitializedAddressSpace;
  290. }
  291. }
  292. // Returns the pointer operands of V.
  293. //
  294. // Precondition: V is an address expression.
  295. static SmallVector<Value *, 2>
  296. getPointerOperands(const Value &V, const DataLayout &DL,
  297. const TargetTransformInfo *TTI) {
  298. const Operator &Op = cast<Operator>(V);
  299. switch (Op.getOpcode()) {
  300. case Instruction::PHI: {
  301. auto IncomingValues = cast<PHINode>(Op).incoming_values();
  302. return {IncomingValues.begin(), IncomingValues.end()};
  303. }
  304. case Instruction::BitCast:
  305. case Instruction::AddrSpaceCast:
  306. case Instruction::GetElementPtr:
  307. return {Op.getOperand(0)};
  308. case Instruction::Select:
  309. return {Op.getOperand(1), Op.getOperand(2)};
  310. case Instruction::Call: {
  311. const IntrinsicInst &II = cast<IntrinsicInst>(Op);
  312. assert(II.getIntrinsicID() == Intrinsic::ptrmask &&
  313. "unexpected intrinsic call");
  314. return {II.getArgOperand(0)};
  315. }
  316. case Instruction::IntToPtr: {
  317. assert(isNoopPtrIntCastPair(&Op, DL, TTI));
  318. auto *P2I = cast<Operator>(Op.getOperand(0));
  319. return {P2I->getOperand(0)};
  320. }
  321. default:
  322. llvm_unreachable("Unexpected instruction type.");
  323. }
  324. }
  325. bool InferAddressSpacesImpl::rewriteIntrinsicOperands(IntrinsicInst *II,
  326. Value *OldV,
  327. Value *NewV) const {
  328. Module *M = II->getParent()->getParent()->getParent();
  329. switch (II->getIntrinsicID()) {
  330. case Intrinsic::objectsize: {
  331. Type *DestTy = II->getType();
  332. Type *SrcTy = NewV->getType();
  333. Function *NewDecl =
  334. Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
  335. II->setArgOperand(0, NewV);
  336. II->setCalledFunction(NewDecl);
  337. return true;
  338. }
  339. case Intrinsic::ptrmask:
  340. // This is handled as an address expression, not as a use memory operation.
  341. return false;
  342. default: {
  343. Value *Rewrite = TTI->rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
  344. if (!Rewrite)
  345. return false;
  346. if (Rewrite != II)
  347. II->replaceAllUsesWith(Rewrite);
  348. return true;
  349. }
  350. }
  351. }
  352. void InferAddressSpacesImpl::collectRewritableIntrinsicOperands(
  353. IntrinsicInst *II, PostorderStackTy &PostorderStack,
  354. DenseSet<Value *> &Visited) const {
  355. auto IID = II->getIntrinsicID();
  356. switch (IID) {
  357. case Intrinsic::ptrmask:
  358. case Intrinsic::objectsize:
  359. appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
  360. PostorderStack, Visited);
  361. break;
  362. default:
  363. SmallVector<int, 2> OpIndexes;
  364. if (TTI->collectFlatAddressOperands(OpIndexes, IID)) {
  365. for (int Idx : OpIndexes) {
  366. appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(Idx),
  367. PostorderStack, Visited);
  368. }
  369. }
  370. break;
  371. }
  372. }
  373. // Returns all flat address expressions in function F. The elements are
  374. // If V is an unvisited flat address expression, appends V to PostorderStack
  375. // and marks it as visited.
  376. void InferAddressSpacesImpl::appendsFlatAddressExpressionToPostorderStack(
  377. Value *V, PostorderStackTy &PostorderStack,
  378. DenseSet<Value *> &Visited) const {
  379. assert(V->getType()->isPointerTy());
  380. // Generic addressing expressions may be hidden in nested constant
  381. // expressions.
  382. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
  383. // TODO: Look in non-address parts, like icmp operands.
  384. if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
  385. PostorderStack.emplace_back(CE, false);
  386. return;
  387. }
  388. if (V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
  389. isAddressExpression(*V, *DL, TTI)) {
  390. if (Visited.insert(V).second) {
  391. PostorderStack.emplace_back(V, false);
  392. Operator *Op = cast<Operator>(V);
  393. for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) {
  394. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) {
  395. if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
  396. PostorderStack.emplace_back(CE, false);
  397. }
  398. }
  399. }
  400. }
  401. }
  402. // Returns all flat address expressions in function F. The elements are ordered
  403. // ordered in postorder.
  404. std::vector<WeakTrackingVH>
  405. InferAddressSpacesImpl::collectFlatAddressExpressions(Function &F) const {
  406. // This function implements a non-recursive postorder traversal of a partial
  407. // use-def graph of function F.
  408. PostorderStackTy PostorderStack;
  409. // The set of visited expressions.
  410. DenseSet<Value *> Visited;
  411. auto PushPtrOperand = [&](Value *Ptr) {
  412. appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack,
  413. Visited);
  414. };
  415. // Look at operations that may be interesting accelerate by moving to a known
  416. // address space. We aim at generating after loads and stores, but pure
  417. // addressing calculations may also be faster.
  418. for (Instruction &I : instructions(F)) {
  419. if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  420. if (!GEP->getType()->isVectorTy())
  421. PushPtrOperand(GEP->getPointerOperand());
  422. } else if (auto *LI = dyn_cast<LoadInst>(&I))
  423. PushPtrOperand(LI->getPointerOperand());
  424. else if (auto *SI = dyn_cast<StoreInst>(&I))
  425. PushPtrOperand(SI->getPointerOperand());
  426. else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
  427. PushPtrOperand(RMW->getPointerOperand());
  428. else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
  429. PushPtrOperand(CmpX->getPointerOperand());
  430. else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
  431. // For memset/memcpy/memmove, any pointer operand can be replaced.
  432. PushPtrOperand(MI->getRawDest());
  433. // Handle 2nd operand for memcpy/memmove.
  434. if (auto *MTI = dyn_cast<MemTransferInst>(MI))
  435. PushPtrOperand(MTI->getRawSource());
  436. } else if (auto *II = dyn_cast<IntrinsicInst>(&I))
  437. collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
  438. else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
  439. // FIXME: Handle vectors of pointers
  440. if (Cmp->getOperand(0)->getType()->isPointerTy()) {
  441. PushPtrOperand(Cmp->getOperand(0));
  442. PushPtrOperand(Cmp->getOperand(1));
  443. }
  444. } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) {
  445. if (!ASC->getType()->isVectorTy())
  446. PushPtrOperand(ASC->getPointerOperand());
  447. } else if (auto *I2P = dyn_cast<IntToPtrInst>(&I)) {
  448. if (isNoopPtrIntCastPair(cast<Operator>(I2P), *DL, TTI))
  449. PushPtrOperand(
  450. cast<Operator>(I2P->getOperand(0))->getOperand(0));
  451. }
  452. }
  453. std::vector<WeakTrackingVH> Postorder; // The resultant postorder.
  454. while (!PostorderStack.empty()) {
  455. Value *TopVal = PostorderStack.back().getPointer();
  456. // If the operands of the expression on the top are already explored,
  457. // adds that expression to the resultant postorder.
  458. if (PostorderStack.back().getInt()) {
  459. if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace)
  460. Postorder.push_back(TopVal);
  461. PostorderStack.pop_back();
  462. continue;
  463. }
  464. // Otherwise, adds its operands to the stack and explores them.
  465. PostorderStack.back().setInt(true);
  466. // Skip values with an assumed address space.
  467. if (TTI->getAssumedAddrSpace(TopVal) == UninitializedAddressSpace) {
  468. for (Value *PtrOperand : getPointerOperands(*TopVal, *DL, TTI)) {
  469. appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
  470. Visited);
  471. }
  472. }
  473. }
  474. return Postorder;
  475. }
  476. // A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
  477. // of OperandUse.get() in the new address space. If the clone is not ready yet,
  478. // returns an undef in the new address space as a placeholder.
  479. static Value *operandWithNewAddressSpaceOrCreateUndef(
  480. const Use &OperandUse, unsigned NewAddrSpace,
  481. const ValueToValueMapTy &ValueWithNewAddrSpace,
  482. const PredicatedAddrSpaceMapTy &PredicatedAS,
  483. SmallVectorImpl<const Use *> *UndefUsesToFix) {
  484. Value *Operand = OperandUse.get();
  485. Type *NewPtrTy = PointerType::getWithSamePointeeType(
  486. cast<PointerType>(Operand->getType()), NewAddrSpace);
  487. if (Constant *C = dyn_cast<Constant>(Operand))
  488. return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
  489. if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
  490. return NewOperand;
  491. Instruction *Inst = cast<Instruction>(OperandUse.getUser());
  492. auto I = PredicatedAS.find(std::make_pair(Inst, Operand));
  493. if (I != PredicatedAS.end()) {
  494. // Insert an addrspacecast on that operand before the user.
  495. unsigned NewAS = I->second;
  496. Type *NewPtrTy = PointerType::getWithSamePointeeType(
  497. cast<PointerType>(Operand->getType()), NewAS);
  498. auto *NewI = new AddrSpaceCastInst(Operand, NewPtrTy);
  499. NewI->insertBefore(Inst);
  500. NewI->setDebugLoc(Inst->getDebugLoc());
  501. return NewI;
  502. }
  503. UndefUsesToFix->push_back(&OperandUse);
  504. return UndefValue::get(NewPtrTy);
  505. }
  506. // Returns a clone of `I` with its operands converted to those specified in
  507. // ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
  508. // operand whose address space needs to be modified might not exist in
  509. // ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and
  510. // adds that operand use to UndefUsesToFix so that caller can fix them later.
  511. //
  512. // Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
  513. // from a pointer whose type already matches. Therefore, this function returns a
  514. // Value* instead of an Instruction*.
  515. //
  516. // This may also return nullptr in the case the instruction could not be
  517. // rewritten.
  518. Value *InferAddressSpacesImpl::cloneInstructionWithNewAddressSpace(
  519. Instruction *I, unsigned NewAddrSpace,
  520. const ValueToValueMapTy &ValueWithNewAddrSpace,
  521. const PredicatedAddrSpaceMapTy &PredicatedAS,
  522. SmallVectorImpl<const Use *> *UndefUsesToFix) const {
  523. Type *NewPtrType = PointerType::getWithSamePointeeType(
  524. cast<PointerType>(I->getType()), NewAddrSpace);
  525. if (I->getOpcode() == Instruction::AddrSpaceCast) {
  526. Value *Src = I->getOperand(0);
  527. // Because `I` is flat, the source address space must be specific.
  528. // Therefore, the inferred address space must be the source space, according
  529. // to our algorithm.
  530. assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
  531. if (Src->getType() != NewPtrType)
  532. return new BitCastInst(Src, NewPtrType);
  533. return Src;
  534. }
  535. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  536. // Technically the intrinsic ID is a pointer typed argument, so specially
  537. // handle calls early.
  538. assert(II->getIntrinsicID() == Intrinsic::ptrmask);
  539. Value *NewPtr = operandWithNewAddressSpaceOrCreateUndef(
  540. II->getArgOperandUse(0), NewAddrSpace, ValueWithNewAddrSpace,
  541. PredicatedAS, UndefUsesToFix);
  542. Value *Rewrite =
  543. TTI->rewriteIntrinsicWithAddressSpace(II, II->getArgOperand(0), NewPtr);
  544. if (Rewrite) {
  545. assert(Rewrite != II && "cannot modify this pointer operation in place");
  546. return Rewrite;
  547. }
  548. return nullptr;
  549. }
  550. unsigned AS = TTI->getAssumedAddrSpace(I);
  551. if (AS != UninitializedAddressSpace) {
  552. // For the assumed address space, insert an `addrspacecast` to make that
  553. // explicit.
  554. Type *NewPtrTy = PointerType::getWithSamePointeeType(
  555. cast<PointerType>(I->getType()), AS);
  556. auto *NewI = new AddrSpaceCastInst(I, NewPtrTy);
  557. NewI->insertAfter(I);
  558. return NewI;
  559. }
  560. // Computes the converted pointer operands.
  561. SmallVector<Value *, 4> NewPointerOperands;
  562. for (const Use &OperandUse : I->operands()) {
  563. if (!OperandUse.get()->getType()->isPointerTy())
  564. NewPointerOperands.push_back(nullptr);
  565. else
  566. NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef(
  567. OperandUse, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS,
  568. UndefUsesToFix));
  569. }
  570. switch (I->getOpcode()) {
  571. case Instruction::BitCast:
  572. return new BitCastInst(NewPointerOperands[0], NewPtrType);
  573. case Instruction::PHI: {
  574. assert(I->getType()->isPointerTy());
  575. PHINode *PHI = cast<PHINode>(I);
  576. PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
  577. for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
  578. unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
  579. NewPHI->addIncoming(NewPointerOperands[OperandNo],
  580. PHI->getIncomingBlock(Index));
  581. }
  582. return NewPHI;
  583. }
  584. case Instruction::GetElementPtr: {
  585. GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
  586. GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
  587. GEP->getSourceElementType(), NewPointerOperands[0],
  588. SmallVector<Value *, 4>(GEP->indices()));
  589. NewGEP->setIsInBounds(GEP->isInBounds());
  590. return NewGEP;
  591. }
  592. case Instruction::Select:
  593. assert(I->getType()->isPointerTy());
  594. return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
  595. NewPointerOperands[2], "", nullptr, I);
  596. case Instruction::IntToPtr: {
  597. assert(isNoopPtrIntCastPair(cast<Operator>(I), *DL, TTI));
  598. Value *Src = cast<Operator>(I->getOperand(0))->getOperand(0);
  599. if (Src->getType() == NewPtrType)
  600. return Src;
  601. // If we had a no-op inttoptr/ptrtoint pair, we may still have inferred a
  602. // source address space from a generic pointer source need to insert a cast
  603. // back.
  604. return CastInst::CreatePointerBitCastOrAddrSpaceCast(Src, NewPtrType);
  605. }
  606. default:
  607. llvm_unreachable("Unexpected opcode");
  608. }
  609. }
  610. // Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
  611. // constant expression `CE` with its operands replaced as specified in
  612. // ValueWithNewAddrSpace.
  613. static Value *cloneConstantExprWithNewAddressSpace(
  614. ConstantExpr *CE, unsigned NewAddrSpace,
  615. const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL,
  616. const TargetTransformInfo *TTI) {
  617. Type *TargetType = CE->getType()->isPointerTy()
  618. ? PointerType::getWithSamePointeeType(
  619. cast<PointerType>(CE->getType()), NewAddrSpace)
  620. : CE->getType();
  621. if (CE->getOpcode() == Instruction::AddrSpaceCast) {
  622. // Because CE is flat, the source address space must be specific.
  623. // Therefore, the inferred address space must be the source space according
  624. // to our algorithm.
  625. assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
  626. NewAddrSpace);
  627. return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
  628. }
  629. if (CE->getOpcode() == Instruction::BitCast) {
  630. if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0)))
  631. return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType);
  632. return ConstantExpr::getAddrSpaceCast(CE, TargetType);
  633. }
  634. if (CE->getOpcode() == Instruction::Select) {
  635. Constant *Src0 = CE->getOperand(1);
  636. Constant *Src1 = CE->getOperand(2);
  637. if (Src0->getType()->getPointerAddressSpace() ==
  638. Src1->getType()->getPointerAddressSpace()) {
  639. return ConstantExpr::getSelect(
  640. CE->getOperand(0), ConstantExpr::getAddrSpaceCast(Src0, TargetType),
  641. ConstantExpr::getAddrSpaceCast(Src1, TargetType));
  642. }
  643. }
  644. if (CE->getOpcode() == Instruction::IntToPtr) {
  645. assert(isNoopPtrIntCastPair(cast<Operator>(CE), *DL, TTI));
  646. Constant *Src = cast<ConstantExpr>(CE->getOperand(0))->getOperand(0);
  647. assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
  648. return ConstantExpr::getBitCast(Src, TargetType);
  649. }
  650. // Computes the operands of the new constant expression.
  651. bool IsNew = false;
  652. SmallVector<Constant *, 4> NewOperands;
  653. for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
  654. Constant *Operand = CE->getOperand(Index);
  655. // If the address space of `Operand` needs to be modified, the new operand
  656. // with the new address space should already be in ValueWithNewAddrSpace
  657. // because (1) the constant expressions we consider (i.e. addrspacecast,
  658. // bitcast, and getelementptr) do not incur cycles in the data flow graph
  659. // and (2) this function is called on constant expressions in postorder.
  660. if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
  661. IsNew = true;
  662. NewOperands.push_back(cast<Constant>(NewOperand));
  663. continue;
  664. }
  665. if (auto *CExpr = dyn_cast<ConstantExpr>(Operand))
  666. if (Value *NewOperand = cloneConstantExprWithNewAddressSpace(
  667. CExpr, NewAddrSpace, ValueWithNewAddrSpace, DL, TTI)) {
  668. IsNew = true;
  669. NewOperands.push_back(cast<Constant>(NewOperand));
  670. continue;
  671. }
  672. // Otherwise, reuses the old operand.
  673. NewOperands.push_back(Operand);
  674. }
  675. // If !IsNew, we will replace the Value with itself. However, replaced values
  676. // are assumed to wrapped in an addrspacecast cast later so drop it now.
  677. if (!IsNew)
  678. return nullptr;
  679. if (CE->getOpcode() == Instruction::GetElementPtr) {
  680. // Needs to specify the source type while constructing a getelementptr
  681. // constant expression.
  682. return CE->getWithOperands(NewOperands, TargetType, /*OnlyIfReduced=*/false,
  683. cast<GEPOperator>(CE)->getSourceElementType());
  684. }
  685. return CE->getWithOperands(NewOperands, TargetType);
  686. }
  687. // Returns a clone of the value `V`, with its operands replaced as specified in
  688. // ValueWithNewAddrSpace. This function is called on every flat address
  689. // expression whose address space needs to be modified, in postorder.
  690. //
  691. // See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix.
  692. Value *InferAddressSpacesImpl::cloneValueWithNewAddressSpace(
  693. Value *V, unsigned NewAddrSpace,
  694. const ValueToValueMapTy &ValueWithNewAddrSpace,
  695. const PredicatedAddrSpaceMapTy &PredicatedAS,
  696. SmallVectorImpl<const Use *> *UndefUsesToFix) const {
  697. // All values in Postorder are flat address expressions.
  698. assert(V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
  699. isAddressExpression(*V, *DL, TTI));
  700. if (Instruction *I = dyn_cast<Instruction>(V)) {
  701. Value *NewV = cloneInstructionWithNewAddressSpace(
  702. I, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, UndefUsesToFix);
  703. if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) {
  704. if (NewI->getParent() == nullptr) {
  705. NewI->insertBefore(I);
  706. NewI->takeName(I);
  707. NewI->setDebugLoc(I->getDebugLoc());
  708. }
  709. }
  710. return NewV;
  711. }
  712. return cloneConstantExprWithNewAddressSpace(
  713. cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace, DL, TTI);
  714. }
  715. // Defines the join operation on the address space lattice (see the file header
  716. // comments).
  717. unsigned InferAddressSpacesImpl::joinAddressSpaces(unsigned AS1,
  718. unsigned AS2) const {
  719. if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
  720. return FlatAddrSpace;
  721. if (AS1 == UninitializedAddressSpace)
  722. return AS2;
  723. if (AS2 == UninitializedAddressSpace)
  724. return AS1;
  725. // The join of two different specific address spaces is flat.
  726. return (AS1 == AS2) ? AS1 : FlatAddrSpace;
  727. }
  728. bool InferAddressSpacesImpl::run(Function &F) {
  729. DL = &F.getParent()->getDataLayout();
  730. if (AssumeDefaultIsFlatAddressSpace)
  731. FlatAddrSpace = 0;
  732. if (FlatAddrSpace == UninitializedAddressSpace) {
  733. FlatAddrSpace = TTI->getFlatAddressSpace();
  734. if (FlatAddrSpace == UninitializedAddressSpace)
  735. return false;
  736. }
  737. // Collects all flat address expressions in postorder.
  738. std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F);
  739. // Runs a data-flow analysis to refine the address spaces of every expression
  740. // in Postorder.
  741. ValueToAddrSpaceMapTy InferredAddrSpace;
  742. PredicatedAddrSpaceMapTy PredicatedAS;
  743. inferAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS);
  744. // Changes the address spaces of the flat address expressions who are inferred
  745. // to point to a specific address space.
  746. return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS,
  747. &F);
  748. }
  749. // Constants need to be tracked through RAUW to handle cases with nested
  750. // constant expressions, so wrap values in WeakTrackingVH.
  751. void InferAddressSpacesImpl::inferAddressSpaces(
  752. ArrayRef<WeakTrackingVH> Postorder,
  753. ValueToAddrSpaceMapTy &InferredAddrSpace,
  754. PredicatedAddrSpaceMapTy &PredicatedAS) const {
  755. SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
  756. // Initially, all expressions are in the uninitialized address space.
  757. for (Value *V : Postorder)
  758. InferredAddrSpace[V] = UninitializedAddressSpace;
  759. while (!Worklist.empty()) {
  760. Value *V = Worklist.pop_back_val();
  761. // Try to update the address space of the stack top according to the
  762. // address spaces of its operands.
  763. if (!updateAddressSpace(*V, InferredAddrSpace, PredicatedAS))
  764. continue;
  765. for (Value *User : V->users()) {
  766. // Skip if User is already in the worklist.
  767. if (Worklist.count(User))
  768. continue;
  769. auto Pos = InferredAddrSpace.find(User);
  770. // Our algorithm only updates the address spaces of flat address
  771. // expressions, which are those in InferredAddrSpace.
  772. if (Pos == InferredAddrSpace.end())
  773. continue;
  774. // Function updateAddressSpace moves the address space down a lattice
  775. // path. Therefore, nothing to do if User is already inferred as flat (the
  776. // bottom element in the lattice).
  777. if (Pos->second == FlatAddrSpace)
  778. continue;
  779. Worklist.insert(User);
  780. }
  781. }
  782. }
  783. unsigned InferAddressSpacesImpl::getPredicatedAddrSpace(const Value &V,
  784. Value *Opnd) const {
  785. const Instruction *I = dyn_cast<Instruction>(&V);
  786. if (!I)
  787. return UninitializedAddressSpace;
  788. Opnd = Opnd->stripInBoundsOffsets();
  789. for (auto &AssumeVH : AC.assumptionsFor(Opnd)) {
  790. if (!AssumeVH)
  791. continue;
  792. CallInst *CI = cast<CallInst>(AssumeVH);
  793. if (!isValidAssumeForContext(CI, I, DT))
  794. continue;
  795. const Value *Ptr;
  796. unsigned AS;
  797. std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(CI->getArgOperand(0));
  798. if (Ptr)
  799. return AS;
  800. }
  801. return UninitializedAddressSpace;
  802. }
  803. bool InferAddressSpacesImpl::updateAddressSpace(
  804. const Value &V, ValueToAddrSpaceMapTy &InferredAddrSpace,
  805. PredicatedAddrSpaceMapTy &PredicatedAS) const {
  806. assert(InferredAddrSpace.count(&V));
  807. LLVM_DEBUG(dbgs() << "Updating the address space of\n " << V << '\n');
  808. // The new inferred address space equals the join of the address spaces
  809. // of all its pointer operands.
  810. unsigned NewAS = UninitializedAddressSpace;
  811. const Operator &Op = cast<Operator>(V);
  812. if (Op.getOpcode() == Instruction::Select) {
  813. Value *Src0 = Op.getOperand(1);
  814. Value *Src1 = Op.getOperand(2);
  815. auto I = InferredAddrSpace.find(Src0);
  816. unsigned Src0AS = (I != InferredAddrSpace.end()) ?
  817. I->second : Src0->getType()->getPointerAddressSpace();
  818. auto J = InferredAddrSpace.find(Src1);
  819. unsigned Src1AS = (J != InferredAddrSpace.end()) ?
  820. J->second : Src1->getType()->getPointerAddressSpace();
  821. auto *C0 = dyn_cast<Constant>(Src0);
  822. auto *C1 = dyn_cast<Constant>(Src1);
  823. // If one of the inputs is a constant, we may be able to do a constant
  824. // addrspacecast of it. Defer inferring the address space until the input
  825. // address space is known.
  826. if ((C1 && Src0AS == UninitializedAddressSpace) ||
  827. (C0 && Src1AS == UninitializedAddressSpace))
  828. return false;
  829. if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
  830. NewAS = Src1AS;
  831. else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
  832. NewAS = Src0AS;
  833. else
  834. NewAS = joinAddressSpaces(Src0AS, Src1AS);
  835. } else {
  836. unsigned AS = TTI->getAssumedAddrSpace(&V);
  837. if (AS != UninitializedAddressSpace) {
  838. // Use the assumed address space directly.
  839. NewAS = AS;
  840. } else {
  841. // Otherwise, infer the address space from its pointer operands.
  842. for (Value *PtrOperand : getPointerOperands(V, *DL, TTI)) {
  843. auto I = InferredAddrSpace.find(PtrOperand);
  844. unsigned OperandAS;
  845. if (I == InferredAddrSpace.end()) {
  846. OperandAS = PtrOperand->getType()->getPointerAddressSpace();
  847. if (OperandAS == FlatAddrSpace) {
  848. // Check AC for assumption dominating V.
  849. unsigned AS = getPredicatedAddrSpace(V, PtrOperand);
  850. if (AS != UninitializedAddressSpace) {
  851. LLVM_DEBUG(dbgs()
  852. << " deduce operand AS from the predicate addrspace "
  853. << AS << '\n');
  854. OperandAS = AS;
  855. // Record this use with the predicated AS.
  856. PredicatedAS[std::make_pair(&V, PtrOperand)] = OperandAS;
  857. }
  858. }
  859. } else
  860. OperandAS = I->second;
  861. // join(flat, *) = flat. So we can break if NewAS is already flat.
  862. NewAS = joinAddressSpaces(NewAS, OperandAS);
  863. if (NewAS == FlatAddrSpace)
  864. break;
  865. }
  866. }
  867. }
  868. unsigned OldAS = InferredAddrSpace.lookup(&V);
  869. assert(OldAS != FlatAddrSpace);
  870. if (OldAS == NewAS)
  871. return false;
  872. // If any updates are made, grabs its users to the worklist because
  873. // their address spaces can also be possibly updated.
  874. LLVM_DEBUG(dbgs() << " to " << NewAS << '\n');
  875. InferredAddrSpace[&V] = NewAS;
  876. return true;
  877. }
  878. /// \p returns true if \p U is the pointer operand of a memory instruction with
  879. /// a single pointer operand that can have its address space changed by simply
  880. /// mutating the use to a new value. If the memory instruction is volatile,
  881. /// return true only if the target allows the memory instruction to be volatile
  882. /// in the new address space.
  883. static bool isSimplePointerUseValidToReplace(const TargetTransformInfo &TTI,
  884. Use &U, unsigned AddrSpace) {
  885. User *Inst = U.getUser();
  886. unsigned OpNo = U.getOperandNo();
  887. bool VolatileIsAllowed = false;
  888. if (auto *I = dyn_cast<Instruction>(Inst))
  889. VolatileIsAllowed = TTI.hasVolatileVariant(I, AddrSpace);
  890. if (auto *LI = dyn_cast<LoadInst>(Inst))
  891. return OpNo == LoadInst::getPointerOperandIndex() &&
  892. (VolatileIsAllowed || !LI->isVolatile());
  893. if (auto *SI = dyn_cast<StoreInst>(Inst))
  894. return OpNo == StoreInst::getPointerOperandIndex() &&
  895. (VolatileIsAllowed || !SI->isVolatile());
  896. if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
  897. return OpNo == AtomicRMWInst::getPointerOperandIndex() &&
  898. (VolatileIsAllowed || !RMW->isVolatile());
  899. if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst))
  900. return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() &&
  901. (VolatileIsAllowed || !CmpX->isVolatile());
  902. return false;
  903. }
  904. /// Update memory intrinsic uses that require more complex processing than
  905. /// simple memory instructions. These require re-mangling and may have multiple
  906. /// pointer operands.
  907. static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV,
  908. Value *NewV) {
  909. IRBuilder<> B(MI);
  910. MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa);
  911. MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope);
  912. MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias);
  913. if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
  914. B.CreateMemSet(NewV, MSI->getValue(), MSI->getLength(), MSI->getDestAlign(),
  915. false, // isVolatile
  916. TBAA, ScopeMD, NoAliasMD);
  917. } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
  918. Value *Src = MTI->getRawSource();
  919. Value *Dest = MTI->getRawDest();
  920. // Be careful in case this is a self-to-self copy.
  921. if (Src == OldV)
  922. Src = NewV;
  923. if (Dest == OldV)
  924. Dest = NewV;
  925. if (isa<MemCpyInlineInst>(MTI)) {
  926. MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
  927. B.CreateMemCpyInline(Dest, MTI->getDestAlign(), Src,
  928. MTI->getSourceAlign(), MTI->getLength(),
  929. false, // isVolatile
  930. TBAA, TBAAStruct, ScopeMD, NoAliasMD);
  931. } else if (isa<MemCpyInst>(MTI)) {
  932. MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
  933. B.CreateMemCpy(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
  934. MTI->getLength(),
  935. false, // isVolatile
  936. TBAA, TBAAStruct, ScopeMD, NoAliasMD);
  937. } else {
  938. assert(isa<MemMoveInst>(MTI));
  939. B.CreateMemMove(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
  940. MTI->getLength(),
  941. false, // isVolatile
  942. TBAA, ScopeMD, NoAliasMD);
  943. }
  944. } else
  945. llvm_unreachable("unhandled MemIntrinsic");
  946. MI->eraseFromParent();
  947. return true;
  948. }
  949. // \p returns true if it is OK to change the address space of constant \p C with
  950. // a ConstantExpr addrspacecast.
  951. bool InferAddressSpacesImpl::isSafeToCastConstAddrSpace(Constant *C,
  952. unsigned NewAS) const {
  953. assert(NewAS != UninitializedAddressSpace);
  954. unsigned SrcAS = C->getType()->getPointerAddressSpace();
  955. if (SrcAS == NewAS || isa<UndefValue>(C))
  956. return true;
  957. // Prevent illegal casts between different non-flat address spaces.
  958. if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
  959. return false;
  960. if (isa<ConstantPointerNull>(C))
  961. return true;
  962. if (auto *Op = dyn_cast<Operator>(C)) {
  963. // If we already have a constant addrspacecast, it should be safe to cast it
  964. // off.
  965. if (Op->getOpcode() == Instruction::AddrSpaceCast)
  966. return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS);
  967. if (Op->getOpcode() == Instruction::IntToPtr &&
  968. Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
  969. return true;
  970. }
  971. return false;
  972. }
  973. static Value::use_iterator skipToNextUser(Value::use_iterator I,
  974. Value::use_iterator End) {
  975. User *CurUser = I->getUser();
  976. ++I;
  977. while (I != End && I->getUser() == CurUser)
  978. ++I;
  979. return I;
  980. }
  981. bool InferAddressSpacesImpl::rewriteWithNewAddressSpaces(
  982. ArrayRef<WeakTrackingVH> Postorder,
  983. const ValueToAddrSpaceMapTy &InferredAddrSpace,
  984. const PredicatedAddrSpaceMapTy &PredicatedAS, Function *F) const {
  985. // For each address expression to be modified, creates a clone of it with its
  986. // pointer operands converted to the new address space. Since the pointer
  987. // operands are converted, the clone is naturally in the new address space by
  988. // construction.
  989. ValueToValueMapTy ValueWithNewAddrSpace;
  990. SmallVector<const Use *, 32> UndefUsesToFix;
  991. for (Value* V : Postorder) {
  992. unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
  993. // In some degenerate cases (e.g. invalid IR in unreachable code), we may
  994. // not even infer the value to have its original address space.
  995. if (NewAddrSpace == UninitializedAddressSpace)
  996. continue;
  997. if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
  998. Value *New =
  999. cloneValueWithNewAddressSpace(V, NewAddrSpace, ValueWithNewAddrSpace,
  1000. PredicatedAS, &UndefUsesToFix);
  1001. if (New)
  1002. ValueWithNewAddrSpace[V] = New;
  1003. }
  1004. }
  1005. if (ValueWithNewAddrSpace.empty())
  1006. return false;
  1007. // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace.
  1008. for (const Use *UndefUse : UndefUsesToFix) {
  1009. User *V = UndefUse->getUser();
  1010. User *NewV = cast_or_null<User>(ValueWithNewAddrSpace.lookup(V));
  1011. if (!NewV)
  1012. continue;
  1013. unsigned OperandNo = UndefUse->getOperandNo();
  1014. assert(isa<UndefValue>(NewV->getOperand(OperandNo)));
  1015. NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get()));
  1016. }
  1017. SmallVector<Instruction *, 16> DeadInstructions;
  1018. // Replaces the uses of the old address expressions with the new ones.
  1019. for (const WeakTrackingVH &WVH : Postorder) {
  1020. assert(WVH && "value was unexpectedly deleted");
  1021. Value *V = WVH;
  1022. Value *NewV = ValueWithNewAddrSpace.lookup(V);
  1023. if (NewV == nullptr)
  1024. continue;
  1025. LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n with\n "
  1026. << *NewV << '\n');
  1027. if (Constant *C = dyn_cast<Constant>(V)) {
  1028. Constant *Replace = ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
  1029. C->getType());
  1030. if (C != Replace) {
  1031. LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace
  1032. << ": " << *Replace << '\n');
  1033. C->replaceAllUsesWith(Replace);
  1034. V = Replace;
  1035. }
  1036. }
  1037. Value::use_iterator I, E, Next;
  1038. for (I = V->use_begin(), E = V->use_end(); I != E; ) {
  1039. Use &U = *I;
  1040. // Some users may see the same pointer operand in multiple operands. Skip
  1041. // to the next instruction.
  1042. I = skipToNextUser(I, E);
  1043. if (isSimplePointerUseValidToReplace(
  1044. *TTI, U, V->getType()->getPointerAddressSpace())) {
  1045. // If V is used as the pointer operand of a compatible memory operation,
  1046. // sets the pointer operand to NewV. This replacement does not change
  1047. // the element type, so the resultant load/store is still valid.
  1048. U.set(NewV);
  1049. continue;
  1050. }
  1051. User *CurUser = U.getUser();
  1052. // Skip if the current user is the new value itself.
  1053. if (CurUser == NewV)
  1054. continue;
  1055. // Handle more complex cases like intrinsic that need to be remangled.
  1056. if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
  1057. if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
  1058. continue;
  1059. }
  1060. if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
  1061. if (rewriteIntrinsicOperands(II, V, NewV))
  1062. continue;
  1063. }
  1064. if (isa<Instruction>(CurUser)) {
  1065. if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
  1066. // If we can infer that both pointers are in the same addrspace,
  1067. // transform e.g.
  1068. // %cmp = icmp eq float* %p, %q
  1069. // into
  1070. // %cmp = icmp eq float addrspace(3)* %new_p, %new_q
  1071. unsigned NewAS = NewV->getType()->getPointerAddressSpace();
  1072. int SrcIdx = U.getOperandNo();
  1073. int OtherIdx = (SrcIdx == 0) ? 1 : 0;
  1074. Value *OtherSrc = Cmp->getOperand(OtherIdx);
  1075. if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
  1076. if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
  1077. Cmp->setOperand(OtherIdx, OtherNewV);
  1078. Cmp->setOperand(SrcIdx, NewV);
  1079. continue;
  1080. }
  1081. }
  1082. // Even if the type mismatches, we can cast the constant.
  1083. if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
  1084. if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
  1085. Cmp->setOperand(SrcIdx, NewV);
  1086. Cmp->setOperand(OtherIdx,
  1087. ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType()));
  1088. continue;
  1089. }
  1090. }
  1091. }
  1092. if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) {
  1093. unsigned NewAS = NewV->getType()->getPointerAddressSpace();
  1094. if (ASC->getDestAddressSpace() == NewAS) {
  1095. if (!cast<PointerType>(ASC->getType())
  1096. ->hasSameElementTypeAs(
  1097. cast<PointerType>(NewV->getType()))) {
  1098. BasicBlock::iterator InsertPos;
  1099. if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
  1100. InsertPos = std::next(NewVInst->getIterator());
  1101. else if (Instruction *VInst = dyn_cast<Instruction>(V))
  1102. InsertPos = std::next(VInst->getIterator());
  1103. else
  1104. InsertPos = ASC->getIterator();
  1105. NewV = CastInst::Create(Instruction::BitCast, NewV,
  1106. ASC->getType(), "", &*InsertPos);
  1107. }
  1108. ASC->replaceAllUsesWith(NewV);
  1109. DeadInstructions.push_back(ASC);
  1110. continue;
  1111. }
  1112. }
  1113. // Otherwise, replaces the use with flat(NewV).
  1114. if (Instruction *VInst = dyn_cast<Instruction>(V)) {
  1115. // Don't create a copy of the original addrspacecast.
  1116. if (U == V && isa<AddrSpaceCastInst>(V))
  1117. continue;
  1118. // Insert the addrspacecast after NewV.
  1119. BasicBlock::iterator InsertPos;
  1120. if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
  1121. InsertPos = std::next(NewVInst->getIterator());
  1122. else
  1123. InsertPos = std::next(VInst->getIterator());
  1124. while (isa<PHINode>(InsertPos))
  1125. ++InsertPos;
  1126. U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
  1127. } else {
  1128. U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
  1129. V->getType()));
  1130. }
  1131. }
  1132. }
  1133. if (V->use_empty()) {
  1134. if (Instruction *I = dyn_cast<Instruction>(V))
  1135. DeadInstructions.push_back(I);
  1136. }
  1137. }
  1138. for (Instruction *I : DeadInstructions)
  1139. RecursivelyDeleteTriviallyDeadInstructions(I);
  1140. return true;
  1141. }
  1142. bool InferAddressSpaces::runOnFunction(Function &F) {
  1143. if (skipFunction(F))
  1144. return false;
  1145. auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  1146. DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
  1147. return InferAddressSpacesImpl(
  1148. getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), DT,
  1149. &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
  1150. FlatAddrSpace)
  1151. .run(F);
  1152. }
  1153. FunctionPass *llvm::createInferAddressSpacesPass(unsigned AddressSpace) {
  1154. return new InferAddressSpaces(AddressSpace);
  1155. }
  1156. InferAddressSpacesPass::InferAddressSpacesPass()
  1157. : FlatAddrSpace(UninitializedAddressSpace) {}
  1158. InferAddressSpacesPass::InferAddressSpacesPass(unsigned AddressSpace)
  1159. : FlatAddrSpace(AddressSpace) {}
  1160. PreservedAnalyses InferAddressSpacesPass::run(Function &F,
  1161. FunctionAnalysisManager &AM) {
  1162. bool Changed =
  1163. InferAddressSpacesImpl(AM.getResult<AssumptionAnalysis>(F),
  1164. AM.getCachedResult<DominatorTreeAnalysis>(F),
  1165. &AM.getResult<TargetIRAnalysis>(F), FlatAddrSpace)
  1166. .run(F);
  1167. if (Changed) {
  1168. PreservedAnalyses PA;
  1169. PA.preserveSet<CFGAnalyses>();
  1170. PA.preserve<DominatorTreeAnalysis>();
  1171. return PA;
  1172. }
  1173. return PreservedAnalyses::all();
  1174. }