1 //===-- AArch64AddressTypePromotion.cpp --- Promote type for addr accesses -==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass tries to promote the computations use to obtained a sign extended
11 // value used into memory accesses.
13 // a = add nsw i32 b, 3
14 // d = sext i32 a to i64
15 // e = getelementptr ..., i64 d
18 // f = sext i32 b to i64
19 // a = add nsw i64 f, 3
20 // e = getelementptr ..., i64 a
22 // This is legal to do so if the computations are markers with either nsw or nuw
24 // Moreover, the current heuristic is simple: it does not create new sext
25 // operations, i.e., it gives up when a sext would have forked (e.g., if
26 // a = add i32 b, c, two sexts are required to promote the computation).
28 // FIXME: This pass may be useful for other targets too.
29 // ===---------------------------------------------------------------------===//
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
47 #define DEBUG_TYPE "aarch64-type-promotion"
50 EnableAddressTypePromotion("aarch64-type-promotion", cl::Hidden,
51 cl::desc("Enable the type promotion pass"),
54 EnableMerge("aarch64-type-promotion-merge", cl::Hidden,
55 cl::desc("Enable merging of redundant sexts when one is dominating"
59 //===----------------------------------------------------------------------===//
60 // AArch64AddressTypePromotion
61 //===----------------------------------------------------------------------===//
64 void initializeAArch64AddressTypePromotionPass(PassRegistry &);
68 class AArch64AddressTypePromotion : public FunctionPass {
72 AArch64AddressTypePromotion()
73 : FunctionPass(ID), Func(nullptr), ConsideredSExtType(nullptr) {
74 initializeAArch64AddressTypePromotionPass(*PassRegistry::getPassRegistry());
77 const char *getPassName() const override {
78 return "AArch64 Address Type Promotion";
81 /// Iterate over the functions and promote the computation of interesting
83 bool runOnFunction(Function &F) override;
86 /// The current function.
88 /// Filter out all sexts that does not have this type.
89 /// Currently initialized with Int64Ty.
90 Type *ConsideredSExtType;
92 // This transformation requires dominator info.
93 void getAnalysisUsage(AnalysisUsage &AU) const override {
95 AU.addRequired<DominatorTreeWrapperPass>();
96 AU.addPreserved<DominatorTreeWrapperPass>();
97 FunctionPass::getAnalysisUsage(AU);
100 typedef SmallPtrSet<Instruction *, 32> SetOfInstructions;
101 typedef SmallVector<Instruction *, 16> Instructions;
102 typedef DenseMap<Value *, Instructions> ValueToInsts;
104 /// Check if it is profitable to move a sext through this instruction.
105 /// Currently, we consider it is profitable if:
106 /// - Inst is used only once (no need to insert truncate).
107 /// - Inst has only one operand that will require a sext operation (we do
108 /// do not create new sext operation).
109 bool shouldGetThrough(const Instruction *Inst);
111 /// Check if it is possible and legal to move a sext through this
113 /// Current heuristic considers that we can get through:
114 /// - Arithmetic operation marked with the nsw or nuw flag.
115 /// - Other sext operation.
116 /// - Truncate operation if it was just dropping sign extended bits.
117 bool canGetThrough(const Instruction *Inst);
119 /// Move sext operations through safe to sext instructions.
120 bool propagateSignExtension(Instructions &SExtInsts);
122 /// Is this sext should be considered for code motion.
123 /// We look for sext with ConsideredSExtType and uses in at least one
124 // GetElementPtrInst.
125 bool shouldConsiderSExt(const Instruction *SExt) const;
127 /// Collect all interesting sext operations, i.e., the ones with the right
128 /// type and used in memory accesses.
129 /// More precisely, a sext instruction is considered as interesting if it
130 /// is used in a "complex" getelementptr or it exits at least another
131 /// sext instruction that sign extended the same initial value.
132 /// A getelementptr is considered as "complex" if it has more than 2
134 void analyzeSExtension(Instructions &SExtInsts);
136 /// Merge redundant sign extension operations in common dominator.
137 void mergeSExts(ValueToInsts &ValToSExtendedUses,
138 SetOfInstructions &ToRemove);
140 } // end anonymous namespace.
142 char AArch64AddressTypePromotion::ID = 0;
144 INITIALIZE_PASS_BEGIN(AArch64AddressTypePromotion, "aarch64-type-promotion",
145 "AArch64 Type Promotion Pass", false, false)
146 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
147 INITIALIZE_PASS_END(AArch64AddressTypePromotion, "aarch64-type-promotion",
148 "AArch64 Type Promotion Pass", false, false)
150 FunctionPass *llvm::createAArch64AddressTypePromotionPass() {
151 return new AArch64AddressTypePromotion();
154 bool AArch64AddressTypePromotion::canGetThrough(const Instruction *Inst) {
155 if (isa<SExtInst>(Inst))
158 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
159 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
160 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
163 // sext(trunc(sext)) --> sext
164 if (isa<TruncInst>(Inst) && isa<SExtInst>(Inst->getOperand(0))) {
165 const Instruction *Opnd = cast<Instruction>(Inst->getOperand(0));
166 // Check that the truncate just drop sign extended bits.
167 if (Inst->getType()->getIntegerBitWidth() >=
168 Opnd->getOperand(0)->getType()->getIntegerBitWidth() &&
169 Inst->getOperand(0)->getType()->getIntegerBitWidth() <=
170 ConsideredSExtType->getIntegerBitWidth())
177 bool AArch64AddressTypePromotion::shouldGetThrough(const Instruction *Inst) {
178 // If the type of the sext is the same as the considered one, this sext
179 // will become useless.
180 // Otherwise, we will have to do something to preserve the original value,
181 // unless it is used once.
182 if (isa<SExtInst>(Inst) &&
183 (Inst->getType() == ConsideredSExtType || Inst->hasOneUse()))
186 // If the Inst is used more that once, we may need to insert truncate
187 // operations and we don't do that at the moment.
188 if (!Inst->hasOneUse())
191 // This truncate is used only once, thus if we can get thourgh, it will become
193 if (isa<TruncInst>(Inst))
196 // If both operands are not constant, a new sext will be created here.
197 // Current heuristic is: each step should be profitable.
198 // Therefore we don't allow to increase the number of sext even if it may
199 // be profitable later on.
200 if (isa<BinaryOperator>(Inst) && isa<ConstantInt>(Inst->getOperand(1)))
206 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
207 if (isa<SelectInst>(Inst) && OpIdx == 0)
213 AArch64AddressTypePromotion::shouldConsiderSExt(const Instruction *SExt) const {
214 if (SExt->getType() != ConsideredSExtType)
217 for (const User *U : SExt->users()) {
218 if (isa<GetElementPtrInst>(U))
226 // - SExtInsts contains all the sext instructions that are use direclty in
227 // GetElementPtrInst, i.e., access to memory.
229 // - For each sext operation in SExtInsts:
230 // Let var be the operand of sext.
231 // while it is profitable (see shouldGetThrough), legal, and safe
232 // (see canGetThrough) to move sext through var's definition:
233 // * promote the type of var's definition.
234 // * fold var into sext uses.
235 // * move sext above var's definition.
236 // * update sext operand to use the operand of var that should be sign
237 // extended (by construction there is only one).
241 // b = sext i32 a to i64 <- is it legal/safe/profitable to get through 'a'
244 // => Yes, update the code
245 // b = sext i32 c to i64
251 AArch64AddressTypePromotion::propagateSignExtension(Instructions &SExtInsts) {
252 DEBUG(dbgs() << "*** Propagate Sign Extension ***\n");
254 bool LocalChange = false;
255 SetOfInstructions ToRemove;
256 ValueToInsts ValToSExtendedUses;
257 while (!SExtInsts.empty()) {
258 // Get through simple chain.
259 Instruction *SExt = SExtInsts.pop_back_val();
261 DEBUG(dbgs() << "Consider:\n" << *SExt << '\n');
263 // If this SExt has already been merged continue.
264 if (SExt->use_empty() && ToRemove.count(SExt)) {
265 DEBUG(dbgs() << "No uses => marked as delete\n");
269 // Now try to get through the chain of definitions.
270 while (isa<Instruction>(SExt->getOperand(0))) {
271 Instruction *Inst = dyn_cast<Instruction>(SExt->getOperand(0));
272 DEBUG(dbgs() << "Try to get through:\n" << *Inst << '\n');
273 if (!canGetThrough(Inst) || !shouldGetThrough(Inst)) {
274 // We cannot get through something that is not an Instruction
275 // or not safe to SExt.
276 DEBUG(dbgs() << "Cannot get through\n");
281 // If this is a sign extend, it becomes useless.
282 if (isa<SExtInst>(Inst) || isa<TruncInst>(Inst)) {
283 DEBUG(dbgs() << "SExt or trunc, mark it as to remove\n");
284 // We cannot use replaceAllUsesWith here because we may trigger some
285 // assertion on the type as all involved sext operation may have not
287 while (!Inst->use_empty()) {
288 Use &U = *Inst->use_begin();
289 Instruction *User = dyn_cast<Instruction>(U.getUser());
290 assert(User && "User of sext is not an Instruction!");
291 User->setOperand(U.getOperandNo(), SExt);
293 ToRemove.insert(Inst);
294 SExt->setOperand(0, Inst->getOperand(0));
295 SExt->moveBefore(Inst);
299 // Get through the Instruction:
300 // 1. Update its type.
301 // 2. Replace the uses of SExt by Inst.
302 // 3. Sign extend each operand that needs to be sign extended.
305 Inst->mutateType(SExt->getType());
307 SExt->replaceAllUsesWith(Inst);
309 Instruction *SExtForOpnd = SExt;
311 DEBUG(dbgs() << "Propagate SExt to operands\n");
312 for (int OpIdx = 0, EndOpIdx = Inst->getNumOperands(); OpIdx != EndOpIdx;
314 DEBUG(dbgs() << "Operand:\n" << *(Inst->getOperand(OpIdx)) << '\n');
315 if (Inst->getOperand(OpIdx)->getType() == SExt->getType() ||
316 !shouldSExtOperand(Inst, OpIdx)) {
317 DEBUG(dbgs() << "No need to propagate\n");
320 // Check if we can statically sign extend the operand.
321 Value *Opnd = Inst->getOperand(OpIdx);
322 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
323 DEBUG(dbgs() << "Statically sign extend\n");
324 Inst->setOperand(OpIdx, ConstantInt::getSigned(SExt->getType(),
325 Cst->getSExtValue()));
328 // UndefValue are typed, so we have to statically sign extend them.
329 if (isa<UndefValue>(Opnd)) {
330 DEBUG(dbgs() << "Statically sign extend\n");
331 Inst->setOperand(OpIdx, UndefValue::get(SExt->getType()));
335 // Otherwise we have to explicity sign extend it.
336 assert(SExtForOpnd &&
337 "Only one operand should have been sign extended");
339 SExtForOpnd->setOperand(0, Opnd);
341 DEBUG(dbgs() << "Move before:\n" << *Inst << "\nSign extend\n");
342 // Move the sign extension before the insertion point.
343 SExtForOpnd->moveBefore(Inst);
344 Inst->setOperand(OpIdx, SExtForOpnd);
345 // If more sext are required, new instructions will have to be created.
346 SExtForOpnd = nullptr;
348 if (SExtForOpnd == SExt) {
349 DEBUG(dbgs() << "Sign extension is useless now\n");
350 ToRemove.insert(SExt);
355 // If the use is already of the right type, connect its uses to its argument
357 // This can happen for an Instruction which all uses are sign extended.
358 if (!ToRemove.count(SExt) &&
359 SExt->getType() == SExt->getOperand(0)->getType()) {
360 DEBUG(dbgs() << "Sign extension is useless, attach its use to "
362 SExt->replaceAllUsesWith(SExt->getOperand(0));
363 ToRemove.insert(SExt);
365 ValToSExtendedUses[SExt->getOperand(0)].push_back(SExt);
369 mergeSExts(ValToSExtendedUses, ToRemove);
371 // Remove all instructions marked as ToRemove.
372 for (Instruction *I: ToRemove)
373 I->eraseFromParent();
377 void AArch64AddressTypePromotion::mergeSExts(ValueToInsts &ValToSExtendedUses,
378 SetOfInstructions &ToRemove) {
379 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
381 for (auto &Entry : ValToSExtendedUses) {
382 Instructions &Insts = Entry.second;
384 for (Instruction *Inst : Insts) {
385 if (ToRemove.count(Inst))
387 bool inserted = false;
388 for (auto Pt : CurPts) {
389 if (DT.dominates(Inst, Pt)) {
390 DEBUG(dbgs() << "Replace all uses of:\n" << *Pt << "\nwith:\n"
392 (Pt)->replaceAllUsesWith(Inst);
398 if (!DT.dominates(Pt, Inst))
399 // Give up if we need to merge in a common dominator as the
400 // expermients show it is not profitable.
403 DEBUG(dbgs() << "Replace all uses of:\n" << *Inst << "\nwith:\n"
405 Inst->replaceAllUsesWith(Pt);
406 ToRemove.insert(Inst);
411 CurPts.push_back(Inst);
416 void AArch64AddressTypePromotion::analyzeSExtension(Instructions &SExtInsts) {
417 DEBUG(dbgs() << "*** Analyze Sign Extensions ***\n");
419 DenseMap<Value *, Instruction *> SeenChains;
421 for (auto &BB : *Func) {
422 for (auto &II : BB) {
423 Instruction *SExt = &II;
425 // Collect all sext operation per type.
426 if (!isa<SExtInst>(SExt) || !shouldConsiderSExt(SExt))
429 DEBUG(dbgs() << "Found:\n" << (*SExt) << '\n');
431 // Cases where we actually perform the optimization:
432 // 1. SExt is used in a getelementptr with more than 2 operand =>
433 // likely we can merge some computation if they are done on 64 bits.
434 // 2. The beginning of the SExt chain is SExt several time. =>
435 // code sharing is possible.
439 for (const User *U : SExt->users()) {
440 const Instruction *Inst = dyn_cast<GetElementPtrInst>(U);
441 if (Inst && Inst->getNumOperands() > 2) {
442 DEBUG(dbgs() << "Interesting use in GetElementPtrInst\n" << *Inst
450 // Check the head of the chain.
451 Instruction *Inst = SExt;
455 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
456 if (BinOp && isa<ConstantInt>(BinOp->getOperand(0)))
458 Last = Inst->getOperand(OpdIdx);
459 Inst = dyn_cast<Instruction>(Last);
460 } while (Inst && canGetThrough(Inst) && shouldGetThrough(Inst));
462 DEBUG(dbgs() << "Head of the chain:\n" << *Last << '\n');
463 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
464 SeenChains.find(Last);
465 if (insert || AlreadySeen != SeenChains.end()) {
466 DEBUG(dbgs() << "Insert\n");
467 SExtInsts.push_back(SExt);
468 if (AlreadySeen != SeenChains.end() && AlreadySeen->second != nullptr) {
469 DEBUG(dbgs() << "Insert chain member\n");
470 SExtInsts.push_back(AlreadySeen->second);
471 SeenChains[Last] = nullptr;
474 DEBUG(dbgs() << "Record its chain membership\n");
475 SeenChains[Last] = SExt;
481 bool AArch64AddressTypePromotion::runOnFunction(Function &F) {
482 if (!EnableAddressTypePromotion || F.isDeclaration())
485 ConsideredSExtType = Type::getInt64Ty(Func->getContext());
487 DEBUG(dbgs() << "*** " << getPassName() << ": " << Func->getName() << '\n');
489 Instructions SExtInsts;
490 analyzeSExtension(SExtInsts);
491 return propagateSignExtension(SExtInsts);