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