InstCombineVectorOps.cpp 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817
  1. //===- InstCombineVectorOps.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. // This file implements instcombine for ExtractElement, InsertElement and
  10. // ShuffleVector.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "InstCombineInternal.h"
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallBitVector.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/InstructionSimplify.h"
  22. #include "llvm/Analysis/VectorUtils.h"
  23. #include "llvm/IR/BasicBlock.h"
  24. #include "llvm/IR/Constant.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/InstrTypes.h"
  28. #include "llvm/IR/Instruction.h"
  29. #include "llvm/IR/Instructions.h"
  30. #include "llvm/IR/Operator.h"
  31. #include "llvm/IR/PatternMatch.h"
  32. #include "llvm/IR/Type.h"
  33. #include "llvm/IR/User.h"
  34. #include "llvm/IR/Value.h"
  35. #include "llvm/Support/Casting.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  38. #include <cassert>
  39. #include <cstdint>
  40. #include <iterator>
  41. #include <utility>
  42. #define DEBUG_TYPE "instcombine"
  43. #include "llvm/Transforms/Utils/InstructionWorklist.h"
  44. using namespace llvm;
  45. using namespace PatternMatch;
  46. STATISTIC(NumAggregateReconstructionsSimplified,
  47. "Number of aggregate reconstructions turned into reuse of the "
  48. "original aggregate");
  49. /// Return true if the value is cheaper to scalarize than it is to leave as a
  50. /// vector operation. If the extract index \p EI is a constant integer then
  51. /// some operations may be cheap to scalarize.
  52. ///
  53. /// FIXME: It's possible to create more instructions than previously existed.
  54. static bool cheapToScalarize(Value *V, Value *EI) {
  55. ConstantInt *CEI = dyn_cast<ConstantInt>(EI);
  56. // If we can pick a scalar constant value out of a vector, that is free.
  57. if (auto *C = dyn_cast<Constant>(V))
  58. return CEI || C->getSplatValue();
  59. if (CEI && match(V, m_Intrinsic<Intrinsic::experimental_stepvector>())) {
  60. ElementCount EC = cast<VectorType>(V->getType())->getElementCount();
  61. // Index needs to be lower than the minimum size of the vector, because
  62. // for scalable vector, the vector size is known at run time.
  63. return CEI->getValue().ult(EC.getKnownMinValue());
  64. }
  65. // An insertelement to the same constant index as our extract will simplify
  66. // to the scalar inserted element. An insertelement to a different constant
  67. // index is irrelevant to our extract.
  68. if (match(V, m_InsertElt(m_Value(), m_Value(), m_ConstantInt())))
  69. return CEI;
  70. if (match(V, m_OneUse(m_Load(m_Value()))))
  71. return true;
  72. if (match(V, m_OneUse(m_UnOp())))
  73. return true;
  74. Value *V0, *V1;
  75. if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1)))))
  76. if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
  77. return true;
  78. CmpInst::Predicate UnusedPred;
  79. if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1)))))
  80. if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
  81. return true;
  82. return false;
  83. }
  84. // If we have a PHI node with a vector type that is only used to feed
  85. // itself and be an operand of extractelement at a constant location,
  86. // try to replace the PHI of the vector type with a PHI of a scalar type.
  87. Instruction *InstCombinerImpl::scalarizePHI(ExtractElementInst &EI,
  88. PHINode *PN) {
  89. SmallVector<Instruction *, 2> Extracts;
  90. // The users we want the PHI to have are:
  91. // 1) The EI ExtractElement (we already know this)
  92. // 2) Possibly more ExtractElements with the same index.
  93. // 3) Another operand, which will feed back into the PHI.
  94. Instruction *PHIUser = nullptr;
  95. for (auto U : PN->users()) {
  96. if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
  97. if (EI.getIndexOperand() == EU->getIndexOperand())
  98. Extracts.push_back(EU);
  99. else
  100. return nullptr;
  101. } else if (!PHIUser) {
  102. PHIUser = cast<Instruction>(U);
  103. } else {
  104. return nullptr;
  105. }
  106. }
  107. if (!PHIUser)
  108. return nullptr;
  109. // Verify that this PHI user has one use, which is the PHI itself,
  110. // and that it is a binary operation which is cheap to scalarize.
  111. // otherwise return nullptr.
  112. if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
  113. !(isa<BinaryOperator>(PHIUser)) ||
  114. !cheapToScalarize(PHIUser, EI.getIndexOperand()))
  115. return nullptr;
  116. // Create a scalar PHI node that will replace the vector PHI node
  117. // just before the current PHI node.
  118. PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
  119. PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
  120. // Scalarize each PHI operand.
  121. for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
  122. Value *PHIInVal = PN->getIncomingValue(i);
  123. BasicBlock *inBB = PN->getIncomingBlock(i);
  124. Value *Elt = EI.getIndexOperand();
  125. // If the operand is the PHI induction variable:
  126. if (PHIInVal == PHIUser) {
  127. // Scalarize the binary operation. Its first operand is the
  128. // scalar PHI, and the second operand is extracted from the other
  129. // vector operand.
  130. BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
  131. unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
  132. Value *Op = InsertNewInstWith(
  133. ExtractElementInst::Create(B0->getOperand(opId), Elt,
  134. B0->getOperand(opId)->getName() + ".Elt"),
  135. *B0);
  136. Value *newPHIUser = InsertNewInstWith(
  137. BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
  138. scalarPHI, Op, B0), *B0);
  139. scalarPHI->addIncoming(newPHIUser, inBB);
  140. } else {
  141. // Scalarize PHI input:
  142. Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
  143. // Insert the new instruction into the predecessor basic block.
  144. Instruction *pos = dyn_cast<Instruction>(PHIInVal);
  145. BasicBlock::iterator InsertPos;
  146. if (pos && !isa<PHINode>(pos)) {
  147. InsertPos = ++pos->getIterator();
  148. } else {
  149. InsertPos = inBB->getFirstInsertionPt();
  150. }
  151. InsertNewInstWith(newEI, *InsertPos);
  152. scalarPHI->addIncoming(newEI, inBB);
  153. }
  154. }
  155. for (auto E : Extracts)
  156. replaceInstUsesWith(*E, scalarPHI);
  157. return &EI;
  158. }
  159. Instruction *InstCombinerImpl::foldBitcastExtElt(ExtractElementInst &Ext) {
  160. Value *X;
  161. uint64_t ExtIndexC;
  162. if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
  163. !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
  164. return nullptr;
  165. ElementCount NumElts =
  166. cast<VectorType>(Ext.getVectorOperandType())->getElementCount();
  167. Type *DestTy = Ext.getType();
  168. bool IsBigEndian = DL.isBigEndian();
  169. // If we are casting an integer to vector and extracting a portion, that is
  170. // a shift-right and truncate.
  171. // TODO: Allow FP dest type by casting the trunc to FP?
  172. if (X->getType()->isIntegerTy() && DestTy->isIntegerTy() &&
  173. isDesirableIntType(X->getType()->getPrimitiveSizeInBits())) {
  174. assert(isa<FixedVectorType>(Ext.getVectorOperand()->getType()) &&
  175. "Expected fixed vector type for bitcast from scalar integer");
  176. // Big endian requires adjusting the extract index since MSB is at index 0.
  177. // LittleEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 X to i8
  178. // BigEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 (X >> 24) to i8
  179. if (IsBigEndian)
  180. ExtIndexC = NumElts.getKnownMinValue() - 1 - ExtIndexC;
  181. unsigned ShiftAmountC = ExtIndexC * DestTy->getPrimitiveSizeInBits();
  182. if (!ShiftAmountC || Ext.getVectorOperand()->hasOneUse()) {
  183. Value *Lshr = Builder.CreateLShr(X, ShiftAmountC, "extelt.offset");
  184. return new TruncInst(Lshr, DestTy);
  185. }
  186. }
  187. if (!X->getType()->isVectorTy())
  188. return nullptr;
  189. // If this extractelement is using a bitcast from a vector of the same number
  190. // of elements, see if we can find the source element from the source vector:
  191. // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
  192. auto *SrcTy = cast<VectorType>(X->getType());
  193. ElementCount NumSrcElts = SrcTy->getElementCount();
  194. if (NumSrcElts == NumElts)
  195. if (Value *Elt = findScalarElement(X, ExtIndexC))
  196. return new BitCastInst(Elt, DestTy);
  197. assert(NumSrcElts.isScalable() == NumElts.isScalable() &&
  198. "Src and Dst must be the same sort of vector type");
  199. // If the source elements are wider than the destination, try to shift and
  200. // truncate a subset of scalar bits of an insert op.
  201. if (NumSrcElts.getKnownMinValue() < NumElts.getKnownMinValue()) {
  202. Value *Scalar;
  203. uint64_t InsIndexC;
  204. if (!match(X, m_InsertElt(m_Value(), m_Value(Scalar),
  205. m_ConstantInt(InsIndexC))))
  206. return nullptr;
  207. // The extract must be from the subset of vector elements that we inserted
  208. // into. Example: if we inserted element 1 of a <2 x i64> and we are
  209. // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
  210. // of elements 4-7 of the bitcasted vector.
  211. unsigned NarrowingRatio =
  212. NumElts.getKnownMinValue() / NumSrcElts.getKnownMinValue();
  213. if (ExtIndexC / NarrowingRatio != InsIndexC)
  214. return nullptr;
  215. // We are extracting part of the original scalar. How that scalar is
  216. // inserted into the vector depends on the endian-ness. Example:
  217. // Vector Byte Elt Index: 0 1 2 3 4 5 6 7
  218. // +--+--+--+--+--+--+--+--+
  219. // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3|
  220. // extelt <4 x i16> V', 3: | |S2|S3|
  221. // +--+--+--+--+--+--+--+--+
  222. // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
  223. // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
  224. // In this example, we must right-shift little-endian. Big-endian is just a
  225. // truncate.
  226. unsigned Chunk = ExtIndexC % NarrowingRatio;
  227. if (IsBigEndian)
  228. Chunk = NarrowingRatio - 1 - Chunk;
  229. // Bail out if this is an FP vector to FP vector sequence. That would take
  230. // more instructions than we started with unless there is no shift, and it
  231. // may not be handled as well in the backend.
  232. bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
  233. bool NeedDestBitcast = DestTy->isFloatingPointTy();
  234. if (NeedSrcBitcast && NeedDestBitcast)
  235. return nullptr;
  236. unsigned SrcWidth = SrcTy->getScalarSizeInBits();
  237. unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
  238. unsigned ShAmt = Chunk * DestWidth;
  239. // TODO: This limitation is more strict than necessary. We could sum the
  240. // number of new instructions and subtract the number eliminated to know if
  241. // we can proceed.
  242. if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse())
  243. if (NeedSrcBitcast || NeedDestBitcast)
  244. return nullptr;
  245. if (NeedSrcBitcast) {
  246. Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth);
  247. Scalar = Builder.CreateBitCast(Scalar, SrcIntTy);
  248. }
  249. if (ShAmt) {
  250. // Bail out if we could end with more instructions than we started with.
  251. if (!Ext.getVectorOperand()->hasOneUse())
  252. return nullptr;
  253. Scalar = Builder.CreateLShr(Scalar, ShAmt);
  254. }
  255. if (NeedDestBitcast) {
  256. Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth);
  257. return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
  258. }
  259. return new TruncInst(Scalar, DestTy);
  260. }
  261. return nullptr;
  262. }
  263. /// Find elements of V demanded by UserInstr.
  264. static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr) {
  265. unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
  266. // Conservatively assume that all elements are needed.
  267. APInt UsedElts(APInt::getAllOnes(VWidth));
  268. switch (UserInstr->getOpcode()) {
  269. case Instruction::ExtractElement: {
  270. ExtractElementInst *EEI = cast<ExtractElementInst>(UserInstr);
  271. assert(EEI->getVectorOperand() == V);
  272. ConstantInt *EEIIndexC = dyn_cast<ConstantInt>(EEI->getIndexOperand());
  273. if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) {
  274. UsedElts = APInt::getOneBitSet(VWidth, EEIIndexC->getZExtValue());
  275. }
  276. break;
  277. }
  278. case Instruction::ShuffleVector: {
  279. ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr);
  280. unsigned MaskNumElts =
  281. cast<FixedVectorType>(UserInstr->getType())->getNumElements();
  282. UsedElts = APInt(VWidth, 0);
  283. for (unsigned i = 0; i < MaskNumElts; i++) {
  284. unsigned MaskVal = Shuffle->getMaskValue(i);
  285. if (MaskVal == -1u || MaskVal >= 2 * VWidth)
  286. continue;
  287. if (Shuffle->getOperand(0) == V && (MaskVal < VWidth))
  288. UsedElts.setBit(MaskVal);
  289. if (Shuffle->getOperand(1) == V &&
  290. ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
  291. UsedElts.setBit(MaskVal - VWidth);
  292. }
  293. break;
  294. }
  295. default:
  296. break;
  297. }
  298. return UsedElts;
  299. }
  300. /// Find union of elements of V demanded by all its users.
  301. /// If it is known by querying findDemandedEltsBySingleUser that
  302. /// no user demands an element of V, then the corresponding bit
  303. /// remains unset in the returned value.
  304. static APInt findDemandedEltsByAllUsers(Value *V) {
  305. unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
  306. APInt UnionUsedElts(VWidth, 0);
  307. for (const Use &U : V->uses()) {
  308. if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
  309. UnionUsedElts |= findDemandedEltsBySingleUser(V, I);
  310. } else {
  311. UnionUsedElts = APInt::getAllOnes(VWidth);
  312. break;
  313. }
  314. if (UnionUsedElts.isAllOnes())
  315. break;
  316. }
  317. return UnionUsedElts;
  318. }
  319. /// Given a constant index for a extractelement or insertelement instruction,
  320. /// return it with the canonical type if it isn't already canonical. We
  321. /// arbitrarily pick 64 bit as our canonical type. The actual bitwidth doesn't
  322. /// matter, we just want a consistent type to simplify CSE.
  323. ConstantInt *getPreferredVectorIndex(ConstantInt *IndexC) {
  324. const unsigned IndexBW = IndexC->getType()->getBitWidth();
  325. if (IndexBW == 64 || IndexC->getValue().getActiveBits() > 64)
  326. return nullptr;
  327. return ConstantInt::get(IndexC->getContext(),
  328. IndexC->getValue().zextOrTrunc(64));
  329. }
  330. Instruction *InstCombinerImpl::visitExtractElementInst(ExtractElementInst &EI) {
  331. Value *SrcVec = EI.getVectorOperand();
  332. Value *Index = EI.getIndexOperand();
  333. if (Value *V = SimplifyExtractElementInst(SrcVec, Index,
  334. SQ.getWithInstruction(&EI)))
  335. return replaceInstUsesWith(EI, V);
  336. // If extracting a specified index from the vector, see if we can recursively
  337. // find a previously computed scalar that was inserted into the vector.
  338. auto *IndexC = dyn_cast<ConstantInt>(Index);
  339. if (IndexC) {
  340. // Canonicalize type of constant indices to i64 to simplify CSE
  341. if (auto *NewIdx = getPreferredVectorIndex(IndexC))
  342. return replaceOperand(EI, 1, NewIdx);
  343. ElementCount EC = EI.getVectorOperandType()->getElementCount();
  344. unsigned NumElts = EC.getKnownMinValue();
  345. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(SrcVec)) {
  346. Intrinsic::ID IID = II->getIntrinsicID();
  347. // Index needs to be lower than the minimum size of the vector, because
  348. // for scalable vector, the vector size is known at run time.
  349. if (IID == Intrinsic::experimental_stepvector &&
  350. IndexC->getValue().ult(NumElts)) {
  351. Type *Ty = EI.getType();
  352. unsigned BitWidth = Ty->getIntegerBitWidth();
  353. Value *Idx;
  354. // Return index when its value does not exceed the allowed limit
  355. // for the element type of the vector, otherwise return undefined.
  356. if (IndexC->getValue().getActiveBits() <= BitWidth)
  357. Idx = ConstantInt::get(Ty, IndexC->getValue().zextOrTrunc(BitWidth));
  358. else
  359. Idx = UndefValue::get(Ty);
  360. return replaceInstUsesWith(EI, Idx);
  361. }
  362. }
  363. // InstSimplify should handle cases where the index is invalid.
  364. // For fixed-length vector, it's invalid to extract out-of-range element.
  365. if (!EC.isScalable() && IndexC->getValue().uge(NumElts))
  366. return nullptr;
  367. if (Instruction *I = foldBitcastExtElt(EI))
  368. return I;
  369. // If there's a vector PHI feeding a scalar use through this extractelement
  370. // instruction, try to scalarize the PHI.
  371. if (auto *Phi = dyn_cast<PHINode>(SrcVec))
  372. if (Instruction *ScalarPHI = scalarizePHI(EI, Phi))
  373. return ScalarPHI;
  374. }
  375. // TODO come up with a n-ary matcher that subsumes both unary and
  376. // binary matchers.
  377. UnaryOperator *UO;
  378. if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, Index)) {
  379. // extelt (unop X), Index --> unop (extelt X, Index)
  380. Value *X = UO->getOperand(0);
  381. Value *E = Builder.CreateExtractElement(X, Index);
  382. return UnaryOperator::CreateWithCopiedFlags(UO->getOpcode(), E, UO);
  383. }
  384. BinaryOperator *BO;
  385. if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, Index)) {
  386. // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index)
  387. Value *X = BO->getOperand(0), *Y = BO->getOperand(1);
  388. Value *E0 = Builder.CreateExtractElement(X, Index);
  389. Value *E1 = Builder.CreateExtractElement(Y, Index);
  390. return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO);
  391. }
  392. Value *X, *Y;
  393. CmpInst::Predicate Pred;
  394. if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) &&
  395. cheapToScalarize(SrcVec, Index)) {
  396. // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index)
  397. Value *E0 = Builder.CreateExtractElement(X, Index);
  398. Value *E1 = Builder.CreateExtractElement(Y, Index);
  399. return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1);
  400. }
  401. if (auto *I = dyn_cast<Instruction>(SrcVec)) {
  402. if (auto *IE = dyn_cast<InsertElementInst>(I)) {
  403. // instsimplify already handled the case where the indices are constants
  404. // and equal by value, if both are constants, they must not be the same
  405. // value, extract from the pre-inserted value instead.
  406. if (isa<Constant>(IE->getOperand(2)) && IndexC)
  407. return replaceOperand(EI, 0, IE->getOperand(0));
  408. } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
  409. auto *VecType = cast<VectorType>(GEP->getType());
  410. ElementCount EC = VecType->getElementCount();
  411. uint64_t IdxVal = IndexC ? IndexC->getZExtValue() : 0;
  412. if (IndexC && IdxVal < EC.getKnownMinValue() && GEP->hasOneUse()) {
  413. // Find out why we have a vector result - these are a few examples:
  414. // 1. We have a scalar pointer and a vector of indices, or
  415. // 2. We have a vector of pointers and a scalar index, or
  416. // 3. We have a vector of pointers and a vector of indices, etc.
  417. // Here we only consider combining when there is exactly one vector
  418. // operand, since the optimization is less obviously a win due to
  419. // needing more than one extractelements.
  420. unsigned VectorOps =
  421. llvm::count_if(GEP->operands(), [](const Value *V) {
  422. return isa<VectorType>(V->getType());
  423. });
  424. if (VectorOps == 1) {
  425. Value *NewPtr = GEP->getPointerOperand();
  426. if (isa<VectorType>(NewPtr->getType()))
  427. NewPtr = Builder.CreateExtractElement(NewPtr, IndexC);
  428. SmallVector<Value *> NewOps;
  429. for (unsigned I = 1; I != GEP->getNumOperands(); ++I) {
  430. Value *Op = GEP->getOperand(I);
  431. if (isa<VectorType>(Op->getType()))
  432. NewOps.push_back(Builder.CreateExtractElement(Op, IndexC));
  433. else
  434. NewOps.push_back(Op);
  435. }
  436. GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
  437. GEP->getSourceElementType(), NewPtr, NewOps);
  438. NewGEP->setIsInBounds(GEP->isInBounds());
  439. return NewGEP;
  440. }
  441. }
  442. } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
  443. // If this is extracting an element from a shufflevector, figure out where
  444. // it came from and extract from the appropriate input element instead.
  445. // Restrict the following transformation to fixed-length vector.
  446. if (isa<FixedVectorType>(SVI->getType()) && isa<ConstantInt>(Index)) {
  447. int SrcIdx =
  448. SVI->getMaskValue(cast<ConstantInt>(Index)->getZExtValue());
  449. Value *Src;
  450. unsigned LHSWidth = cast<FixedVectorType>(SVI->getOperand(0)->getType())
  451. ->getNumElements();
  452. if (SrcIdx < 0)
  453. return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
  454. if (SrcIdx < (int)LHSWidth)
  455. Src = SVI->getOperand(0);
  456. else {
  457. SrcIdx -= LHSWidth;
  458. Src = SVI->getOperand(1);
  459. }
  460. Type *Int32Ty = Type::getInt32Ty(EI.getContext());
  461. return ExtractElementInst::Create(
  462. Src, ConstantInt::get(Int32Ty, SrcIdx, false));
  463. }
  464. } else if (auto *CI = dyn_cast<CastInst>(I)) {
  465. // Canonicalize extractelement(cast) -> cast(extractelement).
  466. // Bitcasts can change the number of vector elements, and they cost
  467. // nothing.
  468. if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
  469. Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index);
  470. return CastInst::Create(CI->getOpcode(), EE, EI.getType());
  471. }
  472. }
  473. }
  474. // Run demanded elements after other transforms as this can drop flags on
  475. // binops. If there's two paths to the same final result, we prefer the
  476. // one which doesn't force us to drop flags.
  477. if (IndexC) {
  478. ElementCount EC = EI.getVectorOperandType()->getElementCount();
  479. unsigned NumElts = EC.getKnownMinValue();
  480. // This instruction only demands the single element from the input vector.
  481. // Skip for scalable type, the number of elements is unknown at
  482. // compile-time.
  483. if (!EC.isScalable() && NumElts != 1) {
  484. // If the input vector has a single use, simplify it based on this use
  485. // property.
  486. if (SrcVec->hasOneUse()) {
  487. APInt UndefElts(NumElts, 0);
  488. APInt DemandedElts(NumElts, 0);
  489. DemandedElts.setBit(IndexC->getZExtValue());
  490. if (Value *V =
  491. SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts))
  492. return replaceOperand(EI, 0, V);
  493. } else {
  494. // If the input vector has multiple uses, simplify it based on a union
  495. // of all elements used.
  496. APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec);
  497. if (!DemandedElts.isAllOnes()) {
  498. APInt UndefElts(NumElts, 0);
  499. if (Value *V = SimplifyDemandedVectorElts(
  500. SrcVec, DemandedElts, UndefElts, 0 /* Depth */,
  501. true /* AllowMultipleUsers */)) {
  502. if (V != SrcVec) {
  503. SrcVec->replaceAllUsesWith(V);
  504. return &EI;
  505. }
  506. }
  507. }
  508. }
  509. }
  510. }
  511. return nullptr;
  512. }
  513. /// If V is a shuffle of values that ONLY returns elements from either LHS or
  514. /// RHS, return the shuffle mask and true. Otherwise, return false.
  515. static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
  516. SmallVectorImpl<int> &Mask) {
  517. assert(LHS->getType() == RHS->getType() &&
  518. "Invalid CollectSingleShuffleElements");
  519. unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
  520. if (match(V, m_Undef())) {
  521. Mask.assign(NumElts, -1);
  522. return true;
  523. }
  524. if (V == LHS) {
  525. for (unsigned i = 0; i != NumElts; ++i)
  526. Mask.push_back(i);
  527. return true;
  528. }
  529. if (V == RHS) {
  530. for (unsigned i = 0; i != NumElts; ++i)
  531. Mask.push_back(i + NumElts);
  532. return true;
  533. }
  534. if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
  535. // If this is an insert of an extract from some other vector, include it.
  536. Value *VecOp = IEI->getOperand(0);
  537. Value *ScalarOp = IEI->getOperand(1);
  538. Value *IdxOp = IEI->getOperand(2);
  539. if (!isa<ConstantInt>(IdxOp))
  540. return false;
  541. unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
  542. if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
  543. // We can handle this if the vector we are inserting into is
  544. // transitively ok.
  545. if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
  546. // If so, update the mask to reflect the inserted undef.
  547. Mask[InsertedIdx] = -1;
  548. return true;
  549. }
  550. } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
  551. if (isa<ConstantInt>(EI->getOperand(1))) {
  552. unsigned ExtractedIdx =
  553. cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
  554. unsigned NumLHSElts =
  555. cast<FixedVectorType>(LHS->getType())->getNumElements();
  556. // This must be extracting from either LHS or RHS.
  557. if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
  558. // We can handle this if the vector we are inserting into is
  559. // transitively ok.
  560. if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
  561. // If so, update the mask to reflect the inserted value.
  562. if (EI->getOperand(0) == LHS) {
  563. Mask[InsertedIdx % NumElts] = ExtractedIdx;
  564. } else {
  565. assert(EI->getOperand(0) == RHS);
  566. Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts;
  567. }
  568. return true;
  569. }
  570. }
  571. }
  572. }
  573. }
  574. return false;
  575. }
  576. /// If we have insertion into a vector that is wider than the vector that we
  577. /// are extracting from, try to widen the source vector to allow a single
  578. /// shufflevector to replace one or more insert/extract pairs.
  579. static void replaceExtractElements(InsertElementInst *InsElt,
  580. ExtractElementInst *ExtElt,
  581. InstCombinerImpl &IC) {
  582. auto *InsVecType = cast<FixedVectorType>(InsElt->getType());
  583. auto *ExtVecType = cast<FixedVectorType>(ExtElt->getVectorOperandType());
  584. unsigned NumInsElts = InsVecType->getNumElements();
  585. unsigned NumExtElts = ExtVecType->getNumElements();
  586. // The inserted-to vector must be wider than the extracted-from vector.
  587. if (InsVecType->getElementType() != ExtVecType->getElementType() ||
  588. NumExtElts >= NumInsElts)
  589. return;
  590. // Create a shuffle mask to widen the extended-from vector using poison
  591. // values. The mask selects all of the values of the original vector followed
  592. // by as many poison values as needed to create a vector of the same length
  593. // as the inserted-to vector.
  594. SmallVector<int, 16> ExtendMask;
  595. for (unsigned i = 0; i < NumExtElts; ++i)
  596. ExtendMask.push_back(i);
  597. for (unsigned i = NumExtElts; i < NumInsElts; ++i)
  598. ExtendMask.push_back(-1);
  599. Value *ExtVecOp = ExtElt->getVectorOperand();
  600. auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
  601. BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
  602. ? ExtVecOpInst->getParent()
  603. : ExtElt->getParent();
  604. // TODO: This restriction matches the basic block check below when creating
  605. // new extractelement instructions. If that limitation is removed, this one
  606. // could also be removed. But for now, we just bail out to ensure that we
  607. // will replace the extractelement instruction that is feeding our
  608. // insertelement instruction. This allows the insertelement to then be
  609. // replaced by a shufflevector. If the insertelement is not replaced, we can
  610. // induce infinite looping because there's an optimization for extractelement
  611. // that will delete our widening shuffle. This would trigger another attempt
  612. // here to create that shuffle, and we spin forever.
  613. if (InsertionBlock != InsElt->getParent())
  614. return;
  615. // TODO: This restriction matches the check in visitInsertElementInst() and
  616. // prevents an infinite loop caused by not turning the extract/insert pair
  617. // into a shuffle. We really should not need either check, but we're lacking
  618. // folds for shufflevectors because we're afraid to generate shuffle masks
  619. // that the backend can't handle.
  620. if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
  621. return;
  622. auto *WideVec = new ShuffleVectorInst(ExtVecOp, ExtendMask);
  623. // Insert the new shuffle after the vector operand of the extract is defined
  624. // (as long as it's not a PHI) or at the start of the basic block of the
  625. // extract, so any subsequent extracts in the same basic block can use it.
  626. // TODO: Insert before the earliest ExtractElementInst that is replaced.
  627. if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
  628. WideVec->insertAfter(ExtVecOpInst);
  629. else
  630. IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
  631. // Replace extracts from the original narrow vector with extracts from the new
  632. // wide vector.
  633. for (User *U : ExtVecOp->users()) {
  634. ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
  635. if (!OldExt || OldExt->getParent() != WideVec->getParent())
  636. continue;
  637. auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
  638. NewExt->insertAfter(OldExt);
  639. IC.replaceInstUsesWith(*OldExt, NewExt);
  640. }
  641. }
  642. /// We are building a shuffle to create V, which is a sequence of insertelement,
  643. /// extractelement pairs. If PermittedRHS is set, then we must either use it or
  644. /// not rely on the second vector source. Return a std::pair containing the
  645. /// left and right vectors of the proposed shuffle (or 0), and set the Mask
  646. /// parameter as required.
  647. ///
  648. /// Note: we intentionally don't try to fold earlier shuffles since they have
  649. /// often been chosen carefully to be efficiently implementable on the target.
  650. using ShuffleOps = std::pair<Value *, Value *>;
  651. static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl<int> &Mask,
  652. Value *PermittedRHS,
  653. InstCombinerImpl &IC) {
  654. assert(V->getType()->isVectorTy() && "Invalid shuffle!");
  655. unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
  656. if (match(V, m_Undef())) {
  657. Mask.assign(NumElts, -1);
  658. return std::make_pair(
  659. PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
  660. }
  661. if (isa<ConstantAggregateZero>(V)) {
  662. Mask.assign(NumElts, 0);
  663. return std::make_pair(V, nullptr);
  664. }
  665. if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
  666. // If this is an insert of an extract from some other vector, include it.
  667. Value *VecOp = IEI->getOperand(0);
  668. Value *ScalarOp = IEI->getOperand(1);
  669. Value *IdxOp = IEI->getOperand(2);
  670. if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
  671. if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
  672. unsigned ExtractedIdx =
  673. cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
  674. unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
  675. // Either the extracted from or inserted into vector must be RHSVec,
  676. // otherwise we'd end up with a shuffle of three inputs.
  677. if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
  678. Value *RHS = EI->getOperand(0);
  679. ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
  680. assert(LR.second == nullptr || LR.second == RHS);
  681. if (LR.first->getType() != RHS->getType()) {
  682. // Although we are giving up for now, see if we can create extracts
  683. // that match the inserts for another round of combining.
  684. replaceExtractElements(IEI, EI, IC);
  685. // We tried our best, but we can't find anything compatible with RHS
  686. // further up the chain. Return a trivial shuffle.
  687. for (unsigned i = 0; i < NumElts; ++i)
  688. Mask[i] = i;
  689. return std::make_pair(V, nullptr);
  690. }
  691. unsigned NumLHSElts =
  692. cast<FixedVectorType>(RHS->getType())->getNumElements();
  693. Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx;
  694. return std::make_pair(LR.first, RHS);
  695. }
  696. if (VecOp == PermittedRHS) {
  697. // We've gone as far as we can: anything on the other side of the
  698. // extractelement will already have been converted into a shuffle.
  699. unsigned NumLHSElts =
  700. cast<FixedVectorType>(EI->getOperand(0)->getType())
  701. ->getNumElements();
  702. for (unsigned i = 0; i != NumElts; ++i)
  703. Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i);
  704. return std::make_pair(EI->getOperand(0), PermittedRHS);
  705. }
  706. // If this insertelement is a chain that comes from exactly these two
  707. // vectors, return the vector and the effective shuffle.
  708. if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
  709. collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
  710. Mask))
  711. return std::make_pair(EI->getOperand(0), PermittedRHS);
  712. }
  713. }
  714. }
  715. // Otherwise, we can't do anything fancy. Return an identity vector.
  716. for (unsigned i = 0; i != NumElts; ++i)
  717. Mask.push_back(i);
  718. return std::make_pair(V, nullptr);
  719. }
  720. /// Look for chain of insertvalue's that fully define an aggregate, and trace
  721. /// back the values inserted, see if they are all were extractvalue'd from
  722. /// the same source aggregate from the exact same element indexes.
  723. /// If they were, just reuse the source aggregate.
  724. /// This potentially deals with PHI indirections.
  725. Instruction *InstCombinerImpl::foldAggregateConstructionIntoAggregateReuse(
  726. InsertValueInst &OrigIVI) {
  727. Type *AggTy = OrigIVI.getType();
  728. unsigned NumAggElts;
  729. switch (AggTy->getTypeID()) {
  730. case Type::StructTyID:
  731. NumAggElts = AggTy->getStructNumElements();
  732. break;
  733. case Type::ArrayTyID:
  734. NumAggElts = AggTy->getArrayNumElements();
  735. break;
  736. default:
  737. llvm_unreachable("Unhandled aggregate type?");
  738. }
  739. // Arbitrary aggregate size cut-off. Motivation for limit of 2 is to be able
  740. // to handle clang C++ exception struct (which is hardcoded as {i8*, i32}),
  741. // FIXME: any interesting patterns to be caught with larger limit?
  742. assert(NumAggElts > 0 && "Aggregate should have elements.");
  743. if (NumAggElts > 2)
  744. return nullptr;
  745. static constexpr auto NotFound = None;
  746. static constexpr auto FoundMismatch = nullptr;
  747. // Try to find a value of each element of an aggregate.
  748. // FIXME: deal with more complex, not one-dimensional, aggregate types
  749. SmallVector<Optional<Instruction *>, 2> AggElts(NumAggElts, NotFound);
  750. // Do we know values for each element of the aggregate?
  751. auto KnowAllElts = [&AggElts]() {
  752. return all_of(AggElts,
  753. [](Optional<Instruction *> Elt) { return Elt != NotFound; });
  754. };
  755. int Depth = 0;
  756. // Arbitrary `insertvalue` visitation depth limit. Let's be okay with
  757. // every element being overwritten twice, which should never happen.
  758. static const int DepthLimit = 2 * NumAggElts;
  759. // Recurse up the chain of `insertvalue` aggregate operands until either we've
  760. // reconstructed full initializer or can't visit any more `insertvalue`'s.
  761. for (InsertValueInst *CurrIVI = &OrigIVI;
  762. Depth < DepthLimit && CurrIVI && !KnowAllElts();
  763. CurrIVI = dyn_cast<InsertValueInst>(CurrIVI->getAggregateOperand()),
  764. ++Depth) {
  765. auto *InsertedValue =
  766. dyn_cast<Instruction>(CurrIVI->getInsertedValueOperand());
  767. if (!InsertedValue)
  768. return nullptr; // Inserted value must be produced by an instruction.
  769. ArrayRef<unsigned int> Indices = CurrIVI->getIndices();
  770. // Don't bother with more than single-level aggregates.
  771. if (Indices.size() != 1)
  772. return nullptr; // FIXME: deal with more complex aggregates?
  773. // Now, we may have already previously recorded the value for this element
  774. // of an aggregate. If we did, that means the CurrIVI will later be
  775. // overwritten with the already-recorded value. But if not, let's record it!
  776. Optional<Instruction *> &Elt = AggElts[Indices.front()];
  777. Elt = Elt.getValueOr(InsertedValue);
  778. // FIXME: should we handle chain-terminating undef base operand?
  779. }
  780. // Was that sufficient to deduce the full initializer for the aggregate?
  781. if (!KnowAllElts())
  782. return nullptr; // Give up then.
  783. // We now want to find the source[s] of the aggregate elements we've found.
  784. // And with "source" we mean the original aggregate[s] from which
  785. // the inserted elements were extracted. This may require PHI translation.
  786. enum class AggregateDescription {
  787. /// When analyzing the value that was inserted into an aggregate, we did
  788. /// not manage to find defining `extractvalue` instruction to analyze.
  789. NotFound,
  790. /// When analyzing the value that was inserted into an aggregate, we did
  791. /// manage to find defining `extractvalue` instruction[s], and everything
  792. /// matched perfectly - aggregate type, element insertion/extraction index.
  793. Found,
  794. /// When analyzing the value that was inserted into an aggregate, we did
  795. /// manage to find defining `extractvalue` instruction, but there was
  796. /// a mismatch: either the source type from which the extraction was didn't
  797. /// match the aggregate type into which the insertion was,
  798. /// or the extraction/insertion channels mismatched,
  799. /// or different elements had different source aggregates.
  800. FoundMismatch
  801. };
  802. auto Describe = [](Optional<Value *> SourceAggregate) {
  803. if (SourceAggregate == NotFound)
  804. return AggregateDescription::NotFound;
  805. if (*SourceAggregate == FoundMismatch)
  806. return AggregateDescription::FoundMismatch;
  807. return AggregateDescription::Found;
  808. };
  809. // Given the value \p Elt that was being inserted into element \p EltIdx of an
  810. // aggregate AggTy, see if \p Elt was originally defined by an
  811. // appropriate extractvalue (same element index, same aggregate type).
  812. // If found, return the source aggregate from which the extraction was.
  813. // If \p PredBB is provided, does PHI translation of an \p Elt first.
  814. auto FindSourceAggregate =
  815. [&](Instruction *Elt, unsigned EltIdx, Optional<BasicBlock *> UseBB,
  816. Optional<BasicBlock *> PredBB) -> Optional<Value *> {
  817. // For now(?), only deal with, at most, a single level of PHI indirection.
  818. if (UseBB && PredBB)
  819. Elt = dyn_cast<Instruction>(Elt->DoPHITranslation(*UseBB, *PredBB));
  820. // FIXME: deal with multiple levels of PHI indirection?
  821. // Did we find an extraction?
  822. auto *EVI = dyn_cast_or_null<ExtractValueInst>(Elt);
  823. if (!EVI)
  824. return NotFound;
  825. Value *SourceAggregate = EVI->getAggregateOperand();
  826. // Is the extraction from the same type into which the insertion was?
  827. if (SourceAggregate->getType() != AggTy)
  828. return FoundMismatch;
  829. // And the element index doesn't change between extraction and insertion?
  830. if (EVI->getNumIndices() != 1 || EltIdx != EVI->getIndices().front())
  831. return FoundMismatch;
  832. return SourceAggregate; // AggregateDescription::Found
  833. };
  834. // Given elements AggElts that were constructing an aggregate OrigIVI,
  835. // see if we can find appropriate source aggregate for each of the elements,
  836. // and see it's the same aggregate for each element. If so, return it.
  837. auto FindCommonSourceAggregate =
  838. [&](Optional<BasicBlock *> UseBB,
  839. Optional<BasicBlock *> PredBB) -> Optional<Value *> {
  840. Optional<Value *> SourceAggregate;
  841. for (auto I : enumerate(AggElts)) {
  842. assert(Describe(SourceAggregate) != AggregateDescription::FoundMismatch &&
  843. "We don't store nullptr in SourceAggregate!");
  844. assert((Describe(SourceAggregate) == AggregateDescription::Found) ==
  845. (I.index() != 0) &&
  846. "SourceAggregate should be valid after the first element,");
  847. // For this element, is there a plausible source aggregate?
  848. // FIXME: we could special-case undef element, IFF we know that in the
  849. // source aggregate said element isn't poison.
  850. Optional<Value *> SourceAggregateForElement =
  851. FindSourceAggregate(*I.value(), I.index(), UseBB, PredBB);
  852. // Okay, what have we found? Does that correlate with previous findings?
  853. // Regardless of whether or not we have previously found source
  854. // aggregate for previous elements (if any), if we didn't find one for
  855. // this element, passthrough whatever we have just found.
  856. if (Describe(SourceAggregateForElement) != AggregateDescription::Found)
  857. return SourceAggregateForElement;
  858. // Okay, we have found source aggregate for this element.
  859. // Let's see what we already know from previous elements, if any.
  860. switch (Describe(SourceAggregate)) {
  861. case AggregateDescription::NotFound:
  862. // This is apparently the first element that we have examined.
  863. SourceAggregate = SourceAggregateForElement; // Record the aggregate!
  864. continue; // Great, now look at next element.
  865. case AggregateDescription::Found:
  866. // We have previously already successfully examined other elements.
  867. // Is this the same source aggregate we've found for other elements?
  868. if (*SourceAggregateForElement != *SourceAggregate)
  869. return FoundMismatch;
  870. continue; // Still the same aggregate, look at next element.
  871. case AggregateDescription::FoundMismatch:
  872. llvm_unreachable("Can't happen. We would have early-exited then.");
  873. };
  874. }
  875. assert(Describe(SourceAggregate) == AggregateDescription::Found &&
  876. "Must be a valid Value");
  877. return *SourceAggregate;
  878. };
  879. Optional<Value *> SourceAggregate;
  880. // Can we find the source aggregate without looking at predecessors?
  881. SourceAggregate = FindCommonSourceAggregate(/*UseBB=*/None, /*PredBB=*/None);
  882. if (Describe(SourceAggregate) != AggregateDescription::NotFound) {
  883. if (Describe(SourceAggregate) == AggregateDescription::FoundMismatch)
  884. return nullptr; // Conflicting source aggregates!
  885. ++NumAggregateReconstructionsSimplified;
  886. return replaceInstUsesWith(OrigIVI, *SourceAggregate);
  887. }
  888. // Okay, apparently we need to look at predecessors.
  889. // We should be smart about picking the "use" basic block, which will be the
  890. // merge point for aggregate, where we'll insert the final PHI that will be
  891. // used instead of OrigIVI. Basic block of OrigIVI is *not* the right choice.
  892. // We should look in which blocks each of the AggElts is being defined,
  893. // they all should be defined in the same basic block.
  894. BasicBlock *UseBB = nullptr;
  895. for (const Optional<Instruction *> &I : AggElts) {
  896. BasicBlock *BB = (*I)->getParent();
  897. // If it's the first instruction we've encountered, record the basic block.
  898. if (!UseBB) {
  899. UseBB = BB;
  900. continue;
  901. }
  902. // Otherwise, this must be the same basic block we've seen previously.
  903. if (UseBB != BB)
  904. return nullptr;
  905. }
  906. // If *all* of the elements are basic-block-independent, meaning they are
  907. // either function arguments, or constant expressions, then if we didn't
  908. // handle them without predecessor-aware handling, we won't handle them now.
  909. if (!UseBB)
  910. return nullptr;
  911. // If we didn't manage to find source aggregate without looking at
  912. // predecessors, and there are no predecessors to look at, then we're done.
  913. if (pred_empty(UseBB))
  914. return nullptr;
  915. // Arbitrary predecessor count limit.
  916. static const int PredCountLimit = 64;
  917. // Cache the (non-uniqified!) list of predecessors in a vector,
  918. // checking the limit at the same time for efficiency.
  919. SmallVector<BasicBlock *, 4> Preds; // May have duplicates!
  920. for (BasicBlock *Pred : predecessors(UseBB)) {
  921. // Don't bother if there are too many predecessors.
  922. if (Preds.size() >= PredCountLimit) // FIXME: only count duplicates once?
  923. return nullptr;
  924. Preds.emplace_back(Pred);
  925. }
  926. // For each predecessor, what is the source aggregate,
  927. // from which all the elements were originally extracted from?
  928. // Note that we want for the map to have stable iteration order!
  929. SmallDenseMap<BasicBlock *, Value *, 4> SourceAggregates;
  930. for (BasicBlock *Pred : Preds) {
  931. std::pair<decltype(SourceAggregates)::iterator, bool> IV =
  932. SourceAggregates.insert({Pred, nullptr});
  933. // Did we already evaluate this predecessor?
  934. if (!IV.second)
  935. continue;
  936. // Let's hope that when coming from predecessor Pred, all elements of the
  937. // aggregate produced by OrigIVI must have been originally extracted from
  938. // the same aggregate. Is that so? Can we find said original aggregate?
  939. SourceAggregate = FindCommonSourceAggregate(UseBB, Pred);
  940. if (Describe(SourceAggregate) != AggregateDescription::Found)
  941. return nullptr; // Give up.
  942. IV.first->second = *SourceAggregate;
  943. }
  944. // All good! Now we just need to thread the source aggregates here.
  945. // Note that we have to insert the new PHI here, ourselves, because we can't
  946. // rely on InstCombinerImpl::run() inserting it into the right basic block.
  947. // Note that the same block can be a predecessor more than once,
  948. // and we need to preserve that invariant for the PHI node.
  949. BuilderTy::InsertPointGuard Guard(Builder);
  950. Builder.SetInsertPoint(UseBB->getFirstNonPHI());
  951. auto *PHI =
  952. Builder.CreatePHI(AggTy, Preds.size(), OrigIVI.getName() + ".merged");
  953. for (BasicBlock *Pred : Preds)
  954. PHI->addIncoming(SourceAggregates[Pred], Pred);
  955. ++NumAggregateReconstructionsSimplified;
  956. return replaceInstUsesWith(OrigIVI, PHI);
  957. }
  958. /// Try to find redundant insertvalue instructions, like the following ones:
  959. /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
  960. /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
  961. /// Here the second instruction inserts values at the same indices, as the
  962. /// first one, making the first one redundant.
  963. /// It should be transformed to:
  964. /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
  965. Instruction *InstCombinerImpl::visitInsertValueInst(InsertValueInst &I) {
  966. bool IsRedundant = false;
  967. ArrayRef<unsigned int> FirstIndices = I.getIndices();
  968. // If there is a chain of insertvalue instructions (each of them except the
  969. // last one has only one use and it's another insertvalue insn from this
  970. // chain), check if any of the 'children' uses the same indices as the first
  971. // instruction. In this case, the first one is redundant.
  972. Value *V = &I;
  973. unsigned Depth = 0;
  974. while (V->hasOneUse() && Depth < 10) {
  975. User *U = V->user_back();
  976. auto UserInsInst = dyn_cast<InsertValueInst>(U);
  977. if (!UserInsInst || U->getOperand(0) != V)
  978. break;
  979. if (UserInsInst->getIndices() == FirstIndices) {
  980. IsRedundant = true;
  981. break;
  982. }
  983. V = UserInsInst;
  984. Depth++;
  985. }
  986. if (IsRedundant)
  987. return replaceInstUsesWith(I, I.getOperand(0));
  988. if (Instruction *NewI = foldAggregateConstructionIntoAggregateReuse(I))
  989. return NewI;
  990. return nullptr;
  991. }
  992. static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
  993. // Can not analyze scalable type, the number of elements is not a compile-time
  994. // constant.
  995. if (isa<ScalableVectorType>(Shuf.getOperand(0)->getType()))
  996. return false;
  997. int MaskSize = Shuf.getShuffleMask().size();
  998. int VecSize =
  999. cast<FixedVectorType>(Shuf.getOperand(0)->getType())->getNumElements();
  1000. // A vector select does not change the size of the operands.
  1001. if (MaskSize != VecSize)
  1002. return false;
  1003. // Each mask element must be undefined or choose a vector element from one of
  1004. // the source operands without crossing vector lanes.
  1005. for (int i = 0; i != MaskSize; ++i) {
  1006. int Elt = Shuf.getMaskValue(i);
  1007. if (Elt != -1 && Elt != i && Elt != i + VecSize)
  1008. return false;
  1009. }
  1010. return true;
  1011. }
  1012. /// Turn a chain of inserts that splats a value into an insert + shuffle:
  1013. /// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
  1014. /// shufflevector(insertelt(X, %k, 0), poison, zero)
  1015. static Instruction *foldInsSequenceIntoSplat(InsertElementInst &InsElt) {
  1016. // We are interested in the last insert in a chain. So if this insert has a
  1017. // single user and that user is an insert, bail.
  1018. if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
  1019. return nullptr;
  1020. VectorType *VecTy = InsElt.getType();
  1021. // Can not handle scalable type, the number of elements is not a compile-time
  1022. // constant.
  1023. if (isa<ScalableVectorType>(VecTy))
  1024. return nullptr;
  1025. unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
  1026. // Do not try to do this for a one-element vector, since that's a nop,
  1027. // and will cause an inf-loop.
  1028. if (NumElements == 1)
  1029. return nullptr;
  1030. Value *SplatVal = InsElt.getOperand(1);
  1031. InsertElementInst *CurrIE = &InsElt;
  1032. SmallBitVector ElementPresent(NumElements, false);
  1033. InsertElementInst *FirstIE = nullptr;
  1034. // Walk the chain backwards, keeping track of which indices we inserted into,
  1035. // until we hit something that isn't an insert of the splatted value.
  1036. while (CurrIE) {
  1037. auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
  1038. if (!Idx || CurrIE->getOperand(1) != SplatVal)
  1039. return nullptr;
  1040. auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
  1041. // Check none of the intermediate steps have any additional uses, except
  1042. // for the root insertelement instruction, which can be re-used, if it
  1043. // inserts at position 0.
  1044. if (CurrIE != &InsElt &&
  1045. (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
  1046. return nullptr;
  1047. ElementPresent[Idx->getZExtValue()] = true;
  1048. FirstIE = CurrIE;
  1049. CurrIE = NextIE;
  1050. }
  1051. // If this is just a single insertelement (not a sequence), we are done.
  1052. if (FirstIE == &InsElt)
  1053. return nullptr;
  1054. // If we are not inserting into an undef vector, make sure we've seen an
  1055. // insert into every element.
  1056. // TODO: If the base vector is not undef, it might be better to create a splat
  1057. // and then a select-shuffle (blend) with the base vector.
  1058. if (!match(FirstIE->getOperand(0), m_Undef()))
  1059. if (!ElementPresent.all())
  1060. return nullptr;
  1061. // Create the insert + shuffle.
  1062. Type *Int32Ty = Type::getInt32Ty(InsElt.getContext());
  1063. PoisonValue *PoisonVec = PoisonValue::get(VecTy);
  1064. Constant *Zero = ConstantInt::get(Int32Ty, 0);
  1065. if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
  1066. FirstIE = InsertElementInst::Create(PoisonVec, SplatVal, Zero, "", &InsElt);
  1067. // Splat from element 0, but replace absent elements with undef in the mask.
  1068. SmallVector<int, 16> Mask(NumElements, 0);
  1069. for (unsigned i = 0; i != NumElements; ++i)
  1070. if (!ElementPresent[i])
  1071. Mask[i] = -1;
  1072. return new ShuffleVectorInst(FirstIE, Mask);
  1073. }
  1074. /// Try to fold an insert element into an existing splat shuffle by changing
  1075. /// the shuffle's mask to include the index of this insert element.
  1076. static Instruction *foldInsEltIntoSplat(InsertElementInst &InsElt) {
  1077. // Check if the vector operand of this insert is a canonical splat shuffle.
  1078. auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
  1079. if (!Shuf || !Shuf->isZeroEltSplat())
  1080. return nullptr;
  1081. // Bail out early if shuffle is scalable type. The number of elements in
  1082. // shuffle mask is unknown at compile-time.
  1083. if (isa<ScalableVectorType>(Shuf->getType()))
  1084. return nullptr;
  1085. // Check for a constant insertion index.
  1086. uint64_t IdxC;
  1087. if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
  1088. return nullptr;
  1089. // Check if the splat shuffle's input is the same as this insert's scalar op.
  1090. Value *X = InsElt.getOperand(1);
  1091. Value *Op0 = Shuf->getOperand(0);
  1092. if (!match(Op0, m_InsertElt(m_Undef(), m_Specific(X), m_ZeroInt())))
  1093. return nullptr;
  1094. // Replace the shuffle mask element at the index of this insert with a zero.
  1095. // For example:
  1096. // inselt (shuf (inselt undef, X, 0), _, <0,undef,0,undef>), X, 1
  1097. // --> shuf (inselt undef, X, 0), poison, <0,0,0,undef>
  1098. unsigned NumMaskElts =
  1099. cast<FixedVectorType>(Shuf->getType())->getNumElements();
  1100. SmallVector<int, 16> NewMask(NumMaskElts);
  1101. for (unsigned i = 0; i != NumMaskElts; ++i)
  1102. NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i);
  1103. return new ShuffleVectorInst(Op0, NewMask);
  1104. }
  1105. /// Try to fold an extract+insert element into an existing identity shuffle by
  1106. /// changing the shuffle's mask to include the index of this insert element.
  1107. static Instruction *foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt) {
  1108. // Check if the vector operand of this insert is an identity shuffle.
  1109. auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
  1110. if (!Shuf || !match(Shuf->getOperand(1), m_Undef()) ||
  1111. !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
  1112. return nullptr;
  1113. // Bail out early if shuffle is scalable type. The number of elements in
  1114. // shuffle mask is unknown at compile-time.
  1115. if (isa<ScalableVectorType>(Shuf->getType()))
  1116. return nullptr;
  1117. // Check for a constant insertion index.
  1118. uint64_t IdxC;
  1119. if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
  1120. return nullptr;
  1121. // Check if this insert's scalar op is extracted from the identity shuffle's
  1122. // input vector.
  1123. Value *Scalar = InsElt.getOperand(1);
  1124. Value *X = Shuf->getOperand(0);
  1125. if (!match(Scalar, m_ExtractElt(m_Specific(X), m_SpecificInt(IdxC))))
  1126. return nullptr;
  1127. // Replace the shuffle mask element at the index of this extract+insert with
  1128. // that same index value.
  1129. // For example:
  1130. // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask'
  1131. unsigned NumMaskElts =
  1132. cast<FixedVectorType>(Shuf->getType())->getNumElements();
  1133. SmallVector<int, 16> NewMask(NumMaskElts);
  1134. ArrayRef<int> OldMask = Shuf->getShuffleMask();
  1135. for (unsigned i = 0; i != NumMaskElts; ++i) {
  1136. if (i != IdxC) {
  1137. // All mask elements besides the inserted element remain the same.
  1138. NewMask[i] = OldMask[i];
  1139. } else if (OldMask[i] == (int)IdxC) {
  1140. // If the mask element was already set, there's nothing to do
  1141. // (demanded elements analysis may unset it later).
  1142. return nullptr;
  1143. } else {
  1144. assert(OldMask[i] == UndefMaskElem &&
  1145. "Unexpected shuffle mask element for identity shuffle");
  1146. NewMask[i] = IdxC;
  1147. }
  1148. }
  1149. return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask);
  1150. }
  1151. /// If we have an insertelement instruction feeding into another insertelement
  1152. /// and the 2nd is inserting a constant into the vector, canonicalize that
  1153. /// constant insertion before the insertion of a variable:
  1154. ///
  1155. /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
  1156. /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
  1157. ///
  1158. /// This has the potential of eliminating the 2nd insertelement instruction
  1159. /// via constant folding of the scalar constant into a vector constant.
  1160. static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
  1161. InstCombiner::BuilderTy &Builder) {
  1162. auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
  1163. if (!InsElt1 || !InsElt1->hasOneUse())
  1164. return nullptr;
  1165. Value *X, *Y;
  1166. Constant *ScalarC;
  1167. ConstantInt *IdxC1, *IdxC2;
  1168. if (match(InsElt1->getOperand(0), m_Value(X)) &&
  1169. match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
  1170. match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
  1171. match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
  1172. match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
  1173. Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
  1174. return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
  1175. }
  1176. return nullptr;
  1177. }
  1178. /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
  1179. /// --> shufflevector X, CVec', Mask'
  1180. static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
  1181. auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
  1182. // Bail out if the parent has more than one use. In that case, we'd be
  1183. // replacing the insertelt with a shuffle, and that's not a clear win.
  1184. if (!Inst || !Inst->hasOneUse())
  1185. return nullptr;
  1186. if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
  1187. // The shuffle must have a constant vector operand. The insertelt must have
  1188. // a constant scalar being inserted at a constant position in the vector.
  1189. Constant *ShufConstVec, *InsEltScalar;
  1190. uint64_t InsEltIndex;
  1191. if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
  1192. !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
  1193. !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
  1194. return nullptr;
  1195. // Adding an element to an arbitrary shuffle could be expensive, but a
  1196. // shuffle that selects elements from vectors without crossing lanes is
  1197. // assumed cheap.
  1198. // If we're just adding a constant into that shuffle, it will still be
  1199. // cheap.
  1200. if (!isShuffleEquivalentToSelect(*Shuf))
  1201. return nullptr;
  1202. // From the above 'select' check, we know that the mask has the same number
  1203. // of elements as the vector input operands. We also know that each constant
  1204. // input element is used in its lane and can not be used more than once by
  1205. // the shuffle. Therefore, replace the constant in the shuffle's constant
  1206. // vector with the insertelt constant. Replace the constant in the shuffle's
  1207. // mask vector with the insertelt index plus the length of the vector
  1208. // (because the constant vector operand of a shuffle is always the 2nd
  1209. // operand).
  1210. ArrayRef<int> Mask = Shuf->getShuffleMask();
  1211. unsigned NumElts = Mask.size();
  1212. SmallVector<Constant *, 16> NewShufElts(NumElts);
  1213. SmallVector<int, 16> NewMaskElts(NumElts);
  1214. for (unsigned I = 0; I != NumElts; ++I) {
  1215. if (I == InsEltIndex) {
  1216. NewShufElts[I] = InsEltScalar;
  1217. NewMaskElts[I] = InsEltIndex + NumElts;
  1218. } else {
  1219. // Copy over the existing values.
  1220. NewShufElts[I] = ShufConstVec->getAggregateElement(I);
  1221. NewMaskElts[I] = Mask[I];
  1222. }
  1223. // Bail if we failed to find an element.
  1224. if (!NewShufElts[I])
  1225. return nullptr;
  1226. }
  1227. // Create new operands for a shuffle that includes the constant of the
  1228. // original insertelt. The old shuffle will be dead now.
  1229. return new ShuffleVectorInst(Shuf->getOperand(0),
  1230. ConstantVector::get(NewShufElts), NewMaskElts);
  1231. } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
  1232. // Transform sequences of insertelements ops with constant data/indexes into
  1233. // a single shuffle op.
  1234. // Can not handle scalable type, the number of elements needed to create
  1235. // shuffle mask is not a compile-time constant.
  1236. if (isa<ScalableVectorType>(InsElt.getType()))
  1237. return nullptr;
  1238. unsigned NumElts =
  1239. cast<FixedVectorType>(InsElt.getType())->getNumElements();
  1240. uint64_t InsertIdx[2];
  1241. Constant *Val[2];
  1242. if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
  1243. !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
  1244. !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
  1245. !match(IEI->getOperand(1), m_Constant(Val[1])))
  1246. return nullptr;
  1247. SmallVector<Constant *, 16> Values(NumElts);
  1248. SmallVector<int, 16> Mask(NumElts);
  1249. auto ValI = std::begin(Val);
  1250. // Generate new constant vector and mask.
  1251. // We have 2 values/masks from the insertelements instructions. Insert them
  1252. // into new value/mask vectors.
  1253. for (uint64_t I : InsertIdx) {
  1254. if (!Values[I]) {
  1255. Values[I] = *ValI;
  1256. Mask[I] = NumElts + I;
  1257. }
  1258. ++ValI;
  1259. }
  1260. // Remaining values are filled with 'undef' values.
  1261. for (unsigned I = 0; I < NumElts; ++I) {
  1262. if (!Values[I]) {
  1263. Values[I] = UndefValue::get(InsElt.getType()->getElementType());
  1264. Mask[I] = I;
  1265. }
  1266. }
  1267. // Create new operands for a shuffle that includes the constant of the
  1268. // original insertelt.
  1269. return new ShuffleVectorInst(IEI->getOperand(0),
  1270. ConstantVector::get(Values), Mask);
  1271. }
  1272. return nullptr;
  1273. }
  1274. /// If both the base vector and the inserted element are extended from the same
  1275. /// type, do the insert element in the narrow source type followed by extend.
  1276. /// TODO: This can be extended to include other cast opcodes, but particularly
  1277. /// if we create a wider insertelement, make sure codegen is not harmed.
  1278. static Instruction *narrowInsElt(InsertElementInst &InsElt,
  1279. InstCombiner::BuilderTy &Builder) {
  1280. // We are creating a vector extend. If the original vector extend has another
  1281. // use, that would mean we end up with 2 vector extends, so avoid that.
  1282. // TODO: We could ease the use-clause to "if at least one op has one use"
  1283. // (assuming that the source types match - see next TODO comment).
  1284. Value *Vec = InsElt.getOperand(0);
  1285. if (!Vec->hasOneUse())
  1286. return nullptr;
  1287. Value *Scalar = InsElt.getOperand(1);
  1288. Value *X, *Y;
  1289. CastInst::CastOps CastOpcode;
  1290. if (match(Vec, m_FPExt(m_Value(X))) && match(Scalar, m_FPExt(m_Value(Y))))
  1291. CastOpcode = Instruction::FPExt;
  1292. else if (match(Vec, m_SExt(m_Value(X))) && match(Scalar, m_SExt(m_Value(Y))))
  1293. CastOpcode = Instruction::SExt;
  1294. else if (match(Vec, m_ZExt(m_Value(X))) && match(Scalar, m_ZExt(m_Value(Y))))
  1295. CastOpcode = Instruction::ZExt;
  1296. else
  1297. return nullptr;
  1298. // TODO: We can allow mismatched types by creating an intermediate cast.
  1299. if (X->getType()->getScalarType() != Y->getType())
  1300. return nullptr;
  1301. // inselt (ext X), (ext Y), Index --> ext (inselt X, Y, Index)
  1302. Value *NewInsElt = Builder.CreateInsertElement(X, Y, InsElt.getOperand(2));
  1303. return CastInst::Create(CastOpcode, NewInsElt, InsElt.getType());
  1304. }
  1305. Instruction *InstCombinerImpl::visitInsertElementInst(InsertElementInst &IE) {
  1306. Value *VecOp = IE.getOperand(0);
  1307. Value *ScalarOp = IE.getOperand(1);
  1308. Value *IdxOp = IE.getOperand(2);
  1309. if (auto *V = SimplifyInsertElementInst(
  1310. VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
  1311. return replaceInstUsesWith(IE, V);
  1312. // Canonicalize type of constant indices to i64 to simplify CSE
  1313. if (auto *IndexC = dyn_cast<ConstantInt>(IdxOp))
  1314. if (auto *NewIdx = getPreferredVectorIndex(IndexC))
  1315. return replaceOperand(IE, 2, NewIdx);
  1316. // If the scalar is bitcast and inserted into undef, do the insert in the
  1317. // source type followed by bitcast.
  1318. // TODO: Generalize for insert into any constant, not just undef?
  1319. Value *ScalarSrc;
  1320. if (match(VecOp, m_Undef()) &&
  1321. match(ScalarOp, m_OneUse(m_BitCast(m_Value(ScalarSrc)))) &&
  1322. (ScalarSrc->getType()->isIntegerTy() ||
  1323. ScalarSrc->getType()->isFloatingPointTy())) {
  1324. // inselt undef, (bitcast ScalarSrc), IdxOp -->
  1325. // bitcast (inselt undef, ScalarSrc, IdxOp)
  1326. Type *ScalarTy = ScalarSrc->getType();
  1327. Type *VecTy = VectorType::get(ScalarTy, IE.getType()->getElementCount());
  1328. UndefValue *NewUndef = UndefValue::get(VecTy);
  1329. Value *NewInsElt = Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp);
  1330. return new BitCastInst(NewInsElt, IE.getType());
  1331. }
  1332. // If the vector and scalar are both bitcast from the same element type, do
  1333. // the insert in that source type followed by bitcast.
  1334. Value *VecSrc;
  1335. if (match(VecOp, m_BitCast(m_Value(VecSrc))) &&
  1336. match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) &&
  1337. (VecOp->hasOneUse() || ScalarOp->hasOneUse()) &&
  1338. VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() &&
  1339. cast<VectorType>(VecSrc->getType())->getElementType() ==
  1340. ScalarSrc->getType()) {
  1341. // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp -->
  1342. // bitcast (inselt VecSrc, ScalarSrc, IdxOp)
  1343. Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
  1344. return new BitCastInst(NewInsElt, IE.getType());
  1345. }
  1346. // If the inserted element was extracted from some other fixed-length vector
  1347. // and both indexes are valid constants, try to turn this into a shuffle.
  1348. // Can not handle scalable vector type, the number of elements needed to
  1349. // create shuffle mask is not a compile-time constant.
  1350. uint64_t InsertedIdx, ExtractedIdx;
  1351. Value *ExtVecOp;
  1352. if (isa<FixedVectorType>(IE.getType()) &&
  1353. match(IdxOp, m_ConstantInt(InsertedIdx)) &&
  1354. match(ScalarOp,
  1355. m_ExtractElt(m_Value(ExtVecOp), m_ConstantInt(ExtractedIdx))) &&
  1356. isa<FixedVectorType>(ExtVecOp->getType()) &&
  1357. ExtractedIdx <
  1358. cast<FixedVectorType>(ExtVecOp->getType())->getNumElements()) {
  1359. // TODO: Looking at the user(s) to determine if this insert is a
  1360. // fold-to-shuffle opportunity does not match the usual instcombine
  1361. // constraints. We should decide if the transform is worthy based only
  1362. // on this instruction and its operands, but that may not work currently.
  1363. //
  1364. // Here, we are trying to avoid creating shuffles before reaching
  1365. // the end of a chain of extract-insert pairs. This is complicated because
  1366. // we do not generally form arbitrary shuffle masks in instcombine
  1367. // (because those may codegen poorly), but collectShuffleElements() does
  1368. // exactly that.
  1369. //
  1370. // The rules for determining what is an acceptable target-independent
  1371. // shuffle mask are fuzzy because they evolve based on the backend's
  1372. // capabilities and real-world impact.
  1373. auto isShuffleRootCandidate = [](InsertElementInst &Insert) {
  1374. if (!Insert.hasOneUse())
  1375. return true;
  1376. auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back());
  1377. if (!InsertUser)
  1378. return true;
  1379. return false;
  1380. };
  1381. // Try to form a shuffle from a chain of extract-insert ops.
  1382. if (isShuffleRootCandidate(IE)) {
  1383. SmallVector<int, 16> Mask;
  1384. ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
  1385. // The proposed shuffle may be trivial, in which case we shouldn't
  1386. // perform the combine.
  1387. if (LR.first != &IE && LR.second != &IE) {
  1388. // We now have a shuffle of LHS, RHS, Mask.
  1389. if (LR.second == nullptr)
  1390. LR.second = UndefValue::get(LR.first->getType());
  1391. return new ShuffleVectorInst(LR.first, LR.second, Mask);
  1392. }
  1393. }
  1394. }
  1395. if (auto VecTy = dyn_cast<FixedVectorType>(VecOp->getType())) {
  1396. unsigned VWidth = VecTy->getNumElements();
  1397. APInt UndefElts(VWidth, 0);
  1398. APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
  1399. if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
  1400. if (V != &IE)
  1401. return replaceInstUsesWith(IE, V);
  1402. return &IE;
  1403. }
  1404. }
  1405. if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
  1406. return Shuf;
  1407. if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
  1408. return NewInsElt;
  1409. if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE))
  1410. return Broadcast;
  1411. if (Instruction *Splat = foldInsEltIntoSplat(IE))
  1412. return Splat;
  1413. if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE))
  1414. return IdentityShuf;
  1415. if (Instruction *Ext = narrowInsElt(IE, Builder))
  1416. return Ext;
  1417. return nullptr;
  1418. }
  1419. /// Return true if we can evaluate the specified expression tree if the vector
  1420. /// elements were shuffled in a different order.
  1421. static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask,
  1422. unsigned Depth = 5) {
  1423. // We can always reorder the elements of a constant.
  1424. if (isa<Constant>(V))
  1425. return true;
  1426. // We won't reorder vector arguments. No IPO here.
  1427. Instruction *I = dyn_cast<Instruction>(V);
  1428. if (!I) return false;
  1429. // Two users may expect different orders of the elements. Don't try it.
  1430. if (!I->hasOneUse())
  1431. return false;
  1432. if (Depth == 0) return false;
  1433. switch (I->getOpcode()) {
  1434. case Instruction::UDiv:
  1435. case Instruction::SDiv:
  1436. case Instruction::URem:
  1437. case Instruction::SRem:
  1438. // Propagating an undefined shuffle mask element to integer div/rem is not
  1439. // allowed because those opcodes can create immediate undefined behavior
  1440. // from an undefined element in an operand.
  1441. if (llvm::is_contained(Mask, -1))
  1442. return false;
  1443. LLVM_FALLTHROUGH;
  1444. case Instruction::Add:
  1445. case Instruction::FAdd:
  1446. case Instruction::Sub:
  1447. case Instruction::FSub:
  1448. case Instruction::Mul:
  1449. case Instruction::FMul:
  1450. case Instruction::FDiv:
  1451. case Instruction::FRem:
  1452. case Instruction::Shl:
  1453. case Instruction::LShr:
  1454. case Instruction::AShr:
  1455. case Instruction::And:
  1456. case Instruction::Or:
  1457. case Instruction::Xor:
  1458. case Instruction::ICmp:
  1459. case Instruction::FCmp:
  1460. case Instruction::Trunc:
  1461. case Instruction::ZExt:
  1462. case Instruction::SExt:
  1463. case Instruction::FPToUI:
  1464. case Instruction::FPToSI:
  1465. case Instruction::UIToFP:
  1466. case Instruction::SIToFP:
  1467. case Instruction::FPTrunc:
  1468. case Instruction::FPExt:
  1469. case Instruction::GetElementPtr: {
  1470. // Bail out if we would create longer vector ops. We could allow creating
  1471. // longer vector ops, but that may result in more expensive codegen.
  1472. Type *ITy = I->getType();
  1473. if (ITy->isVectorTy() &&
  1474. Mask.size() > cast<FixedVectorType>(ITy)->getNumElements())
  1475. return false;
  1476. for (Value *Operand : I->operands()) {
  1477. if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
  1478. return false;
  1479. }
  1480. return true;
  1481. }
  1482. case Instruction::InsertElement: {
  1483. ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
  1484. if (!CI) return false;
  1485. int ElementNumber = CI->getLimitedValue();
  1486. // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
  1487. // can't put an element into multiple indices.
  1488. bool SeenOnce = false;
  1489. for (int i = 0, e = Mask.size(); i != e; ++i) {
  1490. if (Mask[i] == ElementNumber) {
  1491. if (SeenOnce)
  1492. return false;
  1493. SeenOnce = true;
  1494. }
  1495. }
  1496. return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
  1497. }
  1498. }
  1499. return false;
  1500. }
  1501. /// Rebuild a new instruction just like 'I' but with the new operands given.
  1502. /// In the event of type mismatch, the type of the operands is correct.
  1503. static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
  1504. // We don't want to use the IRBuilder here because we want the replacement
  1505. // instructions to appear next to 'I', not the builder's insertion point.
  1506. switch (I->getOpcode()) {
  1507. case Instruction::Add:
  1508. case Instruction::FAdd:
  1509. case Instruction::Sub:
  1510. case Instruction::FSub:
  1511. case Instruction::Mul:
  1512. case Instruction::FMul:
  1513. case Instruction::UDiv:
  1514. case Instruction::SDiv:
  1515. case Instruction::FDiv:
  1516. case Instruction::URem:
  1517. case Instruction::SRem:
  1518. case Instruction::FRem:
  1519. case Instruction::Shl:
  1520. case Instruction::LShr:
  1521. case Instruction::AShr:
  1522. case Instruction::And:
  1523. case Instruction::Or:
  1524. case Instruction::Xor: {
  1525. BinaryOperator *BO = cast<BinaryOperator>(I);
  1526. assert(NewOps.size() == 2 && "binary operator with #ops != 2");
  1527. BinaryOperator *New =
  1528. BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
  1529. NewOps[0], NewOps[1], "", BO);
  1530. if (isa<OverflowingBinaryOperator>(BO)) {
  1531. New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
  1532. New->setHasNoSignedWrap(BO->hasNoSignedWrap());
  1533. }
  1534. if (isa<PossiblyExactOperator>(BO)) {
  1535. New->setIsExact(BO->isExact());
  1536. }
  1537. if (isa<FPMathOperator>(BO))
  1538. New->copyFastMathFlags(I);
  1539. return New;
  1540. }
  1541. case Instruction::ICmp:
  1542. assert(NewOps.size() == 2 && "icmp with #ops != 2");
  1543. return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
  1544. NewOps[0], NewOps[1]);
  1545. case Instruction::FCmp:
  1546. assert(NewOps.size() == 2 && "fcmp with #ops != 2");
  1547. return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
  1548. NewOps[0], NewOps[1]);
  1549. case Instruction::Trunc:
  1550. case Instruction::ZExt:
  1551. case Instruction::SExt:
  1552. case Instruction::FPToUI:
  1553. case Instruction::FPToSI:
  1554. case Instruction::UIToFP:
  1555. case Instruction::SIToFP:
  1556. case Instruction::FPTrunc:
  1557. case Instruction::FPExt: {
  1558. // It's possible that the mask has a different number of elements from
  1559. // the original cast. We recompute the destination type to match the mask.
  1560. Type *DestTy = VectorType::get(
  1561. I->getType()->getScalarType(),
  1562. cast<VectorType>(NewOps[0]->getType())->getElementCount());
  1563. assert(NewOps.size() == 1 && "cast with #ops != 1");
  1564. return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
  1565. "", I);
  1566. }
  1567. case Instruction::GetElementPtr: {
  1568. Value *Ptr = NewOps[0];
  1569. ArrayRef<Value*> Idx = NewOps.slice(1);
  1570. GetElementPtrInst *GEP = GetElementPtrInst::Create(
  1571. cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
  1572. GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
  1573. return GEP;
  1574. }
  1575. }
  1576. llvm_unreachable("failed to rebuild vector instructions");
  1577. }
  1578. static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
  1579. // Mask.size() does not need to be equal to the number of vector elements.
  1580. assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
  1581. Type *EltTy = V->getType()->getScalarType();
  1582. Type *I32Ty = IntegerType::getInt32Ty(V->getContext());
  1583. if (match(V, m_Undef()))
  1584. return UndefValue::get(FixedVectorType::get(EltTy, Mask.size()));
  1585. if (isa<ConstantAggregateZero>(V))
  1586. return ConstantAggregateZero::get(FixedVectorType::get(EltTy, Mask.size()));
  1587. if (Constant *C = dyn_cast<Constant>(V))
  1588. return ConstantExpr::getShuffleVector(C, PoisonValue::get(C->getType()),
  1589. Mask);
  1590. Instruction *I = cast<Instruction>(V);
  1591. switch (I->getOpcode()) {
  1592. case Instruction::Add:
  1593. case Instruction::FAdd:
  1594. case Instruction::Sub:
  1595. case Instruction::FSub:
  1596. case Instruction::Mul:
  1597. case Instruction::FMul:
  1598. case Instruction::UDiv:
  1599. case Instruction::SDiv:
  1600. case Instruction::FDiv:
  1601. case Instruction::URem:
  1602. case Instruction::SRem:
  1603. case Instruction::FRem:
  1604. case Instruction::Shl:
  1605. case Instruction::LShr:
  1606. case Instruction::AShr:
  1607. case Instruction::And:
  1608. case Instruction::Or:
  1609. case Instruction::Xor:
  1610. case Instruction::ICmp:
  1611. case Instruction::FCmp:
  1612. case Instruction::Trunc:
  1613. case Instruction::ZExt:
  1614. case Instruction::SExt:
  1615. case Instruction::FPToUI:
  1616. case Instruction::FPToSI:
  1617. case Instruction::UIToFP:
  1618. case Instruction::SIToFP:
  1619. case Instruction::FPTrunc:
  1620. case Instruction::FPExt:
  1621. case Instruction::Select:
  1622. case Instruction::GetElementPtr: {
  1623. SmallVector<Value*, 8> NewOps;
  1624. bool NeedsRebuild =
  1625. (Mask.size() !=
  1626. cast<FixedVectorType>(I->getType())->getNumElements());
  1627. for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
  1628. Value *V;
  1629. // Recursively call evaluateInDifferentElementOrder on vector arguments
  1630. // as well. E.g. GetElementPtr may have scalar operands even if the
  1631. // return value is a vector, so we need to examine the operand type.
  1632. if (I->getOperand(i)->getType()->isVectorTy())
  1633. V = evaluateInDifferentElementOrder(I->getOperand(i), Mask);
  1634. else
  1635. V = I->getOperand(i);
  1636. NewOps.push_back(V);
  1637. NeedsRebuild |= (V != I->getOperand(i));
  1638. }
  1639. if (NeedsRebuild) {
  1640. return buildNew(I, NewOps);
  1641. }
  1642. return I;
  1643. }
  1644. case Instruction::InsertElement: {
  1645. int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
  1646. // The insertelement was inserting at Element. Figure out which element
  1647. // that becomes after shuffling. The answer is guaranteed to be unique
  1648. // by CanEvaluateShuffled.
  1649. bool Found = false;
  1650. int Index = 0;
  1651. for (int e = Mask.size(); Index != e; ++Index) {
  1652. if (Mask[Index] == Element) {
  1653. Found = true;
  1654. break;
  1655. }
  1656. }
  1657. // If element is not in Mask, no need to handle the operand 1 (element to
  1658. // be inserted). Just evaluate values in operand 0 according to Mask.
  1659. if (!Found)
  1660. return evaluateInDifferentElementOrder(I->getOperand(0), Mask);
  1661. Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask);
  1662. return InsertElementInst::Create(V, I->getOperand(1),
  1663. ConstantInt::get(I32Ty, Index), "", I);
  1664. }
  1665. }
  1666. llvm_unreachable("failed to reorder elements of vector instruction!");
  1667. }
  1668. // Returns true if the shuffle is extracting a contiguous range of values from
  1669. // LHS, for example:
  1670. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  1671. // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
  1672. // Shuffles to: |EE|FF|GG|HH|
  1673. // +--+--+--+--+
  1674. static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
  1675. ArrayRef<int> Mask) {
  1676. unsigned LHSElems =
  1677. cast<FixedVectorType>(SVI.getOperand(0)->getType())->getNumElements();
  1678. unsigned MaskElems = Mask.size();
  1679. unsigned BegIdx = Mask.front();
  1680. unsigned EndIdx = Mask.back();
  1681. if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
  1682. return false;
  1683. for (unsigned I = 0; I != MaskElems; ++I)
  1684. if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
  1685. return false;
  1686. return true;
  1687. }
  1688. /// These are the ingredients in an alternate form binary operator as described
  1689. /// below.
  1690. struct BinopElts {
  1691. BinaryOperator::BinaryOps Opcode;
  1692. Value *Op0;
  1693. Value *Op1;
  1694. BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0,
  1695. Value *V0 = nullptr, Value *V1 = nullptr) :
  1696. Opcode(Opc), Op0(V0), Op1(V1) {}
  1697. operator bool() const { return Opcode != 0; }
  1698. };
  1699. /// Binops may be transformed into binops with different opcodes and operands.
  1700. /// Reverse the usual canonicalization to enable folds with the non-canonical
  1701. /// form of the binop. If a transform is possible, return the elements of the
  1702. /// new binop. If not, return invalid elements.
  1703. static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) {
  1704. Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
  1705. Type *Ty = BO->getType();
  1706. switch (BO->getOpcode()) {
  1707. case Instruction::Shl: {
  1708. // shl X, C --> mul X, (1 << C)
  1709. Constant *C;
  1710. if (match(BO1, m_Constant(C))) {
  1711. Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C);
  1712. return { Instruction::Mul, BO0, ShlOne };
  1713. }
  1714. break;
  1715. }
  1716. case Instruction::Or: {
  1717. // or X, C --> add X, C (when X and C have no common bits set)
  1718. const APInt *C;
  1719. if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL))
  1720. return { Instruction::Add, BO0, BO1 };
  1721. break;
  1722. }
  1723. default:
  1724. break;
  1725. }
  1726. return {};
  1727. }
  1728. static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) {
  1729. assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
  1730. // Are we shuffling together some value and that same value after it has been
  1731. // modified by a binop with a constant?
  1732. Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
  1733. Constant *C;
  1734. bool Op0IsBinop;
  1735. if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
  1736. Op0IsBinop = true;
  1737. else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
  1738. Op0IsBinop = false;
  1739. else
  1740. return nullptr;
  1741. // The identity constant for a binop leaves a variable operand unchanged. For
  1742. // a vector, this is a splat of something like 0, -1, or 1.
  1743. // If there's no identity constant for this binop, we're done.
  1744. auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
  1745. BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
  1746. Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
  1747. if (!IdC)
  1748. return nullptr;
  1749. // Shuffle identity constants into the lanes that return the original value.
  1750. // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
  1751. // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
  1752. // The existing binop constant vector remains in the same operand position.
  1753. ArrayRef<int> Mask = Shuf.getShuffleMask();
  1754. Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
  1755. ConstantExpr::getShuffleVector(IdC, C, Mask);
  1756. bool MightCreatePoisonOrUB =
  1757. is_contained(Mask, UndefMaskElem) &&
  1758. (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
  1759. if (MightCreatePoisonOrUB)
  1760. NewC = InstCombiner::getSafeVectorConstantForBinop(BOpcode, NewC, true);
  1761. // shuf (bop X, C), X, M --> bop X, C'
  1762. // shuf X, (bop X, C), M --> bop X, C'
  1763. Value *X = Op0IsBinop ? Op1 : Op0;
  1764. Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
  1765. NewBO->copyIRFlags(BO);
  1766. // An undef shuffle mask element may propagate as an undef constant element in
  1767. // the new binop. That would produce poison where the original code might not.
  1768. // If we already made a safe constant, then there's no danger.
  1769. if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
  1770. NewBO->dropPoisonGeneratingFlags();
  1771. return NewBO;
  1772. }
  1773. /// If we have an insert of a scalar to a non-zero element of an undefined
  1774. /// vector and then shuffle that value, that's the same as inserting to the zero
  1775. /// element and shuffling. Splatting from the zero element is recognized as the
  1776. /// canonical form of splat.
  1777. static Instruction *canonicalizeInsertSplat(ShuffleVectorInst &Shuf,
  1778. InstCombiner::BuilderTy &Builder) {
  1779. Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
  1780. ArrayRef<int> Mask = Shuf.getShuffleMask();
  1781. Value *X;
  1782. uint64_t IndexC;
  1783. // Match a shuffle that is a splat to a non-zero element.
  1784. if (!match(Op0, m_OneUse(m_InsertElt(m_Undef(), m_Value(X),
  1785. m_ConstantInt(IndexC)))) ||
  1786. !match(Op1, m_Undef()) || match(Mask, m_ZeroMask()) || IndexC == 0)
  1787. return nullptr;
  1788. // Insert into element 0 of an undef vector.
  1789. UndefValue *UndefVec = UndefValue::get(Shuf.getType());
  1790. Constant *Zero = Builder.getInt32(0);
  1791. Value *NewIns = Builder.CreateInsertElement(UndefVec, X, Zero);
  1792. // Splat from element 0. Any mask element that is undefined remains undefined.
  1793. // For example:
  1794. // shuf (inselt undef, X, 2), _, <2,2,undef>
  1795. // --> shuf (inselt undef, X, 0), poison, <0,0,undef>
  1796. unsigned NumMaskElts =
  1797. cast<FixedVectorType>(Shuf.getType())->getNumElements();
  1798. SmallVector<int, 16> NewMask(NumMaskElts, 0);
  1799. for (unsigned i = 0; i != NumMaskElts; ++i)
  1800. if (Mask[i] == UndefMaskElem)
  1801. NewMask[i] = Mask[i];
  1802. return new ShuffleVectorInst(NewIns, NewMask);
  1803. }
  1804. /// Try to fold shuffles that are the equivalent of a vector select.
  1805. Instruction *InstCombinerImpl::foldSelectShuffle(ShuffleVectorInst &Shuf) {
  1806. if (!Shuf.isSelect())
  1807. return nullptr;
  1808. // Canonicalize to choose from operand 0 first unless operand 1 is undefined.
  1809. // Commuting undef to operand 0 conflicts with another canonicalization.
  1810. unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
  1811. if (!match(Shuf.getOperand(1), m_Undef()) &&
  1812. Shuf.getMaskValue(0) >= (int)NumElts) {
  1813. // TODO: Can we assert that both operands of a shuffle-select are not undef
  1814. // (otherwise, it would have been folded by instsimplify?
  1815. Shuf.commute();
  1816. return &Shuf;
  1817. }
  1818. if (Instruction *I = foldSelectShuffleWith1Binop(Shuf))
  1819. return I;
  1820. BinaryOperator *B0, *B1;
  1821. if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
  1822. !match(Shuf.getOperand(1), m_BinOp(B1)))
  1823. return nullptr;
  1824. Value *X, *Y;
  1825. Constant *C0, *C1;
  1826. bool ConstantsAreOp1;
  1827. if (match(B0, m_BinOp(m_Value(X), m_Constant(C0))) &&
  1828. match(B1, m_BinOp(m_Value(Y), m_Constant(C1))))
  1829. ConstantsAreOp1 = true;
  1830. else if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
  1831. match(B1, m_BinOp(m_Constant(C1), m_Value(Y))))
  1832. ConstantsAreOp1 = false;
  1833. else
  1834. return nullptr;
  1835. // We need matching binops to fold the lanes together.
  1836. BinaryOperator::BinaryOps Opc0 = B0->getOpcode();
  1837. BinaryOperator::BinaryOps Opc1 = B1->getOpcode();
  1838. bool DropNSW = false;
  1839. if (ConstantsAreOp1 && Opc0 != Opc1) {
  1840. // TODO: We drop "nsw" if shift is converted into multiply because it may
  1841. // not be correct when the shift amount is BitWidth - 1. We could examine
  1842. // each vector element to determine if it is safe to keep that flag.
  1843. if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
  1844. DropNSW = true;
  1845. if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
  1846. assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
  1847. Opc0 = AltB0.Opcode;
  1848. C0 = cast<Constant>(AltB0.Op1);
  1849. } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
  1850. assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
  1851. Opc1 = AltB1.Opcode;
  1852. C1 = cast<Constant>(AltB1.Op1);
  1853. }
  1854. }
  1855. if (Opc0 != Opc1)
  1856. return nullptr;
  1857. // The opcodes must be the same. Use a new name to make that clear.
  1858. BinaryOperator::BinaryOps BOpc = Opc0;
  1859. // Select the constant elements needed for the single binop.
  1860. ArrayRef<int> Mask = Shuf.getShuffleMask();
  1861. Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask);
  1862. // We are moving a binop after a shuffle. When a shuffle has an undefined
  1863. // mask element, the result is undefined, but it is not poison or undefined
  1864. // behavior. That is not necessarily true for div/rem/shift.
  1865. bool MightCreatePoisonOrUB =
  1866. is_contained(Mask, UndefMaskElem) &&
  1867. (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc));
  1868. if (MightCreatePoisonOrUB)
  1869. NewC = InstCombiner::getSafeVectorConstantForBinop(BOpc, NewC,
  1870. ConstantsAreOp1);
  1871. Value *V;
  1872. if (X == Y) {
  1873. // Remove a binop and the shuffle by rearranging the constant:
  1874. // shuffle (op V, C0), (op V, C1), M --> op V, C'
  1875. // shuffle (op C0, V), (op C1, V), M --> op C', V
  1876. V = X;
  1877. } else {
  1878. // If there are 2 different variable operands, we must create a new shuffle
  1879. // (select) first, so check uses to ensure that we don't end up with more
  1880. // instructions than we started with.
  1881. if (!B0->hasOneUse() && !B1->hasOneUse())
  1882. return nullptr;
  1883. // If we use the original shuffle mask and op1 is *variable*, we would be
  1884. // putting an undef into operand 1 of div/rem/shift. This is either UB or
  1885. // poison. We do not have to guard against UB when *constants* are op1
  1886. // because safe constants guarantee that we do not overflow sdiv/srem (and
  1887. // there's no danger for other opcodes).
  1888. // TODO: To allow this case, create a new shuffle mask with no undefs.
  1889. if (MightCreatePoisonOrUB && !ConstantsAreOp1)
  1890. return nullptr;
  1891. // Note: In general, we do not create new shuffles in InstCombine because we
  1892. // do not know if a target can lower an arbitrary shuffle optimally. In this
  1893. // case, the shuffle uses the existing mask, so there is no additional risk.
  1894. // Select the variable vectors first, then perform the binop:
  1895. // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
  1896. // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
  1897. V = Builder.CreateShuffleVector(X, Y, Mask);
  1898. }
  1899. Value *NewBO = ConstantsAreOp1 ? Builder.CreateBinOp(BOpc, V, NewC) :
  1900. Builder.CreateBinOp(BOpc, NewC, V);
  1901. // Flags are intersected from the 2 source binops. But there are 2 exceptions:
  1902. // 1. If we changed an opcode, poison conditions might have changed.
  1903. // 2. If the shuffle had undef mask elements, the new binop might have undefs
  1904. // where the original code did not. But if we already made a safe constant,
  1905. // then there's no danger.
  1906. if (auto *NewI = dyn_cast<Instruction>(NewBO)) {
  1907. NewI->copyIRFlags(B0);
  1908. NewI->andIRFlags(B1);
  1909. if (DropNSW)
  1910. NewI->setHasNoSignedWrap(false);
  1911. if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
  1912. NewI->dropPoisonGeneratingFlags();
  1913. }
  1914. return replaceInstUsesWith(Shuf, NewBO);
  1915. }
  1916. /// Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
  1917. /// Example (little endian):
  1918. /// shuf (bitcast <4 x i16> X to <8 x i8>), <0, 2, 4, 6> --> trunc X to <4 x i8>
  1919. static Instruction *foldTruncShuffle(ShuffleVectorInst &Shuf,
  1920. bool IsBigEndian) {
  1921. // This must be a bitcasted shuffle of 1 vector integer operand.
  1922. Type *DestType = Shuf.getType();
  1923. Value *X;
  1924. if (!match(Shuf.getOperand(0), m_BitCast(m_Value(X))) ||
  1925. !match(Shuf.getOperand(1), m_Undef()) || !DestType->isIntOrIntVectorTy())
  1926. return nullptr;
  1927. // The source type must have the same number of elements as the shuffle,
  1928. // and the source element type must be larger than the shuffle element type.
  1929. Type *SrcType = X->getType();
  1930. if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() ||
  1931. cast<FixedVectorType>(SrcType)->getNumElements() !=
  1932. cast<FixedVectorType>(DestType)->getNumElements() ||
  1933. SrcType->getScalarSizeInBits() % DestType->getScalarSizeInBits() != 0)
  1934. return nullptr;
  1935. assert(Shuf.changesLength() && !Shuf.increasesLength() &&
  1936. "Expected a shuffle that decreases length");
  1937. // Last, check that the mask chooses the correct low bits for each narrow
  1938. // element in the result.
  1939. uint64_t TruncRatio =
  1940. SrcType->getScalarSizeInBits() / DestType->getScalarSizeInBits();
  1941. ArrayRef<int> Mask = Shuf.getShuffleMask();
  1942. for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
  1943. if (Mask[i] == UndefMaskElem)
  1944. continue;
  1945. uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio;
  1946. assert(LSBIndex <= INT32_MAX && "Overflowed 32-bits");
  1947. if (Mask[i] != (int)LSBIndex)
  1948. return nullptr;
  1949. }
  1950. return new TruncInst(X, DestType);
  1951. }
  1952. /// Match a shuffle-select-shuffle pattern where the shuffles are widening and
  1953. /// narrowing (concatenating with undef and extracting back to the original
  1954. /// length). This allows replacing the wide select with a narrow select.
  1955. static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf,
  1956. InstCombiner::BuilderTy &Builder) {
  1957. // This must be a narrowing identity shuffle. It extracts the 1st N elements
  1958. // of the 1st vector operand of a shuffle.
  1959. if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract())
  1960. return nullptr;
  1961. // The vector being shuffled must be a vector select that we can eliminate.
  1962. // TODO: The one-use requirement could be eased if X and/or Y are constants.
  1963. Value *Cond, *X, *Y;
  1964. if (!match(Shuf.getOperand(0),
  1965. m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))))
  1966. return nullptr;
  1967. // We need a narrow condition value. It must be extended with undef elements
  1968. // and have the same number of elements as this shuffle.
  1969. unsigned NarrowNumElts =
  1970. cast<FixedVectorType>(Shuf.getType())->getNumElements();
  1971. Value *NarrowCond;
  1972. if (!match(Cond, m_OneUse(m_Shuffle(m_Value(NarrowCond), m_Undef()))) ||
  1973. cast<FixedVectorType>(NarrowCond->getType())->getNumElements() !=
  1974. NarrowNumElts ||
  1975. !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
  1976. return nullptr;
  1977. // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) -->
  1978. // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask)
  1979. Value *NarrowX = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
  1980. Value *NarrowY = Builder.CreateShuffleVector(Y, Shuf.getShuffleMask());
  1981. return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
  1982. }
  1983. /// Try to fold an extract subvector operation.
  1984. static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) {
  1985. Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
  1986. if (!Shuf.isIdentityWithExtract() || !match(Op1, m_Undef()))
  1987. return nullptr;
  1988. // Check if we are extracting all bits of an inserted scalar:
  1989. // extract-subvec (bitcast (inselt ?, X, 0) --> bitcast X to subvec type
  1990. Value *X;
  1991. if (match(Op0, m_BitCast(m_InsertElt(m_Value(), m_Value(X), m_Zero()))) &&
  1992. X->getType()->getPrimitiveSizeInBits() ==
  1993. Shuf.getType()->getPrimitiveSizeInBits())
  1994. return new BitCastInst(X, Shuf.getType());
  1995. // Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
  1996. Value *Y;
  1997. ArrayRef<int> Mask;
  1998. if (!match(Op0, m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask))))
  1999. return nullptr;
  2000. // Be conservative with shuffle transforms. If we can't kill the 1st shuffle,
  2001. // then combining may result in worse codegen.
  2002. if (!Op0->hasOneUse())
  2003. return nullptr;
  2004. // We are extracting a subvector from a shuffle. Remove excess elements from
  2005. // the 1st shuffle mask to eliminate the extract.
  2006. //
  2007. // This transform is conservatively limited to identity extracts because we do
  2008. // not allow arbitrary shuffle mask creation as a target-independent transform
  2009. // (because we can't guarantee that will lower efficiently).
  2010. //
  2011. // If the extracting shuffle has an undef mask element, it transfers to the
  2012. // new shuffle mask. Otherwise, copy the original mask element. Example:
  2013. // shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> -->
  2014. // shuf X, Y, <C0, undef, C2, undef>
  2015. unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
  2016. SmallVector<int, 16> NewMask(NumElts);
  2017. assert(NumElts < Mask.size() &&
  2018. "Identity with extract must have less elements than its inputs");
  2019. for (unsigned i = 0; i != NumElts; ++i) {
  2020. int ExtractMaskElt = Shuf.getMaskValue(i);
  2021. int MaskElt = Mask[i];
  2022. NewMask[i] = ExtractMaskElt == UndefMaskElem ? ExtractMaskElt : MaskElt;
  2023. }
  2024. return new ShuffleVectorInst(X, Y, NewMask);
  2025. }
  2026. /// Try to replace a shuffle with an insertelement or try to replace a shuffle
  2027. /// operand with the operand of an insertelement.
  2028. static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf,
  2029. InstCombinerImpl &IC) {
  2030. Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1);
  2031. SmallVector<int, 16> Mask;
  2032. Shuf.getShuffleMask(Mask);
  2033. int NumElts = Mask.size();
  2034. int InpNumElts = cast<FixedVectorType>(V0->getType())->getNumElements();
  2035. // This is a specialization of a fold in SimplifyDemandedVectorElts. We may
  2036. // not be able to handle it there if the insertelement has >1 use.
  2037. // If the shuffle has an insertelement operand but does not choose the
  2038. // inserted scalar element from that value, then we can replace that shuffle
  2039. // operand with the source vector of the insertelement.
  2040. Value *X;
  2041. uint64_t IdxC;
  2042. if (match(V0, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
  2043. // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask
  2044. if (!is_contained(Mask, (int)IdxC))
  2045. return IC.replaceOperand(Shuf, 0, X);
  2046. }
  2047. if (match(V1, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
  2048. // Offset the index constant by the vector width because we are checking for
  2049. // accesses to the 2nd vector input of the shuffle.
  2050. IdxC += InpNumElts;
  2051. // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask
  2052. if (!is_contained(Mask, (int)IdxC))
  2053. return IC.replaceOperand(Shuf, 1, X);
  2054. }
  2055. // For the rest of the transform, the shuffle must not change vector sizes.
  2056. // TODO: This restriction could be removed if the insert has only one use
  2057. // (because the transform would require a new length-changing shuffle).
  2058. if (NumElts != InpNumElts)
  2059. return nullptr;
  2060. // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC'
  2061. auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) {
  2062. // We need an insertelement with a constant index.
  2063. if (!match(V0, m_InsertElt(m_Value(), m_Value(Scalar),
  2064. m_ConstantInt(IndexC))))
  2065. return false;
  2066. // Test the shuffle mask to see if it splices the inserted scalar into the
  2067. // operand 1 vector of the shuffle.
  2068. int NewInsIndex = -1;
  2069. for (int i = 0; i != NumElts; ++i) {
  2070. // Ignore undef mask elements.
  2071. if (Mask[i] == -1)
  2072. continue;
  2073. // The shuffle takes elements of operand 1 without lane changes.
  2074. if (Mask[i] == NumElts + i)
  2075. continue;
  2076. // The shuffle must choose the inserted scalar exactly once.
  2077. if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
  2078. return false;
  2079. // The shuffle is placing the inserted scalar into element i.
  2080. NewInsIndex = i;
  2081. }
  2082. assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?");
  2083. // Index is updated to the potentially translated insertion lane.
  2084. IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex);
  2085. return true;
  2086. };
  2087. // If the shuffle is unnecessary, insert the scalar operand directly into
  2088. // operand 1 of the shuffle. Example:
  2089. // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0
  2090. Value *Scalar;
  2091. ConstantInt *IndexC;
  2092. if (isShufflingScalarIntoOp1(Scalar, IndexC))
  2093. return InsertElementInst::Create(V1, Scalar, IndexC);
  2094. // Try again after commuting shuffle. Example:
  2095. // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> -->
  2096. // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3
  2097. std::swap(V0, V1);
  2098. ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
  2099. if (isShufflingScalarIntoOp1(Scalar, IndexC))
  2100. return InsertElementInst::Create(V1, Scalar, IndexC);
  2101. return nullptr;
  2102. }
  2103. static Instruction *foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf) {
  2104. // Match the operands as identity with padding (also known as concatenation
  2105. // with undef) shuffles of the same source type. The backend is expected to
  2106. // recreate these concatenations from a shuffle of narrow operands.
  2107. auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0));
  2108. auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1));
  2109. if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
  2110. !Shuffle1 || !Shuffle1->isIdentityWithPadding())
  2111. return nullptr;
  2112. // We limit this transform to power-of-2 types because we expect that the
  2113. // backend can convert the simplified IR patterns to identical nodes as the
  2114. // original IR.
  2115. // TODO: If we can verify the same behavior for arbitrary types, the
  2116. // power-of-2 checks can be removed.
  2117. Value *X = Shuffle0->getOperand(0);
  2118. Value *Y = Shuffle1->getOperand(0);
  2119. if (X->getType() != Y->getType() ||
  2120. !isPowerOf2_32(cast<FixedVectorType>(Shuf.getType())->getNumElements()) ||
  2121. !isPowerOf2_32(
  2122. cast<FixedVectorType>(Shuffle0->getType())->getNumElements()) ||
  2123. !isPowerOf2_32(cast<FixedVectorType>(X->getType())->getNumElements()) ||
  2124. match(X, m_Undef()) || match(Y, m_Undef()))
  2125. return nullptr;
  2126. assert(match(Shuffle0->getOperand(1), m_Undef()) &&
  2127. match(Shuffle1->getOperand(1), m_Undef()) &&
  2128. "Unexpected operand for identity shuffle");
  2129. // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source
  2130. // operands directly by adjusting the shuffle mask to account for the narrower
  2131. // types:
  2132. // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask'
  2133. int NarrowElts = cast<FixedVectorType>(X->getType())->getNumElements();
  2134. int WideElts = cast<FixedVectorType>(Shuffle0->getType())->getNumElements();
  2135. assert(WideElts > NarrowElts && "Unexpected types for identity with padding");
  2136. ArrayRef<int> Mask = Shuf.getShuffleMask();
  2137. SmallVector<int, 16> NewMask(Mask.size(), -1);
  2138. for (int i = 0, e = Mask.size(); i != e; ++i) {
  2139. if (Mask[i] == -1)
  2140. continue;
  2141. // If this shuffle is choosing an undef element from 1 of the sources, that
  2142. // element is undef.
  2143. if (Mask[i] < WideElts) {
  2144. if (Shuffle0->getMaskValue(Mask[i]) == -1)
  2145. continue;
  2146. } else {
  2147. if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
  2148. continue;
  2149. }
  2150. // If this shuffle is choosing from the 1st narrow op, the mask element is
  2151. // the same. If this shuffle is choosing from the 2nd narrow op, the mask
  2152. // element is offset down to adjust for the narrow vector widths.
  2153. if (Mask[i] < WideElts) {
  2154. assert(Mask[i] < NarrowElts && "Unexpected shuffle mask");
  2155. NewMask[i] = Mask[i];
  2156. } else {
  2157. assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask");
  2158. NewMask[i] = Mask[i] - (WideElts - NarrowElts);
  2159. }
  2160. }
  2161. return new ShuffleVectorInst(X, Y, NewMask);
  2162. }
  2163. Instruction *InstCombinerImpl::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
  2164. Value *LHS = SVI.getOperand(0);
  2165. Value *RHS = SVI.getOperand(1);
  2166. SimplifyQuery ShufQuery = SQ.getWithInstruction(&SVI);
  2167. if (auto *V = SimplifyShuffleVectorInst(LHS, RHS, SVI.getShuffleMask(),
  2168. SVI.getType(), ShufQuery))
  2169. return replaceInstUsesWith(SVI, V);
  2170. // Bail out for scalable vectors
  2171. if (isa<ScalableVectorType>(LHS->getType()))
  2172. return nullptr;
  2173. unsigned VWidth = cast<FixedVectorType>(SVI.getType())->getNumElements();
  2174. unsigned LHSWidth = cast<FixedVectorType>(LHS->getType())->getNumElements();
  2175. // shuffle (bitcast X), (bitcast Y), Mask --> bitcast (shuffle X, Y, Mask)
  2176. //
  2177. // if X and Y are of the same (vector) type, and the element size is not
  2178. // changed by the bitcasts, we can distribute the bitcasts through the
  2179. // shuffle, hopefully reducing the number of instructions. We make sure that
  2180. // at least one bitcast only has one use, so we don't *increase* the number of
  2181. // instructions here.
  2182. Value *X, *Y;
  2183. if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_BitCast(m_Value(Y))) &&
  2184. X->getType()->isVectorTy() && X->getType() == Y->getType() &&
  2185. X->getType()->getScalarSizeInBits() ==
  2186. SVI.getType()->getScalarSizeInBits() &&
  2187. (LHS->hasOneUse() || RHS->hasOneUse())) {
  2188. Value *V = Builder.CreateShuffleVector(X, Y, SVI.getShuffleMask(),
  2189. SVI.getName() + ".uncasted");
  2190. return new BitCastInst(V, SVI.getType());
  2191. }
  2192. ArrayRef<int> Mask = SVI.getShuffleMask();
  2193. Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
  2194. // Peek through a bitcasted shuffle operand by scaling the mask. If the
  2195. // simulated shuffle can simplify, then this shuffle is unnecessary:
  2196. // shuf (bitcast X), undef, Mask --> bitcast X'
  2197. // TODO: This could be extended to allow length-changing shuffles.
  2198. // The transform might also be obsoleted if we allowed canonicalization
  2199. // of bitcasted shuffles.
  2200. if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_Undef()) &&
  2201. X->getType()->isVectorTy() && VWidth == LHSWidth) {
  2202. // Try to create a scaled mask constant.
  2203. auto *XType = cast<FixedVectorType>(X->getType());
  2204. unsigned XNumElts = XType->getNumElements();
  2205. SmallVector<int, 16> ScaledMask;
  2206. if (XNumElts >= VWidth) {
  2207. assert(XNumElts % VWidth == 0 && "Unexpected vector bitcast");
  2208. narrowShuffleMaskElts(XNumElts / VWidth, Mask, ScaledMask);
  2209. } else {
  2210. assert(VWidth % XNumElts == 0 && "Unexpected vector bitcast");
  2211. if (!widenShuffleMaskElts(VWidth / XNumElts, Mask, ScaledMask))
  2212. ScaledMask.clear();
  2213. }
  2214. if (!ScaledMask.empty()) {
  2215. // If the shuffled source vector simplifies, cast that value to this
  2216. // shuffle's type.
  2217. if (auto *V = SimplifyShuffleVectorInst(X, UndefValue::get(XType),
  2218. ScaledMask, XType, ShufQuery))
  2219. return BitCastInst::Create(Instruction::BitCast, V, SVI.getType());
  2220. }
  2221. }
  2222. // shuffle x, x, mask --> shuffle x, undef, mask'
  2223. if (LHS == RHS) {
  2224. assert(!match(RHS, m_Undef()) &&
  2225. "Shuffle with 2 undef ops not simplified?");
  2226. return new ShuffleVectorInst(LHS, createUnaryMask(Mask, LHSWidth));
  2227. }
  2228. // shuffle undef, x, mask --> shuffle x, undef, mask'
  2229. if (match(LHS, m_Undef())) {
  2230. SVI.commute();
  2231. return &SVI;
  2232. }
  2233. if (Instruction *I = canonicalizeInsertSplat(SVI, Builder))
  2234. return I;
  2235. if (Instruction *I = foldSelectShuffle(SVI))
  2236. return I;
  2237. if (Instruction *I = foldTruncShuffle(SVI, DL.isBigEndian()))
  2238. return I;
  2239. if (Instruction *I = narrowVectorSelect(SVI, Builder))
  2240. return I;
  2241. APInt UndefElts(VWidth, 0);
  2242. APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
  2243. if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
  2244. if (V != &SVI)
  2245. return replaceInstUsesWith(SVI, V);
  2246. return &SVI;
  2247. }
  2248. if (Instruction *I = foldIdentityExtractShuffle(SVI))
  2249. return I;
  2250. // These transforms have the potential to lose undef knowledge, so they are
  2251. // intentionally placed after SimplifyDemandedVectorElts().
  2252. if (Instruction *I = foldShuffleWithInsert(SVI, *this))
  2253. return I;
  2254. if (Instruction *I = foldIdentityPaddedShuffles(SVI))
  2255. return I;
  2256. if (match(RHS, m_Undef()) && canEvaluateShuffled(LHS, Mask)) {
  2257. Value *V = evaluateInDifferentElementOrder(LHS, Mask);
  2258. return replaceInstUsesWith(SVI, V);
  2259. }
  2260. // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
  2261. // a non-vector type. We can instead bitcast the original vector followed by
  2262. // an extract of the desired element:
  2263. //
  2264. // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
  2265. // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
  2266. // %1 = bitcast <4 x i8> %sroa to i32
  2267. // Becomes:
  2268. // %bc = bitcast <16 x i8> %in to <4 x i32>
  2269. // %ext = extractelement <4 x i32> %bc, i32 0
  2270. //
  2271. // If the shuffle is extracting a contiguous range of values from the input
  2272. // vector then each use which is a bitcast of the extracted size can be
  2273. // replaced. This will work if the vector types are compatible, and the begin
  2274. // index is aligned to a value in the casted vector type. If the begin index
  2275. // isn't aligned then we can shuffle the original vector (keeping the same
  2276. // vector type) before extracting.
  2277. //
  2278. // This code will bail out if the target type is fundamentally incompatible
  2279. // with vectors of the source type.
  2280. //
  2281. // Example of <16 x i8>, target type i32:
  2282. // Index range [4,8): v-----------v Will work.
  2283. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  2284. // <16 x i8>: | | | | | | | | | | | | | | | | |
  2285. // <4 x i32>: | | | | |
  2286. // +-----------+-----------+-----------+-----------+
  2287. // Index range [6,10): ^-----------^ Needs an extra shuffle.
  2288. // Target type i40: ^--------------^ Won't work, bail.
  2289. bool MadeChange = false;
  2290. if (isShuffleExtractingFromLHS(SVI, Mask)) {
  2291. Value *V = LHS;
  2292. unsigned MaskElems = Mask.size();
  2293. auto *SrcTy = cast<FixedVectorType>(V->getType());
  2294. unsigned VecBitWidth = SrcTy->getPrimitiveSizeInBits().getFixedSize();
  2295. unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
  2296. assert(SrcElemBitWidth && "vector elements must have a bitwidth");
  2297. unsigned SrcNumElems = SrcTy->getNumElements();
  2298. SmallVector<BitCastInst *, 8> BCs;
  2299. DenseMap<Type *, Value *> NewBCs;
  2300. for (User *U : SVI.users())
  2301. if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
  2302. if (!BC->use_empty())
  2303. // Only visit bitcasts that weren't previously handled.
  2304. BCs.push_back(BC);
  2305. for (BitCastInst *BC : BCs) {
  2306. unsigned BegIdx = Mask.front();
  2307. Type *TgtTy = BC->getDestTy();
  2308. unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
  2309. if (!TgtElemBitWidth)
  2310. continue;
  2311. unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
  2312. bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
  2313. bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
  2314. if (!VecBitWidthsEqual)
  2315. continue;
  2316. if (!VectorType::isValidElementType(TgtTy))
  2317. continue;
  2318. auto *CastSrcTy = FixedVectorType::get(TgtTy, TgtNumElems);
  2319. if (!BegIsAligned) {
  2320. // Shuffle the input so [0,NumElements) contains the output, and
  2321. // [NumElems,SrcNumElems) is undef.
  2322. SmallVector<int, 16> ShuffleMask(SrcNumElems, -1);
  2323. for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
  2324. ShuffleMask[I] = Idx;
  2325. V = Builder.CreateShuffleVector(V, ShuffleMask,
  2326. SVI.getName() + ".extract");
  2327. BegIdx = 0;
  2328. }
  2329. unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
  2330. assert(SrcElemsPerTgtElem);
  2331. BegIdx /= SrcElemsPerTgtElem;
  2332. bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
  2333. auto *NewBC =
  2334. BCAlreadyExists
  2335. ? NewBCs[CastSrcTy]
  2336. : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
  2337. if (!BCAlreadyExists)
  2338. NewBCs[CastSrcTy] = NewBC;
  2339. auto *Ext = Builder.CreateExtractElement(
  2340. NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
  2341. // The shufflevector isn't being replaced: the bitcast that used it
  2342. // is. InstCombine will visit the newly-created instructions.
  2343. replaceInstUsesWith(*BC, Ext);
  2344. MadeChange = true;
  2345. }
  2346. }
  2347. // If the LHS is a shufflevector itself, see if we can combine it with this
  2348. // one without producing an unusual shuffle.
  2349. // Cases that might be simplified:
  2350. // 1.
  2351. // x1=shuffle(v1,v2,mask1)
  2352. // x=shuffle(x1,undef,mask)
  2353. // ==>
  2354. // x=shuffle(v1,undef,newMask)
  2355. // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
  2356. // 2.
  2357. // x1=shuffle(v1,undef,mask1)
  2358. // x=shuffle(x1,x2,mask)
  2359. // where v1.size() == mask1.size()
  2360. // ==>
  2361. // x=shuffle(v1,x2,newMask)
  2362. // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
  2363. // 3.
  2364. // x2=shuffle(v2,undef,mask2)
  2365. // x=shuffle(x1,x2,mask)
  2366. // where v2.size() == mask2.size()
  2367. // ==>
  2368. // x=shuffle(x1,v2,newMask)
  2369. // newMask[i] = (mask[i] < x1.size())
  2370. // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
  2371. // 4.
  2372. // x1=shuffle(v1,undef,mask1)
  2373. // x2=shuffle(v2,undef,mask2)
  2374. // x=shuffle(x1,x2,mask)
  2375. // where v1.size() == v2.size()
  2376. // ==>
  2377. // x=shuffle(v1,v2,newMask)
  2378. // newMask[i] = (mask[i] < x1.size())
  2379. // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
  2380. //
  2381. // Here we are really conservative:
  2382. // we are absolutely afraid of producing a shuffle mask not in the input
  2383. // program, because the code gen may not be smart enough to turn a merged
  2384. // shuffle into two specific shuffles: it may produce worse code. As such,
  2385. // we only merge two shuffles if the result is either a splat or one of the
  2386. // input shuffle masks. In this case, merging the shuffles just removes
  2387. // one instruction, which we know is safe. This is good for things like
  2388. // turning: (splat(splat)) -> splat, or
  2389. // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
  2390. ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
  2391. ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
  2392. if (LHSShuffle)
  2393. if (!match(LHSShuffle->getOperand(1), m_Undef()) && !match(RHS, m_Undef()))
  2394. LHSShuffle = nullptr;
  2395. if (RHSShuffle)
  2396. if (!match(RHSShuffle->getOperand(1), m_Undef()))
  2397. RHSShuffle = nullptr;
  2398. if (!LHSShuffle && !RHSShuffle)
  2399. return MadeChange ? &SVI : nullptr;
  2400. Value* LHSOp0 = nullptr;
  2401. Value* LHSOp1 = nullptr;
  2402. Value* RHSOp0 = nullptr;
  2403. unsigned LHSOp0Width = 0;
  2404. unsigned RHSOp0Width = 0;
  2405. if (LHSShuffle) {
  2406. LHSOp0 = LHSShuffle->getOperand(0);
  2407. LHSOp1 = LHSShuffle->getOperand(1);
  2408. LHSOp0Width = cast<FixedVectorType>(LHSOp0->getType())->getNumElements();
  2409. }
  2410. if (RHSShuffle) {
  2411. RHSOp0 = RHSShuffle->getOperand(0);
  2412. RHSOp0Width = cast<FixedVectorType>(RHSOp0->getType())->getNumElements();
  2413. }
  2414. Value* newLHS = LHS;
  2415. Value* newRHS = RHS;
  2416. if (LHSShuffle) {
  2417. // case 1
  2418. if (match(RHS, m_Undef())) {
  2419. newLHS = LHSOp0;
  2420. newRHS = LHSOp1;
  2421. }
  2422. // case 2 or 4
  2423. else if (LHSOp0Width == LHSWidth) {
  2424. newLHS = LHSOp0;
  2425. }
  2426. }
  2427. // case 3 or 4
  2428. if (RHSShuffle && RHSOp0Width == LHSWidth) {
  2429. newRHS = RHSOp0;
  2430. }
  2431. // case 4
  2432. if (LHSOp0 == RHSOp0) {
  2433. newLHS = LHSOp0;
  2434. newRHS = nullptr;
  2435. }
  2436. if (newLHS == LHS && newRHS == RHS)
  2437. return MadeChange ? &SVI : nullptr;
  2438. ArrayRef<int> LHSMask;
  2439. ArrayRef<int> RHSMask;
  2440. if (newLHS != LHS)
  2441. LHSMask = LHSShuffle->getShuffleMask();
  2442. if (RHSShuffle && newRHS != RHS)
  2443. RHSMask = RHSShuffle->getShuffleMask();
  2444. unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
  2445. SmallVector<int, 16> newMask;
  2446. bool isSplat = true;
  2447. int SplatElt = -1;
  2448. // Create a new mask for the new ShuffleVectorInst so that the new
  2449. // ShuffleVectorInst is equivalent to the original one.
  2450. for (unsigned i = 0; i < VWidth; ++i) {
  2451. int eltMask;
  2452. if (Mask[i] < 0) {
  2453. // This element is an undef value.
  2454. eltMask = -1;
  2455. } else if (Mask[i] < (int)LHSWidth) {
  2456. // This element is from left hand side vector operand.
  2457. //
  2458. // If LHS is going to be replaced (case 1, 2, or 4), calculate the
  2459. // new mask value for the element.
  2460. if (newLHS != LHS) {
  2461. eltMask = LHSMask[Mask[i]];
  2462. // If the value selected is an undef value, explicitly specify it
  2463. // with a -1 mask value.
  2464. if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
  2465. eltMask = -1;
  2466. } else
  2467. eltMask = Mask[i];
  2468. } else {
  2469. // This element is from right hand side vector operand
  2470. //
  2471. // If the value selected is an undef value, explicitly specify it
  2472. // with a -1 mask value. (case 1)
  2473. if (match(RHS, m_Undef()))
  2474. eltMask = -1;
  2475. // If RHS is going to be replaced (case 3 or 4), calculate the
  2476. // new mask value for the element.
  2477. else if (newRHS != RHS) {
  2478. eltMask = RHSMask[Mask[i]-LHSWidth];
  2479. // If the value selected is an undef value, explicitly specify it
  2480. // with a -1 mask value.
  2481. if (eltMask >= (int)RHSOp0Width) {
  2482. assert(match(RHSShuffle->getOperand(1), m_Undef()) &&
  2483. "should have been check above");
  2484. eltMask = -1;
  2485. }
  2486. } else
  2487. eltMask = Mask[i]-LHSWidth;
  2488. // If LHS's width is changed, shift the mask value accordingly.
  2489. // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
  2490. // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
  2491. // If newRHS == newLHS, we want to remap any references from newRHS to
  2492. // newLHS so that we can properly identify splats that may occur due to
  2493. // obfuscation across the two vectors.
  2494. if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
  2495. eltMask += newLHSWidth;
  2496. }
  2497. // Check if this could still be a splat.
  2498. if (eltMask >= 0) {
  2499. if (SplatElt >= 0 && SplatElt != eltMask)
  2500. isSplat = false;
  2501. SplatElt = eltMask;
  2502. }
  2503. newMask.push_back(eltMask);
  2504. }
  2505. // If the result mask is equal to one of the original shuffle masks,
  2506. // or is a splat, do the replacement.
  2507. if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
  2508. if (!newRHS)
  2509. newRHS = UndefValue::get(newLHS->getType());
  2510. return new ShuffleVectorInst(newLHS, newRHS, newMask);
  2511. }
  2512. return MadeChange ? &SVI : nullptr;
  2513. }