1f1f57a31SAmjad Aboud //===- TruncInstCombine.cpp -----------------------------------------------===//
2f1f57a31SAmjad Aboud //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f1f57a31SAmjad Aboud //
7f1f57a31SAmjad Aboud //===----------------------------------------------------------------------===//
8f1f57a31SAmjad Aboud //
90dd84013SAnton Afanasyev // TruncInstCombine - looks for expression graphs post-dominated by TruncInst
100dd84013SAnton Afanasyev // and for each eligible graph, it will create a reduced bit-width expression,
110dd84013SAnton Afanasyev // replace the old expression with this new one and remove the old expression.
120dd84013SAnton Afanasyev // Eligible expression graph is such that:
13f1f57a31SAmjad Aboud //   1. Contains only supported instructions.
14f1f57a31SAmjad Aboud //   2. Supported leaves: ZExtInst, SExtInst, TruncInst and Constant value.
15f1f57a31SAmjad Aboud //   3. Can be evaluated into type with reduced legal bit-width.
160dd84013SAnton Afanasyev //   4. All instructions in the graph must not have users outside the graph.
17f1f57a31SAmjad Aboud //      The only exception is for {ZExt, SExt}Inst with operand type equal to
18f1f57a31SAmjad Aboud //      the new reduced type evaluated in (3).
19f1f57a31SAmjad Aboud //
20f1f57a31SAmjad Aboud // The motivation for this optimization is that evaluating and expression using
21f1f57a31SAmjad Aboud // smaller bit-width is preferable, especially for vectorization where we can
22f1f57a31SAmjad Aboud // fit more values in one vectorized instruction. In addition, this optimization
23f1f57a31SAmjad Aboud // may decrease the number of cast instructions, but will not increase it.
24f1f57a31SAmjad Aboud //
25f1f57a31SAmjad Aboud //===----------------------------------------------------------------------===//
26f1f57a31SAmjad Aboud 
27f1f57a31SAmjad Aboud #include "AggressiveInstCombineInternal.h"
28f1f57a31SAmjad Aboud #include "llvm/ADT/STLExtras.h"
29e987ee63SRoman Lebedev #include "llvm/ADT/Statistic.h"
30f1f57a31SAmjad Aboud #include "llvm/Analysis/ConstantFolding.h"
31f1f57a31SAmjad Aboud #include "llvm/Analysis/TargetLibraryInfo.h"
32f1f57a31SAmjad Aboud #include "llvm/IR/DataLayout.h"
33d895bff5SAmjad Aboud #include "llvm/IR/Dominators.h"
34f1f57a31SAmjad Aboud #include "llvm/IR/IRBuilder.h"
350347f3eaSSimon Pilgrim #include "llvm/IR/Instruction.h"
361f3e35b6SAnton Afanasyev #include "llvm/Support/KnownBits.h"
37e987ee63SRoman Lebedev 
38f1f57a31SAmjad Aboud using namespace llvm;
39f1f57a31SAmjad Aboud 
40f1f57a31SAmjad Aboud #define DEBUG_TYPE "aggressive-instcombine"
41f1f57a31SAmjad Aboud 
420dd84013SAnton Afanasyev STATISTIC(NumExprsReduced, "Number of truncations eliminated by reducing bit "
430dd84013SAnton Afanasyev                            "width of expression graph");
44e987ee63SRoman Lebedev STATISTIC(NumInstrsReduced,
45e987ee63SRoman Lebedev           "Number of instructions whose bit width was reduced");
46e987ee63SRoman Lebedev 
47f1f57a31SAmjad Aboud /// Given an instruction and a container, it fills all the relevant operands of
480dd84013SAnton Afanasyev /// that instruction, with respect to the Trunc expression graph optimizaton.
49f1f57a31SAmjad Aboud static void getRelevantOperands(Instruction *I, SmallVectorImpl<Value *> &Ops) {
50f1f57a31SAmjad Aboud   unsigned Opc = I->getOpcode();
51f1f57a31SAmjad Aboud   switch (Opc) {
52f1f57a31SAmjad Aboud   case Instruction::Trunc:
53f1f57a31SAmjad Aboud   case Instruction::ZExt:
54f1f57a31SAmjad Aboud   case Instruction::SExt:
55f1f57a31SAmjad Aboud     // These CastInst are considered leaves of the evaluated expression, thus,
56f1f57a31SAmjad Aboud     // their operands are not relevent.
57f1f57a31SAmjad Aboud     break;
58f1f57a31SAmjad Aboud   case Instruction::Add:
59f1f57a31SAmjad Aboud   case Instruction::Sub:
60f1f57a31SAmjad Aboud   case Instruction::Mul:
61f1f57a31SAmjad Aboud   case Instruction::And:
62f1f57a31SAmjad Aboud   case Instruction::Or:
63f1f57a31SAmjad Aboud   case Instruction::Xor:
641f3e35b6SAnton Afanasyev   case Instruction::Shl:
65cfb6dfcbSAnton Afanasyev   case Instruction::LShr:
66bed58763SAnton Afanasyev   case Instruction::AShr:
6754d8ebbbSAnton Afanasyev   case Instruction::UDiv:
6854d8ebbbSAnton Afanasyev   case Instruction::URem:
696a5f49a1SAnton Afanasyev   case Instruction::InsertElement:
70f1f57a31SAmjad Aboud     Ops.push_back(I->getOperand(0));
71f1f57a31SAmjad Aboud     Ops.push_back(I->getOperand(1));
72f1f57a31SAmjad Aboud     break;
736a5f49a1SAnton Afanasyev   case Instruction::ExtractElement:
746a5f49a1SAnton Afanasyev     Ops.push_back(I->getOperand(0));
756a5f49a1SAnton Afanasyev     break;
763bda9059SAyman Musa   case Instruction::Select:
773bda9059SAyman Musa     Ops.push_back(I->getOperand(1));
783bda9059SAyman Musa     Ops.push_back(I->getOperand(2));
793bda9059SAyman Musa     break;
800dd84013SAnton Afanasyev   case Instruction::PHI:
810dd84013SAnton Afanasyev     for (Value *V : cast<PHINode>(I)->incoming_values())
820dd84013SAnton Afanasyev       Ops.push_back(V);
830dd84013SAnton Afanasyev     break;
84f1f57a31SAmjad Aboud   default:
85f1f57a31SAmjad Aboud     llvm_unreachable("Unreachable!");
86f1f57a31SAmjad Aboud   }
87f1f57a31SAmjad Aboud }
88f1f57a31SAmjad Aboud 
890dd84013SAnton Afanasyev bool TruncInstCombine::buildTruncExpressionGraph() {
90f1f57a31SAmjad Aboud   SmallVector<Value *, 8> Worklist;
91f1f57a31SAmjad Aboud   SmallVector<Instruction *, 8> Stack;
920dd84013SAnton Afanasyev   // Clear old instructions info.
93f1f57a31SAmjad Aboud   InstInfoMap.clear();
94f1f57a31SAmjad Aboud 
95f1f57a31SAmjad Aboud   Worklist.push_back(CurrentTruncInst->getOperand(0));
96f1f57a31SAmjad Aboud 
97f1f57a31SAmjad Aboud   while (!Worklist.empty()) {
98f1f57a31SAmjad Aboud     Value *Curr = Worklist.back();
99f1f57a31SAmjad Aboud 
100f1f57a31SAmjad Aboud     if (isa<Constant>(Curr)) {
101f1f57a31SAmjad Aboud       Worklist.pop_back();
102f1f57a31SAmjad Aboud       continue;
103f1f57a31SAmjad Aboud     }
104f1f57a31SAmjad Aboud 
105f1f57a31SAmjad Aboud     auto *I = dyn_cast<Instruction>(Curr);
106f1f57a31SAmjad Aboud     if (!I)
107f1f57a31SAmjad Aboud       return false;
108f1f57a31SAmjad Aboud 
109f1f57a31SAmjad Aboud     if (!Stack.empty() && Stack.back() == I) {
110f1f57a31SAmjad Aboud       // Already handled all instruction operands, can remove it from both the
111f1f57a31SAmjad Aboud       // Worklist and the Stack, and add it to the instruction info map.
112f1f57a31SAmjad Aboud       Worklist.pop_back();
113f1f57a31SAmjad Aboud       Stack.pop_back();
114f1f57a31SAmjad Aboud       // Insert I to the Info map.
115f1f57a31SAmjad Aboud       InstInfoMap.insert(std::make_pair(I, Info()));
116f1f57a31SAmjad Aboud       continue;
117f1f57a31SAmjad Aboud     }
118f1f57a31SAmjad Aboud 
119f1f57a31SAmjad Aboud     if (InstInfoMap.count(I)) {
120f1f57a31SAmjad Aboud       Worklist.pop_back();
121f1f57a31SAmjad Aboud       continue;
122f1f57a31SAmjad Aboud     }
123f1f57a31SAmjad Aboud 
124f1f57a31SAmjad Aboud     // Add the instruction to the stack before start handling its operands.
125f1f57a31SAmjad Aboud     Stack.push_back(I);
126f1f57a31SAmjad Aboud 
127f1f57a31SAmjad Aboud     unsigned Opc = I->getOpcode();
128f1f57a31SAmjad Aboud     switch (Opc) {
129f1f57a31SAmjad Aboud     case Instruction::Trunc:
130f1f57a31SAmjad Aboud     case Instruction::ZExt:
131f1f57a31SAmjad Aboud     case Instruction::SExt:
132f1f57a31SAmjad Aboud       // trunc(trunc(x)) -> trunc(x)
133f1f57a31SAmjad Aboud       // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
134f1f57a31SAmjad Aboud       // trunc(ext(x)) -> trunc(x) if the source type is larger than the new
135f1f57a31SAmjad Aboud       // dest
136f1f57a31SAmjad Aboud       break;
137f1f57a31SAmjad Aboud     case Instruction::Add:
138f1f57a31SAmjad Aboud     case Instruction::Sub:
139f1f57a31SAmjad Aboud     case Instruction::Mul:
140f1f57a31SAmjad Aboud     case Instruction::And:
141f1f57a31SAmjad Aboud     case Instruction::Or:
1423bda9059SAyman Musa     case Instruction::Xor:
1431f3e35b6SAnton Afanasyev     case Instruction::Shl:
144cfb6dfcbSAnton Afanasyev     case Instruction::LShr:
145bed58763SAnton Afanasyev     case Instruction::AShr:
14654d8ebbbSAnton Afanasyev     case Instruction::UDiv:
14754d8ebbbSAnton Afanasyev     case Instruction::URem:
1486a5f49a1SAnton Afanasyev     case Instruction::InsertElement:
1496a5f49a1SAnton Afanasyev     case Instruction::ExtractElement:
15035f02aa0SAyman Musa     case Instruction::Select: {
151f1f57a31SAmjad Aboud       SmallVector<Value *, 2> Operands;
152f1f57a31SAmjad Aboud       getRelevantOperands(I, Operands);
153e53472deSKazu Hirata       append_range(Worklist, Operands);
154f1f57a31SAmjad Aboud       break;
155f1f57a31SAmjad Aboud     }
1560dd84013SAnton Afanasyev     case Instruction::PHI: {
1570dd84013SAnton Afanasyev       SmallVector<Value *, 2> Operands;
1580dd84013SAnton Afanasyev       getRelevantOperands(I, Operands);
1590dd84013SAnton Afanasyev       // Add only operands not in Stack to prevent cycle
1600dd84013SAnton Afanasyev       for (auto *Op : Operands)
1610dd84013SAnton Afanasyev         if (all_of(Stack, [Op](Value *V) { return Op != V; }))
1620dd84013SAnton Afanasyev           Worklist.push_back(Op);
1630dd84013SAnton Afanasyev       break;
1640dd84013SAnton Afanasyev     }
165f1f57a31SAmjad Aboud     default:
166f1f57a31SAmjad Aboud       // TODO: Can handle more cases here:
1676a5f49a1SAnton Afanasyev       // 1. shufflevector
16854d8ebbbSAnton Afanasyev       // 2. sdiv, srem
169f1f57a31SAmjad Aboud       // ...
170f1f57a31SAmjad Aboud       return false;
171f1f57a31SAmjad Aboud     }
172f1f57a31SAmjad Aboud   }
173f1f57a31SAmjad Aboud   return true;
174f1f57a31SAmjad Aboud }
175f1f57a31SAmjad Aboud 
176f1f57a31SAmjad Aboud unsigned TruncInstCombine::getMinBitWidth() {
177f1f57a31SAmjad Aboud   SmallVector<Value *, 8> Worklist;
178f1f57a31SAmjad Aboud   SmallVector<Instruction *, 8> Stack;
179f1f57a31SAmjad Aboud 
180f1f57a31SAmjad Aboud   Value *Src = CurrentTruncInst->getOperand(0);
181f1f57a31SAmjad Aboud   Type *DstTy = CurrentTruncInst->getType();
182f1f57a31SAmjad Aboud   unsigned TruncBitWidth = DstTy->getScalarSizeInBits();
183f1f57a31SAmjad Aboud   unsigned OrigBitWidth =
184f1f57a31SAmjad Aboud       CurrentTruncInst->getOperand(0)->getType()->getScalarSizeInBits();
185f1f57a31SAmjad Aboud 
186f1f57a31SAmjad Aboud   if (isa<Constant>(Src))
187f1f57a31SAmjad Aboud     return TruncBitWidth;
188f1f57a31SAmjad Aboud 
189f1f57a31SAmjad Aboud   Worklist.push_back(Src);
190f1f57a31SAmjad Aboud   InstInfoMap[cast<Instruction>(Src)].ValidBitWidth = TruncBitWidth;
191f1f57a31SAmjad Aboud 
192f1f57a31SAmjad Aboud   while (!Worklist.empty()) {
193f1f57a31SAmjad Aboud     Value *Curr = Worklist.back();
194f1f57a31SAmjad Aboud 
195f1f57a31SAmjad Aboud     if (isa<Constant>(Curr)) {
196f1f57a31SAmjad Aboud       Worklist.pop_back();
197f1f57a31SAmjad Aboud       continue;
198f1f57a31SAmjad Aboud     }
199f1f57a31SAmjad Aboud 
200f1f57a31SAmjad Aboud     // Otherwise, it must be an instruction.
201f1f57a31SAmjad Aboud     auto *I = cast<Instruction>(Curr);
202f1f57a31SAmjad Aboud 
203f1f57a31SAmjad Aboud     auto &Info = InstInfoMap[I];
204f1f57a31SAmjad Aboud 
205f1f57a31SAmjad Aboud     SmallVector<Value *, 2> Operands;
206f1f57a31SAmjad Aboud     getRelevantOperands(I, Operands);
207f1f57a31SAmjad Aboud 
208f1f57a31SAmjad Aboud     if (!Stack.empty() && Stack.back() == I) {
209f1f57a31SAmjad Aboud       // Already handled all instruction operands, can remove it from both, the
210f1f57a31SAmjad Aboud       // Worklist and the Stack, and update MinBitWidth.
211f1f57a31SAmjad Aboud       Worklist.pop_back();
212f1f57a31SAmjad Aboud       Stack.pop_back();
213f1f57a31SAmjad Aboud       for (auto *Operand : Operands)
214f1f57a31SAmjad Aboud         if (auto *IOp = dyn_cast<Instruction>(Operand))
215f1f57a31SAmjad Aboud           Info.MinBitWidth =
216f1f57a31SAmjad Aboud               std::max(Info.MinBitWidth, InstInfoMap[IOp].MinBitWidth);
217f1f57a31SAmjad Aboud       continue;
218f1f57a31SAmjad Aboud     }
219f1f57a31SAmjad Aboud 
220f1f57a31SAmjad Aboud     // Add the instruction to the stack before start handling its operands.
221f1f57a31SAmjad Aboud     Stack.push_back(I);
222f1f57a31SAmjad Aboud     unsigned ValidBitWidth = Info.ValidBitWidth;
223f1f57a31SAmjad Aboud 
224f1f57a31SAmjad Aboud     // Update minimum bit-width before handling its operands. This is required
225f1f57a31SAmjad Aboud     // when the instruction is part of a loop.
226f1f57a31SAmjad Aboud     Info.MinBitWidth = std::max(Info.MinBitWidth, Info.ValidBitWidth);
227f1f57a31SAmjad Aboud 
228f1f57a31SAmjad Aboud     for (auto *Operand : Operands)
229f1f57a31SAmjad Aboud       if (auto *IOp = dyn_cast<Instruction>(Operand)) {
230f1f57a31SAmjad Aboud         // If we already calculated the minimum bit-width for this valid
231f1f57a31SAmjad Aboud         // bit-width, or for a smaller valid bit-width, then just keep the
232f1f57a31SAmjad Aboud         // answer we already calculated.
233f1f57a31SAmjad Aboud         unsigned IOpBitwidth = InstInfoMap.lookup(IOp).ValidBitWidth;
234f1f57a31SAmjad Aboud         if (IOpBitwidth >= ValidBitWidth)
235f1f57a31SAmjad Aboud           continue;
23649a4d85fSAyman Musa         InstInfoMap[IOp].ValidBitWidth = ValidBitWidth;
237f1f57a31SAmjad Aboud         Worklist.push_back(IOp);
238f1f57a31SAmjad Aboud       }
239f1f57a31SAmjad Aboud   }
240f1f57a31SAmjad Aboud   unsigned MinBitWidth = InstInfoMap.lookup(cast<Instruction>(Src)).MinBitWidth;
241f1f57a31SAmjad Aboud   assert(MinBitWidth >= TruncBitWidth);
242f1f57a31SAmjad Aboud 
243f1f57a31SAmjad Aboud   if (MinBitWidth > TruncBitWidth) {
244f1f57a31SAmjad Aboud     // In this case reducing expression with vector type might generate a new
245f1f57a31SAmjad Aboud     // vector type, which is not preferable as it might result in generating
246f1f57a31SAmjad Aboud     // sub-optimal code.
247f1f57a31SAmjad Aboud     if (DstTy->isVectorTy())
248f1f57a31SAmjad Aboud       return OrigBitWidth;
249f1f57a31SAmjad Aboud     // Use the smallest integer type in the range [MinBitWidth, OrigBitWidth).
250f1f57a31SAmjad Aboud     Type *Ty = DL.getSmallestLegalIntType(DstTy->getContext(), MinBitWidth);
251f1f57a31SAmjad Aboud     // Update minimum bit-width with the new destination type bit-width if
252f1f57a31SAmjad Aboud     // succeeded to find such, otherwise, with original bit-width.
253f1f57a31SAmjad Aboud     MinBitWidth = Ty ? Ty->getScalarSizeInBits() : OrigBitWidth;
254f1f57a31SAmjad Aboud   } else { // MinBitWidth == TruncBitWidth
255f1f57a31SAmjad Aboud     // In this case the expression can be evaluated with the trunc instruction
256f1f57a31SAmjad Aboud     // destination type, and trunc instruction can be omitted. However, we
257f1f57a31SAmjad Aboud     // should not perform the evaluation if the original type is a legal scalar
258f1f57a31SAmjad Aboud     // type and the target type is illegal.
259f1f57a31SAmjad Aboud     bool FromLegal = MinBitWidth == 1 || DL.isLegalInteger(OrigBitWidth);
260f1f57a31SAmjad Aboud     bool ToLegal = MinBitWidth == 1 || DL.isLegalInteger(MinBitWidth);
261f1f57a31SAmjad Aboud     if (!DstTy->isVectorTy() && FromLegal && !ToLegal)
262f1f57a31SAmjad Aboud       return OrigBitWidth;
263f1f57a31SAmjad Aboud   }
264f1f57a31SAmjad Aboud   return MinBitWidth;
265f1f57a31SAmjad Aboud }
266f1f57a31SAmjad Aboud 
267f1f57a31SAmjad Aboud Type *TruncInstCombine::getBestTruncatedType() {
2680dd84013SAnton Afanasyev   if (!buildTruncExpressionGraph())
269f1f57a31SAmjad Aboud     return nullptr;
270f1f57a31SAmjad Aboud 
271f1f57a31SAmjad Aboud   // We don't want to duplicate instructions, which isn't profitable. Thus, we
272f1f57a31SAmjad Aboud   // can't shrink something that has multiple users, unless all users are
273f1f57a31SAmjad Aboud   // post-dominated by the trunc instruction, i.e., were visited during the
274f1f57a31SAmjad Aboud   // expression evaluation.
275f1f57a31SAmjad Aboud   unsigned DesiredBitWidth = 0;
276f1f57a31SAmjad Aboud   for (auto Itr : InstInfoMap) {
277f1f57a31SAmjad Aboud     Instruction *I = Itr.first;
278f1f57a31SAmjad Aboud     if (I->hasOneUse())
279f1f57a31SAmjad Aboud       continue;
280f1f57a31SAmjad Aboud     bool IsExtInst = (isa<ZExtInst>(I) || isa<SExtInst>(I));
281f1f57a31SAmjad Aboud     for (auto *U : I->users())
282f1f57a31SAmjad Aboud       if (auto *UI = dyn_cast<Instruction>(U))
283f1f57a31SAmjad Aboud         if (UI != CurrentTruncInst && !InstInfoMap.count(UI)) {
284f1f57a31SAmjad Aboud           if (!IsExtInst)
285f1f57a31SAmjad Aboud             return nullptr;
286f1f57a31SAmjad Aboud           // If this is an extension from the dest type, we can eliminate it,
287f1f57a31SAmjad Aboud           // even if it has multiple users. Thus, update the DesiredBitWidth and
288f1f57a31SAmjad Aboud           // validate all extension instructions agrees on same DesiredBitWidth.
289f1f57a31SAmjad Aboud           unsigned ExtInstBitWidth =
290f1f57a31SAmjad Aboud               I->getOperand(0)->getType()->getScalarSizeInBits();
291f1f57a31SAmjad Aboud           if (DesiredBitWidth && DesiredBitWidth != ExtInstBitWidth)
292f1f57a31SAmjad Aboud             return nullptr;
293f1f57a31SAmjad Aboud           DesiredBitWidth = ExtInstBitWidth;
294f1f57a31SAmjad Aboud         }
295f1f57a31SAmjad Aboud   }
296f1f57a31SAmjad Aboud 
297f1f57a31SAmjad Aboud   unsigned OrigBitWidth =
298f1f57a31SAmjad Aboud       CurrentTruncInst->getOperand(0)->getType()->getScalarSizeInBits();
299f1f57a31SAmjad Aboud 
300cfb6dfcbSAnton Afanasyev   // Initialize MinBitWidth for shift instructions with the minimum number
301bed58763SAnton Afanasyev   // that is greater than shift amount (i.e. shift amount + 1).
302bed58763SAnton Afanasyev   // For `lshr` adjust MinBitWidth so that all potentially truncated
303bed58763SAnton Afanasyev   // bits of the value-to-be-shifted are zeros.
304bed58763SAnton Afanasyev   // For `ashr` adjust MinBitWidth so that all potentially truncated
305bed58763SAnton Afanasyev   // bits of the value-to-be-shifted are sign bits (all zeros or ones)
306bed58763SAnton Afanasyev   // and even one (first) untruncated bit is sign bit.
307bed58763SAnton Afanasyev   // Exit early if MinBitWidth is not less than original bitwidth.
3081f3e35b6SAnton Afanasyev   for (auto &Itr : InstInfoMap) {
3091f3e35b6SAnton Afanasyev     Instruction *I = Itr.first;
310bed58763SAnton Afanasyev     if (I->isShift()) {
3118c0a1940SAnton Afanasyev       KnownBits KnownRHS = computeKnownBits(I->getOperand(1));
312803270c0SAnton Afanasyev       unsigned MinBitWidth = KnownRHS.getMaxValue()
3133890ce70SAnton Afanasyev                                  .uadd_sat(APInt(OrigBitWidth, 1))
3143890ce70SAnton Afanasyev                                  .getLimitedValue(OrigBitWidth);
3153890ce70SAnton Afanasyev       if (MinBitWidth == OrigBitWidth)
3161f3e35b6SAnton Afanasyev         return nullptr;
317cfb6dfcbSAnton Afanasyev       if (I->getOpcode() == Instruction::LShr) {
3188c0a1940SAnton Afanasyev         KnownBits KnownLHS = computeKnownBits(I->getOperand(0));
319cfb6dfcbSAnton Afanasyev         MinBitWidth =
320cfb6dfcbSAnton Afanasyev             std::max(MinBitWidth, KnownLHS.getMaxValue().getActiveBits());
321bed58763SAnton Afanasyev       }
322bed58763SAnton Afanasyev       if (I->getOpcode() == Instruction::AShr) {
3238c0a1940SAnton Afanasyev         unsigned NumSignBits = ComputeNumSignBits(I->getOperand(0));
324bed58763SAnton Afanasyev         MinBitWidth = std::max(MinBitWidth, OrigBitWidth - NumSignBits + 1);
325bed58763SAnton Afanasyev       }
326cfb6dfcbSAnton Afanasyev       if (MinBitWidth >= OrigBitWidth)
327cfb6dfcbSAnton Afanasyev         return nullptr;
3281f3e35b6SAnton Afanasyev       Itr.second.MinBitWidth = MinBitWidth;
3291f3e35b6SAnton Afanasyev     }
33054d8ebbbSAnton Afanasyev     if (I->getOpcode() == Instruction::UDiv ||
33154d8ebbbSAnton Afanasyev         I->getOpcode() == Instruction::URem) {
33254d8ebbbSAnton Afanasyev       unsigned MinBitWidth = 0;
33354d8ebbbSAnton Afanasyev       for (const auto &Op : I->operands()) {
33454d8ebbbSAnton Afanasyev         KnownBits Known = computeKnownBits(Op);
33554d8ebbbSAnton Afanasyev         MinBitWidth =
33654d8ebbbSAnton Afanasyev             std::max(Known.getMaxValue().getActiveBits(), MinBitWidth);
33754d8ebbbSAnton Afanasyev         if (MinBitWidth >= OrigBitWidth)
33854d8ebbbSAnton Afanasyev           return nullptr;
33954d8ebbbSAnton Afanasyev       }
34054d8ebbbSAnton Afanasyev       Itr.second.MinBitWidth = MinBitWidth;
34154d8ebbbSAnton Afanasyev     }
3421f3e35b6SAnton Afanasyev   }
3431f3e35b6SAnton Afanasyev 
344f1f57a31SAmjad Aboud   // Calculate minimum allowed bit-width allowed for shrinking the currently
345f1f57a31SAmjad Aboud   // visited truncate's operand.
346f1f57a31SAmjad Aboud   unsigned MinBitWidth = getMinBitWidth();
347f1f57a31SAmjad Aboud 
348f1f57a31SAmjad Aboud   // Check that we can shrink to smaller bit-width than original one and that
349f1f57a31SAmjad Aboud   // it is similar to the DesiredBitWidth is such exists.
350f1f57a31SAmjad Aboud   if (MinBitWidth >= OrigBitWidth ||
351f1f57a31SAmjad Aboud       (DesiredBitWidth && DesiredBitWidth != MinBitWidth))
352f1f57a31SAmjad Aboud     return nullptr;
353f1f57a31SAmjad Aboud 
354f1f57a31SAmjad Aboud   return IntegerType::get(CurrentTruncInst->getContext(), MinBitWidth);
355f1f57a31SAmjad Aboud }
356f1f57a31SAmjad Aboud 
357f1f57a31SAmjad Aboud /// Given a reduced scalar type \p Ty and a \p V value, return a reduced type
358f1f57a31SAmjad Aboud /// for \p V, according to its type, if it vector type, return the vector
359f1f57a31SAmjad Aboud /// version of \p Ty, otherwise return \p Ty.
360f1f57a31SAmjad Aboud static Type *getReducedType(Value *V, Type *Ty) {
361f1f57a31SAmjad Aboud   assert(Ty && !Ty->isVectorTy() && "Expect Scalar Type");
362137674f8SJun Ma   if (auto *VTy = dyn_cast<VectorType>(V->getType()))
363137674f8SJun Ma     return VectorType::get(Ty, VTy->getElementCount());
364f1f57a31SAmjad Aboud   return Ty;
365f1f57a31SAmjad Aboud }
366f1f57a31SAmjad Aboud 
367f1f57a31SAmjad Aboud Value *TruncInstCombine::getReducedOperand(Value *V, Type *SclTy) {
368f1f57a31SAmjad Aboud   Type *Ty = getReducedType(V, SclTy);
369f1f57a31SAmjad Aboud   if (auto *C = dyn_cast<Constant>(V)) {
370f1f57a31SAmjad Aboud     C = ConstantExpr::getIntegerCast(C, Ty, false);
371f1f57a31SAmjad Aboud     // If we got a constantexpr back, try to simplify it with DL info.
3720e890cd4SNikita Popov     return ConstantFoldConstant(C, DL, &TLI);
373f1f57a31SAmjad Aboud   }
374f1f57a31SAmjad Aboud 
375f1f57a31SAmjad Aboud   auto *I = cast<Instruction>(V);
376f1f57a31SAmjad Aboud   Info Entry = InstInfoMap.lookup(I);
377f1f57a31SAmjad Aboud   assert(Entry.NewValue);
378f1f57a31SAmjad Aboud   return Entry.NewValue;
379f1f57a31SAmjad Aboud }
380f1f57a31SAmjad Aboud 
3810dd84013SAnton Afanasyev void TruncInstCombine::ReduceExpressionGraph(Type *SclTy) {
382e987ee63SRoman Lebedev   NumInstrsReduced += InstInfoMap.size();
3830dd84013SAnton Afanasyev   // Pairs of old and new phi-nodes
3840dd84013SAnton Afanasyev   SmallVector<std::pair<PHINode *, PHINode *>, 2> OldNewPHINodes;
385f1f57a31SAmjad Aboud   for (auto &Itr : InstInfoMap) { // Forward
386f1f57a31SAmjad Aboud     Instruction *I = Itr.first;
387f1f57a31SAmjad Aboud     TruncInstCombine::Info &NodeInfo = Itr.second;
388f1f57a31SAmjad Aboud 
389f1f57a31SAmjad Aboud     assert(!NodeInfo.NewValue && "Instruction has been evaluated");
390f1f57a31SAmjad Aboud 
391f1f57a31SAmjad Aboud     IRBuilder<> Builder(I);
392f1f57a31SAmjad Aboud     Value *Res = nullptr;
393f1f57a31SAmjad Aboud     unsigned Opc = I->getOpcode();
394f1f57a31SAmjad Aboud     switch (Opc) {
395f1f57a31SAmjad Aboud     case Instruction::Trunc:
396f1f57a31SAmjad Aboud     case Instruction::ZExt:
397f1f57a31SAmjad Aboud     case Instruction::SExt: {
398f1f57a31SAmjad Aboud       Type *Ty = getReducedType(I, SclTy);
399f1f57a31SAmjad Aboud       // If the source type of the cast is the type we're trying for then we can
400f1f57a31SAmjad Aboud       // just return the source.  There's no need to insert it because it is not
401f1f57a31SAmjad Aboud       // new.
402f1f57a31SAmjad Aboud       if (I->getOperand(0)->getType() == Ty) {
403b86b771cSAmjad Aboud         assert(!isa<TruncInst>(I) && "Cannot reach here with TruncInst");
404f1f57a31SAmjad Aboud         NodeInfo.NewValue = I->getOperand(0);
405f1f57a31SAmjad Aboud         continue;
406f1f57a31SAmjad Aboud       }
407f1f57a31SAmjad Aboud       // Otherwise, must be the same type of cast, so just reinsert a new one.
408f1f57a31SAmjad Aboud       // This also handles the case of zext(trunc(x)) -> zext(x).
409f1f57a31SAmjad Aboud       Res = Builder.CreateIntCast(I->getOperand(0), Ty,
410f1f57a31SAmjad Aboud                                   Opc == Instruction::SExt);
411f1f57a31SAmjad Aboud 
412f1f57a31SAmjad Aboud       // Update Worklist entries with new value if needed.
413b86b771cSAmjad Aboud       // There are three possible changes to the Worklist:
414b86b771cSAmjad Aboud       // 1. Update Old-TruncInst -> New-TruncInst.
415b86b771cSAmjad Aboud       // 2. Remove Old-TruncInst (if New node is not TruncInst).
416b86b771cSAmjad Aboud       // 3. Add New-TruncInst (if Old node was not TruncInst).
4175e8e89d8SSimon Pilgrim       auto *Entry = find(Worklist, I);
418b86b771cSAmjad Aboud       if (Entry != Worklist.end()) {
419b86b771cSAmjad Aboud         if (auto *NewCI = dyn_cast<TruncInst>(Res))
420f1f57a31SAmjad Aboud           *Entry = NewCI;
421b86b771cSAmjad Aboud         else
422b86b771cSAmjad Aboud           Worklist.erase(Entry);
423b86b771cSAmjad Aboud       } else if (auto *NewCI = dyn_cast<TruncInst>(Res))
424b86b771cSAmjad Aboud           Worklist.push_back(NewCI);
425f1f57a31SAmjad Aboud       break;
426f1f57a31SAmjad Aboud     }
427f1f57a31SAmjad Aboud     case Instruction::Add:
428f1f57a31SAmjad Aboud     case Instruction::Sub:
429f1f57a31SAmjad Aboud     case Instruction::Mul:
430f1f57a31SAmjad Aboud     case Instruction::And:
431f1f57a31SAmjad Aboud     case Instruction::Or:
4321f3e35b6SAnton Afanasyev     case Instruction::Xor:
433cfb6dfcbSAnton Afanasyev     case Instruction::Shl:
434bed58763SAnton Afanasyev     case Instruction::LShr:
43554d8ebbbSAnton Afanasyev     case Instruction::AShr:
43654d8ebbbSAnton Afanasyev     case Instruction::UDiv:
43754d8ebbbSAnton Afanasyev     case Instruction::URem: {
438f1f57a31SAmjad Aboud       Value *LHS = getReducedOperand(I->getOperand(0), SclTy);
439f1f57a31SAmjad Aboud       Value *RHS = getReducedOperand(I->getOperand(1), SclTy);
440f1f57a31SAmjad Aboud       Res = Builder.CreateBinOp((Instruction::BinaryOps)Opc, LHS, RHS);
441cfb6dfcbSAnton Afanasyev       // Preserve `exact` flag since truncation doesn't change exactness
442bed58763SAnton Afanasyev       if (auto *PEO = dyn_cast<PossiblyExactOperator>(I))
443dd19f342SSanjay Patel         if (auto *ResI = dyn_cast<Instruction>(Res))
444bed58763SAnton Afanasyev           ResI->setIsExact(PEO->isExact());
445f1f57a31SAmjad Aboud       break;
446f1f57a31SAmjad Aboud     }
4476a5f49a1SAnton Afanasyev     case Instruction::ExtractElement: {
4486a5f49a1SAnton Afanasyev       Value *Vec = getReducedOperand(I->getOperand(0), SclTy);
4496a5f49a1SAnton Afanasyev       Value *Idx = I->getOperand(1);
4506a5f49a1SAnton Afanasyev       Res = Builder.CreateExtractElement(Vec, Idx);
4516a5f49a1SAnton Afanasyev       break;
4526a5f49a1SAnton Afanasyev     }
4536a5f49a1SAnton Afanasyev     case Instruction::InsertElement: {
4546a5f49a1SAnton Afanasyev       Value *Vec = getReducedOperand(I->getOperand(0), SclTy);
4556a5f49a1SAnton Afanasyev       Value *NewElt = getReducedOperand(I->getOperand(1), SclTy);
4566a5f49a1SAnton Afanasyev       Value *Idx = I->getOperand(2);
4576a5f49a1SAnton Afanasyev       Res = Builder.CreateInsertElement(Vec, NewElt, Idx);
4586a5f49a1SAnton Afanasyev       break;
4596a5f49a1SAnton Afanasyev     }
4603bda9059SAyman Musa     case Instruction::Select: {
4613bda9059SAyman Musa       Value *Op0 = I->getOperand(0);
4623bda9059SAyman Musa       Value *LHS = getReducedOperand(I->getOperand(1), SclTy);
4633bda9059SAyman Musa       Value *RHS = getReducedOperand(I->getOperand(2), SclTy);
4643bda9059SAyman Musa       Res = Builder.CreateSelect(Op0, LHS, RHS);
4653bda9059SAyman Musa       break;
4663bda9059SAyman Musa     }
4670dd84013SAnton Afanasyev     case Instruction::PHI: {
4680dd84013SAnton Afanasyev       Res = Builder.CreatePHI(getReducedType(I, SclTy), I->getNumOperands());
4690dd84013SAnton Afanasyev       OldNewPHINodes.push_back(
4700dd84013SAnton Afanasyev           std::make_pair(cast<PHINode>(I), cast<PHINode>(Res)));
4710dd84013SAnton Afanasyev       break;
4720dd84013SAnton Afanasyev     }
473f1f57a31SAmjad Aboud     default:
474f1f57a31SAmjad Aboud       llvm_unreachable("Unhandled instruction");
475f1f57a31SAmjad Aboud     }
476f1f57a31SAmjad Aboud 
477f1f57a31SAmjad Aboud     NodeInfo.NewValue = Res;
478f1f57a31SAmjad Aboud     if (auto *ResI = dyn_cast<Instruction>(Res))
479f1f57a31SAmjad Aboud       ResI->takeName(I);
480f1f57a31SAmjad Aboud   }
481f1f57a31SAmjad Aboud 
4820dd84013SAnton Afanasyev   for (auto &Node : OldNewPHINodes) {
4830dd84013SAnton Afanasyev     PHINode *OldPN = Node.first;
4840dd84013SAnton Afanasyev     PHINode *NewPN = Node.second;
4850dd84013SAnton Afanasyev     for (auto Incoming : zip(OldPN->incoming_values(), OldPN->blocks()))
4860dd84013SAnton Afanasyev       NewPN->addIncoming(getReducedOperand(std::get<0>(Incoming), SclTy),
4870dd84013SAnton Afanasyev                          std::get<1>(Incoming));
4880dd84013SAnton Afanasyev   }
4890dd84013SAnton Afanasyev 
490f1f57a31SAmjad Aboud   Value *Res = getReducedOperand(CurrentTruncInst->getOperand(0), SclTy);
491f1f57a31SAmjad Aboud   Type *DstTy = CurrentTruncInst->getType();
492f1f57a31SAmjad Aboud   if (Res->getType() != DstTy) {
493f1f57a31SAmjad Aboud     IRBuilder<> Builder(CurrentTruncInst);
494f1f57a31SAmjad Aboud     Res = Builder.CreateIntCast(Res, DstTy, false);
495f1f57a31SAmjad Aboud     if (auto *ResI = dyn_cast<Instruction>(Res))
496f1f57a31SAmjad Aboud       ResI->takeName(CurrentTruncInst);
497f1f57a31SAmjad Aboud   }
498f1f57a31SAmjad Aboud   CurrentTruncInst->replaceAllUsesWith(Res);
499f1f57a31SAmjad Aboud 
5000dd84013SAnton Afanasyev   // Erase old expression graph, which was replaced by the reduced expression
5010dd84013SAnton Afanasyev   // graph.
5028ad6d5e4SAnton Afanasyev   CurrentTruncInst->eraseFromParent();
5030dd84013SAnton Afanasyev   // First, erase old phi-nodes and its uses
5040dd84013SAnton Afanasyev   for (auto &Node : OldNewPHINodes) {
5050dd84013SAnton Afanasyev     PHINode *OldPN = Node.first;
5060dd84013SAnton Afanasyev     OldPN->replaceAllUsesWith(PoisonValue::get(OldPN->getType()));
507*904a00d1SAnton Afanasyev     InstInfoMap.erase(OldPN);
5080dd84013SAnton Afanasyev     OldPN->eraseFromParent();
5090dd84013SAnton Afanasyev   }
5100dd84013SAnton Afanasyev   // Now we have expression graph turned into dag.
5110dd84013SAnton Afanasyev   // We iterate backward, which means we visit the instruction before we
5120dd84013SAnton Afanasyev   // visit any of its operands, this way, when we get to the operand, we already
5130dd84013SAnton Afanasyev   // removed the instructions (from the expression dag) that uses it.
5147787a8f1SKazu Hirata   for (auto &I : llvm::reverse(InstInfoMap)) {
515f1f57a31SAmjad Aboud     // We still need to check that the instruction has no users before we erase
516f1f57a31SAmjad Aboud     // it, because {SExt, ZExt}Inst Instruction might have other users that was
517f1f57a31SAmjad Aboud     // not reduced, in such case, we need to keep that instruction.
5187787a8f1SKazu Hirata     if (I.first->use_empty())
5197787a8f1SKazu Hirata       I.first->eraseFromParent();
5200dd84013SAnton Afanasyev     else
5210dd84013SAnton Afanasyev       assert((isa<SExtInst>(I.first) || isa<ZExtInst>(I.first)) &&
5220dd84013SAnton Afanasyev              "Only {SExt, ZExt}Inst might have unreduced users");
523f1f57a31SAmjad Aboud   }
524f1f57a31SAmjad Aboud }
525f1f57a31SAmjad Aboud 
526f1f57a31SAmjad Aboud bool TruncInstCombine::run(Function &F) {
527f1f57a31SAmjad Aboud   bool MadeIRChange = false;
528f1f57a31SAmjad Aboud 
529f1f57a31SAmjad Aboud   // Collect all TruncInst in the function into the Worklist for evaluating.
530d895bff5SAmjad Aboud   for (auto &BB : F) {
531d895bff5SAmjad Aboud     // Ignore unreachable basic block.
532d895bff5SAmjad Aboud     if (!DT.isReachableFromEntry(&BB))
533d895bff5SAmjad Aboud       continue;
534f1f57a31SAmjad Aboud     for (auto &I : BB)
535f1f57a31SAmjad Aboud       if (auto *CI = dyn_cast<TruncInst>(&I))
536f1f57a31SAmjad Aboud         Worklist.push_back(CI);
537d895bff5SAmjad Aboud   }
538f1f57a31SAmjad Aboud 
539f1f57a31SAmjad Aboud   // Process all TruncInst in the Worklist, for each instruction:
5400dd84013SAnton Afanasyev   //   1. Check if it dominates an eligible expression graph to be reduced.
5410dd84013SAnton Afanasyev   //   2. Create a reduced expression graph and replace the old one with it.
542f1f57a31SAmjad Aboud   while (!Worklist.empty()) {
543f1f57a31SAmjad Aboud     CurrentTruncInst = Worklist.pop_back_val();
544f1f57a31SAmjad Aboud 
545f1f57a31SAmjad Aboud     if (Type *NewDstSclTy = getBestTruncatedType()) {
546d34e60caSNicola Zaghen       LLVM_DEBUG(
5470dd84013SAnton Afanasyev           dbgs() << "ICE: TruncInstCombine reducing type of expression graph "
548f1f57a31SAmjad Aboud                     "dominated by: "
549f1f57a31SAmjad Aboud                  << CurrentTruncInst << '\n');
5500dd84013SAnton Afanasyev       ReduceExpressionGraph(NewDstSclTy);
5510dd84013SAnton Afanasyev       ++NumExprsReduced;
552f1f57a31SAmjad Aboud       MadeIRChange = true;
553f1f57a31SAmjad Aboud     }
554f1f57a31SAmjad Aboud   }
555f1f57a31SAmjad Aboud 
556f1f57a31SAmjad Aboud   return MadeIRChange;
557f1f57a31SAmjad Aboud }
558