InstCombineCasts.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906
  1. //===- InstCombineCasts.cpp -----------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the visit functions for cast operations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "InstCombineInternal.h"
  14. #include "llvm/Analysis/ConstantFolding.h"
  15. #include "llvm/IR/DataLayout.h"
  16. #include "llvm/IR/PatternMatch.h"
  17. #include "llvm/Analysis/TargetLibraryInfo.h"
  18. using namespace llvm;
  19. using namespace PatternMatch;
  20. #define DEBUG_TYPE "instcombine"
  21. /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
  22. /// expression. If so, decompose it, returning some value X, such that Val is
  23. /// X*Scale+Offset.
  24. ///
  25. static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
  26. uint64_t &Offset) {
  27. if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
  28. Offset = CI->getZExtValue();
  29. Scale = 0;
  30. return ConstantInt::get(Val->getType(), 0);
  31. }
  32. if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
  33. // Cannot look past anything that might overflow.
  34. OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
  35. if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
  36. Scale = 1;
  37. Offset = 0;
  38. return Val;
  39. }
  40. if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
  41. if (I->getOpcode() == Instruction::Shl) {
  42. // This is a value scaled by '1 << the shift amt'.
  43. Scale = UINT64_C(1) << RHS->getZExtValue();
  44. Offset = 0;
  45. return I->getOperand(0);
  46. }
  47. if (I->getOpcode() == Instruction::Mul) {
  48. // This value is scaled by 'RHS'.
  49. Scale = RHS->getZExtValue();
  50. Offset = 0;
  51. return I->getOperand(0);
  52. }
  53. if (I->getOpcode() == Instruction::Add) {
  54. // We have X+C. Check to see if we really have (X*C2)+C1,
  55. // where C1 is divisible by C2.
  56. unsigned SubScale;
  57. Value *SubVal =
  58. DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
  59. Offset += RHS->getZExtValue();
  60. Scale = SubScale;
  61. return SubVal;
  62. }
  63. }
  64. }
  65. // Otherwise, we can't look past this.
  66. Scale = 1;
  67. Offset = 0;
  68. return Val;
  69. }
  70. /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
  71. /// try to eliminate the cast by moving the type information into the alloc.
  72. Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
  73. AllocaInst &AI) {
  74. PointerType *PTy = cast<PointerType>(CI.getType());
  75. BuilderTy AllocaBuilder(*Builder);
  76. AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
  77. // Get the type really allocated and the type casted to.
  78. Type *AllocElTy = AI.getAllocatedType();
  79. Type *CastElTy = PTy->getElementType();
  80. if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
  81. unsigned AllocElTyAlign = DL.getABITypeAlignment(AllocElTy);
  82. unsigned CastElTyAlign = DL.getABITypeAlignment(CastElTy);
  83. if (CastElTyAlign < AllocElTyAlign) return nullptr;
  84. // If the allocation has multiple uses, only promote it if we are strictly
  85. // increasing the alignment of the resultant allocation. If we keep it the
  86. // same, we open the door to infinite loops of various kinds.
  87. if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
  88. uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy);
  89. uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy);
  90. if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
  91. // If the allocation has multiple uses, only promote it if we're not
  92. // shrinking the amount of memory being allocated.
  93. uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy);
  94. uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy);
  95. if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
  96. // See if we can satisfy the modulus by pulling a scale out of the array
  97. // size argument.
  98. unsigned ArraySizeScale;
  99. uint64_t ArrayOffset;
  100. Value *NumElements = // See if the array size is a decomposable linear expr.
  101. DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
  102. // If we can now satisfy the modulus, by using a non-1 scale, we really can
  103. // do the xform.
  104. if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
  105. (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return nullptr;
  106. unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
  107. Value *Amt = nullptr;
  108. if (Scale == 1) {
  109. Amt = NumElements;
  110. } else {
  111. Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
  112. // Insert before the alloca, not before the cast.
  113. Amt = AllocaBuilder.CreateMul(Amt, NumElements);
  114. }
  115. if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
  116. Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
  117. Offset, true);
  118. Amt = AllocaBuilder.CreateAdd(Amt, Off);
  119. }
  120. AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
  121. New->setAlignment(AI.getAlignment());
  122. New->takeName(&AI);
  123. New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
  124. // If the allocation has multiple real uses, insert a cast and change all
  125. // things that used it to use the new cast. This will also hack on CI, but it
  126. // will die soon.
  127. if (!AI.hasOneUse()) {
  128. // New is the allocation instruction, pointer typed. AI is the original
  129. // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
  130. Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
  131. ReplaceInstUsesWith(AI, NewCast);
  132. }
  133. return ReplaceInstUsesWith(CI, New);
  134. }
  135. /// EvaluateInDifferentType - Given an expression that
  136. /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
  137. /// insert the code to evaluate the expression.
  138. Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
  139. bool isSigned) {
  140. if (Constant *C = dyn_cast<Constant>(V)) {
  141. C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
  142. // If we got a constantexpr back, try to simplify it with DL info.
  143. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
  144. C = ConstantFoldConstantExpression(CE, DL, TLI);
  145. return C;
  146. }
  147. // Otherwise, it must be an instruction.
  148. Instruction *I = cast<Instruction>(V);
  149. Instruction *Res = nullptr;
  150. unsigned Opc = I->getOpcode();
  151. switch (Opc) {
  152. case Instruction::Add:
  153. case Instruction::Sub:
  154. case Instruction::Mul:
  155. case Instruction::And:
  156. case Instruction::Or:
  157. case Instruction::Xor:
  158. case Instruction::AShr:
  159. case Instruction::LShr:
  160. case Instruction::Shl:
  161. case Instruction::UDiv:
  162. case Instruction::URem: {
  163. Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
  164. Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
  165. Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  166. break;
  167. }
  168. case Instruction::Trunc:
  169. case Instruction::ZExt:
  170. case Instruction::SExt:
  171. // If the source type of the cast is the type we're trying for then we can
  172. // just return the source. There's no need to insert it because it is not
  173. // new.
  174. if (I->getOperand(0)->getType() == Ty)
  175. return I->getOperand(0);
  176. // Otherwise, must be the same type of cast, so just reinsert a new one.
  177. // This also handles the case of zext(trunc(x)) -> zext(x).
  178. Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
  179. Opc == Instruction::SExt);
  180. break;
  181. case Instruction::Select: {
  182. Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
  183. Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
  184. Res = SelectInst::Create(I->getOperand(0), True, False);
  185. break;
  186. }
  187. case Instruction::PHI: {
  188. PHINode *OPN = cast<PHINode>(I);
  189. PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
  190. for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
  191. Value *V =
  192. EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
  193. NPN->addIncoming(V, OPN->getIncomingBlock(i));
  194. }
  195. Res = NPN;
  196. break;
  197. }
  198. default:
  199. // TODO: Can handle more cases here.
  200. llvm_unreachable("Unreachable!");
  201. }
  202. Res->takeName(I);
  203. return InsertNewInstWith(Res, *I);
  204. }
  205. /// This function is a wrapper around CastInst::isEliminableCastPair. It
  206. /// simply extracts arguments and returns what that function returns.
  207. static Instruction::CastOps
  208. isEliminableCastPair(const CastInst *CI, ///< First cast instruction
  209. unsigned opcode, ///< Opcode for the second cast
  210. Type *DstTy, ///< Target type for the second cast
  211. const DataLayout &DL) {
  212. Type *SrcTy = CI->getOperand(0)->getType(); // A from above
  213. Type *MidTy = CI->getType(); // B from above
  214. // Get the opcodes of the two Cast instructions
  215. Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
  216. Instruction::CastOps secondOp = Instruction::CastOps(opcode);
  217. Type *SrcIntPtrTy =
  218. SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
  219. Type *MidIntPtrTy =
  220. MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr;
  221. Type *DstIntPtrTy =
  222. DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
  223. unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
  224. DstTy, SrcIntPtrTy, MidIntPtrTy,
  225. DstIntPtrTy);
  226. // We don't want to form an inttoptr or ptrtoint that converts to an integer
  227. // type that differs from the pointer size.
  228. if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
  229. (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
  230. Res = 0;
  231. return Instruction::CastOps(Res);
  232. }
  233. /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
  234. /// results in any code being generated and is interesting to optimize out. If
  235. /// the cast can be eliminated by some other simple transformation, we prefer
  236. /// to do the simplification first.
  237. bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
  238. Type *Ty) {
  239. // Noop casts and casts of constants should be eliminated trivially.
  240. if (V->getType() == Ty || isa<Constant>(V)) return false;
  241. // If this is another cast that can be eliminated, we prefer to have it
  242. // eliminated.
  243. if (const CastInst *CI = dyn_cast<CastInst>(V))
  244. if (isEliminableCastPair(CI, opc, Ty, DL))
  245. return false;
  246. // If this is a vector sext from a compare, then we don't want to break the
  247. // idiom where each element of the extended vector is either zero or all ones.
  248. if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
  249. return false;
  250. return true;
  251. }
  252. /// @brief Implement the transforms common to all CastInst visitors.
  253. Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
  254. Value *Src = CI.getOperand(0);
  255. // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
  256. // eliminate it now.
  257. if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
  258. if (Instruction::CastOps opc =
  259. isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), DL)) {
  260. // The first cast (CSrc) is eliminable so we need to fix up or replace
  261. // the second cast (CI). CSrc will then have a good chance of being dead.
  262. return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
  263. }
  264. }
  265. // If we are casting a select then fold the cast into the select
  266. if (SelectInst *SI = dyn_cast<SelectInst>(Src))
  267. if (Instruction *NV = FoldOpIntoSelect(CI, SI))
  268. return NV;
  269. // If we are casting a PHI then fold the cast into the PHI
  270. if (isa<PHINode>(Src)) {
  271. // We don't do this if this would create a PHI node with an illegal type if
  272. // it is currently legal.
  273. if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() ||
  274. ShouldChangeType(CI.getType(), Src->getType()))
  275. if (Instruction *NV = FoldOpIntoPhi(CI))
  276. return NV;
  277. }
  278. return nullptr;
  279. }
  280. /// CanEvaluateTruncated - Return true if we can evaluate the specified
  281. /// expression tree as type Ty instead of its larger type, and arrive with the
  282. /// same value. This is used by code that tries to eliminate truncates.
  283. ///
  284. /// Ty will always be a type smaller than V. We should return true if trunc(V)
  285. /// can be computed by computing V in the smaller type. If V is an instruction,
  286. /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
  287. /// makes sense if x and y can be efficiently truncated.
  288. ///
  289. /// This function works on both vectors and scalars.
  290. ///
  291. static bool CanEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC,
  292. Instruction *CxtI) {
  293. // We can always evaluate constants in another type.
  294. if (isa<Constant>(V))
  295. return true;
  296. Instruction *I = dyn_cast<Instruction>(V);
  297. if (!I) return false;
  298. Type *OrigTy = V->getType();
  299. // If this is an extension from the dest type, we can eliminate it, even if it
  300. // has multiple uses.
  301. if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
  302. I->getOperand(0)->getType() == Ty)
  303. return true;
  304. // We can't extend or shrink something that has multiple uses: doing so would
  305. // require duplicating the instruction in general, which isn't profitable.
  306. if (!I->hasOneUse()) return false;
  307. unsigned Opc = I->getOpcode();
  308. switch (Opc) {
  309. case Instruction::Add:
  310. case Instruction::Sub:
  311. case Instruction::Mul:
  312. case Instruction::And:
  313. case Instruction::Or:
  314. case Instruction::Xor:
  315. // These operators can all arbitrarily be extended or truncated.
  316. return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
  317. CanEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
  318. case Instruction::UDiv:
  319. case Instruction::URem: {
  320. // UDiv and URem can be truncated if all the truncated bits are zero.
  321. uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
  322. uint32_t BitWidth = Ty->getScalarSizeInBits();
  323. if (BitWidth < OrigBitWidth) {
  324. APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
  325. if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
  326. IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) {
  327. return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
  328. CanEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
  329. }
  330. }
  331. break;
  332. }
  333. case Instruction::Shl:
  334. // If we are truncating the result of this SHL, and if it's a shift of a
  335. // constant amount, we can always perform a SHL in a smaller type.
  336. if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
  337. uint32_t BitWidth = Ty->getScalarSizeInBits();
  338. if (CI->getLimitedValue(BitWidth) < BitWidth)
  339. return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
  340. }
  341. break;
  342. case Instruction::LShr:
  343. // If this is a truncate of a logical shr, we can truncate it to a smaller
  344. // lshr iff we know that the bits we would otherwise be shifting in are
  345. // already zeros.
  346. if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
  347. uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
  348. uint32_t BitWidth = Ty->getScalarSizeInBits();
  349. if (IC.MaskedValueIsZero(I->getOperand(0),
  350. APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth), 0, CxtI) &&
  351. CI->getLimitedValue(BitWidth) < BitWidth) {
  352. return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
  353. }
  354. }
  355. break;
  356. case Instruction::Trunc:
  357. // trunc(trunc(x)) -> trunc(x)
  358. return true;
  359. case Instruction::ZExt:
  360. case Instruction::SExt:
  361. // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
  362. // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
  363. return true;
  364. case Instruction::Select: {
  365. SelectInst *SI = cast<SelectInst>(I);
  366. return CanEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
  367. CanEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI);
  368. }
  369. case Instruction::PHI: {
  370. // We can change a phi if we can change all operands. Note that we never
  371. // get into trouble with cyclic PHIs here because we only consider
  372. // instructions with a single use.
  373. PHINode *PN = cast<PHINode>(I);
  374. for (Value *IncValue : PN->incoming_values())
  375. if (!CanEvaluateTruncated(IncValue, Ty, IC, CxtI))
  376. return false;
  377. return true;
  378. }
  379. default:
  380. // TODO: Can handle more cases here.
  381. break;
  382. }
  383. return false;
  384. }
  385. Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
  386. if (Instruction *Result = commonCastTransforms(CI))
  387. return Result;
  388. // Test if the trunc is the user of a select which is part of a
  389. // minimum or maximum operation. If so, don't do any more simplification.
  390. // Even simplifying demanded bits can break the canonical form of a
  391. // min/max.
  392. Value *LHS, *RHS;
  393. if (SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0)))
  394. if (matchSelectPattern(SI, LHS, RHS) != SPF_UNKNOWN)
  395. return nullptr;
  396. // See if we can simplify any instructions used by the input whose sole
  397. // purpose is to compute bits we don't care about.
  398. if (SimplifyDemandedInstructionBits(CI))
  399. return &CI;
  400. Value *Src = CI.getOperand(0);
  401. Type *DestTy = CI.getType(), *SrcTy = Src->getType();
  402. // Attempt to truncate the entire input expression tree to the destination
  403. // type. Only do this if the dest type is a simple type, don't convert the
  404. // expression tree to something weird like i93 unless the source is also
  405. // strange.
  406. if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
  407. CanEvaluateTruncated(Src, DestTy, *this, &CI)) {
  408. // If this cast is a truncate, evaluting in a different type always
  409. // eliminates the cast, so it is always a win.
  410. DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
  411. " to avoid cast: " << CI << '\n');
  412. Value *Res = EvaluateInDifferentType(Src, DestTy, false);
  413. assert(Res->getType() == DestTy);
  414. return ReplaceInstUsesWith(CI, Res);
  415. }
  416. // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
  417. if (DestTy->getScalarSizeInBits() == 1) {
  418. Constant *One = ConstantInt::get(Src->getType(), 1);
  419. Src = Builder->CreateAnd(Src, One);
  420. Value *Zero = Constant::getNullValue(Src->getType());
  421. return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
  422. }
  423. // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
  424. Value *A = nullptr; ConstantInt *Cst = nullptr;
  425. if (Src->hasOneUse() &&
  426. match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
  427. // We have three types to worry about here, the type of A, the source of
  428. // the truncate (MidSize), and the destination of the truncate. We know that
  429. // ASize < MidSize and MidSize > ResultSize, but don't know the relation
  430. // between ASize and ResultSize.
  431. unsigned ASize = A->getType()->getPrimitiveSizeInBits();
  432. // If the shift amount is larger than the size of A, then the result is
  433. // known to be zero because all the input bits got shifted out.
  434. if (Cst->getZExtValue() >= ASize)
  435. return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
  436. // Since we're doing an lshr and a zero extend, and know that the shift
  437. // amount is smaller than ASize, it is always safe to do the shift in A's
  438. // type, then zero extend or truncate to the result.
  439. Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
  440. Shift->takeName(Src);
  441. return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
  442. }
  443. // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
  444. // type isn't non-native.
  445. if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
  446. ShouldChangeType(Src->getType(), CI.getType()) &&
  447. match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
  448. Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
  449. return BinaryOperator::CreateAnd(NewTrunc,
  450. ConstantExpr::getTrunc(Cst, CI.getType()));
  451. }
  452. return nullptr;
  453. }
  454. /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
  455. /// in order to eliminate the icmp.
  456. Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
  457. bool DoXform) {
  458. // If we are just checking for a icmp eq of a single bit and zext'ing it
  459. // to an integer, then shift the bit to the appropriate place and then
  460. // cast to integer to avoid the comparison.
  461. if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
  462. const APInt &Op1CV = Op1C->getValue();
  463. // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
  464. // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
  465. if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
  466. (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
  467. if (!DoXform) return ICI;
  468. Value *In = ICI->getOperand(0);
  469. Value *Sh = ConstantInt::get(In->getType(),
  470. In->getType()->getScalarSizeInBits()-1);
  471. In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
  472. if (In->getType() != CI.getType())
  473. In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
  474. if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
  475. Constant *One = ConstantInt::get(In->getType(), 1);
  476. In = Builder->CreateXor(In, One, In->getName()+".not");
  477. }
  478. return ReplaceInstUsesWith(CI, In);
  479. }
  480. // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
  481. // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
  482. // zext (X == 1) to i32 --> X iff X has only the low bit set.
  483. // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
  484. // zext (X != 0) to i32 --> X iff X has only the low bit set.
  485. // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
  486. // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
  487. // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
  488. if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
  489. // This only works for EQ and NE
  490. ICI->isEquality()) {
  491. // If Op1C some other power of two, convert:
  492. uint32_t BitWidth = Op1C->getType()->getBitWidth();
  493. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  494. computeKnownBits(ICI->getOperand(0), KnownZero, KnownOne, 0, &CI);
  495. APInt KnownZeroMask(~KnownZero);
  496. if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
  497. if (!DoXform) return ICI;
  498. bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
  499. if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
  500. // (X&4) == 2 --> false
  501. // (X&4) != 2 --> true
  502. Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
  503. isNE);
  504. Res = ConstantExpr::getZExt(Res, CI.getType());
  505. return ReplaceInstUsesWith(CI, Res);
  506. }
  507. uint32_t ShiftAmt = KnownZeroMask.logBase2();
  508. Value *In = ICI->getOperand(0);
  509. if (ShiftAmt) {
  510. // Perform a logical shr by shiftamt.
  511. // Insert the shift to put the result in the low bit.
  512. In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
  513. In->getName()+".lobit");
  514. }
  515. if ((Op1CV != 0) == isNE) { // Toggle the low bit.
  516. Constant *One = ConstantInt::get(In->getType(), 1);
  517. In = Builder->CreateXor(In, One);
  518. }
  519. if (CI.getType() == In->getType())
  520. return ReplaceInstUsesWith(CI, In);
  521. return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
  522. }
  523. }
  524. }
  525. // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
  526. // It is also profitable to transform icmp eq into not(xor(A, B)) because that
  527. // may lead to additional simplifications.
  528. if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
  529. if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
  530. uint32_t BitWidth = ITy->getBitWidth();
  531. Value *LHS = ICI->getOperand(0);
  532. Value *RHS = ICI->getOperand(1);
  533. APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
  534. APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
  535. computeKnownBits(LHS, KnownZeroLHS, KnownOneLHS, 0, &CI);
  536. computeKnownBits(RHS, KnownZeroRHS, KnownOneRHS, 0, &CI);
  537. if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
  538. APInt KnownBits = KnownZeroLHS | KnownOneLHS;
  539. APInt UnknownBit = ~KnownBits;
  540. if (UnknownBit.countPopulation() == 1) {
  541. if (!DoXform) return ICI;
  542. Value *Result = Builder->CreateXor(LHS, RHS);
  543. // Mask off any bits that are set and won't be shifted away.
  544. if (KnownOneLHS.uge(UnknownBit))
  545. Result = Builder->CreateAnd(Result,
  546. ConstantInt::get(ITy, UnknownBit));
  547. // Shift the bit we're testing down to the lsb.
  548. Result = Builder->CreateLShr(
  549. Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
  550. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  551. Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
  552. Result->takeName(ICI);
  553. return ReplaceInstUsesWith(CI, Result);
  554. }
  555. }
  556. }
  557. }
  558. return nullptr;
  559. }
  560. /// CanEvaluateZExtd - Determine if the specified value can be computed in the
  561. /// specified wider type and produce the same low bits. If not, return false.
  562. ///
  563. /// If this function returns true, it can also return a non-zero number of bits
  564. /// (in BitsToClear) which indicates that the value it computes is correct for
  565. /// the zero extend, but that the additional BitsToClear bits need to be zero'd
  566. /// out. For example, to promote something like:
  567. ///
  568. /// %B = trunc i64 %A to i32
  569. /// %C = lshr i32 %B, 8
  570. /// %E = zext i32 %C to i64
  571. ///
  572. /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
  573. /// set to 8 to indicate that the promoted value needs to have bits 24-31
  574. /// cleared in addition to bits 32-63. Since an 'and' will be generated to
  575. /// clear the top bits anyway, doing this has no extra cost.
  576. ///
  577. /// This function works on both vectors and scalars.
  578. static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
  579. InstCombiner &IC, Instruction *CxtI) {
  580. BitsToClear = 0;
  581. if (isa<Constant>(V))
  582. return true;
  583. Instruction *I = dyn_cast<Instruction>(V);
  584. if (!I) return false;
  585. // If the input is a truncate from the destination type, we can trivially
  586. // eliminate it.
  587. if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
  588. return true;
  589. // We can't extend or shrink something that has multiple uses: doing so would
  590. // require duplicating the instruction in general, which isn't profitable.
  591. if (!I->hasOneUse()) return false;
  592. unsigned Opc = I->getOpcode(), Tmp;
  593. switch (Opc) {
  594. case Instruction::ZExt: // zext(zext(x)) -> zext(x).
  595. case Instruction::SExt: // zext(sext(x)) -> sext(x).
  596. case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
  597. return true;
  598. case Instruction::And:
  599. case Instruction::Or:
  600. case Instruction::Xor:
  601. case Instruction::Add:
  602. case Instruction::Sub:
  603. case Instruction::Mul:
  604. if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
  605. !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI))
  606. return false;
  607. // These can all be promoted if neither operand has 'bits to clear'.
  608. if (BitsToClear == 0 && Tmp == 0)
  609. return true;
  610. // If the operation is an AND/OR/XOR and the bits to clear are zero in the
  611. // other side, BitsToClear is ok.
  612. if (Tmp == 0 &&
  613. (Opc == Instruction::And || Opc == Instruction::Or ||
  614. Opc == Instruction::Xor)) {
  615. // We use MaskedValueIsZero here for generality, but the case we care
  616. // about the most is constant RHS.
  617. unsigned VSize = V->getType()->getScalarSizeInBits();
  618. if (IC.MaskedValueIsZero(I->getOperand(1),
  619. APInt::getHighBitsSet(VSize, BitsToClear),
  620. 0, CxtI))
  621. return true;
  622. }
  623. // Otherwise, we don't know how to analyze this BitsToClear case yet.
  624. return false;
  625. case Instruction::Shl:
  626. // We can promote shl(x, cst) if we can promote x. Since shl overwrites the
  627. // upper bits we can reduce BitsToClear by the shift amount.
  628. if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
  629. if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
  630. return false;
  631. uint64_t ShiftAmt = Amt->getZExtValue();
  632. BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
  633. return true;
  634. }
  635. return false;
  636. case Instruction::LShr:
  637. // We can promote lshr(x, cst) if we can promote x. This requires the
  638. // ultimate 'and' to clear out the high zero bits we're clearing out though.
  639. if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
  640. if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
  641. return false;
  642. BitsToClear += Amt->getZExtValue();
  643. if (BitsToClear > V->getType()->getScalarSizeInBits())
  644. BitsToClear = V->getType()->getScalarSizeInBits();
  645. return true;
  646. }
  647. // Cannot promote variable LSHR.
  648. return false;
  649. case Instruction::Select:
  650. if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
  651. !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
  652. // TODO: If important, we could handle the case when the BitsToClear are
  653. // known zero in the disagreeing side.
  654. Tmp != BitsToClear)
  655. return false;
  656. return true;
  657. case Instruction::PHI: {
  658. // We can change a phi if we can change all operands. Note that we never
  659. // get into trouble with cyclic PHIs here because we only consider
  660. // instructions with a single use.
  661. PHINode *PN = cast<PHINode>(I);
  662. if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
  663. return false;
  664. for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
  665. if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
  666. // TODO: If important, we could handle the case when the BitsToClear
  667. // are known zero in the disagreeing input.
  668. Tmp != BitsToClear)
  669. return false;
  670. return true;
  671. }
  672. default:
  673. // TODO: Can handle more cases here.
  674. return false;
  675. }
  676. }
  677. Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
  678. // If this zero extend is only used by a truncate, let the truncate be
  679. // eliminated before we try to optimize this zext.
  680. if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
  681. return nullptr;
  682. // If one of the common conversion will work, do it.
  683. if (Instruction *Result = commonCastTransforms(CI))
  684. return Result;
  685. // See if we can simplify any instructions used by the input whose sole
  686. // purpose is to compute bits we don't care about.
  687. if (SimplifyDemandedInstructionBits(CI))
  688. return &CI;
  689. Value *Src = CI.getOperand(0);
  690. Type *SrcTy = Src->getType(), *DestTy = CI.getType();
  691. // Attempt to extend the entire input expression tree to the destination
  692. // type. Only do this if the dest type is a simple type, don't convert the
  693. // expression tree to something weird like i93 unless the source is also
  694. // strange.
  695. unsigned BitsToClear;
  696. if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
  697. CanEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) {
  698. assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
  699. "Unreasonable BitsToClear");
  700. // Okay, we can transform this! Insert the new expression now.
  701. DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
  702. " to avoid zero extend: " << CI);
  703. Value *Res = EvaluateInDifferentType(Src, DestTy, false);
  704. assert(Res->getType() == DestTy);
  705. uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
  706. uint32_t DestBitSize = DestTy->getScalarSizeInBits();
  707. // If the high bits are already filled with zeros, just replace this
  708. // cast with the result.
  709. if (MaskedValueIsZero(Res,
  710. APInt::getHighBitsSet(DestBitSize,
  711. DestBitSize-SrcBitsKept),
  712. 0, &CI))
  713. return ReplaceInstUsesWith(CI, Res);
  714. // We need to emit an AND to clear the high bits.
  715. Constant *C = ConstantInt::get(Res->getType(),
  716. APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
  717. return BinaryOperator::CreateAnd(Res, C);
  718. }
  719. // If this is a TRUNC followed by a ZEXT then we are dealing with integral
  720. // types and if the sizes are just right we can convert this into a logical
  721. // 'and' which will be much cheaper than the pair of casts.
  722. if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
  723. // TODO: Subsume this into EvaluateInDifferentType.
  724. // Get the sizes of the types involved. We know that the intermediate type
  725. // will be smaller than A or C, but don't know the relation between A and C.
  726. Value *A = CSrc->getOperand(0);
  727. unsigned SrcSize = A->getType()->getScalarSizeInBits();
  728. unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
  729. unsigned DstSize = CI.getType()->getScalarSizeInBits();
  730. // If we're actually extending zero bits, then if
  731. // SrcSize < DstSize: zext(a & mask)
  732. // SrcSize == DstSize: a & mask
  733. // SrcSize > DstSize: trunc(a) & mask
  734. if (SrcSize < DstSize) {
  735. APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
  736. Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
  737. Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
  738. return new ZExtInst(And, CI.getType());
  739. }
  740. if (SrcSize == DstSize) {
  741. APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
  742. return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
  743. AndValue));
  744. }
  745. if (SrcSize > DstSize) {
  746. Value *Trunc = Builder->CreateTrunc(A, CI.getType());
  747. APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
  748. return BinaryOperator::CreateAnd(Trunc,
  749. ConstantInt::get(Trunc->getType(),
  750. AndValue));
  751. }
  752. }
  753. if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
  754. return transformZExtICmp(ICI, CI);
  755. BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
  756. if (SrcI && SrcI->getOpcode() == Instruction::Or) {
  757. // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
  758. // of the (zext icmp) will be transformed.
  759. ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
  760. ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
  761. if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
  762. (transformZExtICmp(LHS, CI, false) ||
  763. transformZExtICmp(RHS, CI, false))) {
  764. Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
  765. Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
  766. return BinaryOperator::Create(Instruction::Or, LCast, RCast);
  767. }
  768. }
  769. // zext(trunc(X) & C) -> (X & zext(C)).
  770. Constant *C;
  771. Value *X;
  772. if (SrcI &&
  773. match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
  774. X->getType() == CI.getType())
  775. return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
  776. // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
  777. Value *And;
  778. if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
  779. match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
  780. X->getType() == CI.getType()) {
  781. Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
  782. return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
  783. }
  784. // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
  785. if (SrcI && SrcI->hasOneUse() &&
  786. SrcI->getType()->getScalarType()->isIntegerTy(1) &&
  787. match(SrcI, m_Not(m_Value(X))) && (!X->hasOneUse() || !isa<CmpInst>(X))) {
  788. Value *New = Builder->CreateZExt(X, CI.getType());
  789. return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
  790. }
  791. return nullptr;
  792. }
  793. /// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
  794. /// in order to eliminate the icmp.
  795. Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
  796. Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
  797. ICmpInst::Predicate Pred = ICI->getPredicate();
  798. // Don't bother if Op1 isn't of vector or integer type.
  799. if (!Op1->getType()->isIntOrIntVectorTy())
  800. return nullptr;
  801. if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
  802. // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
  803. // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
  804. if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
  805. (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
  806. Value *Sh = ConstantInt::get(Op0->getType(),
  807. Op0->getType()->getScalarSizeInBits()-1);
  808. Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
  809. if (In->getType() != CI.getType())
  810. In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
  811. if (Pred == ICmpInst::ICMP_SGT)
  812. In = Builder->CreateNot(In, In->getName()+".not");
  813. return ReplaceInstUsesWith(CI, In);
  814. }
  815. }
  816. if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
  817. // If we know that only one bit of the LHS of the icmp can be set and we
  818. // have an equality comparison with zero or a power of 2, we can transform
  819. // the icmp and sext into bitwise/integer operations.
  820. if (ICI->hasOneUse() &&
  821. ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
  822. unsigned BitWidth = Op1C->getType()->getBitWidth();
  823. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  824. computeKnownBits(Op0, KnownZero, KnownOne, 0, &CI);
  825. APInt KnownZeroMask(~KnownZero);
  826. if (KnownZeroMask.isPowerOf2()) {
  827. Value *In = ICI->getOperand(0);
  828. // If the icmp tests for a known zero bit we can constant fold it.
  829. if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
  830. Value *V = Pred == ICmpInst::ICMP_NE ?
  831. ConstantInt::getAllOnesValue(CI.getType()) :
  832. ConstantInt::getNullValue(CI.getType());
  833. return ReplaceInstUsesWith(CI, V);
  834. }
  835. if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
  836. // sext ((x & 2^n) == 0) -> (x >> n) - 1
  837. // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
  838. unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
  839. // Perform a right shift to place the desired bit in the LSB.
  840. if (ShiftAmt)
  841. In = Builder->CreateLShr(In,
  842. ConstantInt::get(In->getType(), ShiftAmt));
  843. // At this point "In" is either 1 or 0. Subtract 1 to turn
  844. // {1, 0} -> {0, -1}.
  845. In = Builder->CreateAdd(In,
  846. ConstantInt::getAllOnesValue(In->getType()),
  847. "sext");
  848. } else {
  849. // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
  850. // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
  851. unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
  852. // Perform a left shift to place the desired bit in the MSB.
  853. if (ShiftAmt)
  854. In = Builder->CreateShl(In,
  855. ConstantInt::get(In->getType(), ShiftAmt));
  856. // Distribute the bit over the whole bit width.
  857. In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
  858. BitWidth - 1), "sext");
  859. }
  860. if (CI.getType() == In->getType())
  861. return ReplaceInstUsesWith(CI, In);
  862. return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
  863. }
  864. }
  865. }
  866. return nullptr;
  867. }
  868. /// CanEvaluateSExtd - Return true if we can take the specified value
  869. /// and return it as type Ty without inserting any new casts and without
  870. /// changing the value of the common low bits. This is used by code that tries
  871. /// to promote integer operations to a wider types will allow us to eliminate
  872. /// the extension.
  873. ///
  874. /// This function works on both vectors and scalars.
  875. ///
  876. static bool CanEvaluateSExtd(Value *V, Type *Ty) {
  877. assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
  878. "Can't sign extend type to a smaller type");
  879. // If this is a constant, it can be trivially promoted.
  880. if (isa<Constant>(V))
  881. return true;
  882. Instruction *I = dyn_cast<Instruction>(V);
  883. if (!I) return false;
  884. // If this is a truncate from the dest type, we can trivially eliminate it.
  885. if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
  886. return true;
  887. // We can't extend or shrink something that has multiple uses: doing so would
  888. // require duplicating the instruction in general, which isn't profitable.
  889. if (!I->hasOneUse()) return false;
  890. switch (I->getOpcode()) {
  891. case Instruction::SExt: // sext(sext(x)) -> sext(x)
  892. case Instruction::ZExt: // sext(zext(x)) -> zext(x)
  893. case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
  894. return true;
  895. case Instruction::And:
  896. case Instruction::Or:
  897. case Instruction::Xor:
  898. case Instruction::Add:
  899. case Instruction::Sub:
  900. case Instruction::Mul:
  901. // These operators can all arbitrarily be extended if their inputs can.
  902. return CanEvaluateSExtd(I->getOperand(0), Ty) &&
  903. CanEvaluateSExtd(I->getOperand(1), Ty);
  904. //case Instruction::Shl: TODO
  905. //case Instruction::LShr: TODO
  906. case Instruction::Select:
  907. return CanEvaluateSExtd(I->getOperand(1), Ty) &&
  908. CanEvaluateSExtd(I->getOperand(2), Ty);
  909. case Instruction::PHI: {
  910. // We can change a phi if we can change all operands. Note that we never
  911. // get into trouble with cyclic PHIs here because we only consider
  912. // instructions with a single use.
  913. PHINode *PN = cast<PHINode>(I);
  914. for (Value *IncValue : PN->incoming_values())
  915. if (!CanEvaluateSExtd(IncValue, Ty)) return false;
  916. return true;
  917. }
  918. default:
  919. // TODO: Can handle more cases here.
  920. break;
  921. }
  922. return false;
  923. }
  924. Instruction *InstCombiner::visitSExt(SExtInst &CI) {
  925. // If this sign extend is only used by a truncate, let the truncate be
  926. // eliminated before we try to optimize this sext.
  927. if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
  928. return nullptr;
  929. if (Instruction *I = commonCastTransforms(CI))
  930. return I;
  931. // See if we can simplify any instructions used by the input whose sole
  932. // purpose is to compute bits we don't care about.
  933. if (SimplifyDemandedInstructionBits(CI))
  934. return &CI;
  935. Value *Src = CI.getOperand(0);
  936. Type *SrcTy = Src->getType(), *DestTy = CI.getType();
  937. // If we know that the value being extended is positive, we can use a zext
  938. // instead.
  939. bool KnownZero, KnownOne;
  940. ComputeSignBit(Src, KnownZero, KnownOne, 0, &CI);
  941. if (KnownZero) {
  942. Value *ZExt = Builder->CreateZExt(Src, DestTy);
  943. return ReplaceInstUsesWith(CI, ZExt);
  944. }
  945. // Attempt to extend the entire input expression tree to the destination
  946. // type. Only do this if the dest type is a simple type, don't convert the
  947. // expression tree to something weird like i93 unless the source is also
  948. // strange.
  949. if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
  950. CanEvaluateSExtd(Src, DestTy)) {
  951. // Okay, we can transform this! Insert the new expression now.
  952. DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
  953. " to avoid sign extend: " << CI);
  954. Value *Res = EvaluateInDifferentType(Src, DestTy, true);
  955. assert(Res->getType() == DestTy);
  956. uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
  957. uint32_t DestBitSize = DestTy->getScalarSizeInBits();
  958. // If the high bits are already filled with sign bit, just replace this
  959. // cast with the result.
  960. if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
  961. return ReplaceInstUsesWith(CI, Res);
  962. // We need to emit a shl + ashr to do the sign extend.
  963. Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
  964. return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
  965. ShAmt);
  966. }
  967. // If this input is a trunc from our destination, then turn sext(trunc(x))
  968. // into shifts.
  969. if (TruncInst *TI = dyn_cast<TruncInst>(Src))
  970. if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
  971. uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
  972. uint32_t DestBitSize = DestTy->getScalarSizeInBits();
  973. // We need to emit a shl + ashr to do the sign extend.
  974. Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
  975. Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
  976. return BinaryOperator::CreateAShr(Res, ShAmt);
  977. }
  978. if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
  979. return transformSExtICmp(ICI, CI);
  980. // If the input is a shl/ashr pair of a same constant, then this is a sign
  981. // extension from a smaller value. If we could trust arbitrary bitwidth
  982. // integers, we could turn this into a truncate to the smaller bit and then
  983. // use a sext for the whole extension. Since we don't, look deeper and check
  984. // for a truncate. If the source and dest are the same type, eliminate the
  985. // trunc and extend and just do shifts. For example, turn:
  986. // %a = trunc i32 %i to i8
  987. // %b = shl i8 %a, 6
  988. // %c = ashr i8 %b, 6
  989. // %d = sext i8 %c to i32
  990. // into:
  991. // %a = shl i32 %i, 30
  992. // %d = ashr i32 %a, 30
  993. Value *A = nullptr;
  994. // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
  995. ConstantInt *BA = nullptr, *CA = nullptr;
  996. if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
  997. m_ConstantInt(CA))) &&
  998. BA == CA && A->getType() == CI.getType()) {
  999. unsigned MidSize = Src->getType()->getScalarSizeInBits();
  1000. unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
  1001. unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
  1002. Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
  1003. A = Builder->CreateShl(A, ShAmtV, CI.getName());
  1004. return BinaryOperator::CreateAShr(A, ShAmtV);
  1005. }
  1006. return nullptr;
  1007. }
  1008. /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
  1009. /// in the specified FP type without changing its value.
  1010. static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
  1011. bool losesInfo;
  1012. APFloat F = CFP->getValueAPF();
  1013. (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
  1014. if (!losesInfo)
  1015. return ConstantFP::get(CFP->getContext(), F);
  1016. return nullptr;
  1017. }
  1018. /// LookThroughFPExtensions - If this is an fp extension instruction, look
  1019. /// through it until we get the source value.
  1020. static Value *LookThroughFPExtensions(Value *V) {
  1021. if (Instruction *I = dyn_cast<Instruction>(V))
  1022. if (I->getOpcode() == Instruction::FPExt)
  1023. return LookThroughFPExtensions(I->getOperand(0));
  1024. // If this value is a constant, return the constant in the smallest FP type
  1025. // that can accurately represent it. This allows us to turn
  1026. // (float)((double)X+2.0) into x+2.0f.
  1027. if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
  1028. if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
  1029. return V; // No constant folding of this.
  1030. // See if the value can be truncated to half and then reextended.
  1031. if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
  1032. return V;
  1033. // See if the value can be truncated to float and then reextended.
  1034. if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
  1035. return V;
  1036. if (CFP->getType()->isDoubleTy())
  1037. return V; // Won't shrink.
  1038. if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
  1039. return V;
  1040. // Don't try to shrink to various long double types.
  1041. }
  1042. return V;
  1043. }
  1044. Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
  1045. if (Instruction *I = commonCastTransforms(CI))
  1046. return I;
  1047. // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
  1048. // simpilify this expression to avoid one or more of the trunc/extend
  1049. // operations if we can do so without changing the numerical results.
  1050. //
  1051. // The exact manner in which the widths of the operands interact to limit
  1052. // what we can and cannot do safely varies from operation to operation, and
  1053. // is explained below in the various case statements.
  1054. BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
  1055. if (OpI && OpI->hasOneUse()) {
  1056. Value *LHSOrig = LookThroughFPExtensions(OpI->getOperand(0));
  1057. Value *RHSOrig = LookThroughFPExtensions(OpI->getOperand(1));
  1058. unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
  1059. unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
  1060. unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
  1061. unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
  1062. unsigned DstWidth = CI.getType()->getFPMantissaWidth();
  1063. switch (OpI->getOpcode()) {
  1064. default: break;
  1065. case Instruction::FAdd:
  1066. case Instruction::FSub:
  1067. // For addition and subtraction, the infinitely precise result can
  1068. // essentially be arbitrarily wide; proving that double rounding
  1069. // will not occur because the result of OpI is exact (as we will for
  1070. // FMul, for example) is hopeless. However, we *can* nonetheless
  1071. // frequently know that double rounding cannot occur (or that it is
  1072. // innocuous) by taking advantage of the specific structure of
  1073. // infinitely-precise results that admit double rounding.
  1074. //
  1075. // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
  1076. // to represent both sources, we can guarantee that the double
  1077. // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
  1078. // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
  1079. // for proof of this fact).
  1080. //
  1081. // Note: Figueroa does not consider the case where DstFormat !=
  1082. // SrcFormat. It's possible (likely even!) that this analysis
  1083. // could be tightened for those cases, but they are rare (the main
  1084. // case of interest here is (float)((double)float + float)).
  1085. if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
  1086. if (LHSOrig->getType() != CI.getType())
  1087. LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
  1088. if (RHSOrig->getType() != CI.getType())
  1089. RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
  1090. Instruction *RI =
  1091. BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
  1092. RI->copyFastMathFlags(OpI);
  1093. return RI;
  1094. }
  1095. break;
  1096. case Instruction::FMul:
  1097. // For multiplication, the infinitely precise result has at most
  1098. // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
  1099. // that such a value can be exactly represented, then no double
  1100. // rounding can possibly occur; we can safely perform the operation
  1101. // in the destination format if it can represent both sources.
  1102. if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
  1103. if (LHSOrig->getType() != CI.getType())
  1104. LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
  1105. if (RHSOrig->getType() != CI.getType())
  1106. RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
  1107. Instruction *RI =
  1108. BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
  1109. RI->copyFastMathFlags(OpI);
  1110. return RI;
  1111. }
  1112. break;
  1113. case Instruction::FDiv:
  1114. // For division, we use again use the bound from Figueroa's
  1115. // dissertation. I am entirely certain that this bound can be
  1116. // tightened in the unbalanced operand case by an analysis based on
  1117. // the diophantine rational approximation bound, but the well-known
  1118. // condition used here is a good conservative first pass.
  1119. // TODO: Tighten bound via rigorous analysis of the unbalanced case.
  1120. if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
  1121. if (LHSOrig->getType() != CI.getType())
  1122. LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
  1123. if (RHSOrig->getType() != CI.getType())
  1124. RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
  1125. Instruction *RI =
  1126. BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
  1127. RI->copyFastMathFlags(OpI);
  1128. return RI;
  1129. }
  1130. break;
  1131. case Instruction::FRem:
  1132. // Remainder is straightforward. Remainder is always exact, so the
  1133. // type of OpI doesn't enter into things at all. We simply evaluate
  1134. // in whichever source type is larger, then convert to the
  1135. // destination type.
  1136. if (SrcWidth == OpWidth)
  1137. break;
  1138. if (LHSWidth < SrcWidth)
  1139. LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
  1140. else if (RHSWidth <= SrcWidth)
  1141. RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
  1142. if (LHSOrig != OpI->getOperand(0) || RHSOrig != OpI->getOperand(1)) {
  1143. Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
  1144. if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
  1145. RI->copyFastMathFlags(OpI);
  1146. return CastInst::CreateFPCast(ExactResult, CI.getType());
  1147. }
  1148. }
  1149. // (fptrunc (fneg x)) -> (fneg (fptrunc x))
  1150. if (BinaryOperator::isFNeg(OpI)) {
  1151. Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
  1152. CI.getType());
  1153. Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
  1154. RI->copyFastMathFlags(OpI);
  1155. return RI;
  1156. }
  1157. }
  1158. // (fptrunc (select cond, R1, Cst)) -->
  1159. // (select cond, (fptrunc R1), (fptrunc Cst))
  1160. SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
  1161. if (SI &&
  1162. (isa<ConstantFP>(SI->getOperand(1)) ||
  1163. isa<ConstantFP>(SI->getOperand(2)))) {
  1164. Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
  1165. CI.getType());
  1166. Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
  1167. CI.getType());
  1168. return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
  1169. }
  1170. IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
  1171. if (II) {
  1172. switch (II->getIntrinsicID()) {
  1173. default: break;
  1174. case Intrinsic::fabs: {
  1175. // (fptrunc (fabs x)) -> (fabs (fptrunc x))
  1176. Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
  1177. CI.getType());
  1178. Type *IntrinsicType[] = { CI.getType() };
  1179. Function *Overload =
  1180. Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(),
  1181. II->getIntrinsicID(), IntrinsicType);
  1182. Value *Args[] = { InnerTrunc };
  1183. return CallInst::Create(Overload, Args, II->getName());
  1184. }
  1185. }
  1186. }
  1187. return nullptr;
  1188. }
  1189. Instruction *InstCombiner::visitFPExt(CastInst &CI) {
  1190. return commonCastTransforms(CI);
  1191. }
  1192. // fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X)
  1193. // This is safe if the intermediate type has enough bits in its mantissa to
  1194. // accurately represent all values of X. For example, this won't work with
  1195. // i64 -> float -> i64.
  1196. Instruction *InstCombiner::FoldItoFPtoI(Instruction &FI) {
  1197. if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0)))
  1198. return nullptr;
  1199. Instruction *OpI = cast<Instruction>(FI.getOperand(0));
  1200. Value *SrcI = OpI->getOperand(0);
  1201. Type *FITy = FI.getType();
  1202. Type *OpITy = OpI->getType();
  1203. Type *SrcTy = SrcI->getType();
  1204. bool IsInputSigned = isa<SIToFPInst>(OpI);
  1205. bool IsOutputSigned = isa<FPToSIInst>(FI);
  1206. // We can safely assume the conversion won't overflow the output range,
  1207. // because (for example) (uint8_t)18293.f is undefined behavior.
  1208. // Since we can assume the conversion won't overflow, our decision as to
  1209. // whether the input will fit in the float should depend on the minimum
  1210. // of the input range and output range.
  1211. // This means this is also safe for a signed input and unsigned output, since
  1212. // a negative input would lead to undefined behavior.
  1213. int InputSize = (int)SrcTy->getScalarSizeInBits() - IsInputSigned;
  1214. int OutputSize = (int)FITy->getScalarSizeInBits() - IsOutputSigned;
  1215. int ActualSize = std::min(InputSize, OutputSize);
  1216. if (ActualSize <= OpITy->getFPMantissaWidth()) {
  1217. if (FITy->getScalarSizeInBits() > SrcTy->getScalarSizeInBits()) {
  1218. if (IsInputSigned && IsOutputSigned)
  1219. return new SExtInst(SrcI, FITy);
  1220. return new ZExtInst(SrcI, FITy);
  1221. }
  1222. if (FITy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits())
  1223. return new TruncInst(SrcI, FITy);
  1224. if (SrcTy == FITy)
  1225. return ReplaceInstUsesWith(FI, SrcI);
  1226. return new BitCastInst(SrcI, FITy);
  1227. }
  1228. return nullptr;
  1229. }
  1230. Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
  1231. Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
  1232. if (!OpI)
  1233. return commonCastTransforms(FI);
  1234. if (Instruction *I = FoldItoFPtoI(FI))
  1235. return I;
  1236. return commonCastTransforms(FI);
  1237. }
  1238. Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
  1239. Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
  1240. if (!OpI)
  1241. return commonCastTransforms(FI);
  1242. if (Instruction *I = FoldItoFPtoI(FI))
  1243. return I;
  1244. return commonCastTransforms(FI);
  1245. }
  1246. Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
  1247. return commonCastTransforms(CI);
  1248. }
  1249. Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
  1250. return commonCastTransforms(CI);
  1251. }
  1252. Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
  1253. // If the source integer type is not the intptr_t type for this target, do a
  1254. // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
  1255. // cast to be exposed to other transforms.
  1256. unsigned AS = CI.getAddressSpace();
  1257. if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
  1258. DL.getPointerSizeInBits(AS)) {
  1259. Type *Ty = DL.getIntPtrType(CI.getContext(), AS);
  1260. if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
  1261. Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
  1262. Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
  1263. return new IntToPtrInst(P, CI.getType());
  1264. }
  1265. if (Instruction *I = commonCastTransforms(CI))
  1266. return I;
  1267. return nullptr;
  1268. }
  1269. /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
  1270. Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
  1271. Value *Src = CI.getOperand(0);
  1272. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
  1273. // If casting the result of a getelementptr instruction with no offset, turn
  1274. // this into a cast of the original pointer!
  1275. if (GEP->hasAllZeroIndices() &&
  1276. // HLSL Change Begin.
  1277. // Ignore this optimization for pointer bitcast to pass validation.
  1278. // TODO: enable this optimization when validation is updated.
  1279. 0 &&
  1280. // HLSL Change End.
  1281. // If CI is an addrspacecast and GEP changes the poiner type, merging
  1282. // GEP into CI would undo canonicalizing addrspacecast with different
  1283. // pointer types, causing infinite loops.
  1284. (!isa<AddrSpaceCastInst>(CI) ||
  1285. GEP->getType() == GEP->getPointerOperand()->getType())) {
  1286. // Changing the cast operand is usually not a good idea but it is safe
  1287. // here because the pointer operand is being replaced with another
  1288. // pointer operand so the opcode doesn't need to change.
  1289. Worklist.Add(GEP);
  1290. CI.setOperand(0, GEP->getOperand(0));
  1291. return &CI;
  1292. }
  1293. }
  1294. return commonCastTransforms(CI);
  1295. }
  1296. Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
  1297. // If the destination integer type is not the intptr_t type for this target,
  1298. // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
  1299. // to be exposed to other transforms.
  1300. Type *Ty = CI.getType();
  1301. unsigned AS = CI.getPointerAddressSpace();
  1302. if (Ty->getScalarSizeInBits() == DL.getPointerSizeInBits(AS))
  1303. return commonPointerCastTransforms(CI);
  1304. Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS);
  1305. if (Ty->isVectorTy()) // Handle vectors of pointers.
  1306. PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
  1307. Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
  1308. return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
  1309. }
  1310. /// OptimizeVectorResize - This input value (which is known to have vector type)
  1311. /// is being zero extended or truncated to the specified vector type. Try to
  1312. /// replace it with a shuffle (and vector/vector bitcast) if possible.
  1313. ///
  1314. /// The source and destination vector types may have different element types.
  1315. static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
  1316. InstCombiner &IC) {
  1317. // We can only do this optimization if the output is a multiple of the input
  1318. // element size, or the input is a multiple of the output element size.
  1319. // Convert the input type to have the same element type as the output.
  1320. VectorType *SrcTy = cast<VectorType>(InVal->getType());
  1321. if (SrcTy->getElementType() != DestTy->getElementType()) {
  1322. // The input types don't need to be identical, but for now they must be the
  1323. // same size. There is no specific reason we couldn't handle things like
  1324. // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
  1325. // there yet.
  1326. if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
  1327. DestTy->getElementType()->getPrimitiveSizeInBits())
  1328. return nullptr;
  1329. SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
  1330. InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
  1331. }
  1332. // Now that the element types match, get the shuffle mask and RHS of the
  1333. // shuffle to use, which depends on whether we're increasing or decreasing the
  1334. // size of the input.
  1335. SmallVector<uint32_t, 16> ShuffleMask;
  1336. Value *V2;
  1337. if (SrcTy->getNumElements() > DestTy->getNumElements()) {
  1338. // If we're shrinking the number of elements, just shuffle in the low
  1339. // elements from the input and use undef as the second shuffle input.
  1340. V2 = UndefValue::get(SrcTy);
  1341. for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
  1342. ShuffleMask.push_back(i);
  1343. } else {
  1344. // If we're increasing the number of elements, shuffle in all of the
  1345. // elements from InVal and fill the rest of the result elements with zeros
  1346. // from a constant zero.
  1347. V2 = Constant::getNullValue(SrcTy);
  1348. unsigned SrcElts = SrcTy->getNumElements();
  1349. for (unsigned i = 0, e = SrcElts; i != e; ++i)
  1350. ShuffleMask.push_back(i);
  1351. // The excess elements reference the first element of the zero input.
  1352. for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
  1353. ShuffleMask.push_back(SrcElts);
  1354. }
  1355. return new ShuffleVectorInst(InVal, V2,
  1356. ConstantDataVector::get(V2->getContext(),
  1357. ShuffleMask));
  1358. }
  1359. static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
  1360. return Value % Ty->getPrimitiveSizeInBits() == 0;
  1361. }
  1362. static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
  1363. return Value / Ty->getPrimitiveSizeInBits();
  1364. }
  1365. /// CollectInsertionElements - V is a value which is inserted into a vector of
  1366. /// VecEltTy. Look through the value to see if we can decompose it into
  1367. /// insertions into the vector. See the example in the comment for
  1368. /// OptimizeIntegerToVectorInsertions for the pattern this handles.
  1369. /// The type of V is always a non-zero multiple of VecEltTy's size.
  1370. /// Shift is the number of bits between the lsb of V and the lsb of
  1371. /// the vector.
  1372. ///
  1373. /// This returns false if the pattern can't be matched or true if it can,
  1374. /// filling in Elements with the elements found here.
  1375. static bool CollectInsertionElements(Value *V, unsigned Shift,
  1376. SmallVectorImpl<Value *> &Elements,
  1377. Type *VecEltTy, bool isBigEndian) {
  1378. assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
  1379. "Shift should be a multiple of the element type size");
  1380. // Undef values never contribute useful bits to the result.
  1381. if (isa<UndefValue>(V)) return true;
  1382. // If we got down to a value of the right type, we win, try inserting into the
  1383. // right element.
  1384. if (V->getType() == VecEltTy) {
  1385. // Inserting null doesn't actually insert any elements.
  1386. if (Constant *C = dyn_cast<Constant>(V))
  1387. if (C->isNullValue())
  1388. return true;
  1389. unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
  1390. if (isBigEndian)
  1391. ElementIndex = Elements.size() - ElementIndex - 1;
  1392. // Fail if multiple elements are inserted into this slot.
  1393. if (Elements[ElementIndex])
  1394. return false;
  1395. Elements[ElementIndex] = V;
  1396. return true;
  1397. }
  1398. if (Constant *C = dyn_cast<Constant>(V)) {
  1399. // Figure out the # elements this provides, and bitcast it or slice it up
  1400. // as required.
  1401. unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
  1402. VecEltTy);
  1403. // If the constant is the size of a vector element, we just need to bitcast
  1404. // it to the right type so it gets properly inserted.
  1405. if (NumElts == 1)
  1406. return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
  1407. Shift, Elements, VecEltTy, isBigEndian);
  1408. // Okay, this is a constant that covers multiple elements. Slice it up into
  1409. // pieces and insert each element-sized piece into the vector.
  1410. if (!isa<IntegerType>(C->getType()))
  1411. C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
  1412. C->getType()->getPrimitiveSizeInBits()));
  1413. unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
  1414. Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
  1415. for (unsigned i = 0; i != NumElts; ++i) {
  1416. unsigned ShiftI = Shift+i*ElementSize;
  1417. Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
  1418. ShiftI));
  1419. Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
  1420. if (!CollectInsertionElements(Piece, ShiftI, Elements, VecEltTy,
  1421. isBigEndian))
  1422. return false;
  1423. }
  1424. return true;
  1425. }
  1426. if (!V->hasOneUse()) return false;
  1427. Instruction *I = dyn_cast<Instruction>(V);
  1428. if (!I) return false;
  1429. switch (I->getOpcode()) {
  1430. default: return false; // Unhandled case.
  1431. case Instruction::BitCast:
  1432. return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
  1433. isBigEndian);
  1434. case Instruction::ZExt:
  1435. if (!isMultipleOfTypeSize(
  1436. I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
  1437. VecEltTy))
  1438. return false;
  1439. return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
  1440. isBigEndian);
  1441. case Instruction::Or:
  1442. return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
  1443. isBigEndian) &&
  1444. CollectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
  1445. isBigEndian);
  1446. case Instruction::Shl: {
  1447. // Must be shifting by a constant that is a multiple of the element size.
  1448. ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
  1449. if (!CI) return false;
  1450. Shift += CI->getZExtValue();
  1451. if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
  1452. return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
  1453. isBigEndian);
  1454. }
  1455. }
  1456. }
  1457. /// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
  1458. /// may be doing shifts and ors to assemble the elements of the vector manually.
  1459. /// Try to rip the code out and replace it with insertelements. This is to
  1460. /// optimize code like this:
  1461. ///
  1462. /// %tmp37 = bitcast float %inc to i32
  1463. /// %tmp38 = zext i32 %tmp37 to i64
  1464. /// %tmp31 = bitcast float %inc5 to i32
  1465. /// %tmp32 = zext i32 %tmp31 to i64
  1466. /// %tmp33 = shl i64 %tmp32, 32
  1467. /// %ins35 = or i64 %tmp33, %tmp38
  1468. /// %tmp43 = bitcast i64 %ins35 to <2 x float>
  1469. ///
  1470. /// Into two insertelements that do "buildvector{%inc, %inc5}".
  1471. static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
  1472. InstCombiner &IC) {
  1473. VectorType *DestVecTy = cast<VectorType>(CI.getType());
  1474. Value *IntInput = CI.getOperand(0);
  1475. SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
  1476. if (!CollectInsertionElements(IntInput, 0, Elements,
  1477. DestVecTy->getElementType(),
  1478. IC.getDataLayout().isBigEndian()))
  1479. return nullptr;
  1480. // If we succeeded, we know that all of the element are specified by Elements
  1481. // or are zero if Elements has a null entry. Recast this as a set of
  1482. // insertions.
  1483. Value *Result = Constant::getNullValue(CI.getType());
  1484. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  1485. if (!Elements[i]) continue; // Unset element.
  1486. Result = IC.Builder->CreateInsertElement(Result, Elements[i],
  1487. IC.Builder->getInt32(i));
  1488. }
  1489. return Result;
  1490. }
  1491. /// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
  1492. /// bitcast. The various long double bitcasts can't get in here.
  1493. static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI, InstCombiner &IC,
  1494. const DataLayout &DL) {
  1495. Value *Src = CI.getOperand(0);
  1496. Type *DestTy = CI.getType();
  1497. // If this is a bitcast from int to float, check to see if the int is an
  1498. // extraction from a vector.
  1499. Value *VecInput = nullptr;
  1500. // bitcast(trunc(bitcast(somevector)))
  1501. if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
  1502. isa<VectorType>(VecInput->getType())) {
  1503. VectorType *VecTy = cast<VectorType>(VecInput->getType());
  1504. unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
  1505. if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
  1506. // If the element type of the vector doesn't match the result type,
  1507. // bitcast it to be a vector type we can extract from.
  1508. if (VecTy->getElementType() != DestTy) {
  1509. VecTy = VectorType::get(DestTy,
  1510. VecTy->getPrimitiveSizeInBits() / DestWidth);
  1511. VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
  1512. }
  1513. unsigned Elt = 0;
  1514. if (DL.isBigEndian())
  1515. Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1;
  1516. return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
  1517. }
  1518. }
  1519. // bitcast(trunc(lshr(bitcast(somevector), cst))
  1520. ConstantInt *ShAmt = nullptr;
  1521. if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
  1522. m_ConstantInt(ShAmt)))) &&
  1523. isa<VectorType>(VecInput->getType())) {
  1524. VectorType *VecTy = cast<VectorType>(VecInput->getType());
  1525. unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
  1526. if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
  1527. ShAmt->getZExtValue() % DestWidth == 0) {
  1528. // If the element type of the vector doesn't match the result type,
  1529. // bitcast it to be a vector type we can extract from.
  1530. if (VecTy->getElementType() != DestTy) {
  1531. VecTy = VectorType::get(DestTy,
  1532. VecTy->getPrimitiveSizeInBits() / DestWidth);
  1533. VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
  1534. }
  1535. unsigned Elt = ShAmt->getZExtValue() / DestWidth;
  1536. if (DL.isBigEndian())
  1537. Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1 - Elt;
  1538. return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
  1539. }
  1540. }
  1541. return nullptr;
  1542. }
  1543. Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
  1544. // If the operands are integer typed then apply the integer transforms,
  1545. // otherwise just apply the common ones.
  1546. Value *Src = CI.getOperand(0);
  1547. Type *SrcTy = Src->getType();
  1548. Type *DestTy = CI.getType();
  1549. // Get rid of casts from one type to the same type. These are useless and can
  1550. // be replaced by the operand.
  1551. if (DestTy == Src->getType())
  1552. return ReplaceInstUsesWith(CI, Src);
  1553. if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
  1554. PointerType *SrcPTy = cast<PointerType>(SrcTy);
  1555. Type *DstElTy = DstPTy->getElementType();
  1556. Type *SrcElTy = SrcPTy->getElementType();
  1557. // If we are casting a alloca to a pointer to a type of the same
  1558. // size, rewrite the allocation instruction to allocate the "right" type.
  1559. // There is no need to modify malloc calls because it is their bitcast that
  1560. // needs to be cleaned up.
  1561. if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
  1562. if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
  1563. return V;
  1564. // If the source and destination are pointers, and this cast is equivalent
  1565. // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
  1566. // This can enhance SROA and other transforms that want type-safe pointers.
  1567. unsigned NumZeros = 0;
  1568. while (SrcElTy != DstElTy &&
  1569. isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
  1570. SrcElTy->getNumContainedTypes() /* not "{}" */) {
  1571. SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(0U);
  1572. ++NumZeros;
  1573. }
  1574. // If we found a path from the src to dest, create the getelementptr now.
  1575. if (SrcElTy == DstElTy) {
  1576. SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder->getInt32(0));
  1577. return GetElementPtrInst::CreateInBounds(Src, Idxs);
  1578. }
  1579. }
  1580. // Try to optimize int -> float bitcasts.
  1581. if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
  1582. if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this, DL))
  1583. return I;
  1584. if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
  1585. if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
  1586. Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
  1587. return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
  1588. Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
  1589. // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
  1590. }
  1591. if (isa<IntegerType>(SrcTy)) {
  1592. // If this is a cast from an integer to vector, check to see if the input
  1593. // is a trunc or zext of a bitcast from vector. If so, we can replace all
  1594. // the casts with a shuffle and (potentially) a bitcast.
  1595. if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
  1596. CastInst *SrcCast = cast<CastInst>(Src);
  1597. if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
  1598. if (isa<VectorType>(BCIn->getOperand(0)->getType()))
  1599. if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
  1600. cast<VectorType>(DestTy), *this))
  1601. return I;
  1602. }
  1603. // If the input is an 'or' instruction, we may be doing shifts and ors to
  1604. // assemble the elements of the vector manually. Try to rip the code out
  1605. // and replace it with insertelements.
  1606. if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
  1607. return ReplaceInstUsesWith(CI, V);
  1608. }
  1609. }
  1610. if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
  1611. if (SrcVTy->getNumElements() == 1) {
  1612. // If our destination is not a vector, then make this a straight
  1613. // scalar-scalar cast.
  1614. if (!DestTy->isVectorTy()) {
  1615. Value *Elem =
  1616. Builder->CreateExtractElement(Src,
  1617. Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
  1618. return CastInst::Create(Instruction::BitCast, Elem, DestTy);
  1619. }
  1620. // Otherwise, see if our source is an insert. If so, then use the scalar
  1621. // component directly.
  1622. if (InsertElementInst *IEI =
  1623. dyn_cast<InsertElementInst>(CI.getOperand(0)))
  1624. return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
  1625. DestTy);
  1626. }
  1627. }
  1628. if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
  1629. // Okay, we have (bitcast (shuffle ..)). Check to see if this is
  1630. // a bitcast to a vector with the same # elts.
  1631. if (SVI->hasOneUse() && DestTy->isVectorTy() &&
  1632. DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
  1633. SVI->getType()->getNumElements() ==
  1634. SVI->getOperand(0)->getType()->getVectorNumElements()) {
  1635. BitCastInst *Tmp;
  1636. // If either of the operands is a cast from CI.getType(), then
  1637. // evaluating the shuffle in the casted destination's type will allow
  1638. // us to eliminate at least one cast.
  1639. if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
  1640. Tmp->getOperand(0)->getType() == DestTy) ||
  1641. ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
  1642. Tmp->getOperand(0)->getType() == DestTy)) {
  1643. Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
  1644. Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
  1645. // Return a new shuffle vector. Use the same element ID's, as we
  1646. // know the vector types match #elts.
  1647. return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
  1648. }
  1649. }
  1650. }
  1651. if (SrcTy->isPointerTy())
  1652. return commonPointerCastTransforms(CI);
  1653. return commonCastTransforms(CI);
  1654. }
  1655. Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
  1656. // If the destination pointer element type is not the same as the source's
  1657. // first do a bitcast to the destination type, and then the addrspacecast.
  1658. // This allows the cast to be exposed to other transforms.
  1659. Value *Src = CI.getOperand(0);
  1660. PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
  1661. PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
  1662. Type *DestElemTy = DestTy->getElementType();
  1663. if (SrcTy->getElementType() != DestElemTy) {
  1664. Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace());
  1665. if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) {
  1666. // Handle vectors of pointers.
  1667. MidTy = VectorType::get(MidTy, VT->getNumElements());
  1668. }
  1669. Value *NewBitCast = Builder->CreateBitCast(Src, MidTy);
  1670. return new AddrSpaceCastInst(NewBitCast, CI.getType());
  1671. }
  1672. return commonPointerCastTransforms(CI);
  1673. }