Scalarizer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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 = cast<Instruction>(SV[I]);
  285. CV[I]->takeName(Old);
  286. Old->replaceAllUsesWith(CV[I]);
  287. Old->eraseFromParent();
  288. }
  289. }
  290. SV = CV;
  291. Gathered.push_back(GatherList::value_type(Op, &SV));
  292. }
  293. // Return true if it is safe to transfer the given metadata tag from
  294. // vector to scalar instructions.
  295. bool Scalarizer::canTransferMetadata(unsigned Tag) {
  296. return (Tag == LLVMContext::MD_tbaa
  297. || Tag == LLVMContext::MD_fpmath
  298. || Tag == LLVMContext::MD_tbaa_struct
  299. || Tag == LLVMContext::MD_invariant_load
  300. || Tag == LLVMContext::MD_alias_scope
  301. || Tag == LLVMContext::MD_noalias
  302. || Tag == ParallelLoopAccessMDKind);
  303. }
  304. // Transfer metadata from Op to the instructions in CV if it is known
  305. // to be safe to do so.
  306. void Scalarizer::transferMetadata(Instruction *Op, const ValueVector &CV) {
  307. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  308. Op->getAllMetadataOtherThanDebugLoc(MDs);
  309. for (unsigned I = 0, E = CV.size(); I != E; ++I) {
  310. if (Instruction *New = dyn_cast<Instruction>(CV[I])) {
  311. for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
  312. MI = MDs.begin(),
  313. ME = MDs.end();
  314. MI != ME; ++MI)
  315. if (canTransferMetadata(MI->first))
  316. New->setMetadata(MI->first, MI->second);
  317. New->setDebugLoc(Op->getDebugLoc());
  318. }
  319. }
  320. }
  321. // Try to fill in Layout from Ty, returning true on success. Alignment is
  322. // the alignment of the vector, or 0 if the ABI default should be used.
  323. bool Scalarizer::getVectorLayout(Type *Ty, unsigned Alignment,
  324. VectorLayout &Layout, const DataLayout &DL) {
  325. // Make sure we're dealing with a vector.
  326. Layout.VecTy = dyn_cast<VectorType>(Ty);
  327. if (!Layout.VecTy)
  328. return false;
  329. // Check that we're dealing with full-byte elements.
  330. Layout.ElemTy = Layout.VecTy->getElementType();
  331. if (DL.getTypeSizeInBits(Layout.ElemTy) !=
  332. DL.getTypeStoreSizeInBits(Layout.ElemTy))
  333. return false;
  334. if (Alignment)
  335. Layout.VecAlign = Alignment;
  336. else
  337. Layout.VecAlign = DL.getABITypeAlignment(Layout.VecTy);
  338. Layout.ElemSize = DL.getTypeStoreSize(Layout.ElemTy);
  339. return true;
  340. }
  341. // Scalarize two-operand instruction I, using Split(Builder, X, Y, Name)
  342. // to create an instruction like I with operands X and Y and name Name.
  343. template<typename Splitter>
  344. bool Scalarizer::splitBinary(Instruction &I, const Splitter &Split) {
  345. VectorType *VT = dyn_cast<VectorType>(I.getType());
  346. if (!VT)
  347. return false;
  348. unsigned NumElems = VT->getNumElements();
  349. IRBuilder<> Builder(I.getParent(), &I);
  350. Scatterer Op0 = scatter(&I, I.getOperand(0));
  351. Scatterer Op1 = scatter(&I, I.getOperand(1));
  352. assert(Op0.size() == NumElems && "Mismatched binary operation");
  353. assert(Op1.size() == NumElems && "Mismatched binary operation");
  354. ValueVector Res;
  355. Res.resize(NumElems);
  356. for (unsigned Elem = 0; Elem < NumElems; ++Elem)
  357. Res[Elem] = Split(Builder, Op0[Elem], Op1[Elem],
  358. I.getName() + ".i" + Twine(Elem));
  359. gather(&I, Res);
  360. return true;
  361. }
  362. bool Scalarizer::visitSelectInst(SelectInst &SI) {
  363. VectorType *VT = dyn_cast<VectorType>(SI.getType());
  364. if (!VT)
  365. return false;
  366. unsigned NumElems = VT->getNumElements();
  367. IRBuilder<> Builder(SI.getParent(), &SI);
  368. Scatterer Op1 = scatter(&SI, SI.getOperand(1));
  369. Scatterer Op2 = scatter(&SI, SI.getOperand(2));
  370. assert(Op1.size() == NumElems && "Mismatched select");
  371. assert(Op2.size() == NumElems && "Mismatched select");
  372. ValueVector Res;
  373. Res.resize(NumElems);
  374. if (SI.getOperand(0)->getType()->isVectorTy()) {
  375. Scatterer Op0 = scatter(&SI, SI.getOperand(0));
  376. assert(Op0.size() == NumElems && "Mismatched select");
  377. for (unsigned I = 0; I < NumElems; ++I)
  378. Res[I] = Builder.CreateSelect(Op0[I], Op1[I], Op2[I],
  379. SI.getName() + ".i" + Twine(I));
  380. } else {
  381. Value *Op0 = SI.getOperand(0);
  382. for (unsigned I = 0; I < NumElems; ++I)
  383. Res[I] = Builder.CreateSelect(Op0, Op1[I], Op2[I],
  384. SI.getName() + ".i" + Twine(I));
  385. }
  386. gather(&SI, Res);
  387. return true;
  388. }
  389. bool Scalarizer::visitICmpInst(ICmpInst &ICI) {
  390. return splitBinary(ICI, ICmpSplitter(ICI));
  391. }
  392. bool Scalarizer::visitFCmpInst(FCmpInst &FCI) {
  393. return splitBinary(FCI, FCmpSplitter(FCI));
  394. }
  395. bool Scalarizer::visitBinaryOperator(BinaryOperator &BO) {
  396. return splitBinary(BO, BinarySplitter(BO));
  397. }
  398. bool Scalarizer::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
  399. VectorType *VT = dyn_cast<VectorType>(GEPI.getType());
  400. if (!VT)
  401. return false;
  402. IRBuilder<> Builder(GEPI.getParent(), &GEPI);
  403. unsigned NumElems = VT->getNumElements();
  404. unsigned NumIndices = GEPI.getNumIndices();
  405. Scatterer Base = scatter(&GEPI, GEPI.getOperand(0));
  406. SmallVector<Scatterer, 8> Ops;
  407. Ops.resize(NumIndices);
  408. for (unsigned I = 0; I < NumIndices; ++I)
  409. Ops[I] = scatter(&GEPI, GEPI.getOperand(I + 1));
  410. ValueVector Res;
  411. Res.resize(NumElems);
  412. for (unsigned I = 0; I < NumElems; ++I) {
  413. SmallVector<Value *, 8> Indices;
  414. Indices.resize(NumIndices);
  415. for (unsigned J = 0; J < NumIndices; ++J)
  416. Indices[J] = Ops[J][I];
  417. Res[I] = Builder.CreateGEP(GEPI.getSourceElementType(), Base[I], Indices,
  418. GEPI.getName() + ".i" + Twine(I));
  419. if (GEPI.isInBounds())
  420. if (GetElementPtrInst *NewGEPI = dyn_cast<GetElementPtrInst>(Res[I]))
  421. NewGEPI->setIsInBounds();
  422. }
  423. gather(&GEPI, Res);
  424. return true;
  425. }
  426. bool Scalarizer::visitCastInst(CastInst &CI) {
  427. VectorType *VT = dyn_cast<VectorType>(CI.getDestTy());
  428. if (!VT)
  429. return false;
  430. unsigned NumElems = VT->getNumElements();
  431. IRBuilder<> Builder(CI.getParent(), &CI);
  432. Scatterer Op0 = scatter(&CI, CI.getOperand(0));
  433. assert(Op0.size() == NumElems && "Mismatched cast");
  434. ValueVector Res;
  435. Res.resize(NumElems);
  436. for (unsigned I = 0; I < NumElems; ++I)
  437. Res[I] = Builder.CreateCast(CI.getOpcode(), Op0[I], VT->getElementType(),
  438. CI.getName() + ".i" + Twine(I));
  439. gather(&CI, Res);
  440. return true;
  441. }
  442. bool Scalarizer::visitBitCastInst(BitCastInst &BCI) {
  443. VectorType *DstVT = dyn_cast<VectorType>(BCI.getDestTy());
  444. VectorType *SrcVT = dyn_cast<VectorType>(BCI.getSrcTy());
  445. if (!DstVT || !SrcVT)
  446. return false;
  447. unsigned DstNumElems = DstVT->getNumElements();
  448. unsigned SrcNumElems = SrcVT->getNumElements();
  449. IRBuilder<> Builder(BCI.getParent(), &BCI);
  450. Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
  451. ValueVector Res;
  452. Res.resize(DstNumElems);
  453. if (DstNumElems == SrcNumElems) {
  454. for (unsigned I = 0; I < DstNumElems; ++I)
  455. Res[I] = Builder.CreateBitCast(Op0[I], DstVT->getElementType(),
  456. BCI.getName() + ".i" + Twine(I));
  457. } else if (DstNumElems > SrcNumElems) {
  458. // <M x t1> -> <N*M x t2>. Convert each t1 to <N x t2> and copy the
  459. // individual elements to the destination.
  460. unsigned FanOut = DstNumElems / SrcNumElems;
  461. Type *MidTy = VectorType::get(DstVT->getElementType(), FanOut);
  462. unsigned ResI = 0;
  463. for (unsigned Op0I = 0; Op0I < SrcNumElems; ++Op0I) {
  464. Value *V = Op0[Op0I];
  465. Instruction *VI;
  466. // Look through any existing bitcasts before converting to <N x t2>.
  467. // In the best case, the resulting conversion might be a no-op.
  468. while ((VI = dyn_cast<Instruction>(V)) &&
  469. VI->getOpcode() == Instruction::BitCast)
  470. V = VI->getOperand(0);
  471. V = Builder.CreateBitCast(V, MidTy, V->getName() + ".cast");
  472. Scatterer Mid = scatter(&BCI, V);
  473. for (unsigned MidI = 0; MidI < FanOut; ++MidI)
  474. Res[ResI++] = Mid[MidI];
  475. }
  476. } else {
  477. // <N*M x t1> -> <M x t2>. Convert each group of <N x t1> into a t2.
  478. unsigned FanIn = SrcNumElems / DstNumElems;
  479. Type *MidTy = VectorType::get(SrcVT->getElementType(), FanIn);
  480. unsigned Op0I = 0;
  481. for (unsigned ResI = 0; ResI < DstNumElems; ++ResI) {
  482. Value *V = UndefValue::get(MidTy);
  483. for (unsigned MidI = 0; MidI < FanIn; ++MidI)
  484. V = Builder.CreateInsertElement(V, Op0[Op0I++], Builder.getInt32(MidI),
  485. BCI.getName() + ".i" + Twine(ResI)
  486. + ".upto" + Twine(MidI));
  487. Res[ResI] = Builder.CreateBitCast(V, DstVT->getElementType(),
  488. BCI.getName() + ".i" + Twine(ResI));
  489. }
  490. }
  491. gather(&BCI, Res);
  492. return true;
  493. }
  494. bool Scalarizer::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
  495. VectorType *VT = dyn_cast<VectorType>(SVI.getType());
  496. if (!VT)
  497. return false;
  498. unsigned NumElems = VT->getNumElements();
  499. Scatterer Op0 = scatter(&SVI, SVI.getOperand(0));
  500. Scatterer Op1 = scatter(&SVI, SVI.getOperand(1));
  501. ValueVector Res;
  502. Res.resize(NumElems);
  503. for (unsigned I = 0; I < NumElems; ++I) {
  504. int Selector = SVI.getMaskValue(I);
  505. if (Selector < 0)
  506. Res[I] = UndefValue::get(VT->getElementType());
  507. else if (unsigned(Selector) < Op0.size())
  508. Res[I] = Op0[Selector];
  509. else
  510. Res[I] = Op1[Selector - Op0.size()];
  511. }
  512. gather(&SVI, Res);
  513. return true;
  514. }
  515. bool Scalarizer::visitPHINode(PHINode &PHI) {
  516. VectorType *VT = dyn_cast<VectorType>(PHI.getType());
  517. if (!VT)
  518. return false;
  519. unsigned NumElems = VT->getNumElements();
  520. IRBuilder<> Builder(PHI.getParent(), &PHI);
  521. ValueVector Res;
  522. Res.resize(NumElems);
  523. unsigned NumOps = PHI.getNumOperands();
  524. for (unsigned I = 0; I < NumElems; ++I)
  525. Res[I] = Builder.CreatePHI(VT->getElementType(), NumOps,
  526. PHI.getName() + ".i" + Twine(I));
  527. for (unsigned I = 0; I < NumOps; ++I) {
  528. Scatterer Op = scatter(&PHI, PHI.getIncomingValue(I));
  529. BasicBlock *IncomingBlock = PHI.getIncomingBlock(I);
  530. for (unsigned J = 0; J < NumElems; ++J)
  531. cast<PHINode>(Res[J])->addIncoming(Op[J], IncomingBlock);
  532. }
  533. gather(&PHI, Res);
  534. return true;
  535. }
  536. bool Scalarizer::visitLoadInst(LoadInst &LI) {
  537. if (!ScalarizeLoadStore)
  538. return false;
  539. if (!LI.isSimple())
  540. return false;
  541. VectorLayout Layout;
  542. if (!getVectorLayout(LI.getType(), LI.getAlignment(), Layout,
  543. LI.getModule()->getDataLayout()))
  544. return false;
  545. unsigned NumElems = Layout.VecTy->getNumElements();
  546. IRBuilder<> Builder(LI.getParent(), &LI);
  547. Scatterer Ptr = scatter(&LI, LI.getPointerOperand());
  548. ValueVector Res;
  549. Res.resize(NumElems);
  550. for (unsigned I = 0; I < NumElems; ++I)
  551. Res[I] = Builder.CreateAlignedLoad(Ptr[I], Layout.getElemAlign(I),
  552. LI.getName() + ".i" + Twine(I));
  553. gather(&LI, Res);
  554. return true;
  555. }
  556. bool Scalarizer::visitStoreInst(StoreInst &SI) {
  557. if (!ScalarizeLoadStore)
  558. return false;
  559. if (!SI.isSimple())
  560. return false;
  561. VectorLayout Layout;
  562. Value *FullValue = SI.getValueOperand();
  563. if (!getVectorLayout(FullValue->getType(), SI.getAlignment(), Layout,
  564. SI.getModule()->getDataLayout()))
  565. return false;
  566. unsigned NumElems = Layout.VecTy->getNumElements();
  567. IRBuilder<> Builder(SI.getParent(), &SI);
  568. Scatterer Ptr = scatter(&SI, SI.getPointerOperand());
  569. Scatterer Val = scatter(&SI, FullValue);
  570. ValueVector Stores;
  571. Stores.resize(NumElems);
  572. for (unsigned I = 0; I < NumElems; ++I) {
  573. unsigned Align = Layout.getElemAlign(I);
  574. Stores[I] = Builder.CreateAlignedStore(Val[I], Ptr[I], Align);
  575. }
  576. transferMetadata(&SI, Stores);
  577. return true;
  578. }
  579. // Delete the instructions that we scalarized. If a full vector result
  580. // is still needed, recreate it using InsertElements.
  581. bool Scalarizer::finish() {
  582. if (Gathered.empty())
  583. return false;
  584. // HLSL Change Begins.
  585. // Map from an extract element inst to a Value which replaced it.
  586. DenseMap<Instruction *, Value*> EltMap;
  587. // HLSL Change Ends.
  588. for (GatherList::iterator GMI = Gathered.begin(), GME = Gathered.end();
  589. GMI != GME; ++GMI) {
  590. Instruction *Op = GMI->first;
  591. ValueVector &CV = *GMI->second;
  592. if (!Op->use_empty()) {
  593. // HLSL Change Begins.
  594. // Remove the extract element users if possible.
  595. for (auto UI = Op->user_begin(); UI != Op->user_end(); ) {
  596. if (ExtractElementInst *EEI = dyn_cast<ExtractElementInst>(*(UI++))) {
  597. Value *Idx = EEI->getIndexOperand();
  598. if (!isa<ConstantInt>(Idx))
  599. continue;
  600. unsigned immIdx = cast<ConstantInt>(Idx)->getLimitedValue();
  601. if (immIdx >= CV.size())
  602. continue;
  603. Value *Elt = CV[immIdx];
  604. // Try to find a map for Elt,if it's in EltMap.
  605. while (Instruction *EltI = dyn_cast<Instruction>(Elt)) {
  606. if (EltMap.count(EltI)) {
  607. Elt = EltMap[EltI];
  608. } else
  609. break;
  610. }
  611. EEI->replaceAllUsesWith(Elt);
  612. EltMap[EEI] = Elt;
  613. }
  614. }
  615. if (Op->use_empty()) {
  616. Op->eraseFromParent();
  617. continue;
  618. }
  619. // HLSL Change Ends.
  620. // The value is still needed, so recreate it using a series of
  621. // InsertElements.
  622. Type *Ty = Op->getType();
  623. Value *Res = UndefValue::get(Ty);
  624. BasicBlock *BB = Op->getParent();
  625. unsigned Count = Ty->getVectorNumElements();
  626. IRBuilder<> Builder(BB, Op);
  627. if (isa<PHINode>(Op))
  628. Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
  629. for (unsigned I = 0; I < Count; ++I)
  630. Res = Builder.CreateInsertElement(Res, CV[I], Builder.getInt32(I),
  631. Op->getName() + ".upto" + Twine(I));
  632. Res->takeName(Op);
  633. Op->replaceAllUsesWith(Res);
  634. }
  635. Op->eraseFromParent();
  636. }
  637. // HLSL Change Begins.
  638. for (auto It: EltMap) {
  639. Instruction *I = It.first;
  640. if (I->user_empty())
  641. I->eraseFromParent();
  642. }
  643. // HLSL Change Ends.
  644. Gathered.clear();
  645. Scattered.clear();
  646. return true;
  647. }
  648. FunctionPass *llvm::createScalarizerPass() {
  649. return new Scalarizer();
  650. }