AArch64PromoteConstant.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. //==- AArch64PromoteConstant.cpp - Promote constant to global for AArch64 --==//
  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. // This file implements the AArch64PromoteConstant pass which promotes constants
  10. // to global variables when this is likely to be more efficient. Currently only
  11. // types related to constant vector (i.e., constant vector, array of constant
  12. // vectors, constant structure with a constant vector field, etc.) are promoted
  13. // to global variables. Constant vectors are likely to be lowered in target
  14. // constant pool during instruction selection already; therefore, the access
  15. // will remain the same (memory load), but the structure types are not split
  16. // into different constant pool accesses for each field. A bonus side effect is
  17. // that created globals may be merged by the global merge pass.
  18. //
  19. // FIXME: This pass may be useful for other targets too.
  20. //===----------------------------------------------------------------------===//
  21. #include "AArch64.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/Statistic.h"
  25. #include "llvm/IR/BasicBlock.h"
  26. #include "llvm/IR/Constant.h"
  27. #include "llvm/IR/Constants.h"
  28. #include "llvm/IR/Dominators.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/GlobalValue.h"
  31. #include "llvm/IR/GlobalVariable.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/IR/InlineAsm.h"
  34. #include "llvm/IR/InstIterator.h"
  35. #include "llvm/IR/Instruction.h"
  36. #include "llvm/IR/Instructions.h"
  37. #include "llvm/IR/IntrinsicInst.h"
  38. #include "llvm/IR/Module.h"
  39. #include "llvm/IR/Type.h"
  40. #include "llvm/InitializePasses.h"
  41. #include "llvm/Pass.h"
  42. #include "llvm/Support/Casting.h"
  43. #include "llvm/Support/CommandLine.h"
  44. #include "llvm/Support/Debug.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include <algorithm>
  47. #include <cassert>
  48. #include <utility>
  49. using namespace llvm;
  50. #define DEBUG_TYPE "aarch64-promote-const"
  51. // Stress testing mode - disable heuristics.
  52. static cl::opt<bool> Stress("aarch64-stress-promote-const", cl::Hidden,
  53. cl::desc("Promote all vector constants"));
  54. STATISTIC(NumPromoted, "Number of promoted constants");
  55. STATISTIC(NumPromotedUses, "Number of promoted constants uses");
  56. //===----------------------------------------------------------------------===//
  57. // AArch64PromoteConstant
  58. //===----------------------------------------------------------------------===//
  59. namespace {
  60. /// Promotes interesting constant into global variables.
  61. /// The motivating example is:
  62. /// static const uint16_t TableA[32] = {
  63. /// 41944, 40330, 38837, 37450, 36158, 34953, 33826, 32768,
  64. /// 31776, 30841, 29960, 29128, 28340, 27595, 26887, 26215,
  65. /// 25576, 24967, 24386, 23832, 23302, 22796, 22311, 21846,
  66. /// 21400, 20972, 20561, 20165, 19785, 19419, 19066, 18725,
  67. /// };
  68. ///
  69. /// uint8x16x4_t LoadStatic(void) {
  70. /// uint8x16x4_t ret;
  71. /// ret.val[0] = vld1q_u16(TableA + 0);
  72. /// ret.val[1] = vld1q_u16(TableA + 8);
  73. /// ret.val[2] = vld1q_u16(TableA + 16);
  74. /// ret.val[3] = vld1q_u16(TableA + 24);
  75. /// return ret;
  76. /// }
  77. ///
  78. /// The constants in this example are folded into the uses. Thus, 4 different
  79. /// constants are created.
  80. ///
  81. /// As their type is vector the cheapest way to create them is to load them
  82. /// for the memory.
  83. ///
  84. /// Therefore the final assembly final has 4 different loads. With this pass
  85. /// enabled, only one load is issued for the constants.
  86. class AArch64PromoteConstant : public ModulePass {
  87. public:
  88. struct PromotedConstant {
  89. bool ShouldConvert = false;
  90. GlobalVariable *GV = nullptr;
  91. };
  92. using PromotionCacheTy = SmallDenseMap<Constant *, PromotedConstant, 16>;
  93. struct UpdateRecord {
  94. Constant *C;
  95. Instruction *User;
  96. unsigned Op;
  97. UpdateRecord(Constant *C, Instruction *User, unsigned Op)
  98. : C(C), User(User), Op(Op) {}
  99. };
  100. static char ID;
  101. AArch64PromoteConstant() : ModulePass(ID) {
  102. initializeAArch64PromoteConstantPass(*PassRegistry::getPassRegistry());
  103. }
  104. StringRef getPassName() const override { return "AArch64 Promote Constant"; }
  105. /// Iterate over the functions and promote the interesting constants into
  106. /// global variables with module scope.
  107. bool runOnModule(Module &M) override {
  108. LLVM_DEBUG(dbgs() << getPassName() << '\n');
  109. if (skipModule(M))
  110. return false;
  111. bool Changed = false;
  112. PromotionCacheTy PromotionCache;
  113. for (auto &MF : M) {
  114. Changed |= runOnFunction(MF, PromotionCache);
  115. }
  116. return Changed;
  117. }
  118. private:
  119. /// Look for interesting constants used within the given function.
  120. /// Promote them into global variables, load these global variables within
  121. /// the related function, so that the number of inserted load is minimal.
  122. bool runOnFunction(Function &F, PromotionCacheTy &PromotionCache);
  123. // This transformation requires dominator info
  124. void getAnalysisUsage(AnalysisUsage &AU) const override {
  125. AU.setPreservesCFG();
  126. AU.addRequired<DominatorTreeWrapperPass>();
  127. AU.addPreserved<DominatorTreeWrapperPass>();
  128. }
  129. /// Type to store a list of Uses.
  130. using Uses = SmallVector<std::pair<Instruction *, unsigned>, 4>;
  131. /// Map an insertion point to all the uses it dominates.
  132. using InsertionPoints = DenseMap<Instruction *, Uses>;
  133. /// Find the closest point that dominates the given Use.
  134. Instruction *findInsertionPoint(Instruction &User, unsigned OpNo);
  135. /// Check if the given insertion point is dominated by an existing
  136. /// insertion point.
  137. /// If true, the given use is added to the list of dominated uses for
  138. /// the related existing point.
  139. /// \param NewPt the insertion point to be checked
  140. /// \param User the user of the constant
  141. /// \param OpNo the operand number of the use
  142. /// \param InsertPts existing insertion points
  143. /// \pre NewPt and all instruction in InsertPts belong to the same function
  144. /// \return true if one of the insertion point in InsertPts dominates NewPt,
  145. /// false otherwise
  146. bool isDominated(Instruction *NewPt, Instruction *User, unsigned OpNo,
  147. InsertionPoints &InsertPts);
  148. /// Check if the given insertion point can be merged with an existing
  149. /// insertion point in a common dominator.
  150. /// If true, the given use is added to the list of the created insertion
  151. /// point.
  152. /// \param NewPt the insertion point to be checked
  153. /// \param User the user of the constant
  154. /// \param OpNo the operand number of the use
  155. /// \param InsertPts existing insertion points
  156. /// \pre NewPt and all instruction in InsertPts belong to the same function
  157. /// \pre isDominated returns false for the exact same parameters.
  158. /// \return true if it exists an insertion point in InsertPts that could
  159. /// have been merged with NewPt in a common dominator,
  160. /// false otherwise
  161. bool tryAndMerge(Instruction *NewPt, Instruction *User, unsigned OpNo,
  162. InsertionPoints &InsertPts);
  163. /// Compute the minimal insertion points to dominates all the interesting
  164. /// uses of value.
  165. /// Insertion points are group per function and each insertion point
  166. /// contains a list of all the uses it dominates within the related function
  167. /// \param User the user of the constant
  168. /// \param OpNo the operand number of the constant
  169. /// \param[out] InsertPts output storage of the analysis
  170. void computeInsertionPoint(Instruction *User, unsigned OpNo,
  171. InsertionPoints &InsertPts);
  172. /// Insert a definition of a new global variable at each point contained in
  173. /// InsPtsPerFunc and update the related uses (also contained in
  174. /// InsPtsPerFunc).
  175. void insertDefinitions(Function &F, GlobalVariable &GV,
  176. InsertionPoints &InsertPts);
  177. /// Do the constant promotion indicated by the Updates records, keeping track
  178. /// of globals in PromotionCache.
  179. void promoteConstants(Function &F, SmallVectorImpl<UpdateRecord> &Updates,
  180. PromotionCacheTy &PromotionCache);
  181. /// Transfer the list of dominated uses of IPI to NewPt in InsertPts.
  182. /// Append Use to this list and delete the entry of IPI in InsertPts.
  183. static void appendAndTransferDominatedUses(Instruction *NewPt,
  184. Instruction *User, unsigned OpNo,
  185. InsertionPoints::iterator &IPI,
  186. InsertionPoints &InsertPts) {
  187. // Record the dominated use.
  188. IPI->second.emplace_back(User, OpNo);
  189. // Transfer the dominated uses of IPI to NewPt
  190. // Inserting into the DenseMap may invalidate existing iterator.
  191. // Keep a copy of the key to find the iterator to erase. Keep a copy of the
  192. // value so that we don't have to dereference IPI->second.
  193. Instruction *OldInstr = IPI->first;
  194. Uses OldUses = std::move(IPI->second);
  195. InsertPts[NewPt] = std::move(OldUses);
  196. // Erase IPI.
  197. InsertPts.erase(OldInstr);
  198. }
  199. };
  200. } // end anonymous namespace
  201. char AArch64PromoteConstant::ID = 0;
  202. INITIALIZE_PASS_BEGIN(AArch64PromoteConstant, "aarch64-promote-const",
  203. "AArch64 Promote Constant Pass", false, false)
  204. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  205. INITIALIZE_PASS_END(AArch64PromoteConstant, "aarch64-promote-const",
  206. "AArch64 Promote Constant Pass", false, false)
  207. ModulePass *llvm::createAArch64PromoteConstantPass() {
  208. return new AArch64PromoteConstant();
  209. }
  210. /// Check if the given type uses a vector type.
  211. static bool isConstantUsingVectorTy(const Type *CstTy) {
  212. if (CstTy->isVectorTy())
  213. return true;
  214. if (CstTy->isStructTy()) {
  215. for (unsigned EltIdx = 0, EndEltIdx = CstTy->getStructNumElements();
  216. EltIdx < EndEltIdx; ++EltIdx)
  217. if (isConstantUsingVectorTy(CstTy->getStructElementType(EltIdx)))
  218. return true;
  219. } else if (CstTy->isArrayTy())
  220. return isConstantUsingVectorTy(CstTy->getArrayElementType());
  221. return false;
  222. }
  223. // Returns true if \p C contains only ConstantData leafs and no global values,
  224. // block addresses or constant expressions. Traverses ConstantAggregates.
  225. static bool containsOnlyConstantData(const Constant *C) {
  226. if (isa<ConstantData>(C))
  227. return true;
  228. if (isa<GlobalValue>(C) || isa<BlockAddress>(C) || isa<ConstantExpr>(C))
  229. return false;
  230. return all_of(C->operands(), [](const Use &U) {
  231. return containsOnlyConstantData(cast<Constant>(&U));
  232. });
  233. }
  234. /// Check if the given use (Instruction + OpIdx) of Cst should be converted into
  235. /// a load of a global variable initialized with Cst.
  236. /// A use should be converted if it is legal to do so.
  237. /// For instance, it is not legal to turn the mask operand of a shuffle vector
  238. /// into a load of a global variable.
  239. static bool shouldConvertUse(const Constant *Cst, const Instruction *Instr,
  240. unsigned OpIdx) {
  241. // shufflevector instruction expects a const for the mask argument, i.e., the
  242. // third argument. Do not promote this use in that case.
  243. if (isa<const ShuffleVectorInst>(Instr) && OpIdx == 2)
  244. return false;
  245. // extractvalue instruction expects a const idx.
  246. if (isa<const ExtractValueInst>(Instr) && OpIdx > 0)
  247. return false;
  248. // extractvalue instruction expects a const idx.
  249. if (isa<const InsertValueInst>(Instr) && OpIdx > 1)
  250. return false;
  251. if (isa<const AllocaInst>(Instr) && OpIdx > 0)
  252. return false;
  253. // Alignment argument must be constant.
  254. if (isa<const LoadInst>(Instr) && OpIdx > 0)
  255. return false;
  256. // Alignment argument must be constant.
  257. if (isa<const StoreInst>(Instr) && OpIdx > 1)
  258. return false;
  259. // Index must be constant.
  260. if (isa<const GetElementPtrInst>(Instr) && OpIdx > 0)
  261. return false;
  262. // Personality function and filters must be constant.
  263. // Give up on that instruction.
  264. if (isa<const LandingPadInst>(Instr))
  265. return false;
  266. // Switch instruction expects constants to compare to.
  267. if (isa<const SwitchInst>(Instr))
  268. return false;
  269. // Expected address must be a constant.
  270. if (isa<const IndirectBrInst>(Instr))
  271. return false;
  272. // Do not mess with intrinsics.
  273. if (isa<const IntrinsicInst>(Instr))
  274. return false;
  275. // Do not mess with inline asm.
  276. const CallInst *CI = dyn_cast<const CallInst>(Instr);
  277. return !(CI && CI->isInlineAsm());
  278. }
  279. /// Check if the given Cst should be converted into
  280. /// a load of a global variable initialized with Cst.
  281. /// A constant should be converted if it is likely that the materialization of
  282. /// the constant will be tricky. Thus, we give up on zero or undef values.
  283. ///
  284. /// \todo Currently, accept only vector related types.
  285. /// Also we give up on all simple vector type to keep the existing
  286. /// behavior. Otherwise, we should push here all the check of the lowering of
  287. /// BUILD_VECTOR. By giving up, we lose the potential benefit of merging
  288. /// constant via global merge and the fact that the same constant is stored
  289. /// only once with this method (versus, as many function that uses the constant
  290. /// for the regular approach, even for float).
  291. /// Again, the simplest solution would be to promote every
  292. /// constant and rematerialize them when they are actually cheap to create.
  293. static bool shouldConvertImpl(const Constant *Cst) {
  294. if (isa<const UndefValue>(Cst))
  295. return false;
  296. // FIXME: In some cases, it may be interesting to promote in memory
  297. // a zero initialized constant.
  298. // E.g., when the type of Cst require more instructions than the
  299. // adrp/add/load sequence or when this sequence can be shared by several
  300. // instances of Cst.
  301. // Ideally, we could promote this into a global and rematerialize the constant
  302. // when it was a bad idea.
  303. if (Cst->isZeroValue())
  304. return false;
  305. if (Stress)
  306. return true;
  307. // FIXME: see function \todo
  308. if (Cst->getType()->isVectorTy())
  309. return false;
  310. return isConstantUsingVectorTy(Cst->getType());
  311. }
  312. static bool
  313. shouldConvert(Constant &C,
  314. AArch64PromoteConstant::PromotionCacheTy &PromotionCache) {
  315. auto Converted = PromotionCache.insert(
  316. std::make_pair(&C, AArch64PromoteConstant::PromotedConstant()));
  317. if (Converted.second)
  318. Converted.first->second.ShouldConvert = shouldConvertImpl(&C);
  319. return Converted.first->second.ShouldConvert;
  320. }
  321. Instruction *AArch64PromoteConstant::findInsertionPoint(Instruction &User,
  322. unsigned OpNo) {
  323. // If this user is a phi, the insertion point is in the related
  324. // incoming basic block.
  325. if (PHINode *PhiInst = dyn_cast<PHINode>(&User))
  326. return PhiInst->getIncomingBlock(OpNo)->getTerminator();
  327. return &User;
  328. }
  329. bool AArch64PromoteConstant::isDominated(Instruction *NewPt, Instruction *User,
  330. unsigned OpNo,
  331. InsertionPoints &InsertPts) {
  332. DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
  333. *NewPt->getParent()->getParent()).getDomTree();
  334. // Traverse all the existing insertion points and check if one is dominating
  335. // NewPt. If it is, remember that.
  336. for (auto &IPI : InsertPts) {
  337. if (NewPt == IPI.first || DT.dominates(IPI.first, NewPt) ||
  338. // When IPI.first is a terminator instruction, DT may think that
  339. // the result is defined on the edge.
  340. // Here we are testing the insertion point, not the definition.
  341. (IPI.first->getParent() != NewPt->getParent() &&
  342. DT.dominates(IPI.first->getParent(), NewPt->getParent()))) {
  343. // No need to insert this point. Just record the dominated use.
  344. LLVM_DEBUG(dbgs() << "Insertion point dominated by:\n");
  345. LLVM_DEBUG(IPI.first->print(dbgs()));
  346. LLVM_DEBUG(dbgs() << '\n');
  347. IPI.second.emplace_back(User, OpNo);
  348. return true;
  349. }
  350. }
  351. return false;
  352. }
  353. bool AArch64PromoteConstant::tryAndMerge(Instruction *NewPt, Instruction *User,
  354. unsigned OpNo,
  355. InsertionPoints &InsertPts) {
  356. DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
  357. *NewPt->getParent()->getParent()).getDomTree();
  358. BasicBlock *NewBB = NewPt->getParent();
  359. // Traverse all the existing insertion point and check if one is dominated by
  360. // NewPt and thus useless or can be combined with NewPt into a common
  361. // dominator.
  362. for (InsertionPoints::iterator IPI = InsertPts.begin(),
  363. EndIPI = InsertPts.end();
  364. IPI != EndIPI; ++IPI) {
  365. BasicBlock *CurBB = IPI->first->getParent();
  366. if (NewBB == CurBB) {
  367. // Instructions are in the same block.
  368. // By construction, NewPt is dominating the other.
  369. // Indeed, isDominated returned false with the exact same arguments.
  370. LLVM_DEBUG(dbgs() << "Merge insertion point with:\n");
  371. LLVM_DEBUG(IPI->first->print(dbgs()));
  372. LLVM_DEBUG(dbgs() << "\nat considered insertion point.\n");
  373. appendAndTransferDominatedUses(NewPt, User, OpNo, IPI, InsertPts);
  374. return true;
  375. }
  376. // Look for a common dominator
  377. BasicBlock *CommonDominator = DT.findNearestCommonDominator(NewBB, CurBB);
  378. // If none exists, we cannot merge these two points.
  379. if (!CommonDominator)
  380. continue;
  381. if (CommonDominator != NewBB) {
  382. // By construction, the CommonDominator cannot be CurBB.
  383. assert(CommonDominator != CurBB &&
  384. "Instruction has not been rejected during isDominated check!");
  385. // Take the last instruction of the CommonDominator as insertion point
  386. NewPt = CommonDominator->getTerminator();
  387. }
  388. // else, CommonDominator is the block of NewBB, hence NewBB is the last
  389. // possible insertion point in that block.
  390. LLVM_DEBUG(dbgs() << "Merge insertion point with:\n");
  391. LLVM_DEBUG(IPI->first->print(dbgs()));
  392. LLVM_DEBUG(dbgs() << '\n');
  393. LLVM_DEBUG(NewPt->print(dbgs()));
  394. LLVM_DEBUG(dbgs() << '\n');
  395. appendAndTransferDominatedUses(NewPt, User, OpNo, IPI, InsertPts);
  396. return true;
  397. }
  398. return false;
  399. }
  400. void AArch64PromoteConstant::computeInsertionPoint(
  401. Instruction *User, unsigned OpNo, InsertionPoints &InsertPts) {
  402. LLVM_DEBUG(dbgs() << "Considered use, opidx " << OpNo << ":\n");
  403. LLVM_DEBUG(User->print(dbgs()));
  404. LLVM_DEBUG(dbgs() << '\n');
  405. Instruction *InsertionPoint = findInsertionPoint(*User, OpNo);
  406. LLVM_DEBUG(dbgs() << "Considered insertion point:\n");
  407. LLVM_DEBUG(InsertionPoint->print(dbgs()));
  408. LLVM_DEBUG(dbgs() << '\n');
  409. if (isDominated(InsertionPoint, User, OpNo, InsertPts))
  410. return;
  411. // This insertion point is useful, check if we can merge some insertion
  412. // point in a common dominator or if NewPt dominates an existing one.
  413. if (tryAndMerge(InsertionPoint, User, OpNo, InsertPts))
  414. return;
  415. LLVM_DEBUG(dbgs() << "Keep considered insertion point\n");
  416. // It is definitely useful by its own
  417. InsertPts[InsertionPoint].emplace_back(User, OpNo);
  418. }
  419. static void ensurePromotedGV(Function &F, Constant &C,
  420. AArch64PromoteConstant::PromotedConstant &PC) {
  421. assert(PC.ShouldConvert &&
  422. "Expected that we should convert this to a global");
  423. if (PC.GV)
  424. return;
  425. PC.GV = new GlobalVariable(
  426. *F.getParent(), C.getType(), true, GlobalValue::InternalLinkage, nullptr,
  427. "_PromotedConst", nullptr, GlobalVariable::NotThreadLocal);
  428. PC.GV->setInitializer(&C);
  429. LLVM_DEBUG(dbgs() << "Global replacement: ");
  430. LLVM_DEBUG(PC.GV->print(dbgs()));
  431. LLVM_DEBUG(dbgs() << '\n');
  432. ++NumPromoted;
  433. }
  434. void AArch64PromoteConstant::insertDefinitions(Function &F,
  435. GlobalVariable &PromotedGV,
  436. InsertionPoints &InsertPts) {
  437. #ifndef NDEBUG
  438. // Do more checking for debug purposes.
  439. DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
  440. #endif
  441. assert(!InsertPts.empty() && "Empty uses does not need a definition");
  442. for (const auto &IPI : InsertPts) {
  443. // Create the load of the global variable.
  444. IRBuilder<> Builder(IPI.first);
  445. LoadInst *LoadedCst =
  446. Builder.CreateLoad(PromotedGV.getValueType(), &PromotedGV);
  447. LLVM_DEBUG(dbgs() << "**********\n");
  448. LLVM_DEBUG(dbgs() << "New def: ");
  449. LLVM_DEBUG(LoadedCst->print(dbgs()));
  450. LLVM_DEBUG(dbgs() << '\n');
  451. // Update the dominated uses.
  452. for (auto Use : IPI.second) {
  453. #ifndef NDEBUG
  454. assert(DT.dominates(LoadedCst,
  455. findInsertionPoint(*Use.first, Use.second)) &&
  456. "Inserted definition does not dominate all its uses!");
  457. #endif
  458. LLVM_DEBUG({
  459. dbgs() << "Use to update " << Use.second << ":";
  460. Use.first->print(dbgs());
  461. dbgs() << '\n';
  462. });
  463. Use.first->setOperand(Use.second, LoadedCst);
  464. ++NumPromotedUses;
  465. }
  466. }
  467. }
  468. void AArch64PromoteConstant::promoteConstants(
  469. Function &F, SmallVectorImpl<UpdateRecord> &Updates,
  470. PromotionCacheTy &PromotionCache) {
  471. // Promote the constants.
  472. for (auto U = Updates.begin(), E = Updates.end(); U != E;) {
  473. LLVM_DEBUG(dbgs() << "** Compute insertion points **\n");
  474. auto First = U;
  475. Constant *C = First->C;
  476. InsertionPoints InsertPts;
  477. do {
  478. computeInsertionPoint(U->User, U->Op, InsertPts);
  479. } while (++U != E && U->C == C);
  480. auto &Promotion = PromotionCache[C];
  481. ensurePromotedGV(F, *C, Promotion);
  482. insertDefinitions(F, *Promotion.GV, InsertPts);
  483. }
  484. }
  485. bool AArch64PromoteConstant::runOnFunction(Function &F,
  486. PromotionCacheTy &PromotionCache) {
  487. // Look for instructions using constant vector. Promote that constant to a
  488. // global variable. Create as few loads of this variable as possible and
  489. // update the uses accordingly.
  490. SmallVector<UpdateRecord, 64> Updates;
  491. for (Instruction &I : instructions(&F)) {
  492. // Traverse the operand, looking for constant vectors. Replace them by a
  493. // load of a global variable of constant vector type.
  494. for (Use &U : I.operands()) {
  495. Constant *Cst = dyn_cast<Constant>(U);
  496. // There is no point in promoting global values as they are already
  497. // global. Do not promote constants containing constant expression, global
  498. // values or blockaddresses either, as they may require some code
  499. // expansion.
  500. if (!Cst || isa<GlobalValue>(Cst) || !containsOnlyConstantData(Cst))
  501. continue;
  502. // Check if this constant is worth promoting.
  503. if (!shouldConvert(*Cst, PromotionCache))
  504. continue;
  505. // Check if this use should be promoted.
  506. unsigned OpNo = &U - I.op_begin();
  507. if (!shouldConvertUse(Cst, &I, OpNo))
  508. continue;
  509. Updates.emplace_back(Cst, &I, OpNo);
  510. }
  511. }
  512. if (Updates.empty())
  513. return false;
  514. promoteConstants(F, Updates, PromotionCache);
  515. return true;
  516. }