Scalarizer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. //===--- Scalarizer.cpp - Scalarize vector operations ---------------------===//
  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 pass converts vector operations into scalar operations, in order
  11. // to expose optimization opportunities on the individual scalar operations.
  12. // It is mainly intended for targets that do not have vector units, but it
  13. // may also be useful for revectorizing code to different vector widths.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/IR/IRBuilder.h"
  18. #include "llvm/IR/InstVisitor.h"
  19. #include "llvm/Pass.h"
  20. #include "llvm/Support/CommandLine.h"
  21. #include "llvm/Transforms/Scalar.h"
  22. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  23. using namespace llvm;
  24. #define DEBUG_TYPE "scalarizer"
  25. namespace {
  26. // Used to store the scattered form of a vector.
  27. typedef SmallVector<Value *, 8> ValueVector;
  28. // Used to map a vector Value to its scattered form. We use std::map
  29. // because we want iterators to persist across insertion and because the
  30. // values are relatively large.
  31. typedef std::map<Value *, ValueVector> ScatterMap;
  32. // Lists Instructions that have been replaced with scalar implementations,
  33. // along with a pointer to their scattered forms.
  34. typedef SmallVector<std::pair<Instruction *, ValueVector *>, 16> GatherList;
  35. // Provides a very limited vector-like interface for lazily accessing one
  36. // component of a scattered vector or vector pointer.
  37. class Scatterer {
  38. public:
  39. Scatterer() {}
  40. // Scatter V into Size components. If new instructions are needed,
  41. // insert them before BBI in BB. If Cache is nonnull, use it to cache
  42. // the results.
  43. Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
  44. ValueVector *cachePtr = nullptr);
  45. // Return component I, creating a new Value for it if necessary.
  46. Value *operator[](unsigned I);
  47. // Return the number of components.
  48. unsigned size() const { return Size; }
  49. private:
  50. BasicBlock *BB;
  51. BasicBlock::iterator BBI;
  52. Value *V;
  53. ValueVector *CachePtr;
  54. PointerType *PtrTy;
  55. ValueVector Tmp;
  56. unsigned Size;
  57. };
  58. // FCmpSpliiter(FCI)(Builder, X, Y, Name) uses Builder to create an FCmp
  59. // called Name that compares X and Y in the same way as FCI.
  60. struct FCmpSplitter {
  61. FCmpSplitter(FCmpInst &fci) : FCI(fci) {}
  62. Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
  63. const Twine &Name) const {
  64. Value *Cmp = Builder.CreateFCmp(FCI.getPredicate(), Op0, Op1, Name);
  65. // HLSL Change Begins -Transfer FPMath flag.
  66. if (Instruction *FPMath = dyn_cast<Instruction>(Cmp)) {
  67. FPMath->copyFastMathFlags(FCI.getFastMathFlags());
  68. }
  69. // HLSL Change Ends
  70. return Cmp;
  71. }
  72. FCmpInst &FCI;
  73. };
  74. // ICmpSpliiter(ICI)(Builder, X, Y, Name) uses Builder to create an ICmp
  75. // called Name that compares X and Y in the same way as ICI.
  76. struct ICmpSplitter {
  77. ICmpSplitter(ICmpInst &ici) : ICI(ici) {}
  78. Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
  79. const Twine &Name) const {
  80. return Builder.CreateICmp(ICI.getPredicate(), Op0, Op1, Name);
  81. }
  82. ICmpInst &ICI;
  83. };
  84. // BinarySpliiter(BO)(Builder, X, Y, Name) uses Builder to create
  85. // a binary operator like BO called Name with operands X and Y.
  86. struct BinarySplitter {
  87. BinarySplitter(BinaryOperator &bo) : BO(bo) {}
  88. Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
  89. const Twine &Name) const {
  90. Value *BinOp = Builder.CreateBinOp(BO.getOpcode(), Op0, Op1, Name);
  91. // HLSL Change Begins -Transfer FPMath flag.
  92. if (isa<FPMathOperator>(&BO)) {
  93. if (Instruction *FPMath = dyn_cast<Instruction>(BinOp)) {
  94. FPMath->copyFastMathFlags(BO.getFastMathFlags());
  95. }
  96. }
  97. // HLSL Change Ends
  98. return BinOp;
  99. }
  100. BinaryOperator &BO;
  101. };
  102. // Information about a load or store that we're scalarizing.
  103. struct VectorLayout {
  104. VectorLayout() : VecTy(nullptr), ElemTy(nullptr), VecAlign(0), ElemSize(0) {}
  105. // Return the alignment of element I.
  106. uint64_t getElemAlign(unsigned I) {
  107. return MinAlign(VecAlign, I * ElemSize);
  108. }
  109. // The type of the vector.
  110. VectorType *VecTy;
  111. // The type of each element.
  112. Type *ElemTy;
  113. // The alignment of the vector.
  114. uint64_t VecAlign;
  115. // The size of each element.
  116. uint64_t ElemSize;
  117. };
  118. class Scalarizer : public FunctionPass,
  119. public InstVisitor<Scalarizer, bool> {
  120. public:
  121. static char ID;
  122. Scalarizer() :
  123. FunctionPass(ID) {
  124. initializeScalarizerPass(*PassRegistry::getPassRegistry());
  125. }
  126. bool doInitialization(Module &M) override;
  127. bool runOnFunction(Function &F) override;
  128. // InstVisitor methods. They return true if the instruction was scalarized,
  129. // false if nothing changed.
  130. bool visitInstruction(Instruction &) { return false; }
  131. bool visitSelectInst(SelectInst &SI);
  132. bool visitICmpInst(ICmpInst &);
  133. bool visitFCmpInst(FCmpInst &);
  134. bool visitBinaryOperator(BinaryOperator &);
  135. bool visitGetElementPtrInst(GetElementPtrInst &);
  136. bool visitCastInst(CastInst &);
  137. bool visitBitCastInst(BitCastInst &);
  138. bool visitShuffleVectorInst(ShuffleVectorInst &);
  139. bool visitPHINode(PHINode &);
  140. bool visitLoadInst(LoadInst &);
  141. bool visitStoreInst(StoreInst &);
  142. static void registerOptions() {
  143. // This is disabled by default because having separate loads and stores
  144. // makes it more likely that the -combiner-alias-analysis limits will be
  145. // reached.
  146. OptionRegistry::registerOption<bool, Scalarizer,
  147. &Scalarizer::ScalarizeLoadStore>(
  148. "scalarize-load-store",
  149. "Allow the scalarizer pass to scalarize loads and store", false);
  150. }
  151. private:
  152. Scatterer scatter(Instruction *, Value *);
  153. void gather(Instruction *, const ValueVector &);
  154. bool canTransferMetadata(unsigned Kind);
  155. void transferMetadata(Instruction *, const ValueVector &);
  156. bool getVectorLayout(Type *, unsigned, VectorLayout &, const DataLayout &);
  157. bool finish();
  158. template<typename T> bool splitBinary(Instruction &, const T &);
  159. ScatterMap Scattered;
  160. GatherList Gathered;
  161. unsigned ParallelLoopAccessMDKind;
  162. bool ScalarizeLoadStore;
  163. };
  164. char Scalarizer::ID = 0;
  165. } // end anonymous namespace
  166. INITIALIZE_PASS_WITH_OPTIONS(Scalarizer, "scalarizer",
  167. "Scalarize vector operations", false, false)
  168. Scatterer::Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
  169. ValueVector *cachePtr)
  170. : BB(bb), BBI(bbi), V(v), CachePtr(cachePtr) {
  171. Type *Ty = V->getType();
  172. PtrTy = dyn_cast<PointerType>(Ty);
  173. if (PtrTy)
  174. Ty = PtrTy->getElementType();
  175. Size = Ty->getVectorNumElements();
  176. if (!CachePtr)
  177. Tmp.resize(Size, nullptr);
  178. else if (CachePtr->empty())
  179. CachePtr->resize(Size, nullptr);
  180. else
  181. assert(Size == CachePtr->size() && "Inconsistent vector sizes");
  182. }
  183. // Return component I, creating a new Value for it if necessary.
  184. Value *Scatterer::operator[](unsigned I) {
  185. ValueVector &CV = (CachePtr ? *CachePtr : Tmp);
  186. // Try to reuse a previous value.
  187. if (CV[I])
  188. return CV[I];
  189. IRBuilder<> Builder(BB, BBI);
  190. if (PtrTy) {
  191. if (!CV[0]) {
  192. Type *Ty =
  193. PointerType::get(PtrTy->getElementType()->getVectorElementType(),
  194. PtrTy->getAddressSpace());
  195. CV[0] = Builder.CreateBitCast(V, Ty, V->getName() + ".i0");
  196. }
  197. if (I != 0)
  198. CV[I] = Builder.CreateConstGEP1_32(nullptr, CV[0], I,
  199. V->getName() + ".i" + Twine(I));
  200. } else {
  201. // Search through a chain of InsertElementInsts looking for element I.
  202. // Record other elements in the cache. The new V is still suitable
  203. // for all uncached indices.
  204. for (;;) {
  205. InsertElementInst *Insert = dyn_cast<InsertElementInst>(V);
  206. if (!Insert)
  207. break;
  208. ConstantInt *Idx = dyn_cast<ConstantInt>(Insert->getOperand(2));
  209. if (!Idx)
  210. break;
  211. unsigned J = Idx->getZExtValue();
  212. V = Insert->getOperand(0);
  213. if (I == J) {
  214. CV[J] = Insert->getOperand(1);
  215. return CV[J];
  216. } else if (!CV[J]) {
  217. // Only cache the first entry we find for each index we're not actively
  218. // searching for. This prevents us from going too far up the chain and
  219. // caching incorrect entries.
  220. CV[J] = Insert->getOperand(1);
  221. }
  222. }
  223. CV[I] = Builder.CreateExtractElement(V, Builder.getInt32(I),
  224. V->getName() + ".i" + Twine(I));
  225. }
  226. return CV[I];
  227. }
  228. bool Scalarizer::doInitialization(Module &M) {
  229. ParallelLoopAccessMDKind =
  230. M.getContext().getMDKindID("llvm.mem.parallel_loop_access");
  231. ScalarizeLoadStore =
  232. M.getContext().getOption<bool, Scalarizer, &Scalarizer::ScalarizeLoadStore>();
  233. return false;
  234. }
  235. bool Scalarizer::runOnFunction(Function &F) {
  236. for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
  237. BasicBlock *BB = BBI;
  238. for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
  239. Instruction *I = II;
  240. bool Done = visit(I);
  241. ++II;
  242. if (Done && I->getType()->isVoidTy())
  243. I->eraseFromParent();
  244. }
  245. }
  246. return finish();
  247. }
  248. // Return a scattered form of V that can be accessed by Point. V must be a
  249. // vector or a pointer to a vector.
  250. Scatterer Scalarizer::scatter(Instruction *Point, Value *V) {
  251. if (Argument *VArg = dyn_cast<Argument>(V)) {
  252. // Put the scattered form of arguments in the entry block,
  253. // so that it can be used everywhere.
  254. Function *F = VArg->getParent();
  255. BasicBlock *BB = &F->getEntryBlock();
  256. return Scatterer(BB, BB->begin(), V, &Scattered[V]);
  257. }
  258. if (Instruction *VOp = dyn_cast<Instruction>(V)) {
  259. // Put the scattered form of an instruction directly after the
  260. // instruction.
  261. BasicBlock *BB = VOp->getParent();
  262. return Scatterer(BB, std::next(BasicBlock::iterator(VOp)),
  263. V, &Scattered[V]);
  264. }
  265. // In the fallback case, just put the scattered before Point and
  266. // keep the result local to Point.
  267. return Scatterer(Point->getParent(), Point, V);
  268. }
  269. // Replace Op with the gathered form of the components in CV. Defer the
  270. // deletion of Op and creation of the gathered form to the end of the pass,
  271. // so that we can avoid creating the gathered form if all uses of Op are
  272. // replaced with uses of CV.
  273. void Scalarizer::gather(Instruction *Op, const ValueVector &CV) {
  274. // Since we're not deleting Op yet, stub out its operands, so that it
  275. // doesn't make anything live unnecessarily.
  276. for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I)
  277. Op->setOperand(I, UndefValue::get(Op->getOperand(I)->getType()));
  278. transferMetadata(Op, CV);
  279. // If we already have a scattered form of Op (created from ExtractElements
  280. // of Op itself), replace them with the new form.
  281. ValueVector &SV = Scattered[Op];
  282. if (!SV.empty()) {
  283. for (unsigned I = 0, E = SV.size(); I != E; ++I) {
  284. Instruction *Old = dyn_cast_or_null<Instruction>(SV[I]);
  285. // HLSL Change Begin - skip unused scatter elt.
  286. if (!Old)
  287. continue;
  288. // HLSL Change End.
  289. CV[I]->takeName(Old);
  290. Old->replaceAllUsesWith(CV[I]);
  291. Old->eraseFromParent();
  292. }
  293. }
  294. SV = CV;
  295. Gathered.push_back(GatherList::value_type(Op, &SV));
  296. }
  297. // Return true if it is safe to transfer the given metadata tag from
  298. // vector to scalar instructions.
  299. bool Scalarizer::canTransferMetadata(unsigned Tag) {
  300. return (Tag == LLVMContext::MD_tbaa
  301. || Tag == LLVMContext::MD_fpmath
  302. || Tag == LLVMContext::MD_tbaa_struct
  303. || Tag == LLVMContext::MD_invariant_load
  304. || Tag == LLVMContext::MD_alias_scope
  305. || Tag == LLVMContext::MD_noalias
  306. || Tag == ParallelLoopAccessMDKind);
  307. }
  308. // Transfer metadata from Op to the instructions in CV if it is known
  309. // to be safe to do so.
  310. void Scalarizer::transferMetadata(Instruction *Op, const ValueVector &CV) {
  311. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  312. Op->getAllMetadataOtherThanDebugLoc(MDs);
  313. for (unsigned I = 0, E = CV.size(); I != E; ++I) {
  314. if (Instruction *New = dyn_cast<Instruction>(CV[I])) {
  315. for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
  316. MI = MDs.begin(),
  317. ME = MDs.end();
  318. MI != ME; ++MI)
  319. if (canTransferMetadata(MI->first))
  320. New->setMetadata(MI->first, MI->second);
  321. New->setDebugLoc(Op->getDebugLoc());
  322. }
  323. }
  324. }
  325. // Try to fill in Layout from Ty, returning true on success. Alignment is
  326. // the alignment of the vector, or 0 if the ABI default should be used.
  327. bool Scalarizer::getVectorLayout(Type *Ty, unsigned Alignment,
  328. VectorLayout &Layout, const DataLayout &DL) {
  329. // Make sure we're dealing with a vector.
  330. Layout.VecTy = dyn_cast<VectorType>(Ty);
  331. if (!Layout.VecTy)
  332. return false;
  333. // Check that we're dealing with full-byte elements.
  334. Layout.ElemTy = Layout.VecTy->getElementType();
  335. if (DL.getTypeSizeInBits(Layout.ElemTy) !=
  336. DL.getTypeStoreSizeInBits(Layout.ElemTy))
  337. return false;
  338. if (Alignment)
  339. Layout.VecAlign = Alignment;
  340. else
  341. Layout.VecAlign = DL.getABITypeAlignment(Layout.VecTy);
  342. Layout.ElemSize = DL.getTypeStoreSize(Layout.ElemTy);
  343. return true;
  344. }
  345. // Scalarize two-operand instruction I, using Split(Builder, X, Y, Name)
  346. // to create an instruction like I with operands X and Y and name Name.
  347. template<typename Splitter>
  348. bool Scalarizer::splitBinary(Instruction &I, const Splitter &Split) {
  349. VectorType *VT = dyn_cast<VectorType>(I.getType());
  350. if (!VT)
  351. return false;
  352. unsigned NumElems = VT->getNumElements();
  353. IRBuilder<> Builder(I.getParent(), &I);
  354. Scatterer Op0 = scatter(&I, I.getOperand(0));
  355. Scatterer Op1 = scatter(&I, I.getOperand(1));
  356. assert(Op0.size() == NumElems && "Mismatched binary operation");
  357. assert(Op1.size() == NumElems && "Mismatched binary operation");
  358. ValueVector Res;
  359. Res.resize(NumElems);
  360. for (unsigned Elem = 0; Elem < NumElems; ++Elem)
  361. Res[Elem] = Split(Builder, Op0[Elem], Op1[Elem],
  362. I.getName() + ".i" + Twine(Elem));
  363. gather(&I, Res);
  364. return true;
  365. }
  366. bool Scalarizer::visitSelectInst(SelectInst &SI) {
  367. VectorType *VT = dyn_cast<VectorType>(SI.getType());
  368. if (!VT)
  369. return false;
  370. unsigned NumElems = VT->getNumElements();
  371. IRBuilder<> Builder(SI.getParent(), &SI);
  372. Scatterer Op1 = scatter(&SI, SI.getOperand(1));
  373. Scatterer Op2 = scatter(&SI, SI.getOperand(2));
  374. assert(Op1.size() == NumElems && "Mismatched select");
  375. assert(Op2.size() == NumElems && "Mismatched select");
  376. ValueVector Res;
  377. Res.resize(NumElems);
  378. if (SI.getOperand(0)->getType()->isVectorTy()) {
  379. Scatterer Op0 = scatter(&SI, SI.getOperand(0));
  380. assert(Op0.size() == NumElems && "Mismatched select");
  381. for (unsigned I = 0; I < NumElems; ++I)
  382. Res[I] = Builder.CreateSelect(Op0[I], Op1[I], Op2[I],
  383. SI.getName() + ".i" + Twine(I));
  384. } else {
  385. Value *Op0 = SI.getOperand(0);
  386. for (unsigned I = 0; I < NumElems; ++I)
  387. Res[I] = Builder.CreateSelect(Op0, Op1[I], Op2[I],
  388. SI.getName() + ".i" + Twine(I));
  389. }
  390. gather(&SI, Res);
  391. return true;
  392. }
  393. bool Scalarizer::visitICmpInst(ICmpInst &ICI) {
  394. return splitBinary(ICI, ICmpSplitter(ICI));
  395. }
  396. bool Scalarizer::visitFCmpInst(FCmpInst &FCI) {
  397. return splitBinary(FCI, FCmpSplitter(FCI));
  398. }
  399. bool Scalarizer::visitBinaryOperator(BinaryOperator &BO) {
  400. return splitBinary(BO, BinarySplitter(BO));
  401. }
  402. bool Scalarizer::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
  403. VectorType *VT = dyn_cast<VectorType>(GEPI.getType());
  404. if (!VT)
  405. return false;
  406. IRBuilder<> Builder(GEPI.getParent(), &GEPI);
  407. unsigned NumElems = VT->getNumElements();
  408. unsigned NumIndices = GEPI.getNumIndices();
  409. Scatterer Base = scatter(&GEPI, GEPI.getOperand(0));
  410. SmallVector<Scatterer, 8> Ops;
  411. Ops.resize(NumIndices);
  412. for (unsigned I = 0; I < NumIndices; ++I)
  413. Ops[I] = scatter(&GEPI, GEPI.getOperand(I + 1));
  414. ValueVector Res;
  415. Res.resize(NumElems);
  416. for (unsigned I = 0; I < NumElems; ++I) {
  417. SmallVector<Value *, 8> Indices;
  418. Indices.resize(NumIndices);
  419. for (unsigned J = 0; J < NumIndices; ++J)
  420. Indices[J] = Ops[J][I];
  421. Res[I] = Builder.CreateGEP(GEPI.getSourceElementType(), Base[I], Indices,
  422. GEPI.getName() + ".i" + Twine(I));
  423. if (GEPI.isInBounds())
  424. if (GetElementPtrInst *NewGEPI = dyn_cast<GetElementPtrInst>(Res[I]))
  425. NewGEPI->setIsInBounds();
  426. }
  427. gather(&GEPI, Res);
  428. return true;
  429. }
  430. bool Scalarizer::visitCastInst(CastInst &CI) {
  431. VectorType *VT = dyn_cast<VectorType>(CI.getDestTy());
  432. if (!VT)
  433. return false;
  434. unsigned NumElems = VT->getNumElements();
  435. IRBuilder<> Builder(CI.getParent(), &CI);
  436. Scatterer Op0 = scatter(&CI, CI.getOperand(0));
  437. assert(Op0.size() == NumElems && "Mismatched cast");
  438. ValueVector Res;
  439. Res.resize(NumElems);
  440. for (unsigned I = 0; I < NumElems; ++I)
  441. Res[I] = Builder.CreateCast(CI.getOpcode(), Op0[I], VT->getElementType(),
  442. CI.getName() + ".i" + Twine(I));
  443. gather(&CI, Res);
  444. return true;
  445. }
  446. bool Scalarizer::visitBitCastInst(BitCastInst &BCI) {
  447. VectorType *DstVT = dyn_cast<VectorType>(BCI.getDestTy());
  448. VectorType *SrcVT = dyn_cast<VectorType>(BCI.getSrcTy());
  449. if (!DstVT || !SrcVT)
  450. return false;
  451. unsigned DstNumElems = DstVT->getNumElements();
  452. unsigned SrcNumElems = SrcVT->getNumElements();
  453. IRBuilder<> Builder(BCI.getParent(), &BCI);
  454. Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
  455. ValueVector Res;
  456. Res.resize(DstNumElems);
  457. if (DstNumElems == SrcNumElems) {
  458. for (unsigned I = 0; I < DstNumElems; ++I)
  459. Res[I] = Builder.CreateBitCast(Op0[I], DstVT->getElementType(),
  460. BCI.getName() + ".i" + Twine(I));
  461. } else if (DstNumElems > SrcNumElems) {
  462. // <M x t1> -> <N*M x t2>. Convert each t1 to <N x t2> and copy the
  463. // individual elements to the destination.
  464. unsigned FanOut = DstNumElems / SrcNumElems;
  465. Type *MidTy = VectorType::get(DstVT->getElementType(), FanOut);
  466. unsigned ResI = 0;
  467. for (unsigned Op0I = 0; Op0I < SrcNumElems; ++Op0I) {
  468. Value *V = Op0[Op0I];
  469. Instruction *VI;
  470. // Look through any existing bitcasts before converting to <N x t2>.
  471. // In the best case, the resulting conversion might be a no-op.
  472. while ((VI = dyn_cast<Instruction>(V)) &&
  473. VI->getOpcode() == Instruction::BitCast)
  474. V = VI->getOperand(0);
  475. V = Builder.CreateBitCast(V, MidTy, V->getName() + ".cast");
  476. Scatterer Mid = scatter(&BCI, V);
  477. for (unsigned MidI = 0; MidI < FanOut; ++MidI)
  478. Res[ResI++] = Mid[MidI];
  479. }
  480. } else {
  481. // <N*M x t1> -> <M x t2>. Convert each group of <N x t1> into a t2.
  482. unsigned FanIn = SrcNumElems / DstNumElems;
  483. Type *MidTy = VectorType::get(SrcVT->getElementType(), FanIn);
  484. unsigned Op0I = 0;
  485. for (unsigned ResI = 0; ResI < DstNumElems; ++ResI) {
  486. Value *V = UndefValue::get(MidTy);
  487. for (unsigned MidI = 0; MidI < FanIn; ++MidI)
  488. V = Builder.CreateInsertElement(V, Op0[Op0I++], Builder.getInt32(MidI),
  489. BCI.getName() + ".i" + Twine(ResI)
  490. + ".upto" + Twine(MidI));
  491. Res[ResI] = Builder.CreateBitCast(V, DstVT->getElementType(),
  492. BCI.getName() + ".i" + Twine(ResI));
  493. }
  494. }
  495. gather(&BCI, Res);
  496. return true;
  497. }
  498. bool Scalarizer::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
  499. VectorType *VT = dyn_cast<VectorType>(SVI.getType());
  500. if (!VT)
  501. return false;
  502. unsigned NumElems = VT->getNumElements();
  503. Scatterer Op0 = scatter(&SVI, SVI.getOperand(0));
  504. Scatterer Op1 = scatter(&SVI, SVI.getOperand(1));
  505. ValueVector Res;
  506. Res.resize(NumElems);
  507. for (unsigned I = 0; I < NumElems; ++I) {
  508. int Selector = SVI.getMaskValue(I);
  509. if (Selector < 0)
  510. Res[I] = UndefValue::get(VT->getElementType());
  511. else if (unsigned(Selector) < Op0.size())
  512. Res[I] = Op0[Selector];
  513. else
  514. Res[I] = Op1[Selector - Op0.size()];
  515. // HLSL Change Begins: (fix bug in upstream llvm)
  516. if (ExtractElementInst *EA = dyn_cast<ExtractElementInst>(Res[I])) {
  517. // Clone extractelement here, since it is associated with another inst.
  518. // Otherwise it will be added to our Gather, and after the incoming
  519. // instruction is processed, it will be replaced without updating our
  520. // Gather entry. This dead instruction will be accessed by finish(),
  521. // causing assert or crash.
  522. Res[I] = IRBuilder<>(SVI.getNextNode()).Insert(EA->clone());
  523. }
  524. // HLSL Change Ends
  525. }
  526. gather(&SVI, Res);
  527. return true;
  528. }
  529. bool Scalarizer::visitPHINode(PHINode &PHI) {
  530. VectorType *VT = dyn_cast<VectorType>(PHI.getType());
  531. if (!VT)
  532. return false;
  533. unsigned NumElems = VT->getNumElements();
  534. IRBuilder<> Builder(PHI.getParent(), &PHI);
  535. ValueVector Res;
  536. Res.resize(NumElems);
  537. unsigned NumOps = PHI.getNumOperands();
  538. for (unsigned I = 0; I < NumElems; ++I)
  539. Res[I] = Builder.CreatePHI(VT->getElementType(), NumOps,
  540. PHI.getName() + ".i" + Twine(I));
  541. for (unsigned I = 0; I < NumOps; ++I) {
  542. Scatterer Op = scatter(&PHI, PHI.getIncomingValue(I));
  543. BasicBlock *IncomingBlock = PHI.getIncomingBlock(I);
  544. for (unsigned J = 0; J < NumElems; ++J)
  545. cast<PHINode>(Res[J])->addIncoming(Op[J], IncomingBlock);
  546. }
  547. gather(&PHI, Res);
  548. return true;
  549. }
  550. bool Scalarizer::visitLoadInst(LoadInst &LI) {
  551. if (!ScalarizeLoadStore)
  552. return false;
  553. if (!LI.isSimple())
  554. return false;
  555. VectorLayout Layout;
  556. if (!getVectorLayout(LI.getType(), LI.getAlignment(), Layout,
  557. LI.getModule()->getDataLayout()))
  558. return false;
  559. unsigned NumElems = Layout.VecTy->getNumElements();
  560. IRBuilder<> Builder(LI.getParent(), &LI);
  561. Scatterer Ptr = scatter(&LI, LI.getPointerOperand());
  562. ValueVector Res;
  563. Res.resize(NumElems);
  564. for (unsigned I = 0; I < NumElems; ++I)
  565. Res[I] = Builder.CreateAlignedLoad(Ptr[I], Layout.getElemAlign(I),
  566. LI.getName() + ".i" + Twine(I));
  567. gather(&LI, Res);
  568. return true;
  569. }
  570. bool Scalarizer::visitStoreInst(StoreInst &SI) {
  571. if (!ScalarizeLoadStore)
  572. return false;
  573. if (!SI.isSimple())
  574. return false;
  575. VectorLayout Layout;
  576. Value *FullValue = SI.getValueOperand();
  577. if (!getVectorLayout(FullValue->getType(), SI.getAlignment(), Layout,
  578. SI.getModule()->getDataLayout()))
  579. return false;
  580. unsigned NumElems = Layout.VecTy->getNumElements();
  581. IRBuilder<> Builder(SI.getParent(), &SI);
  582. Scatterer Ptr = scatter(&SI, SI.getPointerOperand());
  583. Scatterer Val = scatter(&SI, FullValue);
  584. ValueVector Stores;
  585. Stores.resize(NumElems);
  586. for (unsigned I = 0; I < NumElems; ++I) {
  587. unsigned Align = Layout.getElemAlign(I);
  588. Stores[I] = Builder.CreateAlignedStore(Val[I], Ptr[I], Align);
  589. }
  590. transferMetadata(&SI, Stores);
  591. return true;
  592. }
  593. // Delete the instructions that we scalarized. If a full vector result
  594. // is still needed, recreate it using InsertElements.
  595. bool Scalarizer::finish() {
  596. if (Gathered.empty())
  597. return false;
  598. // HLSL Change Begins.
  599. // Map from an extract element inst to a Value which replaced it.
  600. DenseMap<Instruction *, Value*> EltMap;
  601. // HLSL Change Ends.
  602. for (GatherList::iterator GMI = Gathered.begin(), GME = Gathered.end();
  603. GMI != GME; ++GMI) {
  604. Instruction *Op = GMI->first;
  605. ValueVector &CV = *GMI->second;
  606. if (!Op->use_empty()) {
  607. // HLSL Change Begins.
  608. // Remove the extract element users if possible.
  609. for (auto UI = Op->user_begin(); UI != Op->user_end(); ) {
  610. if (ExtractElementInst *EEI = dyn_cast<ExtractElementInst>(*(UI++))) {
  611. Value *Idx = EEI->getIndexOperand();
  612. if (!isa<ConstantInt>(Idx))
  613. continue;
  614. unsigned immIdx = cast<ConstantInt>(Idx)->getLimitedValue();
  615. if (immIdx >= CV.size())
  616. continue;
  617. Value *Elt = CV[immIdx];
  618. // Try to find a map for Elt,if it's in EltMap.
  619. while (Instruction *EltI = dyn_cast<Instruction>(Elt)) {
  620. if (EltMap.count(EltI)) {
  621. Elt = EltMap[EltI];
  622. } else
  623. break;
  624. }
  625. EEI->replaceAllUsesWith(Elt);
  626. EltMap[EEI] = Elt;
  627. }
  628. }
  629. if (Op->use_empty()) {
  630. Op->eraseFromParent();
  631. continue;
  632. }
  633. // HLSL Change Ends.
  634. // The value is still needed, so recreate it using a series of
  635. // InsertElements.
  636. Type *Ty = Op->getType();
  637. Value *Res = UndefValue::get(Ty);
  638. BasicBlock *BB = Op->getParent();
  639. unsigned Count = Ty->getVectorNumElements();
  640. IRBuilder<> Builder(BB, Op);
  641. if (isa<PHINode>(Op))
  642. Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
  643. for (unsigned I = 0; I < Count; ++I)
  644. Res = Builder.CreateInsertElement(Res, CV[I], Builder.getInt32(I),
  645. Op->getName() + ".upto" + Twine(I));
  646. Res->takeName(Op);
  647. Op->replaceAllUsesWith(Res);
  648. }
  649. Op->eraseFromParent();
  650. }
  651. // HLSL Change Begins.
  652. for (auto It: EltMap) {
  653. Instruction *I = It.first;
  654. if (I->user_empty())
  655. I->eraseFromParent();
  656. }
  657. // HLSL Change Ends.
  658. Gathered.clear();
  659. Scattered.clear();
  660. return true;
  661. }
  662. FunctionPass *llvm::createScalarizerPass() {
  663. return new Scalarizer();
  664. }