VectorCombine.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  1. //===------- VectorCombine.cpp - Optimize partial vector operations -------===//
  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 pass optimizes scalar/vector interactions using target cost models. The
  10. // transforms implemented here may not fit in traditional loop-based or SLP
  11. // vectorization passes.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Vectorize/VectorCombine.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/Analysis/AssumptionCache.h"
  17. #include "llvm/Analysis/BasicAliasAnalysis.h"
  18. #include "llvm/Analysis/GlobalsModRef.h"
  19. #include "llvm/Analysis/Loads.h"
  20. #include "llvm/Analysis/TargetTransformInfo.h"
  21. #include "llvm/Analysis/ValueTracking.h"
  22. #include "llvm/Analysis/VectorUtils.h"
  23. #include "llvm/IR/Dominators.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/IRBuilder.h"
  26. #include "llvm/IR/PatternMatch.h"
  27. #include "llvm/InitializePasses.h"
  28. #include "llvm/Pass.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Transforms/Utils/Local.h"
  31. #include "llvm/Transforms/Vectorize.h"
  32. #include <numeric>
  33. #define DEBUG_TYPE "vector-combine"
  34. #include "llvm/Transforms/Utils/InstructionWorklist.h"
  35. using namespace llvm;
  36. using namespace llvm::PatternMatch;
  37. STATISTIC(NumVecLoad, "Number of vector loads formed");
  38. STATISTIC(NumVecCmp, "Number of vector compares formed");
  39. STATISTIC(NumVecBO, "Number of vector binops formed");
  40. STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
  41. STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
  42. STATISTIC(NumScalarBO, "Number of scalar binops formed");
  43. STATISTIC(NumScalarCmp, "Number of scalar compares formed");
  44. static cl::opt<bool> DisableVectorCombine(
  45. "disable-vector-combine", cl::init(false), cl::Hidden,
  46. cl::desc("Disable all vector combine transforms"));
  47. static cl::opt<bool> DisableBinopExtractShuffle(
  48. "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
  49. cl::desc("Disable binop extract to shuffle transforms"));
  50. static cl::opt<unsigned> MaxInstrsToScan(
  51. "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
  52. cl::desc("Max number of instructions to scan for vector combining."));
  53. static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
  54. namespace {
  55. class VectorCombine {
  56. public:
  57. VectorCombine(Function &F, const TargetTransformInfo &TTI,
  58. const DominatorTree &DT, AAResults &AA, AssumptionCache &AC,
  59. bool TryEarlyFoldsOnly)
  60. : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC),
  61. TryEarlyFoldsOnly(TryEarlyFoldsOnly) {}
  62. bool run();
  63. private:
  64. Function &F;
  65. IRBuilder<> Builder;
  66. const TargetTransformInfo &TTI;
  67. const DominatorTree &DT;
  68. AAResults &AA;
  69. AssumptionCache &AC;
  70. /// If true, only perform beneficial early IR transforms. Do not introduce new
  71. /// vector operations.
  72. bool TryEarlyFoldsOnly;
  73. InstructionWorklist Worklist;
  74. // TODO: Direct calls from the top-level "run" loop use a plain "Instruction"
  75. // parameter. That should be updated to specific sub-classes because the
  76. // run loop was changed to dispatch on opcode.
  77. bool vectorizeLoadInsert(Instruction &I);
  78. bool widenSubvectorLoad(Instruction &I);
  79. ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
  80. ExtractElementInst *Ext1,
  81. unsigned PreferredExtractIndex) const;
  82. bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
  83. const Instruction &I,
  84. ExtractElementInst *&ConvertToShuffle,
  85. unsigned PreferredExtractIndex);
  86. void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
  87. Instruction &I);
  88. void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
  89. Instruction &I);
  90. bool foldExtractExtract(Instruction &I);
  91. bool foldInsExtFNeg(Instruction &I);
  92. bool foldBitcastShuf(Instruction &I);
  93. bool scalarizeBinopOrCmp(Instruction &I);
  94. bool foldExtractedCmps(Instruction &I);
  95. bool foldSingleElementStore(Instruction &I);
  96. bool scalarizeLoadExtract(Instruction &I);
  97. bool foldShuffleOfBinops(Instruction &I);
  98. bool foldShuffleFromReductions(Instruction &I);
  99. bool foldSelectShuffle(Instruction &I, bool FromReduction = false);
  100. void replaceValue(Value &Old, Value &New) {
  101. Old.replaceAllUsesWith(&New);
  102. if (auto *NewI = dyn_cast<Instruction>(&New)) {
  103. New.takeName(&Old);
  104. Worklist.pushUsersToWorkList(*NewI);
  105. Worklist.pushValue(NewI);
  106. }
  107. Worklist.pushValue(&Old);
  108. }
  109. void eraseInstruction(Instruction &I) {
  110. for (Value *Op : I.operands())
  111. Worklist.pushValue(Op);
  112. Worklist.remove(&I);
  113. I.eraseFromParent();
  114. }
  115. };
  116. } // namespace
  117. static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI) {
  118. // Do not widen load if atomic/volatile or under asan/hwasan/memtag/tsan.
  119. // The widened load may load data from dirty regions or create data races
  120. // non-existent in the source.
  121. if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
  122. Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
  123. mustSuppressSpeculation(*Load))
  124. return false;
  125. // We are potentially transforming byte-sized (8-bit) memory accesses, so make
  126. // sure we have all of our type-based constraints in place for this target.
  127. Type *ScalarTy = Load->getType()->getScalarType();
  128. uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
  129. unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
  130. if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
  131. ScalarSize % 8 != 0)
  132. return false;
  133. return true;
  134. }
  135. bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
  136. // Match insert into fixed vector of scalar value.
  137. // TODO: Handle non-zero insert index.
  138. Value *Scalar;
  139. if (!match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
  140. !Scalar->hasOneUse())
  141. return false;
  142. // Optionally match an extract from another vector.
  143. Value *X;
  144. bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
  145. if (!HasExtract)
  146. X = Scalar;
  147. auto *Load = dyn_cast<LoadInst>(X);
  148. if (!canWidenLoad(Load, TTI))
  149. return false;
  150. Type *ScalarTy = Scalar->getType();
  151. uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
  152. unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
  153. // Check safety of replacing the scalar load with a larger vector load.
  154. // We use minimal alignment (maximum flexibility) because we only care about
  155. // the dereferenceable region. When calculating cost and creating a new op,
  156. // we may use a larger value based on alignment attributes.
  157. const DataLayout &DL = I.getModule()->getDataLayout();
  158. Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
  159. assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
  160. unsigned MinVecNumElts = MinVectorSize / ScalarSize;
  161. auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
  162. unsigned OffsetEltIndex = 0;
  163. Align Alignment = Load->getAlign();
  164. if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &AC,
  165. &DT)) {
  166. // It is not safe to load directly from the pointer, but we can still peek
  167. // through gep offsets and check if it safe to load from a base address with
  168. // updated alignment. If it is, we can shuffle the element(s) into place
  169. // after loading.
  170. unsigned OffsetBitWidth = DL.getIndexTypeSizeInBits(SrcPtr->getType());
  171. APInt Offset(OffsetBitWidth, 0);
  172. SrcPtr = SrcPtr->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
  173. // We want to shuffle the result down from a high element of a vector, so
  174. // the offset must be positive.
  175. if (Offset.isNegative())
  176. return false;
  177. // The offset must be a multiple of the scalar element to shuffle cleanly
  178. // in the element's size.
  179. uint64_t ScalarSizeInBytes = ScalarSize / 8;
  180. if (Offset.urem(ScalarSizeInBytes) != 0)
  181. return false;
  182. // If we load MinVecNumElts, will our target element still be loaded?
  183. OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
  184. if (OffsetEltIndex >= MinVecNumElts)
  185. return false;
  186. if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &AC,
  187. &DT))
  188. return false;
  189. // Update alignment with offset value. Note that the offset could be negated
  190. // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
  191. // negation does not change the result of the alignment calculation.
  192. Alignment = commonAlignment(Alignment, Offset.getZExtValue());
  193. }
  194. // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
  195. // Use the greater of the alignment on the load or its source pointer.
  196. Alignment = std::max(SrcPtr->getPointerAlignment(DL), Alignment);
  197. Type *LoadTy = Load->getType();
  198. unsigned AS = Load->getPointerAddressSpace();
  199. InstructionCost OldCost =
  200. TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
  201. APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
  202. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  203. OldCost +=
  204. TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
  205. /* Insert */ true, HasExtract, CostKind);
  206. // New pattern: load VecPtr
  207. InstructionCost NewCost =
  208. TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
  209. // Optionally, we are shuffling the loaded vector element(s) into place.
  210. // For the mask set everything but element 0 to undef to prevent poison from
  211. // propagating from the extra loaded memory. This will also optionally
  212. // shrink/grow the vector from the loaded size to the output size.
  213. // We assume this operation has no cost in codegen if there was no offset.
  214. // Note that we could use freeze to avoid poison problems, but then we might
  215. // still need a shuffle to change the vector size.
  216. auto *Ty = cast<FixedVectorType>(I.getType());
  217. unsigned OutputNumElts = Ty->getNumElements();
  218. SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem);
  219. assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
  220. Mask[0] = OffsetEltIndex;
  221. if (OffsetEltIndex)
  222. NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask);
  223. // We can aggressively convert to the vector form because the backend can
  224. // invert this transform if it does not result in a performance win.
  225. if (OldCost < NewCost || !NewCost.isValid())
  226. return false;
  227. // It is safe and potentially profitable to load a vector directly:
  228. // inselt undef, load Scalar, 0 --> load VecPtr
  229. IRBuilder<> Builder(Load);
  230. Value *CastedPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
  231. SrcPtr, MinVecTy->getPointerTo(AS));
  232. Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
  233. VecLd = Builder.CreateShuffleVector(VecLd, Mask);
  234. replaceValue(I, *VecLd);
  235. ++NumVecLoad;
  236. return true;
  237. }
  238. /// If we are loading a vector and then inserting it into a larger vector with
  239. /// undefined elements, try to load the larger vector and eliminate the insert.
  240. /// This removes a shuffle in IR and may allow combining of other loaded values.
  241. bool VectorCombine::widenSubvectorLoad(Instruction &I) {
  242. // Match subvector insert of fixed vector.
  243. auto *Shuf = cast<ShuffleVectorInst>(&I);
  244. if (!Shuf->isIdentityWithPadding())
  245. return false;
  246. // Allow a non-canonical shuffle mask that is choosing elements from op1.
  247. unsigned NumOpElts =
  248. cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
  249. unsigned OpIndex = any_of(Shuf->getShuffleMask(), [&NumOpElts](int M) {
  250. return M >= (int)(NumOpElts);
  251. });
  252. auto *Load = dyn_cast<LoadInst>(Shuf->getOperand(OpIndex));
  253. if (!canWidenLoad(Load, TTI))
  254. return false;
  255. // We use minimal alignment (maximum flexibility) because we only care about
  256. // the dereferenceable region. When calculating cost and creating a new op,
  257. // we may use a larger value based on alignment attributes.
  258. auto *Ty = cast<FixedVectorType>(I.getType());
  259. const DataLayout &DL = I.getModule()->getDataLayout();
  260. Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
  261. assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
  262. Align Alignment = Load->getAlign();
  263. if (!isSafeToLoadUnconditionally(SrcPtr, Ty, Align(1), DL, Load, &AC, &DT))
  264. return false;
  265. Alignment = std::max(SrcPtr->getPointerAlignment(DL), Alignment);
  266. Type *LoadTy = Load->getType();
  267. unsigned AS = Load->getPointerAddressSpace();
  268. // Original pattern: insert_subvector (load PtrOp)
  269. // This conservatively assumes that the cost of a subvector insert into an
  270. // undef value is 0. We could add that cost if the cost model accurately
  271. // reflects the real cost of that operation.
  272. InstructionCost OldCost =
  273. TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
  274. // New pattern: load PtrOp
  275. InstructionCost NewCost =
  276. TTI.getMemoryOpCost(Instruction::Load, Ty, Alignment, AS);
  277. // We can aggressively convert to the vector form because the backend can
  278. // invert this transform if it does not result in a performance win.
  279. if (OldCost < NewCost || !NewCost.isValid())
  280. return false;
  281. IRBuilder<> Builder(Load);
  282. Value *CastedPtr =
  283. Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Ty->getPointerTo(AS));
  284. Value *VecLd = Builder.CreateAlignedLoad(Ty, CastedPtr, Alignment);
  285. replaceValue(I, *VecLd);
  286. ++NumVecLoad;
  287. return true;
  288. }
  289. /// Determine which, if any, of the inputs should be replaced by a shuffle
  290. /// followed by extract from a different index.
  291. ExtractElementInst *VectorCombine::getShuffleExtract(
  292. ExtractElementInst *Ext0, ExtractElementInst *Ext1,
  293. unsigned PreferredExtractIndex = InvalidIndex) const {
  294. auto *Index0C = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
  295. auto *Index1C = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
  296. assert(Index0C && Index1C && "Expected constant extract indexes");
  297. unsigned Index0 = Index0C->getZExtValue();
  298. unsigned Index1 = Index1C->getZExtValue();
  299. // If the extract indexes are identical, no shuffle is needed.
  300. if (Index0 == Index1)
  301. return nullptr;
  302. Type *VecTy = Ext0->getVectorOperand()->getType();
  303. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  304. assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
  305. InstructionCost Cost0 =
  306. TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
  307. InstructionCost Cost1 =
  308. TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
  309. // If both costs are invalid no shuffle is needed
  310. if (!Cost0.isValid() && !Cost1.isValid())
  311. return nullptr;
  312. // We are extracting from 2 different indexes, so one operand must be shuffled
  313. // before performing a vector operation and/or extract. The more expensive
  314. // extract will be replaced by a shuffle.
  315. if (Cost0 > Cost1)
  316. return Ext0;
  317. if (Cost1 > Cost0)
  318. return Ext1;
  319. // If the costs are equal and there is a preferred extract index, shuffle the
  320. // opposite operand.
  321. if (PreferredExtractIndex == Index0)
  322. return Ext1;
  323. if (PreferredExtractIndex == Index1)
  324. return Ext0;
  325. // Otherwise, replace the extract with the higher index.
  326. return Index0 > Index1 ? Ext0 : Ext1;
  327. }
  328. /// Compare the relative costs of 2 extracts followed by scalar operation vs.
  329. /// vector operation(s) followed by extract. Return true if the existing
  330. /// instructions are cheaper than a vector alternative. Otherwise, return false
  331. /// and if one of the extracts should be transformed to a shufflevector, set
  332. /// \p ConvertToShuffle to that extract instruction.
  333. bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
  334. ExtractElementInst *Ext1,
  335. const Instruction &I,
  336. ExtractElementInst *&ConvertToShuffle,
  337. unsigned PreferredExtractIndex) {
  338. auto *Ext0IndexC = dyn_cast<ConstantInt>(Ext0->getOperand(1));
  339. auto *Ext1IndexC = dyn_cast<ConstantInt>(Ext1->getOperand(1));
  340. assert(Ext0IndexC && Ext1IndexC && "Expected constant extract indexes");
  341. unsigned Opcode = I.getOpcode();
  342. Type *ScalarTy = Ext0->getType();
  343. auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
  344. InstructionCost ScalarOpCost, VectorOpCost;
  345. // Get cost estimates for scalar and vector versions of the operation.
  346. bool IsBinOp = Instruction::isBinaryOp(Opcode);
  347. if (IsBinOp) {
  348. ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
  349. VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
  350. } else {
  351. assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
  352. "Expected a compare");
  353. CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
  354. ScalarOpCost = TTI.getCmpSelInstrCost(
  355. Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
  356. VectorOpCost = TTI.getCmpSelInstrCost(
  357. Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
  358. }
  359. // Get cost estimates for the extract elements. These costs will factor into
  360. // both sequences.
  361. unsigned Ext0Index = Ext0IndexC->getZExtValue();
  362. unsigned Ext1Index = Ext1IndexC->getZExtValue();
  363. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  364. InstructionCost Extract0Cost =
  365. TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Ext0Index);
  366. InstructionCost Extract1Cost =
  367. TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Ext1Index);
  368. // A more expensive extract will always be replaced by a splat shuffle.
  369. // For example, if Ext0 is more expensive:
  370. // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
  371. // extelt (opcode (splat V0, Ext0), V1), Ext1
  372. // TODO: Evaluate whether that always results in lowest cost. Alternatively,
  373. // check the cost of creating a broadcast shuffle and shuffling both
  374. // operands to element 0.
  375. InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
  376. // Extra uses of the extracts mean that we include those costs in the
  377. // vector total because those instructions will not be eliminated.
  378. InstructionCost OldCost, NewCost;
  379. if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
  380. // Handle a special case. If the 2 extracts are identical, adjust the
  381. // formulas to account for that. The extra use charge allows for either the
  382. // CSE'd pattern or an unoptimized form with identical values:
  383. // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
  384. bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
  385. : !Ext0->hasOneUse() || !Ext1->hasOneUse();
  386. OldCost = CheapExtractCost + ScalarOpCost;
  387. NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
  388. } else {
  389. // Handle the general case. Each extract is actually a different value:
  390. // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
  391. OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
  392. NewCost = VectorOpCost + CheapExtractCost +
  393. !Ext0->hasOneUse() * Extract0Cost +
  394. !Ext1->hasOneUse() * Extract1Cost;
  395. }
  396. ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
  397. if (ConvertToShuffle) {
  398. if (IsBinOp && DisableBinopExtractShuffle)
  399. return true;
  400. // If we are extracting from 2 different indexes, then one operand must be
  401. // shuffled before performing the vector operation. The shuffle mask is
  402. // undefined except for 1 lane that is being translated to the remaining
  403. // extraction lane. Therefore, it is a splat shuffle. Ex:
  404. // ShufMask = { undef, undef, 0, undef }
  405. // TODO: The cost model has an option for a "broadcast" shuffle
  406. // (splat-from-element-0), but no option for a more general splat.
  407. NewCost +=
  408. TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
  409. }
  410. // Aggressively form a vector op if the cost is equal because the transform
  411. // may enable further optimization.
  412. // Codegen can reverse this transform (scalarize) if it was not profitable.
  413. return OldCost < NewCost;
  414. }
  415. /// Create a shuffle that translates (shifts) 1 element from the input vector
  416. /// to a new element location.
  417. static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
  418. unsigned NewIndex, IRBuilder<> &Builder) {
  419. // The shuffle mask is undefined except for 1 lane that is being translated
  420. // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
  421. // ShufMask = { 2, undef, undef, undef }
  422. auto *VecTy = cast<FixedVectorType>(Vec->getType());
  423. SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
  424. ShufMask[NewIndex] = OldIndex;
  425. return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
  426. }
  427. /// Given an extract element instruction with constant index operand, shuffle
  428. /// the source vector (shift the scalar element) to a NewIndex for extraction.
  429. /// Return null if the input can be constant folded, so that we are not creating
  430. /// unnecessary instructions.
  431. static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
  432. unsigned NewIndex,
  433. IRBuilder<> &Builder) {
  434. // Shufflevectors can only be created for fixed-width vectors.
  435. if (!isa<FixedVectorType>(ExtElt->getOperand(0)->getType()))
  436. return nullptr;
  437. // If the extract can be constant-folded, this code is unsimplified. Defer
  438. // to other passes to handle that.
  439. Value *X = ExtElt->getVectorOperand();
  440. Value *C = ExtElt->getIndexOperand();
  441. assert(isa<ConstantInt>(C) && "Expected a constant index operand");
  442. if (isa<Constant>(X))
  443. return nullptr;
  444. Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
  445. NewIndex, Builder);
  446. return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
  447. }
  448. /// Try to reduce extract element costs by converting scalar compares to vector
  449. /// compares followed by extract.
  450. /// cmp (ext0 V0, C), (ext1 V1, C)
  451. void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
  452. ExtractElementInst *Ext1, Instruction &I) {
  453. assert(isa<CmpInst>(&I) && "Expected a compare");
  454. assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
  455. cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
  456. "Expected matching constant extract indexes");
  457. // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
  458. ++NumVecCmp;
  459. CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
  460. Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
  461. Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
  462. Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
  463. replaceValue(I, *NewExt);
  464. }
  465. /// Try to reduce extract element costs by converting scalar binops to vector
  466. /// binops followed by extract.
  467. /// bo (ext0 V0, C), (ext1 V1, C)
  468. void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
  469. ExtractElementInst *Ext1, Instruction &I) {
  470. assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
  471. assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
  472. cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
  473. "Expected matching constant extract indexes");
  474. // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
  475. ++NumVecBO;
  476. Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
  477. Value *VecBO =
  478. Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
  479. // All IR flags are safe to back-propagate because any potential poison
  480. // created in unused vector elements is discarded by the extract.
  481. if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
  482. VecBOInst->copyIRFlags(&I);
  483. Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
  484. replaceValue(I, *NewExt);
  485. }
  486. /// Match an instruction with extracted vector operands.
  487. bool VectorCombine::foldExtractExtract(Instruction &I) {
  488. // It is not safe to transform things like div, urem, etc. because we may
  489. // create undefined behavior when executing those on unknown vector elements.
  490. if (!isSafeToSpeculativelyExecute(&I))
  491. return false;
  492. Instruction *I0, *I1;
  493. CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
  494. if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
  495. !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
  496. return false;
  497. Value *V0, *V1;
  498. uint64_t C0, C1;
  499. if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
  500. !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
  501. V0->getType() != V1->getType())
  502. return false;
  503. // If the scalar value 'I' is going to be re-inserted into a vector, then try
  504. // to create an extract to that same element. The extract/insert can be
  505. // reduced to a "select shuffle".
  506. // TODO: If we add a larger pattern match that starts from an insert, this
  507. // probably becomes unnecessary.
  508. auto *Ext0 = cast<ExtractElementInst>(I0);
  509. auto *Ext1 = cast<ExtractElementInst>(I1);
  510. uint64_t InsertIndex = InvalidIndex;
  511. if (I.hasOneUse())
  512. match(I.user_back(),
  513. m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
  514. ExtractElementInst *ExtractToChange;
  515. if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
  516. return false;
  517. if (ExtractToChange) {
  518. unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
  519. ExtractElementInst *NewExtract =
  520. translateExtract(ExtractToChange, CheapExtractIdx, Builder);
  521. if (!NewExtract)
  522. return false;
  523. if (ExtractToChange == Ext0)
  524. Ext0 = NewExtract;
  525. else
  526. Ext1 = NewExtract;
  527. }
  528. if (Pred != CmpInst::BAD_ICMP_PREDICATE)
  529. foldExtExtCmp(Ext0, Ext1, I);
  530. else
  531. foldExtExtBinop(Ext0, Ext1, I);
  532. Worklist.push(Ext0);
  533. Worklist.push(Ext1);
  534. return true;
  535. }
  536. /// Try to replace an extract + scalar fneg + insert with a vector fneg +
  537. /// shuffle.
  538. bool VectorCombine::foldInsExtFNeg(Instruction &I) {
  539. // Match an insert (op (extract)) pattern.
  540. Value *DestVec;
  541. uint64_t Index;
  542. Instruction *FNeg;
  543. if (!match(&I, m_InsertElt(m_Value(DestVec), m_OneUse(m_Instruction(FNeg)),
  544. m_ConstantInt(Index))))
  545. return false;
  546. // Note: This handles the canonical fneg instruction and "fsub -0.0, X".
  547. Value *SrcVec;
  548. Instruction *Extract;
  549. if (!match(FNeg, m_FNeg(m_CombineAnd(
  550. m_Instruction(Extract),
  551. m_ExtractElt(m_Value(SrcVec), m_SpecificInt(Index))))))
  552. return false;
  553. // TODO: We could handle this with a length-changing shuffle.
  554. auto *VecTy = cast<FixedVectorType>(I.getType());
  555. if (SrcVec->getType() != VecTy)
  556. return false;
  557. // Ignore bogus insert/extract index.
  558. unsigned NumElts = VecTy->getNumElements();
  559. if (Index >= NumElts)
  560. return false;
  561. // We are inserting the negated element into the same lane that we extracted
  562. // from. This is equivalent to a select-shuffle that chooses all but the
  563. // negated element from the destination vector.
  564. SmallVector<int> Mask(NumElts);
  565. std::iota(Mask.begin(), Mask.end(), 0);
  566. Mask[Index] = Index + NumElts;
  567. Type *ScalarTy = VecTy->getScalarType();
  568. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  569. InstructionCost OldCost =
  570. TTI.getArithmeticInstrCost(Instruction::FNeg, ScalarTy) +
  571. TTI.getVectorInstrCost(I, VecTy, CostKind, Index);
  572. // If the extract has one use, it will be eliminated, so count it in the
  573. // original cost. If it has more than one use, ignore the cost because it will
  574. // be the same before/after.
  575. if (Extract->hasOneUse())
  576. OldCost += TTI.getVectorInstrCost(*Extract, VecTy, CostKind, Index);
  577. InstructionCost NewCost =
  578. TTI.getArithmeticInstrCost(Instruction::FNeg, VecTy) +
  579. TTI.getShuffleCost(TargetTransformInfo::SK_Select, VecTy, Mask);
  580. if (NewCost > OldCost)
  581. return false;
  582. // insertelt DestVec, (fneg (extractelt SrcVec, Index)), Index -->
  583. // shuffle DestVec, (fneg SrcVec), Mask
  584. Value *VecFNeg = Builder.CreateFNegFMF(SrcVec, FNeg);
  585. Value *Shuf = Builder.CreateShuffleVector(DestVec, VecFNeg, Mask);
  586. replaceValue(I, *Shuf);
  587. return true;
  588. }
  589. /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
  590. /// destination type followed by shuffle. This can enable further transforms by
  591. /// moving bitcasts or shuffles together.
  592. bool VectorCombine::foldBitcastShuf(Instruction &I) {
  593. Value *V;
  594. ArrayRef<int> Mask;
  595. if (!match(&I, m_BitCast(
  596. m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
  597. return false;
  598. // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
  599. // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
  600. // mask for scalable type is a splat or not.
  601. // 2) Disallow non-vector casts and length-changing shuffles.
  602. // TODO: We could allow any shuffle.
  603. auto *SrcTy = dyn_cast<FixedVectorType>(V->getType());
  604. if (!SrcTy || I.getOperand(0)->getType() != SrcTy)
  605. return false;
  606. auto *DestTy = cast<FixedVectorType>(I.getType());
  607. unsigned DestNumElts = DestTy->getNumElements();
  608. unsigned SrcNumElts = SrcTy->getNumElements();
  609. SmallVector<int, 16> NewMask;
  610. if (SrcNumElts <= DestNumElts) {
  611. // The bitcast is from wide to narrow/equal elements. The shuffle mask can
  612. // always be expanded to the equivalent form choosing narrower elements.
  613. assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
  614. unsigned ScaleFactor = DestNumElts / SrcNumElts;
  615. narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
  616. } else {
  617. // The bitcast is from narrow elements to wide elements. The shuffle mask
  618. // must choose consecutive elements to allow casting first.
  619. assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
  620. unsigned ScaleFactor = SrcNumElts / DestNumElts;
  621. if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
  622. return false;
  623. }
  624. // The new shuffle must not cost more than the old shuffle. The bitcast is
  625. // moved ahead of the shuffle, so assume that it has the same cost as before.
  626. InstructionCost DestCost = TTI.getShuffleCost(
  627. TargetTransformInfo::SK_PermuteSingleSrc, DestTy, NewMask);
  628. InstructionCost SrcCost =
  629. TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy, Mask);
  630. if (DestCost > SrcCost || !DestCost.isValid())
  631. return false;
  632. // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
  633. ++NumShufOfBitcast;
  634. Value *CastV = Builder.CreateBitCast(V, DestTy);
  635. Value *Shuf = Builder.CreateShuffleVector(CastV, NewMask);
  636. replaceValue(I, *Shuf);
  637. return true;
  638. }
  639. /// Match a vector binop or compare instruction with at least one inserted
  640. /// scalar operand and convert to scalar binop/cmp followed by insertelement.
  641. bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
  642. CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
  643. Value *Ins0, *Ins1;
  644. if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
  645. !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
  646. return false;
  647. // Do not convert the vector condition of a vector select into a scalar
  648. // condition. That may cause problems for codegen because of differences in
  649. // boolean formats and register-file transfers.
  650. // TODO: Can we account for that in the cost model?
  651. bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
  652. if (IsCmp)
  653. for (User *U : I.users())
  654. if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
  655. return false;
  656. // Match against one or both scalar values being inserted into constant
  657. // vectors:
  658. // vec_op VecC0, (inselt VecC1, V1, Index)
  659. // vec_op (inselt VecC0, V0, Index), VecC1
  660. // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
  661. // TODO: Deal with mismatched index constants and variable indexes?
  662. Constant *VecC0 = nullptr, *VecC1 = nullptr;
  663. Value *V0 = nullptr, *V1 = nullptr;
  664. uint64_t Index0 = 0, Index1 = 0;
  665. if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
  666. m_ConstantInt(Index0))) &&
  667. !match(Ins0, m_Constant(VecC0)))
  668. return false;
  669. if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
  670. m_ConstantInt(Index1))) &&
  671. !match(Ins1, m_Constant(VecC1)))
  672. return false;
  673. bool IsConst0 = !V0;
  674. bool IsConst1 = !V1;
  675. if (IsConst0 && IsConst1)
  676. return false;
  677. if (!IsConst0 && !IsConst1 && Index0 != Index1)
  678. return false;
  679. // Bail for single insertion if it is a load.
  680. // TODO: Handle this once getVectorInstrCost can cost for load/stores.
  681. auto *I0 = dyn_cast_or_null<Instruction>(V0);
  682. auto *I1 = dyn_cast_or_null<Instruction>(V1);
  683. if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
  684. (IsConst1 && I0 && I0->mayReadFromMemory()))
  685. return false;
  686. uint64_t Index = IsConst0 ? Index1 : Index0;
  687. Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
  688. Type *VecTy = I.getType();
  689. assert(VecTy->isVectorTy() &&
  690. (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
  691. (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
  692. ScalarTy->isPointerTy()) &&
  693. "Unexpected types for insert element into binop or cmp");
  694. unsigned Opcode = I.getOpcode();
  695. InstructionCost ScalarOpCost, VectorOpCost;
  696. if (IsCmp) {
  697. CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
  698. ScalarOpCost = TTI.getCmpSelInstrCost(
  699. Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
  700. VectorOpCost = TTI.getCmpSelInstrCost(
  701. Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
  702. } else {
  703. ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
  704. VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
  705. }
  706. // Get cost estimate for the insert element. This cost will factor into
  707. // both sequences.
  708. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  709. InstructionCost InsertCost = TTI.getVectorInstrCost(
  710. Instruction::InsertElement, VecTy, CostKind, Index);
  711. InstructionCost OldCost =
  712. (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
  713. InstructionCost NewCost = ScalarOpCost + InsertCost +
  714. (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
  715. (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
  716. // We want to scalarize unless the vector variant actually has lower cost.
  717. if (OldCost < NewCost || !NewCost.isValid())
  718. return false;
  719. // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
  720. // inselt NewVecC, (scalar_op V0, V1), Index
  721. if (IsCmp)
  722. ++NumScalarCmp;
  723. else
  724. ++NumScalarBO;
  725. // For constant cases, extract the scalar element, this should constant fold.
  726. if (IsConst0)
  727. V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
  728. if (IsConst1)
  729. V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
  730. Value *Scalar =
  731. IsCmp ? Builder.CreateCmp(Pred, V0, V1)
  732. : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
  733. Scalar->setName(I.getName() + ".scalar");
  734. // All IR flags are safe to back-propagate. There is no potential for extra
  735. // poison to be created by the scalar instruction.
  736. if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
  737. ScalarInst->copyIRFlags(&I);
  738. // Fold the vector constants in the original vectors into a new base vector.
  739. Value *NewVecC =
  740. IsCmp ? Builder.CreateCmp(Pred, VecC0, VecC1)
  741. : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, VecC0, VecC1);
  742. Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
  743. replaceValue(I, *Insert);
  744. return true;
  745. }
  746. /// Try to combine a scalar binop + 2 scalar compares of extracted elements of
  747. /// a vector into vector operations followed by extract. Note: The SLP pass
  748. /// may miss this pattern because of implementation problems.
  749. bool VectorCombine::foldExtractedCmps(Instruction &I) {
  750. // We are looking for a scalar binop of booleans.
  751. // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
  752. if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
  753. return false;
  754. // The compare predicates should match, and each compare should have a
  755. // constant operand.
  756. // TODO: Relax the one-use constraints.
  757. Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
  758. Instruction *I0, *I1;
  759. Constant *C0, *C1;
  760. CmpInst::Predicate P0, P1;
  761. if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
  762. !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
  763. P0 != P1)
  764. return false;
  765. // The compare operands must be extracts of the same vector with constant
  766. // extract indexes.
  767. // TODO: Relax the one-use constraints.
  768. Value *X;
  769. uint64_t Index0, Index1;
  770. if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
  771. !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
  772. return false;
  773. auto *Ext0 = cast<ExtractElementInst>(I0);
  774. auto *Ext1 = cast<ExtractElementInst>(I1);
  775. ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
  776. if (!ConvertToShuf)
  777. return false;
  778. // The original scalar pattern is:
  779. // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
  780. CmpInst::Predicate Pred = P0;
  781. unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
  782. : Instruction::ICmp;
  783. auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
  784. if (!VecTy)
  785. return false;
  786. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  787. InstructionCost OldCost =
  788. TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
  789. OldCost += TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
  790. OldCost +=
  791. TTI.getCmpSelInstrCost(CmpOpcode, I0->getType(),
  792. CmpInst::makeCmpResultType(I0->getType()), Pred) *
  793. 2;
  794. OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
  795. // The proposed vector pattern is:
  796. // vcmp = cmp Pred X, VecC
  797. // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
  798. int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
  799. int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
  800. auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
  801. InstructionCost NewCost = TTI.getCmpSelInstrCost(
  802. CmpOpcode, X->getType(), CmpInst::makeCmpResultType(X->getType()), Pred);
  803. SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
  804. ShufMask[CheapIndex] = ExpensiveIndex;
  805. NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy,
  806. ShufMask);
  807. NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
  808. NewCost += TTI.getVectorInstrCost(*Ext0, CmpTy, CostKind, CheapIndex);
  809. // Aggressively form vector ops if the cost is equal because the transform
  810. // may enable further optimization.
  811. // Codegen can reverse this transform (scalarize) if it was not profitable.
  812. if (OldCost < NewCost || !NewCost.isValid())
  813. return false;
  814. // Create a vector constant from the 2 scalar constants.
  815. SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
  816. UndefValue::get(VecTy->getElementType()));
  817. CmpC[Index0] = C0;
  818. CmpC[Index1] = C1;
  819. Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
  820. Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
  821. Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
  822. VCmp, Shuf);
  823. Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
  824. replaceValue(I, *NewExt);
  825. ++NumVecCmpBO;
  826. return true;
  827. }
  828. // Check if memory loc modified between two instrs in the same BB
  829. static bool isMemModifiedBetween(BasicBlock::iterator Begin,
  830. BasicBlock::iterator End,
  831. const MemoryLocation &Loc, AAResults &AA) {
  832. unsigned NumScanned = 0;
  833. return std::any_of(Begin, End, [&](const Instruction &Instr) {
  834. return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
  835. ++NumScanned > MaxInstrsToScan;
  836. });
  837. }
  838. namespace {
  839. /// Helper class to indicate whether a vector index can be safely scalarized and
  840. /// if a freeze needs to be inserted.
  841. class ScalarizationResult {
  842. enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
  843. StatusTy Status;
  844. Value *ToFreeze;
  845. ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
  846. : Status(Status), ToFreeze(ToFreeze) {}
  847. public:
  848. ScalarizationResult(const ScalarizationResult &Other) = default;
  849. ~ScalarizationResult() {
  850. assert(!ToFreeze && "freeze() not called with ToFreeze being set");
  851. }
  852. static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
  853. static ScalarizationResult safe() { return {StatusTy::Safe}; }
  854. static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
  855. return {StatusTy::SafeWithFreeze, ToFreeze};
  856. }
  857. /// Returns true if the index can be scalarize without requiring a freeze.
  858. bool isSafe() const { return Status == StatusTy::Safe; }
  859. /// Returns true if the index cannot be scalarized.
  860. bool isUnsafe() const { return Status == StatusTy::Unsafe; }
  861. /// Returns true if the index can be scalarize, but requires inserting a
  862. /// freeze.
  863. bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
  864. /// Reset the state of Unsafe and clear ToFreze if set.
  865. void discard() {
  866. ToFreeze = nullptr;
  867. Status = StatusTy::Unsafe;
  868. }
  869. /// Freeze the ToFreeze and update the use in \p User to use it.
  870. void freeze(IRBuilder<> &Builder, Instruction &UserI) {
  871. assert(isSafeWithFreeze() &&
  872. "should only be used when freezing is required");
  873. assert(is_contained(ToFreeze->users(), &UserI) &&
  874. "UserI must be a user of ToFreeze");
  875. IRBuilder<>::InsertPointGuard Guard(Builder);
  876. Builder.SetInsertPoint(cast<Instruction>(&UserI));
  877. Value *Frozen =
  878. Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
  879. for (Use &U : make_early_inc_range((UserI.operands())))
  880. if (U.get() == ToFreeze)
  881. U.set(Frozen);
  882. ToFreeze = nullptr;
  883. }
  884. };
  885. } // namespace
  886. /// Check if it is legal to scalarize a memory access to \p VecTy at index \p
  887. /// Idx. \p Idx must access a valid vector element.
  888. static ScalarizationResult canScalarizeAccess(FixedVectorType *VecTy,
  889. Value *Idx, Instruction *CtxI,
  890. AssumptionCache &AC,
  891. const DominatorTree &DT) {
  892. if (auto *C = dyn_cast<ConstantInt>(Idx)) {
  893. if (C->getValue().ult(VecTy->getNumElements()))
  894. return ScalarizationResult::safe();
  895. return ScalarizationResult::unsafe();
  896. }
  897. unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
  898. APInt Zero(IntWidth, 0);
  899. APInt MaxElts(IntWidth, VecTy->getNumElements());
  900. ConstantRange ValidIndices(Zero, MaxElts);
  901. ConstantRange IdxRange(IntWidth, true);
  902. if (isGuaranteedNotToBePoison(Idx, &AC)) {
  903. if (ValidIndices.contains(computeConstantRange(Idx, /* ForSigned */ false,
  904. true, &AC, CtxI, &DT)))
  905. return ScalarizationResult::safe();
  906. return ScalarizationResult::unsafe();
  907. }
  908. // If the index may be poison, check if we can insert a freeze before the
  909. // range of the index is restricted.
  910. Value *IdxBase;
  911. ConstantInt *CI;
  912. if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
  913. IdxRange = IdxRange.binaryAnd(CI->getValue());
  914. } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
  915. IdxRange = IdxRange.urem(CI->getValue());
  916. }
  917. if (ValidIndices.contains(IdxRange))
  918. return ScalarizationResult::safeWithFreeze(IdxBase);
  919. return ScalarizationResult::unsafe();
  920. }
  921. /// The memory operation on a vector of \p ScalarType had alignment of
  922. /// \p VectorAlignment. Compute the maximal, but conservatively correct,
  923. /// alignment that will be valid for the memory operation on a single scalar
  924. /// element of the same type with index \p Idx.
  925. static Align computeAlignmentAfterScalarization(Align VectorAlignment,
  926. Type *ScalarType, Value *Idx,
  927. const DataLayout &DL) {
  928. if (auto *C = dyn_cast<ConstantInt>(Idx))
  929. return commonAlignment(VectorAlignment,
  930. C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
  931. return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
  932. }
  933. // Combine patterns like:
  934. // %0 = load <4 x i32>, <4 x i32>* %a
  935. // %1 = insertelement <4 x i32> %0, i32 %b, i32 1
  936. // store <4 x i32> %1, <4 x i32>* %a
  937. // to:
  938. // %0 = bitcast <4 x i32>* %a to i32*
  939. // %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1
  940. // store i32 %b, i32* %1
  941. bool VectorCombine::foldSingleElementStore(Instruction &I) {
  942. auto *SI = cast<StoreInst>(&I);
  943. if (!SI->isSimple() ||
  944. !isa<FixedVectorType>(SI->getValueOperand()->getType()))
  945. return false;
  946. // TODO: Combine more complicated patterns (multiple insert) by referencing
  947. // TargetTransformInfo.
  948. Instruction *Source;
  949. Value *NewElement;
  950. Value *Idx;
  951. if (!match(SI->getValueOperand(),
  952. m_InsertElt(m_Instruction(Source), m_Value(NewElement),
  953. m_Value(Idx))))
  954. return false;
  955. if (auto *Load = dyn_cast<LoadInst>(Source)) {
  956. auto VecTy = cast<FixedVectorType>(SI->getValueOperand()->getType());
  957. const DataLayout &DL = I.getModule()->getDataLayout();
  958. Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
  959. // Don't optimize for atomic/volatile load or store. Ensure memory is not
  960. // modified between, vector type matches store size, and index is inbounds.
  961. if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
  962. !DL.typeSizeEqualsStoreSize(Load->getType()) ||
  963. SrcAddr != SI->getPointerOperand()->stripPointerCasts())
  964. return false;
  965. auto ScalarizableIdx = canScalarizeAccess(VecTy, Idx, Load, AC, DT);
  966. if (ScalarizableIdx.isUnsafe() ||
  967. isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
  968. MemoryLocation::get(SI), AA))
  969. return false;
  970. if (ScalarizableIdx.isSafeWithFreeze())
  971. ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
  972. Value *GEP = Builder.CreateInBoundsGEP(
  973. SI->getValueOperand()->getType(), SI->getPointerOperand(),
  974. {ConstantInt::get(Idx->getType(), 0), Idx});
  975. StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
  976. NSI->copyMetadata(*SI);
  977. Align ScalarOpAlignment = computeAlignmentAfterScalarization(
  978. std::max(SI->getAlign(), Load->getAlign()), NewElement->getType(), Idx,
  979. DL);
  980. NSI->setAlignment(ScalarOpAlignment);
  981. replaceValue(I, *NSI);
  982. eraseInstruction(I);
  983. return true;
  984. }
  985. return false;
  986. }
  987. /// Try to scalarize vector loads feeding extractelement instructions.
  988. bool VectorCombine::scalarizeLoadExtract(Instruction &I) {
  989. Value *Ptr;
  990. if (!match(&I, m_Load(m_Value(Ptr))))
  991. return false;
  992. auto *FixedVT = cast<FixedVectorType>(I.getType());
  993. auto *LI = cast<LoadInst>(&I);
  994. const DataLayout &DL = I.getModule()->getDataLayout();
  995. if (LI->isVolatile() || !DL.typeSizeEqualsStoreSize(FixedVT))
  996. return false;
  997. InstructionCost OriginalCost =
  998. TTI.getMemoryOpCost(Instruction::Load, FixedVT, LI->getAlign(),
  999. LI->getPointerAddressSpace());
  1000. InstructionCost ScalarizedCost = 0;
  1001. Instruction *LastCheckedInst = LI;
  1002. unsigned NumInstChecked = 0;
  1003. // Check if all users of the load are extracts with no memory modifications
  1004. // between the load and the extract. Compute the cost of both the original
  1005. // code and the scalarized version.
  1006. for (User *U : LI->users()) {
  1007. auto *UI = dyn_cast<ExtractElementInst>(U);
  1008. if (!UI || UI->getParent() != LI->getParent())
  1009. return false;
  1010. if (!isGuaranteedNotToBePoison(UI->getOperand(1), &AC, LI, &DT))
  1011. return false;
  1012. // Check if any instruction between the load and the extract may modify
  1013. // memory.
  1014. if (LastCheckedInst->comesBefore(UI)) {
  1015. for (Instruction &I :
  1016. make_range(std::next(LI->getIterator()), UI->getIterator())) {
  1017. // Bail out if we reached the check limit or the instruction may write
  1018. // to memory.
  1019. if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory())
  1020. return false;
  1021. NumInstChecked++;
  1022. }
  1023. LastCheckedInst = UI;
  1024. }
  1025. auto ScalarIdx = canScalarizeAccess(FixedVT, UI->getOperand(1), &I, AC, DT);
  1026. if (!ScalarIdx.isSafe()) {
  1027. // TODO: Freeze index if it is safe to do so.
  1028. ScalarIdx.discard();
  1029. return false;
  1030. }
  1031. auto *Index = dyn_cast<ConstantInt>(UI->getOperand(1));
  1032. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  1033. OriginalCost +=
  1034. TTI.getVectorInstrCost(Instruction::ExtractElement, FixedVT, CostKind,
  1035. Index ? Index->getZExtValue() : -1);
  1036. ScalarizedCost +=
  1037. TTI.getMemoryOpCost(Instruction::Load, FixedVT->getElementType(),
  1038. Align(1), LI->getPointerAddressSpace());
  1039. ScalarizedCost += TTI.getAddressComputationCost(FixedVT->getElementType());
  1040. }
  1041. if (ScalarizedCost >= OriginalCost)
  1042. return false;
  1043. // Replace extracts with narrow scalar loads.
  1044. for (User *U : LI->users()) {
  1045. auto *EI = cast<ExtractElementInst>(U);
  1046. Builder.SetInsertPoint(EI);
  1047. Value *Idx = EI->getOperand(1);
  1048. Value *GEP =
  1049. Builder.CreateInBoundsGEP(FixedVT, Ptr, {Builder.getInt32(0), Idx});
  1050. auto *NewLoad = cast<LoadInst>(Builder.CreateLoad(
  1051. FixedVT->getElementType(), GEP, EI->getName() + ".scalar"));
  1052. Align ScalarOpAlignment = computeAlignmentAfterScalarization(
  1053. LI->getAlign(), FixedVT->getElementType(), Idx, DL);
  1054. NewLoad->setAlignment(ScalarOpAlignment);
  1055. replaceValue(*EI, *NewLoad);
  1056. }
  1057. return true;
  1058. }
  1059. /// Try to convert "shuffle (binop), (binop)" with a shared binop operand into
  1060. /// "binop (shuffle), (shuffle)".
  1061. bool VectorCombine::foldShuffleOfBinops(Instruction &I) {
  1062. auto *VecTy = cast<FixedVectorType>(I.getType());
  1063. BinaryOperator *B0, *B1;
  1064. ArrayRef<int> Mask;
  1065. if (!match(&I, m_Shuffle(m_OneUse(m_BinOp(B0)), m_OneUse(m_BinOp(B1)),
  1066. m_Mask(Mask))) ||
  1067. B0->getOpcode() != B1->getOpcode() || B0->getType() != VecTy)
  1068. return false;
  1069. // Try to replace a binop with a shuffle if the shuffle is not costly.
  1070. // The new shuffle will choose from a single, common operand, so it may be
  1071. // cheaper than the existing two-operand shuffle.
  1072. SmallVector<int> UnaryMask = createUnaryMask(Mask, Mask.size());
  1073. Instruction::BinaryOps Opcode = B0->getOpcode();
  1074. InstructionCost BinopCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
  1075. InstructionCost ShufCost = TTI.getShuffleCost(
  1076. TargetTransformInfo::SK_PermuteSingleSrc, VecTy, UnaryMask);
  1077. if (ShufCost > BinopCost)
  1078. return false;
  1079. // If we have something like "add X, Y" and "add Z, X", swap ops to match.
  1080. Value *X = B0->getOperand(0), *Y = B0->getOperand(1);
  1081. Value *Z = B1->getOperand(0), *W = B1->getOperand(1);
  1082. if (BinaryOperator::isCommutative(Opcode) && X != Z && Y != W)
  1083. std::swap(X, Y);
  1084. Value *Shuf0, *Shuf1;
  1085. if (X == Z) {
  1086. // shuf (bo X, Y), (bo X, W) --> bo (shuf X), (shuf Y, W)
  1087. Shuf0 = Builder.CreateShuffleVector(X, UnaryMask);
  1088. Shuf1 = Builder.CreateShuffleVector(Y, W, Mask);
  1089. } else if (Y == W) {
  1090. // shuf (bo X, Y), (bo Z, Y) --> bo (shuf X, Z), (shuf Y)
  1091. Shuf0 = Builder.CreateShuffleVector(X, Z, Mask);
  1092. Shuf1 = Builder.CreateShuffleVector(Y, UnaryMask);
  1093. } else {
  1094. return false;
  1095. }
  1096. Value *NewBO = Builder.CreateBinOp(Opcode, Shuf0, Shuf1);
  1097. // Intersect flags from the old binops.
  1098. if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
  1099. NewInst->copyIRFlags(B0);
  1100. NewInst->andIRFlags(B1);
  1101. }
  1102. replaceValue(I, *NewBO);
  1103. return true;
  1104. }
  1105. /// Given a commutative reduction, the order of the input lanes does not alter
  1106. /// the results. We can use this to remove certain shuffles feeding the
  1107. /// reduction, removing the need to shuffle at all.
  1108. bool VectorCombine::foldShuffleFromReductions(Instruction &I) {
  1109. auto *II = dyn_cast<IntrinsicInst>(&I);
  1110. if (!II)
  1111. return false;
  1112. switch (II->getIntrinsicID()) {
  1113. case Intrinsic::vector_reduce_add:
  1114. case Intrinsic::vector_reduce_mul:
  1115. case Intrinsic::vector_reduce_and:
  1116. case Intrinsic::vector_reduce_or:
  1117. case Intrinsic::vector_reduce_xor:
  1118. case Intrinsic::vector_reduce_smin:
  1119. case Intrinsic::vector_reduce_smax:
  1120. case Intrinsic::vector_reduce_umin:
  1121. case Intrinsic::vector_reduce_umax:
  1122. break;
  1123. default:
  1124. return false;
  1125. }
  1126. // Find all the inputs when looking through operations that do not alter the
  1127. // lane order (binops, for example). Currently we look for a single shuffle,
  1128. // and can ignore splat values.
  1129. std::queue<Value *> Worklist;
  1130. SmallPtrSet<Value *, 4> Visited;
  1131. ShuffleVectorInst *Shuffle = nullptr;
  1132. if (auto *Op = dyn_cast<Instruction>(I.getOperand(0)))
  1133. Worklist.push(Op);
  1134. while (!Worklist.empty()) {
  1135. Value *CV = Worklist.front();
  1136. Worklist.pop();
  1137. if (Visited.contains(CV))
  1138. continue;
  1139. // Splats don't change the order, so can be safely ignored.
  1140. if (isSplatValue(CV))
  1141. continue;
  1142. Visited.insert(CV);
  1143. if (auto *CI = dyn_cast<Instruction>(CV)) {
  1144. if (CI->isBinaryOp()) {
  1145. for (auto *Op : CI->operand_values())
  1146. Worklist.push(Op);
  1147. continue;
  1148. } else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) {
  1149. if (Shuffle && Shuffle != SV)
  1150. return false;
  1151. Shuffle = SV;
  1152. continue;
  1153. }
  1154. }
  1155. // Anything else is currently an unknown node.
  1156. return false;
  1157. }
  1158. if (!Shuffle)
  1159. return false;
  1160. // Check all uses of the binary ops and shuffles are also included in the
  1161. // lane-invariant operations (Visited should be the list of lanewise
  1162. // instructions, including the shuffle that we found).
  1163. for (auto *V : Visited)
  1164. for (auto *U : V->users())
  1165. if (!Visited.contains(U) && U != &I)
  1166. return false;
  1167. FixedVectorType *VecType =
  1168. dyn_cast<FixedVectorType>(II->getOperand(0)->getType());
  1169. if (!VecType)
  1170. return false;
  1171. FixedVectorType *ShuffleInputType =
  1172. dyn_cast<FixedVectorType>(Shuffle->getOperand(0)->getType());
  1173. if (!ShuffleInputType)
  1174. return false;
  1175. int NumInputElts = ShuffleInputType->getNumElements();
  1176. // Find the mask from sorting the lanes into order. This is most likely to
  1177. // become a identity or concat mask. Undef elements are pushed to the end.
  1178. SmallVector<int> ConcatMask;
  1179. Shuffle->getShuffleMask(ConcatMask);
  1180. sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; });
  1181. bool UsesSecondVec =
  1182. any_of(ConcatMask, [&](int M) { return M >= NumInputElts; });
  1183. InstructionCost OldCost = TTI.getShuffleCost(
  1184. UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
  1185. Shuffle->getShuffleMask());
  1186. InstructionCost NewCost = TTI.getShuffleCost(
  1187. UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
  1188. ConcatMask);
  1189. LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle
  1190. << "\n");
  1191. LLVM_DEBUG(dbgs() << " OldCost: " << OldCost << " vs NewCost: " << NewCost
  1192. << "\n");
  1193. if (NewCost < OldCost) {
  1194. Builder.SetInsertPoint(Shuffle);
  1195. Value *NewShuffle = Builder.CreateShuffleVector(
  1196. Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask);
  1197. LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n");
  1198. replaceValue(*Shuffle, *NewShuffle);
  1199. }
  1200. // See if we can re-use foldSelectShuffle, getting it to reduce the size of
  1201. // the shuffle into a nicer order, as it can ignore the order of the shuffles.
  1202. return foldSelectShuffle(*Shuffle, true);
  1203. }
  1204. /// This method looks for groups of shuffles acting on binops, of the form:
  1205. /// %x = shuffle ...
  1206. /// %y = shuffle ...
  1207. /// %a = binop %x, %y
  1208. /// %b = binop %x, %y
  1209. /// shuffle %a, %b, selectmask
  1210. /// We may, especially if the shuffle is wider than legal, be able to convert
  1211. /// the shuffle to a form where only parts of a and b need to be computed. On
  1212. /// architectures with no obvious "select" shuffle, this can reduce the total
  1213. /// number of operations if the target reports them as cheaper.
  1214. bool VectorCombine::foldSelectShuffle(Instruction &I, bool FromReduction) {
  1215. auto *SVI = cast<ShuffleVectorInst>(&I);
  1216. auto *VT = cast<FixedVectorType>(I.getType());
  1217. auto *Op0 = dyn_cast<Instruction>(SVI->getOperand(0));
  1218. auto *Op1 = dyn_cast<Instruction>(SVI->getOperand(1));
  1219. if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() ||
  1220. VT != Op0->getType())
  1221. return false;
  1222. auto *SVI0A = dyn_cast<Instruction>(Op0->getOperand(0));
  1223. auto *SVI0B = dyn_cast<Instruction>(Op0->getOperand(1));
  1224. auto *SVI1A = dyn_cast<Instruction>(Op1->getOperand(0));
  1225. auto *SVI1B = dyn_cast<Instruction>(Op1->getOperand(1));
  1226. SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B});
  1227. auto checkSVNonOpUses = [&](Instruction *I) {
  1228. if (!I || I->getOperand(0)->getType() != VT)
  1229. return true;
  1230. return any_of(I->users(), [&](User *U) {
  1231. return U != Op0 && U != Op1 &&
  1232. !(isa<ShuffleVectorInst>(U) &&
  1233. (InputShuffles.contains(cast<Instruction>(U)) ||
  1234. isInstructionTriviallyDead(cast<Instruction>(U))));
  1235. });
  1236. };
  1237. if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) ||
  1238. checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B))
  1239. return false;
  1240. // Collect all the uses that are shuffles that we can transform together. We
  1241. // may not have a single shuffle, but a group that can all be transformed
  1242. // together profitably.
  1243. SmallVector<ShuffleVectorInst *> Shuffles;
  1244. auto collectShuffles = [&](Instruction *I) {
  1245. for (auto *U : I->users()) {
  1246. auto *SV = dyn_cast<ShuffleVectorInst>(U);
  1247. if (!SV || SV->getType() != VT)
  1248. return false;
  1249. if ((SV->getOperand(0) != Op0 && SV->getOperand(0) != Op1) ||
  1250. (SV->getOperand(1) != Op0 && SV->getOperand(1) != Op1))
  1251. return false;
  1252. if (!llvm::is_contained(Shuffles, SV))
  1253. Shuffles.push_back(SV);
  1254. }
  1255. return true;
  1256. };
  1257. if (!collectShuffles(Op0) || !collectShuffles(Op1))
  1258. return false;
  1259. // From a reduction, we need to be processing a single shuffle, otherwise the
  1260. // other uses will not be lane-invariant.
  1261. if (FromReduction && Shuffles.size() > 1)
  1262. return false;
  1263. // Add any shuffle uses for the shuffles we have found, to include them in our
  1264. // cost calculations.
  1265. if (!FromReduction) {
  1266. for (ShuffleVectorInst *SV : Shuffles) {
  1267. for (auto *U : SV->users()) {
  1268. ShuffleVectorInst *SSV = dyn_cast<ShuffleVectorInst>(U);
  1269. if (SSV && isa<UndefValue>(SSV->getOperand(1)) && SSV->getType() == VT)
  1270. Shuffles.push_back(SSV);
  1271. }
  1272. }
  1273. }
  1274. // For each of the output shuffles, we try to sort all the first vector
  1275. // elements to the beginning, followed by the second array elements at the
  1276. // end. If the binops are legalized to smaller vectors, this may reduce total
  1277. // number of binops. We compute the ReconstructMask mask needed to convert
  1278. // back to the original lane order.
  1279. SmallVector<std::pair<int, int>> V1, V2;
  1280. SmallVector<SmallVector<int>> OrigReconstructMasks;
  1281. int MaxV1Elt = 0, MaxV2Elt = 0;
  1282. unsigned NumElts = VT->getNumElements();
  1283. for (ShuffleVectorInst *SVN : Shuffles) {
  1284. SmallVector<int> Mask;
  1285. SVN->getShuffleMask(Mask);
  1286. // Check the operands are the same as the original, or reversed (in which
  1287. // case we need to commute the mask).
  1288. Value *SVOp0 = SVN->getOperand(0);
  1289. Value *SVOp1 = SVN->getOperand(1);
  1290. if (isa<UndefValue>(SVOp1)) {
  1291. auto *SSV = cast<ShuffleVectorInst>(SVOp0);
  1292. SVOp0 = SSV->getOperand(0);
  1293. SVOp1 = SSV->getOperand(1);
  1294. for (unsigned I = 0, E = Mask.size(); I != E; I++) {
  1295. if (Mask[I] >= static_cast<int>(SSV->getShuffleMask().size()))
  1296. return false;
  1297. Mask[I] = Mask[I] < 0 ? Mask[I] : SSV->getMaskValue(Mask[I]);
  1298. }
  1299. }
  1300. if (SVOp0 == Op1 && SVOp1 == Op0) {
  1301. std::swap(SVOp0, SVOp1);
  1302. ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
  1303. }
  1304. if (SVOp0 != Op0 || SVOp1 != Op1)
  1305. return false;
  1306. // Calculate the reconstruction mask for this shuffle, as the mask needed to
  1307. // take the packed values from Op0/Op1 and reconstructing to the original
  1308. // order.
  1309. SmallVector<int> ReconstructMask;
  1310. for (unsigned I = 0; I < Mask.size(); I++) {
  1311. if (Mask[I] < 0) {
  1312. ReconstructMask.push_back(-1);
  1313. } else if (Mask[I] < static_cast<int>(NumElts)) {
  1314. MaxV1Elt = std::max(MaxV1Elt, Mask[I]);
  1315. auto It = find_if(V1, [&](const std::pair<int, int> &A) {
  1316. return Mask[I] == A.first;
  1317. });
  1318. if (It != V1.end())
  1319. ReconstructMask.push_back(It - V1.begin());
  1320. else {
  1321. ReconstructMask.push_back(V1.size());
  1322. V1.emplace_back(Mask[I], V1.size());
  1323. }
  1324. } else {
  1325. MaxV2Elt = std::max<int>(MaxV2Elt, Mask[I] - NumElts);
  1326. auto It = find_if(V2, [&](const std::pair<int, int> &A) {
  1327. return Mask[I] - static_cast<int>(NumElts) == A.first;
  1328. });
  1329. if (It != V2.end())
  1330. ReconstructMask.push_back(NumElts + It - V2.begin());
  1331. else {
  1332. ReconstructMask.push_back(NumElts + V2.size());
  1333. V2.emplace_back(Mask[I] - NumElts, NumElts + V2.size());
  1334. }
  1335. }
  1336. }
  1337. // For reductions, we know that the lane ordering out doesn't alter the
  1338. // result. In-order can help simplify the shuffle away.
  1339. if (FromReduction)
  1340. sort(ReconstructMask);
  1341. OrigReconstructMasks.push_back(std::move(ReconstructMask));
  1342. }
  1343. // If the Maximum element used from V1 and V2 are not larger than the new
  1344. // vectors, the vectors are already packes and performing the optimization
  1345. // again will likely not help any further. This also prevents us from getting
  1346. // stuck in a cycle in case the costs do not also rule it out.
  1347. if (V1.empty() || V2.empty() ||
  1348. (MaxV1Elt == static_cast<int>(V1.size()) - 1 &&
  1349. MaxV2Elt == static_cast<int>(V2.size()) - 1))
  1350. return false;
  1351. // GetBaseMaskValue takes one of the inputs, which may either be a shuffle, a
  1352. // shuffle of another shuffle, or not a shuffle (that is treated like a
  1353. // identity shuffle).
  1354. auto GetBaseMaskValue = [&](Instruction *I, int M) {
  1355. auto *SV = dyn_cast<ShuffleVectorInst>(I);
  1356. if (!SV)
  1357. return M;
  1358. if (isa<UndefValue>(SV->getOperand(1)))
  1359. if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
  1360. if (InputShuffles.contains(SSV))
  1361. return SSV->getMaskValue(SV->getMaskValue(M));
  1362. return SV->getMaskValue(M);
  1363. };
  1364. // Attempt to sort the inputs my ascending mask values to make simpler input
  1365. // shuffles and push complex shuffles down to the uses. We sort on the first
  1366. // of the two input shuffle orders, to try and get at least one input into a
  1367. // nice order.
  1368. auto SortBase = [&](Instruction *A, std::pair<int, int> X,
  1369. std::pair<int, int> Y) {
  1370. int MXA = GetBaseMaskValue(A, X.first);
  1371. int MYA = GetBaseMaskValue(A, Y.first);
  1372. return MXA < MYA;
  1373. };
  1374. stable_sort(V1, [&](std::pair<int, int> A, std::pair<int, int> B) {
  1375. return SortBase(SVI0A, A, B);
  1376. });
  1377. stable_sort(V2, [&](std::pair<int, int> A, std::pair<int, int> B) {
  1378. return SortBase(SVI1A, A, B);
  1379. });
  1380. // Calculate our ReconstructMasks from the OrigReconstructMasks and the
  1381. // modified order of the input shuffles.
  1382. SmallVector<SmallVector<int>> ReconstructMasks;
  1383. for (auto Mask : OrigReconstructMasks) {
  1384. SmallVector<int> ReconstructMask;
  1385. for (int M : Mask) {
  1386. auto FindIndex = [](const SmallVector<std::pair<int, int>> &V, int M) {
  1387. auto It = find_if(V, [M](auto A) { return A.second == M; });
  1388. assert(It != V.end() && "Expected all entries in Mask");
  1389. return std::distance(V.begin(), It);
  1390. };
  1391. if (M < 0)
  1392. ReconstructMask.push_back(-1);
  1393. else if (M < static_cast<int>(NumElts)) {
  1394. ReconstructMask.push_back(FindIndex(V1, M));
  1395. } else {
  1396. ReconstructMask.push_back(NumElts + FindIndex(V2, M));
  1397. }
  1398. }
  1399. ReconstructMasks.push_back(std::move(ReconstructMask));
  1400. }
  1401. // Calculate the masks needed for the new input shuffles, which get padded
  1402. // with undef
  1403. SmallVector<int> V1A, V1B, V2A, V2B;
  1404. for (unsigned I = 0; I < V1.size(); I++) {
  1405. V1A.push_back(GetBaseMaskValue(SVI0A, V1[I].first));
  1406. V1B.push_back(GetBaseMaskValue(SVI0B, V1[I].first));
  1407. }
  1408. for (unsigned I = 0; I < V2.size(); I++) {
  1409. V2A.push_back(GetBaseMaskValue(SVI1A, V2[I].first));
  1410. V2B.push_back(GetBaseMaskValue(SVI1B, V2[I].first));
  1411. }
  1412. while (V1A.size() < NumElts) {
  1413. V1A.push_back(UndefMaskElem);
  1414. V1B.push_back(UndefMaskElem);
  1415. }
  1416. while (V2A.size() < NumElts) {
  1417. V2A.push_back(UndefMaskElem);
  1418. V2B.push_back(UndefMaskElem);
  1419. }
  1420. auto AddShuffleCost = [&](InstructionCost C, Instruction *I) {
  1421. auto *SV = dyn_cast<ShuffleVectorInst>(I);
  1422. if (!SV)
  1423. return C;
  1424. return C + TTI.getShuffleCost(isa<UndefValue>(SV->getOperand(1))
  1425. ? TTI::SK_PermuteSingleSrc
  1426. : TTI::SK_PermuteTwoSrc,
  1427. VT, SV->getShuffleMask());
  1428. };
  1429. auto AddShuffleMaskCost = [&](InstructionCost C, ArrayRef<int> Mask) {
  1430. return C + TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, Mask);
  1431. };
  1432. // Get the costs of the shuffles + binops before and after with the new
  1433. // shuffle masks.
  1434. InstructionCost CostBefore =
  1435. TTI.getArithmeticInstrCost(Op0->getOpcode(), VT) +
  1436. TTI.getArithmeticInstrCost(Op1->getOpcode(), VT);
  1437. CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(),
  1438. InstructionCost(0), AddShuffleCost);
  1439. CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
  1440. InstructionCost(0), AddShuffleCost);
  1441. // The new binops will be unused for lanes past the used shuffle lengths.
  1442. // These types attempt to get the correct cost for that from the target.
  1443. FixedVectorType *Op0SmallVT =
  1444. FixedVectorType::get(VT->getScalarType(), V1.size());
  1445. FixedVectorType *Op1SmallVT =
  1446. FixedVectorType::get(VT->getScalarType(), V2.size());
  1447. InstructionCost CostAfter =
  1448. TTI.getArithmeticInstrCost(Op0->getOpcode(), Op0SmallVT) +
  1449. TTI.getArithmeticInstrCost(Op1->getOpcode(), Op1SmallVT);
  1450. CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(),
  1451. InstructionCost(0), AddShuffleMaskCost);
  1452. std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B});
  1453. CostAfter +=
  1454. std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(),
  1455. InstructionCost(0), AddShuffleMaskCost);
  1456. LLVM_DEBUG(dbgs() << "Found a binop select shuffle pattern: " << I << "\n");
  1457. LLVM_DEBUG(dbgs() << " CostBefore: " << CostBefore
  1458. << " vs CostAfter: " << CostAfter << "\n");
  1459. if (CostBefore <= CostAfter)
  1460. return false;
  1461. // The cost model has passed, create the new instructions.
  1462. auto GetShuffleOperand = [&](Instruction *I, unsigned Op) -> Value * {
  1463. auto *SV = dyn_cast<ShuffleVectorInst>(I);
  1464. if (!SV)
  1465. return I;
  1466. if (isa<UndefValue>(SV->getOperand(1)))
  1467. if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
  1468. if (InputShuffles.contains(SSV))
  1469. return SSV->getOperand(Op);
  1470. return SV->getOperand(Op);
  1471. };
  1472. Builder.SetInsertPoint(SVI0A->getNextNode());
  1473. Value *NSV0A = Builder.CreateShuffleVector(GetShuffleOperand(SVI0A, 0),
  1474. GetShuffleOperand(SVI0A, 1), V1A);
  1475. Builder.SetInsertPoint(SVI0B->getNextNode());
  1476. Value *NSV0B = Builder.CreateShuffleVector(GetShuffleOperand(SVI0B, 0),
  1477. GetShuffleOperand(SVI0B, 1), V1B);
  1478. Builder.SetInsertPoint(SVI1A->getNextNode());
  1479. Value *NSV1A = Builder.CreateShuffleVector(GetShuffleOperand(SVI1A, 0),
  1480. GetShuffleOperand(SVI1A, 1), V2A);
  1481. Builder.SetInsertPoint(SVI1B->getNextNode());
  1482. Value *NSV1B = Builder.CreateShuffleVector(GetShuffleOperand(SVI1B, 0),
  1483. GetShuffleOperand(SVI1B, 1), V2B);
  1484. Builder.SetInsertPoint(Op0);
  1485. Value *NOp0 = Builder.CreateBinOp((Instruction::BinaryOps)Op0->getOpcode(),
  1486. NSV0A, NSV0B);
  1487. if (auto *I = dyn_cast<Instruction>(NOp0))
  1488. I->copyIRFlags(Op0, true);
  1489. Builder.SetInsertPoint(Op1);
  1490. Value *NOp1 = Builder.CreateBinOp((Instruction::BinaryOps)Op1->getOpcode(),
  1491. NSV1A, NSV1B);
  1492. if (auto *I = dyn_cast<Instruction>(NOp1))
  1493. I->copyIRFlags(Op1, true);
  1494. for (int S = 0, E = ReconstructMasks.size(); S != E; S++) {
  1495. Builder.SetInsertPoint(Shuffles[S]);
  1496. Value *NSV = Builder.CreateShuffleVector(NOp0, NOp1, ReconstructMasks[S]);
  1497. replaceValue(*Shuffles[S], *NSV);
  1498. }
  1499. Worklist.pushValue(NSV0A);
  1500. Worklist.pushValue(NSV0B);
  1501. Worklist.pushValue(NSV1A);
  1502. Worklist.pushValue(NSV1B);
  1503. for (auto *S : Shuffles)
  1504. Worklist.add(S);
  1505. return true;
  1506. }
  1507. /// This is the entry point for all transforms. Pass manager differences are
  1508. /// handled in the callers of this function.
  1509. bool VectorCombine::run() {
  1510. if (DisableVectorCombine)
  1511. return false;
  1512. // Don't attempt vectorization if the target does not support vectors.
  1513. if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
  1514. return false;
  1515. bool MadeChange = false;
  1516. auto FoldInst = [this, &MadeChange](Instruction &I) {
  1517. Builder.SetInsertPoint(&I);
  1518. bool IsFixedVectorType = isa<FixedVectorType>(I.getType());
  1519. auto Opcode = I.getOpcode();
  1520. // These folds should be beneficial regardless of when this pass is run
  1521. // in the optimization pipeline.
  1522. // The type checking is for run-time efficiency. We can avoid wasting time
  1523. // dispatching to folding functions if there's no chance of matching.
  1524. if (IsFixedVectorType) {
  1525. switch (Opcode) {
  1526. case Instruction::InsertElement:
  1527. MadeChange |= vectorizeLoadInsert(I);
  1528. break;
  1529. case Instruction::ShuffleVector:
  1530. MadeChange |= widenSubvectorLoad(I);
  1531. break;
  1532. case Instruction::Load:
  1533. MadeChange |= scalarizeLoadExtract(I);
  1534. break;
  1535. default:
  1536. break;
  1537. }
  1538. }
  1539. // This transform works with scalable and fixed vectors
  1540. // TODO: Identify and allow other scalable transforms
  1541. if (isa<VectorType>(I.getType()))
  1542. MadeChange |= scalarizeBinopOrCmp(I);
  1543. if (Opcode == Instruction::Store)
  1544. MadeChange |= foldSingleElementStore(I);
  1545. // If this is an early pipeline invocation of this pass, we are done.
  1546. if (TryEarlyFoldsOnly)
  1547. return;
  1548. // Otherwise, try folds that improve codegen but may interfere with
  1549. // early IR canonicalizations.
  1550. // The type checking is for run-time efficiency. We can avoid wasting time
  1551. // dispatching to folding functions if there's no chance of matching.
  1552. if (IsFixedVectorType) {
  1553. switch (Opcode) {
  1554. case Instruction::InsertElement:
  1555. MadeChange |= foldInsExtFNeg(I);
  1556. break;
  1557. case Instruction::ShuffleVector:
  1558. MadeChange |= foldShuffleOfBinops(I);
  1559. MadeChange |= foldSelectShuffle(I);
  1560. break;
  1561. case Instruction::BitCast:
  1562. MadeChange |= foldBitcastShuf(I);
  1563. break;
  1564. }
  1565. } else {
  1566. switch (Opcode) {
  1567. case Instruction::Call:
  1568. MadeChange |= foldShuffleFromReductions(I);
  1569. break;
  1570. case Instruction::ICmp:
  1571. case Instruction::FCmp:
  1572. MadeChange |= foldExtractExtract(I);
  1573. break;
  1574. default:
  1575. if (Instruction::isBinaryOp(Opcode)) {
  1576. MadeChange |= foldExtractExtract(I);
  1577. MadeChange |= foldExtractedCmps(I);
  1578. }
  1579. break;
  1580. }
  1581. }
  1582. };
  1583. for (BasicBlock &BB : F) {
  1584. // Ignore unreachable basic blocks.
  1585. if (!DT.isReachableFromEntry(&BB))
  1586. continue;
  1587. // Use early increment range so that we can erase instructions in loop.
  1588. for (Instruction &I : make_early_inc_range(BB)) {
  1589. if (I.isDebugOrPseudoInst())
  1590. continue;
  1591. FoldInst(I);
  1592. }
  1593. }
  1594. while (!Worklist.isEmpty()) {
  1595. Instruction *I = Worklist.removeOne();
  1596. if (!I)
  1597. continue;
  1598. if (isInstructionTriviallyDead(I)) {
  1599. eraseInstruction(*I);
  1600. continue;
  1601. }
  1602. FoldInst(*I);
  1603. }
  1604. return MadeChange;
  1605. }
  1606. // Pass manager boilerplate below here.
  1607. namespace {
  1608. class VectorCombineLegacyPass : public FunctionPass {
  1609. public:
  1610. static char ID;
  1611. VectorCombineLegacyPass() : FunctionPass(ID) {
  1612. initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
  1613. }
  1614. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1615. AU.addRequired<AssumptionCacheTracker>();
  1616. AU.addRequired<DominatorTreeWrapperPass>();
  1617. AU.addRequired<TargetTransformInfoWrapperPass>();
  1618. AU.addRequired<AAResultsWrapperPass>();
  1619. AU.setPreservesCFG();
  1620. AU.addPreserved<DominatorTreeWrapperPass>();
  1621. AU.addPreserved<GlobalsAAWrapperPass>();
  1622. AU.addPreserved<AAResultsWrapperPass>();
  1623. AU.addPreserved<BasicAAWrapperPass>();
  1624. FunctionPass::getAnalysisUsage(AU);
  1625. }
  1626. bool runOnFunction(Function &F) override {
  1627. if (skipFunction(F))
  1628. return false;
  1629. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1630. auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  1631. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1632. auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
  1633. VectorCombine Combiner(F, TTI, DT, AA, AC, false);
  1634. return Combiner.run();
  1635. }
  1636. };
  1637. } // namespace
  1638. char VectorCombineLegacyPass::ID = 0;
  1639. INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
  1640. "Optimize scalar/vector ops", false,
  1641. false)
  1642. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1643. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1644. INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
  1645. "Optimize scalar/vector ops", false, false)
  1646. Pass *llvm::createVectorCombinePass() {
  1647. return new VectorCombineLegacyPass();
  1648. }
  1649. PreservedAnalyses VectorCombinePass::run(Function &F,
  1650. FunctionAnalysisManager &FAM) {
  1651. auto &AC = FAM.getResult<AssumptionAnalysis>(F);
  1652. TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
  1653. DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
  1654. AAResults &AA = FAM.getResult<AAManager>(F);
  1655. VectorCombine Combiner(F, TTI, DT, AA, AC, TryEarlyFoldsOnly);
  1656. if (!Combiner.run())
  1657. return PreservedAnalyses::all();
  1658. PreservedAnalyses PA;
  1659. PA.preserveSet<CFGAnalyses>();
  1660. return PA;
  1661. }