TruncInstCombine.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. //===- TruncInstCombine.cpp -----------------------------------------------===//
  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. // TruncInstCombine - looks for expression dags post-dominated by TruncInst and
  10. // for each eligible dag, it will create a reduced bit-width expression, replace
  11. // the old expression with this new one and remove the old expression.
  12. // Eligible expression dag is such that:
  13. // 1. Contains only supported instructions.
  14. // 2. Supported leaves: ZExtInst, SExtInst, TruncInst and Constant value.
  15. // 3. Can be evaluated into type with reduced legal bit-width.
  16. // 4. All instructions in the dag must not have users outside the dag.
  17. // The only exception is for {ZExt, SExt}Inst with operand type equal to
  18. // the new reduced type evaluated in (3).
  19. //
  20. // The motivation for this optimization is that evaluating and expression using
  21. // smaller bit-width is preferable, especially for vectorization where we can
  22. // fit more values in one vectorized instruction. In addition, this optimization
  23. // may decrease the number of cast instructions, but will not increase it.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "AggressiveInstCombineInternal.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/Statistic.h"
  29. #include "llvm/Analysis/ConstantFolding.h"
  30. #include "llvm/Analysis/TargetLibraryInfo.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/Dominators.h"
  33. #include "llvm/IR/IRBuilder.h"
  34. #include "llvm/IR/Instruction.h"
  35. using namespace llvm;
  36. #define DEBUG_TYPE "aggressive-instcombine"
  37. STATISTIC(
  38. NumDAGsReduced,
  39. "Number of truncations eliminated by reducing bit width of expression DAG");
  40. STATISTIC(NumInstrsReduced,
  41. "Number of instructions whose bit width was reduced");
  42. /// Given an instruction and a container, it fills all the relevant operands of
  43. /// that instruction, with respect to the Trunc expression dag optimizaton.
  44. static void getRelevantOperands(Instruction *I, SmallVectorImpl<Value *> &Ops) {
  45. unsigned Opc = I->getOpcode();
  46. switch (Opc) {
  47. case Instruction::Trunc:
  48. case Instruction::ZExt:
  49. case Instruction::SExt:
  50. // These CastInst are considered leaves of the evaluated expression, thus,
  51. // their operands are not relevent.
  52. break;
  53. case Instruction::Add:
  54. case Instruction::Sub:
  55. case Instruction::Mul:
  56. case Instruction::And:
  57. case Instruction::Or:
  58. case Instruction::Xor:
  59. Ops.push_back(I->getOperand(0));
  60. Ops.push_back(I->getOperand(1));
  61. break;
  62. case Instruction::Select:
  63. Ops.push_back(I->getOperand(1));
  64. Ops.push_back(I->getOperand(2));
  65. break;
  66. default:
  67. llvm_unreachable("Unreachable!");
  68. }
  69. }
  70. bool TruncInstCombine::buildTruncExpressionDag() {
  71. SmallVector<Value *, 8> Worklist;
  72. SmallVector<Instruction *, 8> Stack;
  73. // Clear old expression dag.
  74. InstInfoMap.clear();
  75. Worklist.push_back(CurrentTruncInst->getOperand(0));
  76. while (!Worklist.empty()) {
  77. Value *Curr = Worklist.back();
  78. if (isa<Constant>(Curr)) {
  79. Worklist.pop_back();
  80. continue;
  81. }
  82. auto *I = dyn_cast<Instruction>(Curr);
  83. if (!I)
  84. return false;
  85. if (!Stack.empty() && Stack.back() == I) {
  86. // Already handled all instruction operands, can remove it from both the
  87. // Worklist and the Stack, and add it to the instruction info map.
  88. Worklist.pop_back();
  89. Stack.pop_back();
  90. // Insert I to the Info map.
  91. InstInfoMap.insert(std::make_pair(I, Info()));
  92. continue;
  93. }
  94. if (InstInfoMap.count(I)) {
  95. Worklist.pop_back();
  96. continue;
  97. }
  98. // Add the instruction to the stack before start handling its operands.
  99. Stack.push_back(I);
  100. unsigned Opc = I->getOpcode();
  101. switch (Opc) {
  102. case Instruction::Trunc:
  103. case Instruction::ZExt:
  104. case Instruction::SExt:
  105. // trunc(trunc(x)) -> trunc(x)
  106. // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
  107. // trunc(ext(x)) -> trunc(x) if the source type is larger than the new
  108. // dest
  109. break;
  110. case Instruction::Add:
  111. case Instruction::Sub:
  112. case Instruction::Mul:
  113. case Instruction::And:
  114. case Instruction::Or:
  115. case Instruction::Xor:
  116. case Instruction::Select: {
  117. SmallVector<Value *, 2> Operands;
  118. getRelevantOperands(I, Operands);
  119. append_range(Worklist, Operands);
  120. break;
  121. }
  122. default:
  123. // TODO: Can handle more cases here:
  124. // 1. shufflevector, extractelement, insertelement
  125. // 2. udiv, urem
  126. // 3. shl, lshr, ashr
  127. // 4. phi node(and loop handling)
  128. // ...
  129. return false;
  130. }
  131. }
  132. return true;
  133. }
  134. unsigned TruncInstCombine::getMinBitWidth() {
  135. SmallVector<Value *, 8> Worklist;
  136. SmallVector<Instruction *, 8> Stack;
  137. Value *Src = CurrentTruncInst->getOperand(0);
  138. Type *DstTy = CurrentTruncInst->getType();
  139. unsigned TruncBitWidth = DstTy->getScalarSizeInBits();
  140. unsigned OrigBitWidth =
  141. CurrentTruncInst->getOperand(0)->getType()->getScalarSizeInBits();
  142. if (isa<Constant>(Src))
  143. return TruncBitWidth;
  144. Worklist.push_back(Src);
  145. InstInfoMap[cast<Instruction>(Src)].ValidBitWidth = TruncBitWidth;
  146. while (!Worklist.empty()) {
  147. Value *Curr = Worklist.back();
  148. if (isa<Constant>(Curr)) {
  149. Worklist.pop_back();
  150. continue;
  151. }
  152. // Otherwise, it must be an instruction.
  153. auto *I = cast<Instruction>(Curr);
  154. auto &Info = InstInfoMap[I];
  155. SmallVector<Value *, 2> Operands;
  156. getRelevantOperands(I, Operands);
  157. if (!Stack.empty() && Stack.back() == I) {
  158. // Already handled all instruction operands, can remove it from both, the
  159. // Worklist and the Stack, and update MinBitWidth.
  160. Worklist.pop_back();
  161. Stack.pop_back();
  162. for (auto *Operand : Operands)
  163. if (auto *IOp = dyn_cast<Instruction>(Operand))
  164. Info.MinBitWidth =
  165. std::max(Info.MinBitWidth, InstInfoMap[IOp].MinBitWidth);
  166. continue;
  167. }
  168. // Add the instruction to the stack before start handling its operands.
  169. Stack.push_back(I);
  170. unsigned ValidBitWidth = Info.ValidBitWidth;
  171. // Update minimum bit-width before handling its operands. This is required
  172. // when the instruction is part of a loop.
  173. Info.MinBitWidth = std::max(Info.MinBitWidth, Info.ValidBitWidth);
  174. for (auto *Operand : Operands)
  175. if (auto *IOp = dyn_cast<Instruction>(Operand)) {
  176. // If we already calculated the minimum bit-width for this valid
  177. // bit-width, or for a smaller valid bit-width, then just keep the
  178. // answer we already calculated.
  179. unsigned IOpBitwidth = InstInfoMap.lookup(IOp).ValidBitWidth;
  180. if (IOpBitwidth >= ValidBitWidth)
  181. continue;
  182. InstInfoMap[IOp].ValidBitWidth = ValidBitWidth;
  183. Worklist.push_back(IOp);
  184. }
  185. }
  186. unsigned MinBitWidth = InstInfoMap.lookup(cast<Instruction>(Src)).MinBitWidth;
  187. assert(MinBitWidth >= TruncBitWidth);
  188. if (MinBitWidth > TruncBitWidth) {
  189. // In this case reducing expression with vector type might generate a new
  190. // vector type, which is not preferable as it might result in generating
  191. // sub-optimal code.
  192. if (DstTy->isVectorTy())
  193. return OrigBitWidth;
  194. // Use the smallest integer type in the range [MinBitWidth, OrigBitWidth).
  195. Type *Ty = DL.getSmallestLegalIntType(DstTy->getContext(), MinBitWidth);
  196. // Update minimum bit-width with the new destination type bit-width if
  197. // succeeded to find such, otherwise, with original bit-width.
  198. MinBitWidth = Ty ? Ty->getScalarSizeInBits() : OrigBitWidth;
  199. } else { // MinBitWidth == TruncBitWidth
  200. // In this case the expression can be evaluated with the trunc instruction
  201. // destination type, and trunc instruction can be omitted. However, we
  202. // should not perform the evaluation if the original type is a legal scalar
  203. // type and the target type is illegal.
  204. bool FromLegal = MinBitWidth == 1 || DL.isLegalInteger(OrigBitWidth);
  205. bool ToLegal = MinBitWidth == 1 || DL.isLegalInteger(MinBitWidth);
  206. if (!DstTy->isVectorTy() && FromLegal && !ToLegal)
  207. return OrigBitWidth;
  208. }
  209. return MinBitWidth;
  210. }
  211. Type *TruncInstCombine::getBestTruncatedType() {
  212. if (!buildTruncExpressionDag())
  213. return nullptr;
  214. // We don't want to duplicate instructions, which isn't profitable. Thus, we
  215. // can't shrink something that has multiple users, unless all users are
  216. // post-dominated by the trunc instruction, i.e., were visited during the
  217. // expression evaluation.
  218. unsigned DesiredBitWidth = 0;
  219. for (auto Itr : InstInfoMap) {
  220. Instruction *I = Itr.first;
  221. if (I->hasOneUse())
  222. continue;
  223. bool IsExtInst = (isa<ZExtInst>(I) || isa<SExtInst>(I));
  224. for (auto *U : I->users())
  225. if (auto *UI = dyn_cast<Instruction>(U))
  226. if (UI != CurrentTruncInst && !InstInfoMap.count(UI)) {
  227. if (!IsExtInst)
  228. return nullptr;
  229. // If this is an extension from the dest type, we can eliminate it,
  230. // even if it has multiple users. Thus, update the DesiredBitWidth and
  231. // validate all extension instructions agrees on same DesiredBitWidth.
  232. unsigned ExtInstBitWidth =
  233. I->getOperand(0)->getType()->getScalarSizeInBits();
  234. if (DesiredBitWidth && DesiredBitWidth != ExtInstBitWidth)
  235. return nullptr;
  236. DesiredBitWidth = ExtInstBitWidth;
  237. }
  238. }
  239. unsigned OrigBitWidth =
  240. CurrentTruncInst->getOperand(0)->getType()->getScalarSizeInBits();
  241. // Calculate minimum allowed bit-width allowed for shrinking the currently
  242. // visited truncate's operand.
  243. unsigned MinBitWidth = getMinBitWidth();
  244. // Check that we can shrink to smaller bit-width than original one and that
  245. // it is similar to the DesiredBitWidth is such exists.
  246. if (MinBitWidth >= OrigBitWidth ||
  247. (DesiredBitWidth && DesiredBitWidth != MinBitWidth))
  248. return nullptr;
  249. return IntegerType::get(CurrentTruncInst->getContext(), MinBitWidth);
  250. }
  251. /// Given a reduced scalar type \p Ty and a \p V value, return a reduced type
  252. /// for \p V, according to its type, if it vector type, return the vector
  253. /// version of \p Ty, otherwise return \p Ty.
  254. static Type *getReducedType(Value *V, Type *Ty) {
  255. assert(Ty && !Ty->isVectorTy() && "Expect Scalar Type");
  256. if (auto *VTy = dyn_cast<VectorType>(V->getType()))
  257. return VectorType::get(Ty, VTy->getElementCount());
  258. return Ty;
  259. }
  260. Value *TruncInstCombine::getReducedOperand(Value *V, Type *SclTy) {
  261. Type *Ty = getReducedType(V, SclTy);
  262. if (auto *C = dyn_cast<Constant>(V)) {
  263. C = ConstantExpr::getIntegerCast(C, Ty, false);
  264. // If we got a constantexpr back, try to simplify it with DL info.
  265. return ConstantFoldConstant(C, DL, &TLI);
  266. }
  267. auto *I = cast<Instruction>(V);
  268. Info Entry = InstInfoMap.lookup(I);
  269. assert(Entry.NewValue);
  270. return Entry.NewValue;
  271. }
  272. void TruncInstCombine::ReduceExpressionDag(Type *SclTy) {
  273. NumInstrsReduced += InstInfoMap.size();
  274. for (auto &Itr : InstInfoMap) { // Forward
  275. Instruction *I = Itr.first;
  276. TruncInstCombine::Info &NodeInfo = Itr.second;
  277. assert(!NodeInfo.NewValue && "Instruction has been evaluated");
  278. IRBuilder<> Builder(I);
  279. Value *Res = nullptr;
  280. unsigned Opc = I->getOpcode();
  281. switch (Opc) {
  282. case Instruction::Trunc:
  283. case Instruction::ZExt:
  284. case Instruction::SExt: {
  285. Type *Ty = getReducedType(I, SclTy);
  286. // If the source type of the cast is the type we're trying for then we can
  287. // just return the source. There's no need to insert it because it is not
  288. // new.
  289. if (I->getOperand(0)->getType() == Ty) {
  290. assert(!isa<TruncInst>(I) && "Cannot reach here with TruncInst");
  291. NodeInfo.NewValue = I->getOperand(0);
  292. continue;
  293. }
  294. // Otherwise, must be the same type of cast, so just reinsert a new one.
  295. // This also handles the case of zext(trunc(x)) -> zext(x).
  296. Res = Builder.CreateIntCast(I->getOperand(0), Ty,
  297. Opc == Instruction::SExt);
  298. // Update Worklist entries with new value if needed.
  299. // There are three possible changes to the Worklist:
  300. // 1. Update Old-TruncInst -> New-TruncInst.
  301. // 2. Remove Old-TruncInst (if New node is not TruncInst).
  302. // 3. Add New-TruncInst (if Old node was not TruncInst).
  303. auto *Entry = find(Worklist, I);
  304. if (Entry != Worklist.end()) {
  305. if (auto *NewCI = dyn_cast<TruncInst>(Res))
  306. *Entry = NewCI;
  307. else
  308. Worklist.erase(Entry);
  309. } else if (auto *NewCI = dyn_cast<TruncInst>(Res))
  310. Worklist.push_back(NewCI);
  311. break;
  312. }
  313. case Instruction::Add:
  314. case Instruction::Sub:
  315. case Instruction::Mul:
  316. case Instruction::And:
  317. case Instruction::Or:
  318. case Instruction::Xor: {
  319. Value *LHS = getReducedOperand(I->getOperand(0), SclTy);
  320. Value *RHS = getReducedOperand(I->getOperand(1), SclTy);
  321. Res = Builder.CreateBinOp((Instruction::BinaryOps)Opc, LHS, RHS);
  322. break;
  323. }
  324. case Instruction::Select: {
  325. Value *Op0 = I->getOperand(0);
  326. Value *LHS = getReducedOperand(I->getOperand(1), SclTy);
  327. Value *RHS = getReducedOperand(I->getOperand(2), SclTy);
  328. Res = Builder.CreateSelect(Op0, LHS, RHS);
  329. break;
  330. }
  331. default:
  332. llvm_unreachable("Unhandled instruction");
  333. }
  334. NodeInfo.NewValue = Res;
  335. if (auto *ResI = dyn_cast<Instruction>(Res))
  336. ResI->takeName(I);
  337. }
  338. Value *Res = getReducedOperand(CurrentTruncInst->getOperand(0), SclTy);
  339. Type *DstTy = CurrentTruncInst->getType();
  340. if (Res->getType() != DstTy) {
  341. IRBuilder<> Builder(CurrentTruncInst);
  342. Res = Builder.CreateIntCast(Res, DstTy, false);
  343. if (auto *ResI = dyn_cast<Instruction>(Res))
  344. ResI->takeName(CurrentTruncInst);
  345. }
  346. CurrentTruncInst->replaceAllUsesWith(Res);
  347. // Erase old expression dag, which was replaced by the reduced expression dag.
  348. // We iterate backward, which means we visit the instruction before we visit
  349. // any of its operands, this way, when we get to the operand, we already
  350. // removed the instructions (from the expression dag) that uses it.
  351. CurrentTruncInst->eraseFromParent();
  352. for (auto I = InstInfoMap.rbegin(), E = InstInfoMap.rend(); I != E; ++I) {
  353. // We still need to check that the instruction has no users before we erase
  354. // it, because {SExt, ZExt}Inst Instruction might have other users that was
  355. // not reduced, in such case, we need to keep that instruction.
  356. if (I->first->use_empty())
  357. I->first->eraseFromParent();
  358. }
  359. }
  360. bool TruncInstCombine::run(Function &F) {
  361. bool MadeIRChange = false;
  362. // Collect all TruncInst in the function into the Worklist for evaluating.
  363. for (auto &BB : F) {
  364. // Ignore unreachable basic block.
  365. if (!DT.isReachableFromEntry(&BB))
  366. continue;
  367. for (auto &I : BB)
  368. if (auto *CI = dyn_cast<TruncInst>(&I))
  369. Worklist.push_back(CI);
  370. }
  371. // Process all TruncInst in the Worklist, for each instruction:
  372. // 1. Check if it dominates an eligible expression dag to be reduced.
  373. // 2. Create a reduced expression dag and replace the old one with it.
  374. while (!Worklist.empty()) {
  375. CurrentTruncInst = Worklist.pop_back_val();
  376. if (Type *NewDstSclTy = getBestTruncatedType()) {
  377. LLVM_DEBUG(
  378. dbgs() << "ICE: TruncInstCombine reducing type of expression dag "
  379. "dominated by: "
  380. << CurrentTruncInst << '\n');
  381. ReduceExpressionDag(NewDstSclTy);
  382. ++NumDAGsReduced;
  383. MadeIRChange = true;
  384. }
  385. }
  386. return MadeIRChange;
  387. }