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 //
9f1f57a31SAmjad Aboud // TruncInstCombine - looks for expression dags post-dominated by TruncInst and
10f1f57a31SAmjad Aboud // for each eligible dag, it will create a reduced bit-width expression, replace
11f1f57a31SAmjad Aboud // the old expression with this new one and remove the old expression.
12f1f57a31SAmjad Aboud // Eligible expression dag 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.
16f1f57a31SAmjad Aboud //   4. All instructions in the dag must not have users outside the dag.
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"
321f3e35b6SAnton Afanasyev #include "llvm/Analysis/ValueTracking.h"
33f1f57a31SAmjad Aboud #include "llvm/IR/DataLayout.h"
34d895bff5SAmjad Aboud #include "llvm/IR/Dominators.h"
35f1f57a31SAmjad Aboud #include "llvm/IR/IRBuilder.h"
360347f3eaSSimon Pilgrim #include "llvm/IR/Instruction.h"
371f3e35b6SAnton Afanasyev #include "llvm/Support/KnownBits.h"
38e987ee63SRoman Lebedev 
39f1f57a31SAmjad Aboud using namespace llvm;
40f1f57a31SAmjad Aboud 
41f1f57a31SAmjad Aboud #define DEBUG_TYPE "aggressive-instcombine"
42f1f57a31SAmjad Aboud 
43e987ee63SRoman Lebedev STATISTIC(
44e987ee63SRoman Lebedev     NumDAGsReduced,
45e987ee63SRoman Lebedev     "Number of truncations eliminated by reducing bit width of expression DAG");
46e987ee63SRoman Lebedev STATISTIC(NumInstrsReduced,
47e987ee63SRoman Lebedev           "Number of instructions whose bit width was reduced");
48e987ee63SRoman Lebedev 
49f1f57a31SAmjad Aboud /// Given an instruction and a container, it fills all the relevant operands of
50f1f57a31SAmjad Aboud /// that instruction, with respect to the Trunc expression dag optimizaton.
51f1f57a31SAmjad Aboud static void getRelevantOperands(Instruction *I, SmallVectorImpl<Value *> &Ops) {
52f1f57a31SAmjad Aboud   unsigned Opc = I->getOpcode();
53f1f57a31SAmjad Aboud   switch (Opc) {
54f1f57a31SAmjad Aboud   case Instruction::Trunc:
55f1f57a31SAmjad Aboud   case Instruction::ZExt:
56f1f57a31SAmjad Aboud   case Instruction::SExt:
57f1f57a31SAmjad Aboud     // These CastInst are considered leaves of the evaluated expression, thus,
58f1f57a31SAmjad Aboud     // their operands are not relevent.
59f1f57a31SAmjad Aboud     break;
60f1f57a31SAmjad Aboud   case Instruction::Add:
61f1f57a31SAmjad Aboud   case Instruction::Sub:
62f1f57a31SAmjad Aboud   case Instruction::Mul:
63f1f57a31SAmjad Aboud   case Instruction::And:
64f1f57a31SAmjad Aboud   case Instruction::Or:
65f1f57a31SAmjad Aboud   case Instruction::Xor:
661f3e35b6SAnton Afanasyev   case Instruction::Shl:
67cfb6dfcbSAnton Afanasyev   case Instruction::LShr:
68*bed58763SAnton Afanasyev   case Instruction::AShr:
69f1f57a31SAmjad Aboud     Ops.push_back(I->getOperand(0));
70f1f57a31SAmjad Aboud     Ops.push_back(I->getOperand(1));
71f1f57a31SAmjad Aboud     break;
723bda9059SAyman Musa   case Instruction::Select:
733bda9059SAyman Musa     Ops.push_back(I->getOperand(1));
743bda9059SAyman Musa     Ops.push_back(I->getOperand(2));
753bda9059SAyman Musa     break;
76f1f57a31SAmjad Aboud   default:
77f1f57a31SAmjad Aboud     llvm_unreachable("Unreachable!");
78f1f57a31SAmjad Aboud   }
79f1f57a31SAmjad Aboud }
80f1f57a31SAmjad Aboud 
81f1f57a31SAmjad Aboud bool TruncInstCombine::buildTruncExpressionDag() {
82f1f57a31SAmjad Aboud   SmallVector<Value *, 8> Worklist;
83f1f57a31SAmjad Aboud   SmallVector<Instruction *, 8> Stack;
84f1f57a31SAmjad Aboud   // Clear old expression dag.
85f1f57a31SAmjad Aboud   InstInfoMap.clear();
86f1f57a31SAmjad Aboud 
87f1f57a31SAmjad Aboud   Worklist.push_back(CurrentTruncInst->getOperand(0));
88f1f57a31SAmjad Aboud 
89f1f57a31SAmjad Aboud   while (!Worklist.empty()) {
90f1f57a31SAmjad Aboud     Value *Curr = Worklist.back();
91f1f57a31SAmjad Aboud 
92f1f57a31SAmjad Aboud     if (isa<Constant>(Curr)) {
93f1f57a31SAmjad Aboud       Worklist.pop_back();
94f1f57a31SAmjad Aboud       continue;
95f1f57a31SAmjad Aboud     }
96f1f57a31SAmjad Aboud 
97f1f57a31SAmjad Aboud     auto *I = dyn_cast<Instruction>(Curr);
98f1f57a31SAmjad Aboud     if (!I)
99f1f57a31SAmjad Aboud       return false;
100f1f57a31SAmjad Aboud 
101f1f57a31SAmjad Aboud     if (!Stack.empty() && Stack.back() == I) {
102f1f57a31SAmjad Aboud       // Already handled all instruction operands, can remove it from both the
103f1f57a31SAmjad Aboud       // Worklist and the Stack, and add it to the instruction info map.
104f1f57a31SAmjad Aboud       Worklist.pop_back();
105f1f57a31SAmjad Aboud       Stack.pop_back();
106f1f57a31SAmjad Aboud       // Insert I to the Info map.
107f1f57a31SAmjad Aboud       InstInfoMap.insert(std::make_pair(I, Info()));
108f1f57a31SAmjad Aboud       continue;
109f1f57a31SAmjad Aboud     }
110f1f57a31SAmjad Aboud 
111f1f57a31SAmjad Aboud     if (InstInfoMap.count(I)) {
112f1f57a31SAmjad Aboud       Worklist.pop_back();
113f1f57a31SAmjad Aboud       continue;
114f1f57a31SAmjad Aboud     }
115f1f57a31SAmjad Aboud 
116f1f57a31SAmjad Aboud     // Add the instruction to the stack before start handling its operands.
117f1f57a31SAmjad Aboud     Stack.push_back(I);
118f1f57a31SAmjad Aboud 
119f1f57a31SAmjad Aboud     unsigned Opc = I->getOpcode();
120f1f57a31SAmjad Aboud     switch (Opc) {
121f1f57a31SAmjad Aboud     case Instruction::Trunc:
122f1f57a31SAmjad Aboud     case Instruction::ZExt:
123f1f57a31SAmjad Aboud     case Instruction::SExt:
124f1f57a31SAmjad Aboud       // trunc(trunc(x)) -> trunc(x)
125f1f57a31SAmjad Aboud       // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
126f1f57a31SAmjad Aboud       // trunc(ext(x)) -> trunc(x) if the source type is larger than the new
127f1f57a31SAmjad Aboud       // dest
128f1f57a31SAmjad Aboud       break;
129f1f57a31SAmjad Aboud     case Instruction::Add:
130f1f57a31SAmjad Aboud     case Instruction::Sub:
131f1f57a31SAmjad Aboud     case Instruction::Mul:
132f1f57a31SAmjad Aboud     case Instruction::And:
133f1f57a31SAmjad Aboud     case Instruction::Or:
1343bda9059SAyman Musa     case Instruction::Xor:
1351f3e35b6SAnton Afanasyev     case Instruction::Shl:
136cfb6dfcbSAnton Afanasyev     case Instruction::LShr:
137*bed58763SAnton Afanasyev     case Instruction::AShr:
13835f02aa0SAyman Musa     case Instruction::Select: {
139f1f57a31SAmjad Aboud       SmallVector<Value *, 2> Operands;
140f1f57a31SAmjad Aboud       getRelevantOperands(I, Operands);
141e53472deSKazu Hirata       append_range(Worklist, Operands);
142f1f57a31SAmjad Aboud       break;
143f1f57a31SAmjad Aboud     }
144f1f57a31SAmjad Aboud     default:
145f1f57a31SAmjad Aboud       // TODO: Can handle more cases here:
1463bda9059SAyman Musa       // 1. shufflevector, extractelement, insertelement
147f1f57a31SAmjad Aboud       // 2. udiv, urem
148*bed58763SAnton Afanasyev       // 3. phi node(and loop handling)
149f1f57a31SAmjad Aboud       // ...
150f1f57a31SAmjad Aboud       return false;
151f1f57a31SAmjad Aboud     }
152f1f57a31SAmjad Aboud   }
153f1f57a31SAmjad Aboud   return true;
154f1f57a31SAmjad Aboud }
155f1f57a31SAmjad Aboud 
156f1f57a31SAmjad Aboud unsigned TruncInstCombine::getMinBitWidth() {
157f1f57a31SAmjad Aboud   SmallVector<Value *, 8> Worklist;
158f1f57a31SAmjad Aboud   SmallVector<Instruction *, 8> Stack;
159f1f57a31SAmjad Aboud 
160f1f57a31SAmjad Aboud   Value *Src = CurrentTruncInst->getOperand(0);
161f1f57a31SAmjad Aboud   Type *DstTy = CurrentTruncInst->getType();
162f1f57a31SAmjad Aboud   unsigned TruncBitWidth = DstTy->getScalarSizeInBits();
163f1f57a31SAmjad Aboud   unsigned OrigBitWidth =
164f1f57a31SAmjad Aboud       CurrentTruncInst->getOperand(0)->getType()->getScalarSizeInBits();
165f1f57a31SAmjad Aboud 
166f1f57a31SAmjad Aboud   if (isa<Constant>(Src))
167f1f57a31SAmjad Aboud     return TruncBitWidth;
168f1f57a31SAmjad Aboud 
169f1f57a31SAmjad Aboud   Worklist.push_back(Src);
170f1f57a31SAmjad Aboud   InstInfoMap[cast<Instruction>(Src)].ValidBitWidth = TruncBitWidth;
171f1f57a31SAmjad Aboud 
172f1f57a31SAmjad Aboud   while (!Worklist.empty()) {
173f1f57a31SAmjad Aboud     Value *Curr = Worklist.back();
174f1f57a31SAmjad Aboud 
175f1f57a31SAmjad Aboud     if (isa<Constant>(Curr)) {
176f1f57a31SAmjad Aboud       Worklist.pop_back();
177f1f57a31SAmjad Aboud       continue;
178f1f57a31SAmjad Aboud     }
179f1f57a31SAmjad Aboud 
180f1f57a31SAmjad Aboud     // Otherwise, it must be an instruction.
181f1f57a31SAmjad Aboud     auto *I = cast<Instruction>(Curr);
182f1f57a31SAmjad Aboud 
183f1f57a31SAmjad Aboud     auto &Info = InstInfoMap[I];
184f1f57a31SAmjad Aboud 
185f1f57a31SAmjad Aboud     SmallVector<Value *, 2> Operands;
186f1f57a31SAmjad Aboud     getRelevantOperands(I, Operands);
187f1f57a31SAmjad Aboud 
188f1f57a31SAmjad Aboud     if (!Stack.empty() && Stack.back() == I) {
189f1f57a31SAmjad Aboud       // Already handled all instruction operands, can remove it from both, the
190f1f57a31SAmjad Aboud       // Worklist and the Stack, and update MinBitWidth.
191f1f57a31SAmjad Aboud       Worklist.pop_back();
192f1f57a31SAmjad Aboud       Stack.pop_back();
193f1f57a31SAmjad Aboud       for (auto *Operand : Operands)
194f1f57a31SAmjad Aboud         if (auto *IOp = dyn_cast<Instruction>(Operand))
195f1f57a31SAmjad Aboud           Info.MinBitWidth =
196f1f57a31SAmjad Aboud               std::max(Info.MinBitWidth, InstInfoMap[IOp].MinBitWidth);
197f1f57a31SAmjad Aboud       continue;
198f1f57a31SAmjad Aboud     }
199f1f57a31SAmjad Aboud 
200f1f57a31SAmjad Aboud     // Add the instruction to the stack before start handling its operands.
201f1f57a31SAmjad Aboud     Stack.push_back(I);
202f1f57a31SAmjad Aboud     unsigned ValidBitWidth = Info.ValidBitWidth;
203f1f57a31SAmjad Aboud 
204f1f57a31SAmjad Aboud     // Update minimum bit-width before handling its operands. This is required
205f1f57a31SAmjad Aboud     // when the instruction is part of a loop.
206f1f57a31SAmjad Aboud     Info.MinBitWidth = std::max(Info.MinBitWidth, Info.ValidBitWidth);
207f1f57a31SAmjad Aboud 
208f1f57a31SAmjad Aboud     for (auto *Operand : Operands)
209f1f57a31SAmjad Aboud       if (auto *IOp = dyn_cast<Instruction>(Operand)) {
210f1f57a31SAmjad Aboud         // If we already calculated the minimum bit-width for this valid
211f1f57a31SAmjad Aboud         // bit-width, or for a smaller valid bit-width, then just keep the
212f1f57a31SAmjad Aboud         // answer we already calculated.
213f1f57a31SAmjad Aboud         unsigned IOpBitwidth = InstInfoMap.lookup(IOp).ValidBitWidth;
214f1f57a31SAmjad Aboud         if (IOpBitwidth >= ValidBitWidth)
215f1f57a31SAmjad Aboud           continue;
21649a4d85fSAyman Musa         InstInfoMap[IOp].ValidBitWidth = ValidBitWidth;
217f1f57a31SAmjad Aboud         Worklist.push_back(IOp);
218f1f57a31SAmjad Aboud       }
219f1f57a31SAmjad Aboud   }
220f1f57a31SAmjad Aboud   unsigned MinBitWidth = InstInfoMap.lookup(cast<Instruction>(Src)).MinBitWidth;
221f1f57a31SAmjad Aboud   assert(MinBitWidth >= TruncBitWidth);
222f1f57a31SAmjad Aboud 
223f1f57a31SAmjad Aboud   if (MinBitWidth > TruncBitWidth) {
224f1f57a31SAmjad Aboud     // In this case reducing expression with vector type might generate a new
225f1f57a31SAmjad Aboud     // vector type, which is not preferable as it might result in generating
226f1f57a31SAmjad Aboud     // sub-optimal code.
227f1f57a31SAmjad Aboud     if (DstTy->isVectorTy())
228f1f57a31SAmjad Aboud       return OrigBitWidth;
229f1f57a31SAmjad Aboud     // Use the smallest integer type in the range [MinBitWidth, OrigBitWidth).
230f1f57a31SAmjad Aboud     Type *Ty = DL.getSmallestLegalIntType(DstTy->getContext(), MinBitWidth);
231f1f57a31SAmjad Aboud     // Update minimum bit-width with the new destination type bit-width if
232f1f57a31SAmjad Aboud     // succeeded to find such, otherwise, with original bit-width.
233f1f57a31SAmjad Aboud     MinBitWidth = Ty ? Ty->getScalarSizeInBits() : OrigBitWidth;
234f1f57a31SAmjad Aboud   } else { // MinBitWidth == TruncBitWidth
235f1f57a31SAmjad Aboud     // In this case the expression can be evaluated with the trunc instruction
236f1f57a31SAmjad Aboud     // destination type, and trunc instruction can be omitted. However, we
237f1f57a31SAmjad Aboud     // should not perform the evaluation if the original type is a legal scalar
238f1f57a31SAmjad Aboud     // type and the target type is illegal.
239f1f57a31SAmjad Aboud     bool FromLegal = MinBitWidth == 1 || DL.isLegalInteger(OrigBitWidth);
240f1f57a31SAmjad Aboud     bool ToLegal = MinBitWidth == 1 || DL.isLegalInteger(MinBitWidth);
241f1f57a31SAmjad Aboud     if (!DstTy->isVectorTy() && FromLegal && !ToLegal)
242f1f57a31SAmjad Aboud       return OrigBitWidth;
243f1f57a31SAmjad Aboud   }
244f1f57a31SAmjad Aboud   return MinBitWidth;
245f1f57a31SAmjad Aboud }
246f1f57a31SAmjad Aboud 
247f1f57a31SAmjad Aboud Type *TruncInstCombine::getBestTruncatedType() {
248f1f57a31SAmjad Aboud   if (!buildTruncExpressionDag())
249f1f57a31SAmjad Aboud     return nullptr;
250f1f57a31SAmjad Aboud 
251f1f57a31SAmjad Aboud   // We don't want to duplicate instructions, which isn't profitable. Thus, we
252f1f57a31SAmjad Aboud   // can't shrink something that has multiple users, unless all users are
253f1f57a31SAmjad Aboud   // post-dominated by the trunc instruction, i.e., were visited during the
254f1f57a31SAmjad Aboud   // expression evaluation.
255f1f57a31SAmjad Aboud   unsigned DesiredBitWidth = 0;
256f1f57a31SAmjad Aboud   for (auto Itr : InstInfoMap) {
257f1f57a31SAmjad Aboud     Instruction *I = Itr.first;
258f1f57a31SAmjad Aboud     if (I->hasOneUse())
259f1f57a31SAmjad Aboud       continue;
260f1f57a31SAmjad Aboud     bool IsExtInst = (isa<ZExtInst>(I) || isa<SExtInst>(I));
261f1f57a31SAmjad Aboud     for (auto *U : I->users())
262f1f57a31SAmjad Aboud       if (auto *UI = dyn_cast<Instruction>(U))
263f1f57a31SAmjad Aboud         if (UI != CurrentTruncInst && !InstInfoMap.count(UI)) {
264f1f57a31SAmjad Aboud           if (!IsExtInst)
265f1f57a31SAmjad Aboud             return nullptr;
266f1f57a31SAmjad Aboud           // If this is an extension from the dest type, we can eliminate it,
267f1f57a31SAmjad Aboud           // even if it has multiple users. Thus, update the DesiredBitWidth and
268f1f57a31SAmjad Aboud           // validate all extension instructions agrees on same DesiredBitWidth.
269f1f57a31SAmjad Aboud           unsigned ExtInstBitWidth =
270f1f57a31SAmjad Aboud               I->getOperand(0)->getType()->getScalarSizeInBits();
271f1f57a31SAmjad Aboud           if (DesiredBitWidth && DesiredBitWidth != ExtInstBitWidth)
272f1f57a31SAmjad Aboud             return nullptr;
273f1f57a31SAmjad Aboud           DesiredBitWidth = ExtInstBitWidth;
274f1f57a31SAmjad Aboud         }
275f1f57a31SAmjad Aboud   }
276f1f57a31SAmjad Aboud 
277f1f57a31SAmjad Aboud   unsigned OrigBitWidth =
278f1f57a31SAmjad Aboud       CurrentTruncInst->getOperand(0)->getType()->getScalarSizeInBits();
279f1f57a31SAmjad Aboud 
280cfb6dfcbSAnton Afanasyev   // Initialize MinBitWidth for shift instructions with the minimum number
281*bed58763SAnton Afanasyev   // that is greater than shift amount (i.e. shift amount + 1).
282*bed58763SAnton Afanasyev   // For `lshr` adjust MinBitWidth so that all potentially truncated
283*bed58763SAnton Afanasyev   // bits of the value-to-be-shifted are zeros.
284*bed58763SAnton Afanasyev   // For `ashr` adjust MinBitWidth so that all potentially truncated
285*bed58763SAnton Afanasyev   // bits of the value-to-be-shifted are sign bits (all zeros or ones)
286*bed58763SAnton Afanasyev   // and even one (first) untruncated bit is sign bit.
287*bed58763SAnton Afanasyev   // Exit early if MinBitWidth is not less than original bitwidth.
2881f3e35b6SAnton Afanasyev   for (auto &Itr : InstInfoMap) {
2891f3e35b6SAnton Afanasyev     Instruction *I = Itr.first;
290*bed58763SAnton Afanasyev     if (I->isShift()) {
2911f3e35b6SAnton Afanasyev       KnownBits KnownRHS = computeKnownBits(I->getOperand(1), DL);
292803270c0SAnton Afanasyev       unsigned MinBitWidth = KnownRHS.getMaxValue()
2933890ce70SAnton Afanasyev                                  .uadd_sat(APInt(OrigBitWidth, 1))
2943890ce70SAnton Afanasyev                                  .getLimitedValue(OrigBitWidth);
2953890ce70SAnton Afanasyev       if (MinBitWidth == OrigBitWidth)
2961f3e35b6SAnton Afanasyev         return nullptr;
297cfb6dfcbSAnton Afanasyev       if (I->getOpcode() == Instruction::LShr) {
298cfb6dfcbSAnton Afanasyev         KnownBits KnownLHS = computeKnownBits(I->getOperand(0), DL);
299cfb6dfcbSAnton Afanasyev         MinBitWidth =
300cfb6dfcbSAnton Afanasyev             std::max(MinBitWidth, KnownLHS.getMaxValue().getActiveBits());
301*bed58763SAnton Afanasyev       }
302*bed58763SAnton Afanasyev       if (I->getOpcode() == Instruction::AShr) {
303*bed58763SAnton Afanasyev         unsigned NumSignBits = ComputeNumSignBits(I->getOperand(0), DL);
304*bed58763SAnton Afanasyev         MinBitWidth = std::max(MinBitWidth, OrigBitWidth - NumSignBits + 1);
305*bed58763SAnton Afanasyev       }
306cfb6dfcbSAnton Afanasyev       if (MinBitWidth >= OrigBitWidth)
307cfb6dfcbSAnton Afanasyev         return nullptr;
3081f3e35b6SAnton Afanasyev       Itr.second.MinBitWidth = MinBitWidth;
3091f3e35b6SAnton Afanasyev     }
3101f3e35b6SAnton Afanasyev   }
3111f3e35b6SAnton Afanasyev 
312f1f57a31SAmjad Aboud   // Calculate minimum allowed bit-width allowed for shrinking the currently
313f1f57a31SAmjad Aboud   // visited truncate's operand.
314f1f57a31SAmjad Aboud   unsigned MinBitWidth = getMinBitWidth();
315f1f57a31SAmjad Aboud 
316f1f57a31SAmjad Aboud   // Check that we can shrink to smaller bit-width than original one and that
317f1f57a31SAmjad Aboud   // it is similar to the DesiredBitWidth is such exists.
318f1f57a31SAmjad Aboud   if (MinBitWidth >= OrigBitWidth ||
319f1f57a31SAmjad Aboud       (DesiredBitWidth && DesiredBitWidth != MinBitWidth))
320f1f57a31SAmjad Aboud     return nullptr;
321f1f57a31SAmjad Aboud 
322f1f57a31SAmjad Aboud   return IntegerType::get(CurrentTruncInst->getContext(), MinBitWidth);
323f1f57a31SAmjad Aboud }
324f1f57a31SAmjad Aboud 
325f1f57a31SAmjad Aboud /// Given a reduced scalar type \p Ty and a \p V value, return a reduced type
326f1f57a31SAmjad Aboud /// for \p V, according to its type, if it vector type, return the vector
327f1f57a31SAmjad Aboud /// version of \p Ty, otherwise return \p Ty.
328f1f57a31SAmjad Aboud static Type *getReducedType(Value *V, Type *Ty) {
329f1f57a31SAmjad Aboud   assert(Ty && !Ty->isVectorTy() && "Expect Scalar Type");
330137674f8SJun Ma   if (auto *VTy = dyn_cast<VectorType>(V->getType()))
331137674f8SJun Ma     return VectorType::get(Ty, VTy->getElementCount());
332f1f57a31SAmjad Aboud   return Ty;
333f1f57a31SAmjad Aboud }
334f1f57a31SAmjad Aboud 
335f1f57a31SAmjad Aboud Value *TruncInstCombine::getReducedOperand(Value *V, Type *SclTy) {
336f1f57a31SAmjad Aboud   Type *Ty = getReducedType(V, SclTy);
337f1f57a31SAmjad Aboud   if (auto *C = dyn_cast<Constant>(V)) {
338f1f57a31SAmjad Aboud     C = ConstantExpr::getIntegerCast(C, Ty, false);
339f1f57a31SAmjad Aboud     // If we got a constantexpr back, try to simplify it with DL info.
3400e890cd4SNikita Popov     return ConstantFoldConstant(C, DL, &TLI);
341f1f57a31SAmjad Aboud   }
342f1f57a31SAmjad Aboud 
343f1f57a31SAmjad Aboud   auto *I = cast<Instruction>(V);
344f1f57a31SAmjad Aboud   Info Entry = InstInfoMap.lookup(I);
345f1f57a31SAmjad Aboud   assert(Entry.NewValue);
346f1f57a31SAmjad Aboud   return Entry.NewValue;
347f1f57a31SAmjad Aboud }
348f1f57a31SAmjad Aboud 
349f1f57a31SAmjad Aboud void TruncInstCombine::ReduceExpressionDag(Type *SclTy) {
350e987ee63SRoman Lebedev   NumInstrsReduced += InstInfoMap.size();
351f1f57a31SAmjad Aboud   for (auto &Itr : InstInfoMap) { // Forward
352f1f57a31SAmjad Aboud     Instruction *I = Itr.first;
353f1f57a31SAmjad Aboud     TruncInstCombine::Info &NodeInfo = Itr.second;
354f1f57a31SAmjad Aboud 
355f1f57a31SAmjad Aboud     assert(!NodeInfo.NewValue && "Instruction has been evaluated");
356f1f57a31SAmjad Aboud 
357f1f57a31SAmjad Aboud     IRBuilder<> Builder(I);
358f1f57a31SAmjad Aboud     Value *Res = nullptr;
359f1f57a31SAmjad Aboud     unsigned Opc = I->getOpcode();
360f1f57a31SAmjad Aboud     switch (Opc) {
361f1f57a31SAmjad Aboud     case Instruction::Trunc:
362f1f57a31SAmjad Aboud     case Instruction::ZExt:
363f1f57a31SAmjad Aboud     case Instruction::SExt: {
364f1f57a31SAmjad Aboud       Type *Ty = getReducedType(I, SclTy);
365f1f57a31SAmjad Aboud       // If the source type of the cast is the type we're trying for then we can
366f1f57a31SAmjad Aboud       // just return the source.  There's no need to insert it because it is not
367f1f57a31SAmjad Aboud       // new.
368f1f57a31SAmjad Aboud       if (I->getOperand(0)->getType() == Ty) {
369b86b771cSAmjad Aboud         assert(!isa<TruncInst>(I) && "Cannot reach here with TruncInst");
370f1f57a31SAmjad Aboud         NodeInfo.NewValue = I->getOperand(0);
371f1f57a31SAmjad Aboud         continue;
372f1f57a31SAmjad Aboud       }
373f1f57a31SAmjad Aboud       // Otherwise, must be the same type of cast, so just reinsert a new one.
374f1f57a31SAmjad Aboud       // This also handles the case of zext(trunc(x)) -> zext(x).
375f1f57a31SAmjad Aboud       Res = Builder.CreateIntCast(I->getOperand(0), Ty,
376f1f57a31SAmjad Aboud                                   Opc == Instruction::SExt);
377f1f57a31SAmjad Aboud 
378f1f57a31SAmjad Aboud       // Update Worklist entries with new value if needed.
379b86b771cSAmjad Aboud       // There are three possible changes to the Worklist:
380b86b771cSAmjad Aboud       // 1. Update Old-TruncInst -> New-TruncInst.
381b86b771cSAmjad Aboud       // 2. Remove Old-TruncInst (if New node is not TruncInst).
382b86b771cSAmjad Aboud       // 3. Add New-TruncInst (if Old node was not TruncInst).
3835e8e89d8SSimon Pilgrim       auto *Entry = find(Worklist, I);
384b86b771cSAmjad Aboud       if (Entry != Worklist.end()) {
385b86b771cSAmjad Aboud         if (auto *NewCI = dyn_cast<TruncInst>(Res))
386f1f57a31SAmjad Aboud           *Entry = NewCI;
387b86b771cSAmjad Aboud         else
388b86b771cSAmjad Aboud           Worklist.erase(Entry);
389b86b771cSAmjad Aboud       } else if (auto *NewCI = dyn_cast<TruncInst>(Res))
390b86b771cSAmjad Aboud           Worklist.push_back(NewCI);
391f1f57a31SAmjad Aboud       break;
392f1f57a31SAmjad Aboud     }
393f1f57a31SAmjad Aboud     case Instruction::Add:
394f1f57a31SAmjad Aboud     case Instruction::Sub:
395f1f57a31SAmjad Aboud     case Instruction::Mul:
396f1f57a31SAmjad Aboud     case Instruction::And:
397f1f57a31SAmjad Aboud     case Instruction::Or:
3981f3e35b6SAnton Afanasyev     case Instruction::Xor:
399cfb6dfcbSAnton Afanasyev     case Instruction::Shl:
400*bed58763SAnton Afanasyev     case Instruction::LShr:
401*bed58763SAnton Afanasyev     case Instruction::AShr: {
402f1f57a31SAmjad Aboud       Value *LHS = getReducedOperand(I->getOperand(0), SclTy);
403f1f57a31SAmjad Aboud       Value *RHS = getReducedOperand(I->getOperand(1), SclTy);
404f1f57a31SAmjad Aboud       Res = Builder.CreateBinOp((Instruction::BinaryOps)Opc, LHS, RHS);
405cfb6dfcbSAnton Afanasyev       // Preserve `exact` flag since truncation doesn't change exactness
406*bed58763SAnton Afanasyev       if (auto *PEO = dyn_cast<PossiblyExactOperator>(I))
407dd19f342SSanjay Patel         if (auto *ResI = dyn_cast<Instruction>(Res))
408*bed58763SAnton Afanasyev           ResI->setIsExact(PEO->isExact());
409f1f57a31SAmjad Aboud       break;
410f1f57a31SAmjad Aboud     }
4113bda9059SAyman Musa     case Instruction::Select: {
4123bda9059SAyman Musa       Value *Op0 = I->getOperand(0);
4133bda9059SAyman Musa       Value *LHS = getReducedOperand(I->getOperand(1), SclTy);
4143bda9059SAyman Musa       Value *RHS = getReducedOperand(I->getOperand(2), SclTy);
4153bda9059SAyman Musa       Res = Builder.CreateSelect(Op0, LHS, RHS);
4163bda9059SAyman Musa       break;
4173bda9059SAyman Musa     }
418f1f57a31SAmjad Aboud     default:
419f1f57a31SAmjad Aboud       llvm_unreachable("Unhandled instruction");
420f1f57a31SAmjad Aboud     }
421f1f57a31SAmjad Aboud 
422f1f57a31SAmjad Aboud     NodeInfo.NewValue = Res;
423f1f57a31SAmjad Aboud     if (auto *ResI = dyn_cast<Instruction>(Res))
424f1f57a31SAmjad Aboud       ResI->takeName(I);
425f1f57a31SAmjad Aboud   }
426f1f57a31SAmjad Aboud 
427f1f57a31SAmjad Aboud   Value *Res = getReducedOperand(CurrentTruncInst->getOperand(0), SclTy);
428f1f57a31SAmjad Aboud   Type *DstTy = CurrentTruncInst->getType();
429f1f57a31SAmjad Aboud   if (Res->getType() != DstTy) {
430f1f57a31SAmjad Aboud     IRBuilder<> Builder(CurrentTruncInst);
431f1f57a31SAmjad Aboud     Res = Builder.CreateIntCast(Res, DstTy, false);
432f1f57a31SAmjad Aboud     if (auto *ResI = dyn_cast<Instruction>(Res))
433f1f57a31SAmjad Aboud       ResI->takeName(CurrentTruncInst);
434f1f57a31SAmjad Aboud   }
435f1f57a31SAmjad Aboud   CurrentTruncInst->replaceAllUsesWith(Res);
436f1f57a31SAmjad Aboud 
437f1f57a31SAmjad Aboud   // Erase old expression dag, which was replaced by the reduced expression dag.
438f1f57a31SAmjad Aboud   // We iterate backward, which means we visit the instruction before we visit
439f1f57a31SAmjad Aboud   // any of its operands, this way, when we get to the operand, we already
440f1f57a31SAmjad Aboud   // removed the instructions (from the expression dag) that uses it.
441f1f57a31SAmjad Aboud   CurrentTruncInst->eraseFromParent();
442f1f57a31SAmjad Aboud   for (auto I = InstInfoMap.rbegin(), E = InstInfoMap.rend(); I != E; ++I) {
443f1f57a31SAmjad Aboud     // We still need to check that the instruction has no users before we erase
444f1f57a31SAmjad Aboud     // it, because {SExt, ZExt}Inst Instruction might have other users that was
445f1f57a31SAmjad Aboud     // not reduced, in such case, we need to keep that instruction.
4467fc591f8SVedant Kumar     if (I->first->use_empty())
447f1f57a31SAmjad Aboud       I->first->eraseFromParent();
448f1f57a31SAmjad Aboud   }
449f1f57a31SAmjad Aboud }
450f1f57a31SAmjad Aboud 
451f1f57a31SAmjad Aboud bool TruncInstCombine::run(Function &F) {
452f1f57a31SAmjad Aboud   bool MadeIRChange = false;
453f1f57a31SAmjad Aboud 
454f1f57a31SAmjad Aboud   // Collect all TruncInst in the function into the Worklist for evaluating.
455d895bff5SAmjad Aboud   for (auto &BB : F) {
456d895bff5SAmjad Aboud     // Ignore unreachable basic block.
457d895bff5SAmjad Aboud     if (!DT.isReachableFromEntry(&BB))
458d895bff5SAmjad Aboud       continue;
459f1f57a31SAmjad Aboud     for (auto &I : BB)
460f1f57a31SAmjad Aboud       if (auto *CI = dyn_cast<TruncInst>(&I))
461f1f57a31SAmjad Aboud         Worklist.push_back(CI);
462d895bff5SAmjad Aboud   }
463f1f57a31SAmjad Aboud 
464f1f57a31SAmjad Aboud   // Process all TruncInst in the Worklist, for each instruction:
465f1f57a31SAmjad Aboud   //   1. Check if it dominates an eligible expression dag to be reduced.
466f1f57a31SAmjad Aboud   //   2. Create a reduced expression dag and replace the old one with it.
467f1f57a31SAmjad Aboud   while (!Worklist.empty()) {
468f1f57a31SAmjad Aboud     CurrentTruncInst = Worklist.pop_back_val();
469f1f57a31SAmjad Aboud 
470f1f57a31SAmjad Aboud     if (Type *NewDstSclTy = getBestTruncatedType()) {
471d34e60caSNicola Zaghen       LLVM_DEBUG(
472d34e60caSNicola Zaghen           dbgs() << "ICE: TruncInstCombine reducing type of expression dag "
473f1f57a31SAmjad Aboud                     "dominated by: "
474f1f57a31SAmjad Aboud                  << CurrentTruncInst << '\n');
475f1f57a31SAmjad Aboud       ReduceExpressionDag(NewDstSclTy);
476e987ee63SRoman Lebedev       ++NumDAGsReduced;
477f1f57a31SAmjad Aboud       MadeIRChange = true;
478f1f57a31SAmjad Aboud     }
479f1f57a31SAmjad Aboud   }
480f1f57a31SAmjad Aboud 
481f1f57a31SAmjad Aboud   return MadeIRChange;
482f1f57a31SAmjad Aboud }
483