InstCombineVectorOps.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. //===- InstCombineVectorOps.cpp -------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements instcombine for ExtractElement, InsertElement and
  11. // ShuffleVector.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "InstCombineInternal.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/Analysis/InstructionSimplify.h"
  17. #include "llvm/Analysis/VectorUtils.h"
  18. #include "llvm/IR/PatternMatch.h"
  19. using namespace llvm;
  20. using namespace PatternMatch;
  21. #define DEBUG_TYPE "instcombine"
  22. /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
  23. /// is to leave as a vector operation. isConstant indicates whether we're
  24. /// extracting one known element. If false we're extracting a variable index.
  25. static bool CheapToScalarize(Value *V, bool isConstant) {
  26. if (Constant *C = dyn_cast<Constant>(V)) {
  27. if (isConstant) return true;
  28. // If all elts are the same, we can extract it and use any of the values.
  29. if (Constant *Op0 = C->getAggregateElement(0U)) {
  30. for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
  31. ++i)
  32. if (C->getAggregateElement(i) != Op0)
  33. return false;
  34. return true;
  35. }
  36. }
  37. Instruction *I = dyn_cast<Instruction>(V);
  38. if (!I) return false;
  39. // Insert element gets simplified to the inserted element or is deleted if
  40. // this is constant idx extract element and its a constant idx insertelt.
  41. if (I->getOpcode() == Instruction::InsertElement && isConstant &&
  42. isa<ConstantInt>(I->getOperand(2)))
  43. return true;
  44. if (I->getOpcode() == Instruction::Load && I->hasOneUse())
  45. return true;
  46. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
  47. if (BO->hasOneUse() &&
  48. (CheapToScalarize(BO->getOperand(0), isConstant) ||
  49. CheapToScalarize(BO->getOperand(1), isConstant)))
  50. return true;
  51. if (CmpInst *CI = dyn_cast<CmpInst>(I))
  52. if (CI->hasOneUse() &&
  53. (CheapToScalarize(CI->getOperand(0), isConstant) ||
  54. CheapToScalarize(CI->getOperand(1), isConstant)))
  55. return true;
  56. return false;
  57. }
  58. // If we have a PHI node with a vector type that has only 2 uses: feed
  59. // itself and be an operand of extractelement at a constant location,
  60. // try to replace the PHI of the vector type with a PHI of a scalar type.
  61. Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
  62. // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
  63. if (!PN->hasNUses(2))
  64. return nullptr;
  65. // If so, it's known at this point that one operand is PHI and the other is
  66. // an extractelement node. Find the PHI user that is not the extractelement
  67. // node.
  68. auto iu = PN->user_begin();
  69. Instruction *PHIUser = dyn_cast<Instruction>(*iu);
  70. if (PHIUser == cast<Instruction>(&EI))
  71. PHIUser = cast<Instruction>(*(++iu));
  72. // Verify that this PHI user has one use, which is the PHI itself,
  73. // and that it is a binary operation which is cheap to scalarize.
  74. // otherwise return NULL.
  75. if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
  76. !(isa<BinaryOperator>(PHIUser)) || !CheapToScalarize(PHIUser, true))
  77. return nullptr;
  78. // Create a scalar PHI node that will replace the vector PHI node
  79. // just before the current PHI node.
  80. PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
  81. PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
  82. // Scalarize each PHI operand.
  83. for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
  84. Value *PHIInVal = PN->getIncomingValue(i);
  85. BasicBlock *inBB = PN->getIncomingBlock(i);
  86. Value *Elt = EI.getIndexOperand();
  87. // If the operand is the PHI induction variable:
  88. if (PHIInVal == PHIUser) {
  89. // Scalarize the binary operation. Its first operand is the
  90. // scalar PHI, and the second operand is extracted from the other
  91. // vector operand.
  92. BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
  93. unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
  94. Value *Op = InsertNewInstWith(
  95. ExtractElementInst::Create(B0->getOperand(opId), Elt,
  96. B0->getOperand(opId)->getName() + ".Elt"),
  97. *B0);
  98. Value *newPHIUser = InsertNewInstWith(
  99. BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
  100. scalarPHI->addIncoming(newPHIUser, inBB);
  101. } else {
  102. // Scalarize PHI input:
  103. Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
  104. // Insert the new instruction into the predecessor basic block.
  105. Instruction *pos = dyn_cast<Instruction>(PHIInVal);
  106. BasicBlock::iterator InsertPos;
  107. if (pos && !isa<PHINode>(pos)) {
  108. InsertPos = pos;
  109. ++InsertPos;
  110. } else {
  111. InsertPos = inBB->getFirstInsertionPt();
  112. }
  113. InsertNewInstWith(newEI, *InsertPos);
  114. scalarPHI->addIncoming(newEI, inBB);
  115. }
  116. }
  117. return ReplaceInstUsesWith(EI, scalarPHI);
  118. }
  119. Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
  120. if (Value *V = SimplifyExtractElementInst(
  121. EI.getVectorOperand(), EI.getIndexOperand(), DL, TLI, DT, AC))
  122. return ReplaceInstUsesWith(EI, V);
  123. // If vector val is constant with all elements the same, replace EI with
  124. // that element. We handle a known element # below.
  125. if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
  126. if (CheapToScalarize(C, false))
  127. return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
  128. // If extracting a specified index from the vector, see if we can recursively
  129. // find a previously computed scalar that was inserted into the vector.
  130. if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
  131. unsigned IndexVal = IdxC->getZExtValue();
  132. unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
  133. // InstSimplify handles cases where the index is invalid.
  134. assert(IndexVal < VectorWidth);
  135. // This instruction only demands the single element from the input vector.
  136. // If the input vector has a single use, simplify it based on this use
  137. // property.
  138. if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
  139. APInt UndefElts(VectorWidth, 0);
  140. APInt DemandedMask(VectorWidth, 0);
  141. DemandedMask.setBit(IndexVal);
  142. if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
  143. UndefElts)) {
  144. EI.setOperand(0, V);
  145. return &EI;
  146. }
  147. }
  148. // If the this extractelement is directly using a bitcast from a vector of
  149. // the same number of elements, see if we can find the source element from
  150. // it. In this case, we will end up needing to bitcast the scalars.
  151. if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
  152. if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
  153. if (VT->getNumElements() == VectorWidth)
  154. if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
  155. return new BitCastInst(Elt, EI.getType());
  156. }
  157. // If there's a vector PHI feeding a scalar use through this extractelement
  158. // instruction, try to scalarize the PHI.
  159. if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
  160. Instruction *scalarPHI = scalarizePHI(EI, PN);
  161. if (scalarPHI)
  162. return scalarPHI;
  163. }
  164. }
  165. if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
  166. // Push extractelement into predecessor operation if legal and
  167. // profitable to do so
  168. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
  169. if (I->hasOneUse() &&
  170. CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
  171. Value *newEI0 =
  172. Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
  173. EI.getName()+".lhs");
  174. Value *newEI1 =
  175. Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
  176. EI.getName()+".rhs");
  177. return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
  178. }
  179. } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
  180. // Extracting the inserted element?
  181. if (IE->getOperand(2) == EI.getOperand(1))
  182. return ReplaceInstUsesWith(EI, IE->getOperand(1));
  183. // If the inserted and extracted elements are constants, they must not
  184. // be the same value, extract from the pre-inserted value instead.
  185. if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
  186. Worklist.AddValue(EI.getOperand(0));
  187. EI.setOperand(0, IE->getOperand(0));
  188. return &EI;
  189. }
  190. } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
  191. // If this is extracting an element from a shufflevector, figure out where
  192. // it came from and extract from the appropriate input element instead.
  193. if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
  194. int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
  195. Value *Src;
  196. unsigned LHSWidth =
  197. SVI->getOperand(0)->getType()->getVectorNumElements();
  198. if (SrcIdx < 0)
  199. return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
  200. if (SrcIdx < (int)LHSWidth)
  201. Src = SVI->getOperand(0);
  202. else {
  203. SrcIdx -= LHSWidth;
  204. Src = SVI->getOperand(1);
  205. }
  206. Type *Int32Ty = Type::getInt32Ty(EI.getContext());
  207. return ExtractElementInst::Create(Src,
  208. ConstantInt::get(Int32Ty,
  209. SrcIdx, false));
  210. }
  211. } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
  212. // Canonicalize extractelement(cast) -> cast(extractelement)
  213. // bitcasts can change the number of vector elements and they cost nothing
  214. if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
  215. Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
  216. EI.getIndexOperand());
  217. Worklist.AddValue(EE);
  218. return CastInst::Create(CI->getOpcode(), EE, EI.getType());
  219. }
  220. } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  221. if (SI->hasOneUse()) {
  222. // TODO: For a select on vectors, it might be useful to do this if it
  223. // has multiple extractelement uses. For vector select, that seems to
  224. // fight the vectorizer.
  225. // If we are extracting an element from a vector select or a select on
  226. // vectors, a select on the scalars extracted from the vector arguments.
  227. Value *TrueVal = SI->getTrueValue();
  228. Value *FalseVal = SI->getFalseValue();
  229. Value *Cond = SI->getCondition();
  230. if (Cond->getType()->isVectorTy()) {
  231. Cond = Builder->CreateExtractElement(Cond,
  232. EI.getIndexOperand(),
  233. Cond->getName() + ".elt");
  234. }
  235. Value *V1Elem
  236. = Builder->CreateExtractElement(TrueVal,
  237. EI.getIndexOperand(),
  238. TrueVal->getName() + ".elt");
  239. Value *V2Elem
  240. = Builder->CreateExtractElement(FalseVal,
  241. EI.getIndexOperand(),
  242. FalseVal->getName() + ".elt");
  243. return SelectInst::Create(Cond,
  244. V1Elem,
  245. V2Elem,
  246. SI->getName() + ".elt");
  247. }
  248. }
  249. }
  250. return nullptr;
  251. }
  252. /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
  253. /// elements from either LHS or RHS, return the shuffle mask and true.
  254. /// Otherwise, return false.
  255. static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
  256. SmallVectorImpl<Constant*> &Mask) {
  257. assert(LHS->getType() == RHS->getType() &&
  258. "Invalid CollectSingleShuffleElements");
  259. unsigned NumElts = V->getType()->getVectorNumElements();
  260. if (isa<UndefValue>(V)) {
  261. Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
  262. return true;
  263. }
  264. if (V == LHS) {
  265. for (unsigned i = 0; i != NumElts; ++i)
  266. Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
  267. return true;
  268. }
  269. if (V == RHS) {
  270. for (unsigned i = 0; i != NumElts; ++i)
  271. Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
  272. i+NumElts));
  273. return true;
  274. }
  275. if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
  276. // If this is an insert of an extract from some other vector, include it.
  277. Value *VecOp = IEI->getOperand(0);
  278. Value *ScalarOp = IEI->getOperand(1);
  279. Value *IdxOp = IEI->getOperand(2);
  280. if (!isa<ConstantInt>(IdxOp))
  281. return false;
  282. unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
  283. if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
  284. // We can handle this if the vector we are inserting into is
  285. // transitively ok.
  286. if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
  287. // If so, update the mask to reflect the inserted undef.
  288. Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
  289. return true;
  290. }
  291. } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
  292. if (isa<ConstantInt>(EI->getOperand(1))) {
  293. unsigned ExtractedIdx =
  294. cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
  295. unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
  296. // This must be extracting from either LHS or RHS.
  297. if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
  298. // We can handle this if the vector we are inserting into is
  299. // transitively ok.
  300. if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
  301. // If so, update the mask to reflect the inserted value.
  302. if (EI->getOperand(0) == LHS) {
  303. Mask[InsertedIdx % NumElts] =
  304. ConstantInt::get(Type::getInt32Ty(V->getContext()),
  305. ExtractedIdx);
  306. } else {
  307. assert(EI->getOperand(0) == RHS);
  308. Mask[InsertedIdx % NumElts] =
  309. ConstantInt::get(Type::getInt32Ty(V->getContext()),
  310. ExtractedIdx + NumLHSElts);
  311. }
  312. return true;
  313. }
  314. }
  315. }
  316. }
  317. }
  318. return false;
  319. }
  320. /// We are building a shuffle to create V, which is a sequence of insertelement,
  321. /// extractelement pairs. If PermittedRHS is set, then we must either use it or
  322. /// not rely on the second vector source. Return a std::pair containing the
  323. /// left and right vectors of the proposed shuffle (or 0), and set the Mask
  324. /// parameter as required.
  325. ///
  326. /// Note: we intentionally don't try to fold earlier shuffles since they have
  327. /// often been chosen carefully to be efficiently implementable on the target.
  328. typedef std::pair<Value *, Value *> ShuffleOps;
  329. static ShuffleOps CollectShuffleElements(Value *V,
  330. SmallVectorImpl<Constant *> &Mask,
  331. Value *PermittedRHS) {
  332. assert(V->getType()->isVectorTy() && "Invalid shuffle!");
  333. unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
  334. if (isa<UndefValue>(V)) {
  335. Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
  336. return std::make_pair(
  337. PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
  338. }
  339. if (isa<ConstantAggregateZero>(V)) {
  340. Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
  341. return std::make_pair(V, nullptr);
  342. }
  343. if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
  344. // If this is an insert of an extract from some other vector, include it.
  345. Value *VecOp = IEI->getOperand(0);
  346. Value *ScalarOp = IEI->getOperand(1);
  347. Value *IdxOp = IEI->getOperand(2);
  348. if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
  349. if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
  350. unsigned ExtractedIdx =
  351. cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
  352. unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
  353. // Either the extracted from or inserted into vector must be RHSVec,
  354. // otherwise we'd end up with a shuffle of three inputs.
  355. if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
  356. Value *RHS = EI->getOperand(0);
  357. ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
  358. assert(LR.second == nullptr || LR.second == RHS);
  359. if (LR.first->getType() != RHS->getType()) {
  360. // We tried our best, but we can't find anything compatible with RHS
  361. // further up the chain. Return a trivial shuffle.
  362. for (unsigned i = 0; i < NumElts; ++i)
  363. Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
  364. return std::make_pair(V, nullptr);
  365. }
  366. unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
  367. Mask[InsertedIdx % NumElts] =
  368. ConstantInt::get(Type::getInt32Ty(V->getContext()),
  369. NumLHSElts+ExtractedIdx);
  370. return std::make_pair(LR.first, RHS);
  371. }
  372. if (VecOp == PermittedRHS) {
  373. // We've gone as far as we can: anything on the other side of the
  374. // extractelement will already have been converted into a shuffle.
  375. unsigned NumLHSElts =
  376. EI->getOperand(0)->getType()->getVectorNumElements();
  377. for (unsigned i = 0; i != NumElts; ++i)
  378. Mask.push_back(ConstantInt::get(
  379. Type::getInt32Ty(V->getContext()),
  380. i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
  381. return std::make_pair(EI->getOperand(0), PermittedRHS);
  382. }
  383. // If this insertelement is a chain that comes from exactly these two
  384. // vectors, return the vector and the effective shuffle.
  385. if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
  386. CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
  387. Mask))
  388. return std::make_pair(EI->getOperand(0), PermittedRHS);
  389. }
  390. }
  391. }
  392. // Otherwise, can't do anything fancy. Return an identity vector.
  393. for (unsigned i = 0; i != NumElts; ++i)
  394. Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
  395. return std::make_pair(V, nullptr);
  396. }
  397. /// Try to find redundant insertvalue instructions, like the following ones:
  398. /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
  399. /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
  400. /// Here the second instruction inserts values at the same indices, as the
  401. /// first one, making the first one redundant.
  402. /// It should be transformed to:
  403. /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
  404. Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
  405. bool IsRedundant = false;
  406. ArrayRef<unsigned int> FirstIndices = I.getIndices();
  407. // If there is a chain of insertvalue instructions (each of them except the
  408. // last one has only one use and it's another insertvalue insn from this
  409. // chain), check if any of the 'children' uses the same indices as the first
  410. // instruction. In this case, the first one is redundant.
  411. Value *V = &I;
  412. unsigned Depth = 0;
  413. while (V->hasOneUse() && Depth < 10) {
  414. User *U = V->user_back();
  415. auto UserInsInst = dyn_cast<InsertValueInst>(U);
  416. if (!UserInsInst || U->getOperand(0) != V)
  417. break;
  418. if (UserInsInst->getIndices() == FirstIndices) {
  419. IsRedundant = true;
  420. break;
  421. }
  422. V = UserInsInst;
  423. Depth++;
  424. }
  425. if (IsRedundant)
  426. return ReplaceInstUsesWith(I, I.getOperand(0));
  427. return nullptr;
  428. }
  429. Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
  430. Value *VecOp = IE.getOperand(0);
  431. Value *ScalarOp = IE.getOperand(1);
  432. Value *IdxOp = IE.getOperand(2);
  433. // Inserting an undef or into an undefined place, remove this.
  434. if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
  435. ReplaceInstUsesWith(IE, VecOp);
  436. // If the inserted element was extracted from some other vector, and if the
  437. // indexes are constant, try to turn this into a shufflevector operation.
  438. if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
  439. if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
  440. unsigned NumInsertVectorElts = IE.getType()->getNumElements();
  441. unsigned NumExtractVectorElts =
  442. EI->getOperand(0)->getType()->getVectorNumElements();
  443. unsigned ExtractedIdx =
  444. cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
  445. unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
  446. if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
  447. return ReplaceInstUsesWith(IE, VecOp);
  448. if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
  449. return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
  450. // If we are extracting a value from a vector, then inserting it right
  451. // back into the same place, just use the input vector.
  452. if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
  453. return ReplaceInstUsesWith(IE, VecOp);
  454. // If this insertelement isn't used by some other insertelement, turn it
  455. // (and any insertelements it points to), into one big shuffle.
  456. if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
  457. SmallVector<Constant*, 16> Mask;
  458. ShuffleOps LR = CollectShuffleElements(&IE, Mask, nullptr);
  459. // The proposed shuffle may be trivial, in which case we shouldn't
  460. // perform the combine.
  461. if (LR.first != &IE && LR.second != &IE) {
  462. // We now have a shuffle of LHS, RHS, Mask.
  463. if (LR.second == nullptr)
  464. LR.second = UndefValue::get(LR.first->getType());
  465. return new ShuffleVectorInst(LR.first, LR.second,
  466. ConstantVector::get(Mask));
  467. }
  468. }
  469. }
  470. }
  471. unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
  472. APInt UndefElts(VWidth, 0);
  473. APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
  474. if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
  475. if (V != &IE)
  476. return ReplaceInstUsesWith(IE, V);
  477. return &IE;
  478. }
  479. return nullptr;
  480. }
  481. /// Return true if we can evaluate the specified expression tree if the vector
  482. /// elements were shuffled in a different order.
  483. static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
  484. unsigned Depth = 5) {
  485. // We can always reorder the elements of a constant.
  486. if (isa<Constant>(V))
  487. return true;
  488. // We won't reorder vector arguments. No IPO here.
  489. Instruction *I = dyn_cast<Instruction>(V);
  490. if (!I) return false;
  491. // Two users may expect different orders of the elements. Don't try it.
  492. if (!I->hasOneUse())
  493. return false;
  494. if (Depth == 0) return false;
  495. switch (I->getOpcode()) {
  496. case Instruction::Add:
  497. case Instruction::FAdd:
  498. case Instruction::Sub:
  499. case Instruction::FSub:
  500. case Instruction::Mul:
  501. case Instruction::FMul:
  502. case Instruction::UDiv:
  503. case Instruction::SDiv:
  504. case Instruction::FDiv:
  505. case Instruction::URem:
  506. case Instruction::SRem:
  507. case Instruction::FRem:
  508. case Instruction::Shl:
  509. case Instruction::LShr:
  510. case Instruction::AShr:
  511. case Instruction::And:
  512. case Instruction::Or:
  513. case Instruction::Xor:
  514. case Instruction::ICmp:
  515. case Instruction::FCmp:
  516. case Instruction::Trunc:
  517. case Instruction::ZExt:
  518. case Instruction::SExt:
  519. case Instruction::FPToUI:
  520. case Instruction::FPToSI:
  521. case Instruction::UIToFP:
  522. case Instruction::SIToFP:
  523. case Instruction::FPTrunc:
  524. case Instruction::FPExt:
  525. case Instruction::GetElementPtr: {
  526. for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
  527. if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
  528. return false;
  529. }
  530. return true;
  531. }
  532. case Instruction::InsertElement: {
  533. ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
  534. if (!CI) return false;
  535. int ElementNumber = CI->getLimitedValue();
  536. // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
  537. // can't put an element into multiple indices.
  538. bool SeenOnce = false;
  539. for (int i = 0, e = Mask.size(); i != e; ++i) {
  540. if (Mask[i] == ElementNumber) {
  541. if (SeenOnce)
  542. return false;
  543. SeenOnce = true;
  544. }
  545. }
  546. return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
  547. }
  548. }
  549. return false;
  550. }
  551. /// Rebuild a new instruction just like 'I' but with the new operands given.
  552. /// In the event of type mismatch, the type of the operands is correct.
  553. static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
  554. // We don't want to use the IRBuilder here because we want the replacement
  555. // instructions to appear next to 'I', not the builder's insertion point.
  556. switch (I->getOpcode()) {
  557. case Instruction::Add:
  558. case Instruction::FAdd:
  559. case Instruction::Sub:
  560. case Instruction::FSub:
  561. case Instruction::Mul:
  562. case Instruction::FMul:
  563. case Instruction::UDiv:
  564. case Instruction::SDiv:
  565. case Instruction::FDiv:
  566. case Instruction::URem:
  567. case Instruction::SRem:
  568. case Instruction::FRem:
  569. case Instruction::Shl:
  570. case Instruction::LShr:
  571. case Instruction::AShr:
  572. case Instruction::And:
  573. case Instruction::Or:
  574. case Instruction::Xor: {
  575. BinaryOperator *BO = cast<BinaryOperator>(I);
  576. assert(NewOps.size() == 2 && "binary operator with #ops != 2");
  577. BinaryOperator *New =
  578. BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
  579. NewOps[0], NewOps[1], "", BO);
  580. if (isa<OverflowingBinaryOperator>(BO)) {
  581. New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
  582. New->setHasNoSignedWrap(BO->hasNoSignedWrap());
  583. }
  584. if (isa<PossiblyExactOperator>(BO)) {
  585. New->setIsExact(BO->isExact());
  586. }
  587. if (isa<FPMathOperator>(BO))
  588. New->copyFastMathFlags(I);
  589. return New;
  590. }
  591. case Instruction::ICmp:
  592. assert(NewOps.size() == 2 && "icmp with #ops != 2");
  593. return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
  594. NewOps[0], NewOps[1]);
  595. case Instruction::FCmp:
  596. assert(NewOps.size() == 2 && "fcmp with #ops != 2");
  597. return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
  598. NewOps[0], NewOps[1]);
  599. case Instruction::Trunc:
  600. case Instruction::ZExt:
  601. case Instruction::SExt:
  602. case Instruction::FPToUI:
  603. case Instruction::FPToSI:
  604. case Instruction::UIToFP:
  605. case Instruction::SIToFP:
  606. case Instruction::FPTrunc:
  607. case Instruction::FPExt: {
  608. // It's possible that the mask has a different number of elements from
  609. // the original cast. We recompute the destination type to match the mask.
  610. Type *DestTy =
  611. VectorType::get(I->getType()->getScalarType(),
  612. NewOps[0]->getType()->getVectorNumElements());
  613. assert(NewOps.size() == 1 && "cast with #ops != 1");
  614. return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
  615. "", I);
  616. }
  617. case Instruction::GetElementPtr: {
  618. Value *Ptr = NewOps[0];
  619. ArrayRef<Value*> Idx = NewOps.slice(1);
  620. GetElementPtrInst *GEP = GetElementPtrInst::Create(
  621. cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
  622. GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
  623. return GEP;
  624. }
  625. }
  626. llvm_unreachable("failed to rebuild vector instructions");
  627. }
  628. Value *
  629. InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
  630. // Mask.size() does not need to be equal to the number of vector elements.
  631. assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
  632. if (isa<UndefValue>(V)) {
  633. return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
  634. Mask.size()));
  635. }
  636. if (isa<ConstantAggregateZero>(V)) {
  637. return ConstantAggregateZero::get(
  638. VectorType::get(V->getType()->getScalarType(),
  639. Mask.size()));
  640. }
  641. if (Constant *C = dyn_cast<Constant>(V)) {
  642. SmallVector<Constant *, 16> MaskValues;
  643. for (int i = 0, e = Mask.size(); i != e; ++i) {
  644. if (Mask[i] == -1)
  645. MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
  646. else
  647. MaskValues.push_back(Builder->getInt32(Mask[i]));
  648. }
  649. return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
  650. ConstantVector::get(MaskValues));
  651. }
  652. Instruction *I = cast<Instruction>(V);
  653. switch (I->getOpcode()) {
  654. case Instruction::Add:
  655. case Instruction::FAdd:
  656. case Instruction::Sub:
  657. case Instruction::FSub:
  658. case Instruction::Mul:
  659. case Instruction::FMul:
  660. case Instruction::UDiv:
  661. case Instruction::SDiv:
  662. case Instruction::FDiv:
  663. case Instruction::URem:
  664. case Instruction::SRem:
  665. case Instruction::FRem:
  666. case Instruction::Shl:
  667. case Instruction::LShr:
  668. case Instruction::AShr:
  669. case Instruction::And:
  670. case Instruction::Or:
  671. case Instruction::Xor:
  672. case Instruction::ICmp:
  673. case Instruction::FCmp:
  674. case Instruction::Trunc:
  675. case Instruction::ZExt:
  676. case Instruction::SExt:
  677. case Instruction::FPToUI:
  678. case Instruction::FPToSI:
  679. case Instruction::UIToFP:
  680. case Instruction::SIToFP:
  681. case Instruction::FPTrunc:
  682. case Instruction::FPExt:
  683. case Instruction::Select:
  684. case Instruction::GetElementPtr: {
  685. SmallVector<Value*, 8> NewOps;
  686. bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
  687. for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
  688. Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
  689. NewOps.push_back(V);
  690. NeedsRebuild |= (V != I->getOperand(i));
  691. }
  692. if (NeedsRebuild) {
  693. return BuildNew(I, NewOps);
  694. }
  695. return I;
  696. }
  697. case Instruction::InsertElement: {
  698. int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
  699. // The insertelement was inserting at Element. Figure out which element
  700. // that becomes after shuffling. The answer is guaranteed to be unique
  701. // by CanEvaluateShuffled.
  702. bool Found = false;
  703. int Index = 0;
  704. for (int e = Mask.size(); Index != e; ++Index) {
  705. if (Mask[Index] == Element) {
  706. Found = true;
  707. break;
  708. }
  709. }
  710. // If element is not in Mask, no need to handle the operand 1 (element to
  711. // be inserted). Just evaluate values in operand 0 according to Mask.
  712. if (!Found)
  713. return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
  714. Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
  715. return InsertElementInst::Create(V, I->getOperand(1),
  716. Builder->getInt32(Index), "", I);
  717. }
  718. }
  719. llvm_unreachable("failed to reorder elements of vector instruction!");
  720. }
  721. static void RecognizeIdentityMask(const SmallVectorImpl<int> &Mask,
  722. bool &isLHSID, bool &isRHSID) {
  723. isLHSID = isRHSID = true;
  724. for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
  725. if (Mask[i] < 0) continue; // Ignore undef values.
  726. // Is this an identity shuffle of the LHS value?
  727. isLHSID &= (Mask[i] == (int)i);
  728. // Is this an identity shuffle of the RHS value?
  729. isRHSID &= (Mask[i]-e == i);
  730. }
  731. }
  732. // Returns true if the shuffle is extracting a contiguous range of values from
  733. // LHS, for example:
  734. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  735. // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
  736. // Shuffles to: |EE|FF|GG|HH|
  737. // +--+--+--+--+
  738. static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
  739. SmallVector<int, 16> &Mask) {
  740. unsigned LHSElems =
  741. cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
  742. unsigned MaskElems = Mask.size();
  743. unsigned BegIdx = Mask.front();
  744. unsigned EndIdx = Mask.back();
  745. if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
  746. return false;
  747. for (unsigned I = 0; I != MaskElems; ++I)
  748. if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
  749. return false;
  750. return true;
  751. }
  752. Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
  753. Value *LHS = SVI.getOperand(0);
  754. Value *RHS = SVI.getOperand(1);
  755. SmallVector<int, 16> Mask = SVI.getShuffleMask();
  756. Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
  757. bool MadeChange = false;
  758. // Undefined shuffle mask -> undefined value.
  759. if (isa<UndefValue>(SVI.getOperand(2)))
  760. return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
  761. unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
  762. APInt UndefElts(VWidth, 0);
  763. APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
  764. if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
  765. if (V != &SVI)
  766. return ReplaceInstUsesWith(SVI, V);
  767. LHS = SVI.getOperand(0);
  768. RHS = SVI.getOperand(1);
  769. MadeChange = true;
  770. }
  771. unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
  772. // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
  773. // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
  774. if (LHS == RHS || isa<UndefValue>(LHS)) {
  775. if (isa<UndefValue>(LHS) && LHS == RHS) {
  776. // shuffle(undef,undef,mask) -> undef.
  777. Value *Result = (VWidth == LHSWidth)
  778. ? LHS : UndefValue::get(SVI.getType());
  779. return ReplaceInstUsesWith(SVI, Result);
  780. }
  781. // Remap any references to RHS to use LHS.
  782. SmallVector<Constant*, 16> Elts;
  783. for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
  784. if (Mask[i] < 0) {
  785. Elts.push_back(UndefValue::get(Int32Ty));
  786. continue;
  787. }
  788. if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
  789. (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
  790. Mask[i] = -1; // Turn into undef.
  791. Elts.push_back(UndefValue::get(Int32Ty));
  792. } else {
  793. Mask[i] = Mask[i] % e; // Force to LHS.
  794. Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
  795. }
  796. }
  797. SVI.setOperand(0, SVI.getOperand(1));
  798. SVI.setOperand(1, UndefValue::get(RHS->getType()));
  799. SVI.setOperand(2, ConstantVector::get(Elts));
  800. LHS = SVI.getOperand(0);
  801. RHS = SVI.getOperand(1);
  802. MadeChange = true;
  803. }
  804. if (VWidth == LHSWidth) {
  805. // Analyze the shuffle, are the LHS or RHS and identity shuffles?
  806. bool isLHSID, isRHSID;
  807. RecognizeIdentityMask(Mask, isLHSID, isRHSID);
  808. // Eliminate identity shuffles.
  809. if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
  810. if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
  811. }
  812. if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
  813. Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
  814. return ReplaceInstUsesWith(SVI, V);
  815. }
  816. // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
  817. // a non-vector type. We can instead bitcast the original vector followed by
  818. // an extract of the desired element:
  819. //
  820. // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
  821. // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
  822. // %1 = bitcast <4 x i8> %sroa to i32
  823. // Becomes:
  824. // %bc = bitcast <16 x i8> %in to <4 x i32>
  825. // %ext = extractelement <4 x i32> %bc, i32 0
  826. //
  827. // If the shuffle is extracting a contiguous range of values from the input
  828. // vector then each use which is a bitcast of the extracted size can be
  829. // replaced. This will work if the vector types are compatible, and the begin
  830. // index is aligned to a value in the casted vector type. If the begin index
  831. // isn't aligned then we can shuffle the original vector (keeping the same
  832. // vector type) before extracting.
  833. //
  834. // This code will bail out if the target type is fundamentally incompatible
  835. // with vectors of the source type.
  836. //
  837. // Example of <16 x i8>, target type i32:
  838. // Index range [4,8): v-----------v Will work.
  839. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  840. // <16 x i8>: | | | | | | | | | | | | | | | | |
  841. // <4 x i32>: | | | | |
  842. // +-----------+-----------+-----------+-----------+
  843. // Index range [6,10): ^-----------^ Needs an extra shuffle.
  844. // Target type i40: ^--------------^ Won't work, bail.
  845. if (isShuffleExtractingFromLHS(SVI, Mask)) {
  846. Value *V = LHS;
  847. unsigned MaskElems = Mask.size();
  848. unsigned BegIdx = Mask.front();
  849. VectorType *SrcTy = cast<VectorType>(V->getType());
  850. unsigned VecBitWidth = SrcTy->getBitWidth();
  851. unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
  852. assert(SrcElemBitWidth && "vector elements must have a bitwidth");
  853. unsigned SrcNumElems = SrcTy->getNumElements();
  854. SmallVector<BitCastInst *, 8> BCs;
  855. DenseMap<Type *, Value *> NewBCs;
  856. for (User *U : SVI.users())
  857. if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
  858. if (!BC->use_empty())
  859. // Only visit bitcasts that weren't previously handled.
  860. BCs.push_back(BC);
  861. for (BitCastInst *BC : BCs) {
  862. Type *TgtTy = BC->getDestTy();
  863. unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
  864. if (!TgtElemBitWidth)
  865. continue;
  866. unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
  867. bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
  868. bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
  869. if (!VecBitWidthsEqual)
  870. continue;
  871. if (!VectorType::isValidElementType(TgtTy))
  872. continue;
  873. VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
  874. if (!BegIsAligned) {
  875. // Shuffle the input so [0,NumElements) contains the output, and
  876. // [NumElems,SrcNumElems) is undef.
  877. SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
  878. UndefValue::get(Int32Ty));
  879. for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
  880. ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
  881. V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
  882. ConstantVector::get(ShuffleMask),
  883. SVI.getName() + ".extract");
  884. BegIdx = 0;
  885. }
  886. unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
  887. assert(SrcElemsPerTgtElem);
  888. BegIdx /= SrcElemsPerTgtElem;
  889. bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
  890. auto *NewBC =
  891. BCAlreadyExists
  892. ? NewBCs[CastSrcTy]
  893. : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
  894. if (!BCAlreadyExists)
  895. NewBCs[CastSrcTy] = NewBC;
  896. auto *Ext = Builder->CreateExtractElement(
  897. NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
  898. // The shufflevector isn't being replaced: the bitcast that used it
  899. // is. InstCombine will visit the newly-created instructions.
  900. ReplaceInstUsesWith(*BC, Ext);
  901. MadeChange = true;
  902. }
  903. }
  904. // If the LHS is a shufflevector itself, see if we can combine it with this
  905. // one without producing an unusual shuffle.
  906. // Cases that might be simplified:
  907. // 1.
  908. // x1=shuffle(v1,v2,mask1)
  909. // x=shuffle(x1,undef,mask)
  910. // ==>
  911. // x=shuffle(v1,undef,newMask)
  912. // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
  913. // 2.
  914. // x1=shuffle(v1,undef,mask1)
  915. // x=shuffle(x1,x2,mask)
  916. // where v1.size() == mask1.size()
  917. // ==>
  918. // x=shuffle(v1,x2,newMask)
  919. // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
  920. // 3.
  921. // x2=shuffle(v2,undef,mask2)
  922. // x=shuffle(x1,x2,mask)
  923. // where v2.size() == mask2.size()
  924. // ==>
  925. // x=shuffle(x1,v2,newMask)
  926. // newMask[i] = (mask[i] < x1.size())
  927. // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
  928. // 4.
  929. // x1=shuffle(v1,undef,mask1)
  930. // x2=shuffle(v2,undef,mask2)
  931. // x=shuffle(x1,x2,mask)
  932. // where v1.size() == v2.size()
  933. // ==>
  934. // x=shuffle(v1,v2,newMask)
  935. // newMask[i] = (mask[i] < x1.size())
  936. // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
  937. //
  938. // Here we are really conservative:
  939. // we are absolutely afraid of producing a shuffle mask not in the input
  940. // program, because the code gen may not be smart enough to turn a merged
  941. // shuffle into two specific shuffles: it may produce worse code. As such,
  942. // we only merge two shuffles if the result is either a splat or one of the
  943. // input shuffle masks. In this case, merging the shuffles just removes
  944. // one instruction, which we know is safe. This is good for things like
  945. // turning: (splat(splat)) -> splat, or
  946. // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
  947. ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
  948. ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
  949. if (LHSShuffle)
  950. if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
  951. LHSShuffle = nullptr;
  952. if (RHSShuffle)
  953. if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
  954. RHSShuffle = nullptr;
  955. if (!LHSShuffle && !RHSShuffle)
  956. return MadeChange ? &SVI : nullptr;
  957. Value* LHSOp0 = nullptr;
  958. Value* LHSOp1 = nullptr;
  959. Value* RHSOp0 = nullptr;
  960. unsigned LHSOp0Width = 0;
  961. unsigned RHSOp0Width = 0;
  962. if (LHSShuffle) {
  963. LHSOp0 = LHSShuffle->getOperand(0);
  964. LHSOp1 = LHSShuffle->getOperand(1);
  965. LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
  966. }
  967. if (RHSShuffle) {
  968. RHSOp0 = RHSShuffle->getOperand(0);
  969. RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
  970. }
  971. Value* newLHS = LHS;
  972. Value* newRHS = RHS;
  973. if (LHSShuffle) {
  974. // case 1
  975. if (isa<UndefValue>(RHS)) {
  976. newLHS = LHSOp0;
  977. newRHS = LHSOp1;
  978. }
  979. // case 2 or 4
  980. else if (LHSOp0Width == LHSWidth) {
  981. newLHS = LHSOp0;
  982. }
  983. }
  984. // case 3 or 4
  985. if (RHSShuffle && RHSOp0Width == LHSWidth) {
  986. newRHS = RHSOp0;
  987. }
  988. // case 4
  989. if (LHSOp0 == RHSOp0) {
  990. newLHS = LHSOp0;
  991. newRHS = nullptr;
  992. }
  993. if (newLHS == LHS && newRHS == RHS)
  994. return MadeChange ? &SVI : nullptr;
  995. SmallVector<int, 16> LHSMask;
  996. SmallVector<int, 16> RHSMask;
  997. if (newLHS != LHS)
  998. LHSMask = LHSShuffle->getShuffleMask();
  999. if (RHSShuffle && newRHS != RHS)
  1000. RHSMask = RHSShuffle->getShuffleMask();
  1001. unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
  1002. SmallVector<int, 16> newMask;
  1003. bool isSplat = true;
  1004. int SplatElt = -1;
  1005. // Create a new mask for the new ShuffleVectorInst so that the new
  1006. // ShuffleVectorInst is equivalent to the original one.
  1007. for (unsigned i = 0; i < VWidth; ++i) {
  1008. int eltMask;
  1009. if (Mask[i] < 0) {
  1010. // This element is an undef value.
  1011. eltMask = -1;
  1012. } else if (Mask[i] < (int)LHSWidth) {
  1013. // This element is from left hand side vector operand.
  1014. //
  1015. // If LHS is going to be replaced (case 1, 2, or 4), calculate the
  1016. // new mask value for the element.
  1017. if (newLHS != LHS) {
  1018. eltMask = LHSMask[Mask[i]];
  1019. // If the value selected is an undef value, explicitly specify it
  1020. // with a -1 mask value.
  1021. if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
  1022. eltMask = -1;
  1023. } else
  1024. eltMask = Mask[i];
  1025. } else {
  1026. // This element is from right hand side vector operand
  1027. //
  1028. // If the value selected is an undef value, explicitly specify it
  1029. // with a -1 mask value. (case 1)
  1030. if (isa<UndefValue>(RHS))
  1031. eltMask = -1;
  1032. // If RHS is going to be replaced (case 3 or 4), calculate the
  1033. // new mask value for the element.
  1034. else if (newRHS != RHS) {
  1035. eltMask = RHSMask[Mask[i]-LHSWidth];
  1036. // If the value selected is an undef value, explicitly specify it
  1037. // with a -1 mask value.
  1038. if (eltMask >= (int)RHSOp0Width) {
  1039. assert(isa<UndefValue>(RHSShuffle->getOperand(1))
  1040. && "should have been check above");
  1041. eltMask = -1;
  1042. }
  1043. } else
  1044. eltMask = Mask[i]-LHSWidth;
  1045. // If LHS's width is changed, shift the mask value accordingly.
  1046. // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
  1047. // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
  1048. // If newRHS == newLHS, we want to remap any references from newRHS to
  1049. // newLHS so that we can properly identify splats that may occur due to
  1050. // obfuscation across the two vectors.
  1051. if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
  1052. eltMask += newLHSWidth;
  1053. }
  1054. // Check if this could still be a splat.
  1055. if (eltMask >= 0) {
  1056. if (SplatElt >= 0 && SplatElt != eltMask)
  1057. isSplat = false;
  1058. SplatElt = eltMask;
  1059. }
  1060. newMask.push_back(eltMask);
  1061. }
  1062. // If the result mask is equal to one of the original shuffle masks,
  1063. // or is a splat, do the replacement.
  1064. if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
  1065. SmallVector<Constant*, 16> Elts;
  1066. for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
  1067. if (newMask[i] < 0) {
  1068. Elts.push_back(UndefValue::get(Int32Ty));
  1069. } else {
  1070. Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
  1071. }
  1072. }
  1073. if (!newRHS)
  1074. newRHS = UndefValue::get(newLHS->getType());
  1075. return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
  1076. }
  1077. // If the result mask is an identity, replace uses of this instruction with
  1078. // corresponding argument.
  1079. bool isLHSID, isRHSID;
  1080. RecognizeIdentityMask(newMask, isLHSID, isRHSID);
  1081. if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
  1082. if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
  1083. return MadeChange ? &SVI : nullptr;
  1084. }