Scalarizer.cpp 24 KB

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