LoopIdiomRecognize.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
  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 implements an idiom recognizer that transforms simple loops into a
  11. // non-loop form. In cases that this kicks in, it can be a significant
  12. // performance win.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. //
  16. // TODO List:
  17. //
  18. // Future loop memory idioms to recognize:
  19. // memcmp, memmove, strlen, etc.
  20. // Future floating point idioms to recognize in -ffast-math mode:
  21. // fpowi
  22. // Future integer operation idioms to recognize:
  23. // ctpop, ctlz, cttz
  24. //
  25. // Beware that isel's default lowering for ctpop is highly inefficient for
  26. // i64 and larger types when i64 is legal and the value has few bits set. It
  27. // would be good to enhance isel to emit a loop for ctpop in this case.
  28. //
  29. // We should enhance the memset/memcpy recognition to handle multiple stores in
  30. // the loop. This would handle things like:
  31. // void foo(_Complex float *P)
  32. // for (i) { __real__(*P) = 0; __imag__(*P) = 0; }
  33. //
  34. // We should enhance this to handle negative strides through memory.
  35. // Alternatively (and perhaps better) we could rely on an earlier pass to force
  36. // forward iteration through memory, which is generally better for cache
  37. // behavior. Negative strides *do* happen for memset/memcpy loops.
  38. //
  39. // This could recognize common matrix multiplies and dot product idioms and
  40. // replace them with calls to BLAS (if linked in??).
  41. //
  42. //===----------------------------------------------------------------------===//
  43. #include "llvm/Transforms/Scalar.h"
  44. #include "llvm/ADT/Statistic.h"
  45. #include "llvm/Analysis/AliasAnalysis.h"
  46. #include "llvm/Analysis/LoopPass.h"
  47. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  48. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  49. #include "llvm/Analysis/TargetLibraryInfo.h"
  50. #include "llvm/Analysis/TargetTransformInfo.h"
  51. #include "llvm/Analysis/ValueTracking.h"
  52. #include "llvm/IR/DataLayout.h"
  53. #include "llvm/IR/Dominators.h"
  54. #include "llvm/IR/IRBuilder.h"
  55. #include "llvm/IR/IntrinsicInst.h"
  56. #include "llvm/IR/Module.h"
  57. #include "llvm/Support/Debug.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #include "llvm/Transforms/Utils/Local.h"
  60. using namespace llvm;
  61. #define DEBUG_TYPE "loop-idiom"
  62. STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
  63. STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
  64. namespace {
  65. class LoopIdiomRecognize;
  66. /// This class defines some utility functions for loop idiom recognization.
  67. class LIRUtil {
  68. public:
  69. /// Return true iff the block contains nothing but an uncondition branch
  70. /// (aka goto instruction).
  71. static bool isAlmostEmpty(BasicBlock *);
  72. static BranchInst *getBranch(BasicBlock *BB) {
  73. return dyn_cast<BranchInst>(BB->getTerminator());
  74. }
  75. /// Derive the precondition block (i.e the block that guards the loop
  76. /// preheader) from the given preheader.
  77. static BasicBlock *getPrecondBb(BasicBlock *PreHead);
  78. };
  79. /// This class is to recoginize idioms of population-count conducted in
  80. /// a noncountable loop. Currently it only recognizes this pattern:
  81. /// \code
  82. /// while(x) {cnt++; ...; x &= x - 1; ...}
  83. /// \endcode
  84. class NclPopcountRecognize {
  85. LoopIdiomRecognize &LIR;
  86. Loop *CurLoop;
  87. BasicBlock *PreCondBB;
  88. typedef IRBuilder<> IRBuilderTy;
  89. public:
  90. explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
  91. bool recognize();
  92. private:
  93. /// Take a glimpse of the loop to see if we need to go ahead recoginizing
  94. /// the idiom.
  95. bool preliminaryScreen();
  96. /// Check if the given conditional branch is based on the comparison
  97. /// between a variable and zero, and if the variable is non-zero, the
  98. /// control yields to the loop entry. If the branch matches the behavior,
  99. /// the variable involved in the comparion is returned. This function will
  100. /// be called to see if the precondition and postcondition of the loop
  101. /// are in desirable form.
  102. Value *matchCondition(BranchInst *Br, BasicBlock *NonZeroTarget) const;
  103. /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
  104. /// is set to the instruction counting the population bit. 2) \p CntPhi
  105. /// is set to the corresponding phi node. 3) \p Var is set to the value
  106. /// whose population bits are being counted.
  107. bool detectIdiom
  108. (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
  109. /// Insert ctpop intrinsic function and some obviously dead instructions.
  110. void transform(Instruction *CntInst, PHINode *CntPhi, Value *Var);
  111. /// Create llvm.ctpop.* intrinsic function.
  112. CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
  113. };
  114. class LoopIdiomRecognize : public LoopPass {
  115. Loop *CurLoop;
  116. DominatorTree *DT;
  117. ScalarEvolution *SE;
  118. TargetLibraryInfo *TLI;
  119. const TargetTransformInfo *TTI;
  120. public:
  121. static char ID;
  122. explicit LoopIdiomRecognize() : LoopPass(ID) {
  123. initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
  124. DT = nullptr;
  125. SE = nullptr;
  126. TLI = nullptr;
  127. TTI = nullptr;
  128. }
  129. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  130. bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
  131. SmallVectorImpl<BasicBlock*> &ExitBlocks);
  132. bool processLoopStore(StoreInst *SI, const SCEV *BECount);
  133. bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
  134. bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
  135. unsigned StoreAlignment,
  136. Value *SplatValue, Instruction *TheStore,
  137. const SCEVAddRecExpr *Ev,
  138. const SCEV *BECount);
  139. bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
  140. const SCEVAddRecExpr *StoreEv,
  141. const SCEVAddRecExpr *LoadEv,
  142. const SCEV *BECount);
  143. /// This transformation requires natural loop information & requires that
  144. /// loop preheaders be inserted into the CFG.
  145. ///
  146. void getAnalysisUsage(AnalysisUsage &AU) const override {
  147. AU.addRequired<LoopInfoWrapperPass>();
  148. AU.addPreserved<LoopInfoWrapperPass>();
  149. AU.addRequiredID(LoopSimplifyID);
  150. AU.addPreservedID(LoopSimplifyID);
  151. AU.addRequiredID(LCSSAID);
  152. AU.addPreservedID(LCSSAID);
  153. AU.addRequired<AliasAnalysis>();
  154. AU.addPreserved<AliasAnalysis>();
  155. AU.addRequired<ScalarEvolution>();
  156. AU.addPreserved<ScalarEvolution>();
  157. AU.addPreserved<DominatorTreeWrapperPass>();
  158. AU.addRequired<DominatorTreeWrapperPass>();
  159. AU.addRequired<TargetLibraryInfoWrapperPass>();
  160. AU.addRequired<TargetTransformInfoWrapperPass>();
  161. }
  162. DominatorTree *getDominatorTree() {
  163. return DT ? DT
  164. : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
  165. }
  166. ScalarEvolution *getScalarEvolution() {
  167. return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
  168. }
  169. TargetLibraryInfo *getTargetLibraryInfo() {
  170. if (!TLI)
  171. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  172. return TLI;
  173. }
  174. const TargetTransformInfo *getTargetTransformInfo() {
  175. return TTI ? TTI
  176. : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  177. *CurLoop->getHeader()->getParent()));
  178. }
  179. Loop *getLoop() const { return CurLoop; }
  180. private:
  181. bool runOnNoncountableLoop();
  182. bool runOnCountableLoop();
  183. };
  184. }
  185. char LoopIdiomRecognize::ID = 0;
  186. INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
  187. false, false)
  188. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  189. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  190. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  191. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  192. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  193. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  194. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  195. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  196. INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
  197. false, false)
  198. Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
  199. /// deleteDeadInstruction - Delete this instruction. Before we do, go through
  200. /// and zero out all the operands of this instruction. If any of them become
  201. /// dead, delete them and the computation tree that feeds them.
  202. ///
  203. static void deleteDeadInstruction(Instruction *I,
  204. const TargetLibraryInfo *TLI) {
  205. SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
  206. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  207. I->eraseFromParent();
  208. for (Value *Op : Operands)
  209. RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
  210. }
  211. //===----------------------------------------------------------------------===//
  212. //
  213. // Implementation of LIRUtil
  214. //
  215. //===----------------------------------------------------------------------===//
  216. // This function will return true iff the given block contains nothing but goto.
  217. // A typical usage of this function is to check if the preheader function is
  218. // "almost" empty such that generated intrinsic functions can be moved across
  219. // the preheader and be placed at the end of the precondition block without
  220. // the concern of breaking data dependence.
  221. bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
  222. if (BranchInst *Br = getBranch(BB)) {
  223. return Br->isUnconditional() && Br == BB->begin();
  224. }
  225. return false;
  226. }
  227. BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
  228. if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
  229. BranchInst *Br = getBranch(BB);
  230. return Br && Br->isConditional() ? BB : nullptr;
  231. }
  232. return nullptr;
  233. }
  234. //===----------------------------------------------------------------------===//
  235. //
  236. // Implementation of NclPopcountRecognize
  237. //
  238. //===----------------------------------------------------------------------===//
  239. NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
  240. LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {
  241. }
  242. bool NclPopcountRecognize::preliminaryScreen() {
  243. const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
  244. if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
  245. return false;
  246. // Counting population are usually conducted by few arithmetic instructions.
  247. // Such instructions can be easilly "absorbed" by vacant slots in a
  248. // non-compact loop. Therefore, recognizing popcount idiom only makes sense
  249. // in a compact loop.
  250. // Give up if the loop has multiple blocks or multiple backedges.
  251. if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
  252. return false;
  253. BasicBlock *LoopBody = *(CurLoop->block_begin());
  254. if (LoopBody->size() >= 20) {
  255. // The loop is too big, bail out.
  256. return false;
  257. }
  258. // It should have a preheader containing nothing but a goto instruction.
  259. BasicBlock *PreHead = CurLoop->getLoopPreheader();
  260. if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
  261. return false;
  262. // It should have a precondition block where the generated popcount instrinsic
  263. // function will be inserted.
  264. PreCondBB = LIRUtil::getPrecondBb(PreHead);
  265. if (!PreCondBB)
  266. return false;
  267. return true;
  268. }
  269. Value *NclPopcountRecognize::matchCondition(BranchInst *Br,
  270. BasicBlock *LoopEntry) const {
  271. if (!Br || !Br->isConditional())
  272. return nullptr;
  273. ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
  274. if (!Cond)
  275. return nullptr;
  276. ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
  277. if (!CmpZero || !CmpZero->isZero())
  278. return nullptr;
  279. ICmpInst::Predicate Pred = Cond->getPredicate();
  280. if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
  281. (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
  282. return Cond->getOperand(0);
  283. return nullptr;
  284. }
  285. bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
  286. PHINode *&CntPhi,
  287. Value *&Var) const {
  288. // Following code tries to detect this idiom:
  289. //
  290. // if (x0 != 0)
  291. // goto loop-exit // the precondition of the loop
  292. // cnt0 = init-val;
  293. // do {
  294. // x1 = phi (x0, x2);
  295. // cnt1 = phi(cnt0, cnt2);
  296. //
  297. // cnt2 = cnt1 + 1;
  298. // ...
  299. // x2 = x1 & (x1 - 1);
  300. // ...
  301. // } while(x != 0);
  302. //
  303. // loop-exit:
  304. //
  305. // step 1: Check to see if the look-back branch match this pattern:
  306. // "if (a!=0) goto loop-entry".
  307. BasicBlock *LoopEntry;
  308. Instruction *DefX2, *CountInst;
  309. Value *VarX1, *VarX0;
  310. PHINode *PhiX, *CountPhi;
  311. DefX2 = CountInst = nullptr;
  312. VarX1 = VarX0 = nullptr;
  313. PhiX = CountPhi = nullptr;
  314. LoopEntry = *(CurLoop->block_begin());
  315. // step 1: Check if the loop-back branch is in desirable form.
  316. {
  317. if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
  318. DefX2 = dyn_cast<Instruction>(T);
  319. else
  320. return false;
  321. }
  322. // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
  323. {
  324. if (!DefX2 || DefX2->getOpcode() != Instruction::And)
  325. return false;
  326. BinaryOperator *SubOneOp;
  327. if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
  328. VarX1 = DefX2->getOperand(1);
  329. else {
  330. VarX1 = DefX2->getOperand(0);
  331. SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
  332. }
  333. if (!SubOneOp)
  334. return false;
  335. Instruction *SubInst = cast<Instruction>(SubOneOp);
  336. ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
  337. if (!Dec ||
  338. !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
  339. (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
  340. return false;
  341. }
  342. }
  343. // step 3: Check the recurrence of variable X
  344. {
  345. PhiX = dyn_cast<PHINode>(VarX1);
  346. if (!PhiX ||
  347. (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
  348. return false;
  349. }
  350. }
  351. // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
  352. {
  353. CountInst = nullptr;
  354. for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
  355. IterE = LoopEntry->end(); Iter != IterE; Iter++) {
  356. Instruction *Inst = Iter;
  357. if (Inst->getOpcode() != Instruction::Add)
  358. continue;
  359. ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
  360. if (!Inc || !Inc->isOne())
  361. continue;
  362. PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
  363. if (!Phi || Phi->getParent() != LoopEntry)
  364. continue;
  365. // Check if the result of the instruction is live of the loop.
  366. bool LiveOutLoop = false;
  367. for (User *U : Inst->users()) {
  368. if ((cast<Instruction>(U))->getParent() != LoopEntry) {
  369. LiveOutLoop = true; break;
  370. }
  371. }
  372. if (LiveOutLoop) {
  373. CountInst = Inst;
  374. CountPhi = Phi;
  375. break;
  376. }
  377. }
  378. if (!CountInst)
  379. return false;
  380. }
  381. // step 5: check if the precondition is in this form:
  382. // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
  383. {
  384. BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
  385. Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
  386. if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
  387. return false;
  388. CntInst = CountInst;
  389. CntPhi = CountPhi;
  390. Var = T;
  391. }
  392. return true;
  393. }
  394. void NclPopcountRecognize::transform(Instruction *CntInst,
  395. PHINode *CntPhi, Value *Var) {
  396. ScalarEvolution *SE = LIR.getScalarEvolution();
  397. TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
  398. BasicBlock *PreHead = CurLoop->getLoopPreheader();
  399. BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
  400. const DebugLoc DL = CntInst->getDebugLoc();
  401. // Assuming before transformation, the loop is following:
  402. // if (x) // the precondition
  403. // do { cnt++; x &= x - 1; } while(x);
  404. // Step 1: Insert the ctpop instruction at the end of the precondition block
  405. IRBuilderTy Builder(PreCondBr);
  406. Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
  407. {
  408. PopCnt = createPopcntIntrinsic(Builder, Var, DL);
  409. NewCount = PopCntZext =
  410. Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
  411. if (NewCount != PopCnt)
  412. (cast<Instruction>(NewCount))->setDebugLoc(DL);
  413. // TripCnt is exactly the number of iterations the loop has
  414. TripCnt = NewCount;
  415. // If the population counter's initial value is not zero, insert Add Inst.
  416. Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
  417. ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
  418. if (!InitConst || !InitConst->isZero()) {
  419. NewCount = Builder.CreateAdd(NewCount, CntInitVal);
  420. (cast<Instruction>(NewCount))->setDebugLoc(DL);
  421. }
  422. }
  423. // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
  424. // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
  425. // function would be partial dead code, and downstream passes will drag
  426. // it back from the precondition block to the preheader.
  427. {
  428. ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
  429. Value *Opnd0 = PopCntZext;
  430. Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
  431. if (PreCond->getOperand(0) != Var)
  432. std::swap(Opnd0, Opnd1);
  433. ICmpInst *NewPreCond =
  434. cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
  435. PreCondBr->setCondition(NewPreCond);
  436. RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
  437. }
  438. // Step 3: Note that the population count is exactly the trip count of the
  439. // loop in question, which enble us to to convert the loop from noncountable
  440. // loop into a countable one. The benefit is twofold:
  441. //
  442. // - If the loop only counts population, the entire loop become dead after
  443. // the transformation. It is lots easier to prove a countable loop dead
  444. // than to prove a noncountable one. (In some C dialects, a infite loop
  445. // isn't dead even if it computes nothing useful. In general, DCE needs
  446. // to prove a noncountable loop finite before safely delete it.)
  447. //
  448. // - If the loop also performs something else, it remains alive.
  449. // Since it is transformed to countable form, it can be aggressively
  450. // optimized by some optimizations which are in general not applicable
  451. // to a noncountable loop.
  452. //
  453. // After this step, this loop (conceptually) would look like following:
  454. // newcnt = __builtin_ctpop(x);
  455. // t = newcnt;
  456. // if (x)
  457. // do { cnt++; x &= x-1; t--) } while (t > 0);
  458. BasicBlock *Body = *(CurLoop->block_begin());
  459. {
  460. BranchInst *LbBr = LIRUtil::getBranch(Body);
  461. ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
  462. Type *Ty = TripCnt->getType();
  463. PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
  464. Builder.SetInsertPoint(LbCond);
  465. Value *Opnd1 = cast<Value>(TcPhi);
  466. Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
  467. Instruction *TcDec =
  468. cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
  469. TcPhi->addIncoming(TripCnt, PreHead);
  470. TcPhi->addIncoming(TcDec, Body);
  471. CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
  472. CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
  473. LbCond->setPredicate(Pred);
  474. LbCond->setOperand(0, TcDec);
  475. LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
  476. }
  477. // Step 4: All the references to the original population counter outside
  478. // the loop are replaced with the NewCount -- the value returned from
  479. // __builtin_ctpop().
  480. CntInst->replaceUsesOutsideBlock(NewCount, Body);
  481. // step 5: Forget the "non-computable" trip-count SCEV associated with the
  482. // loop. The loop would otherwise not be deleted even if it becomes empty.
  483. SE->forgetLoop(CurLoop);
  484. }
  485. CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
  486. Value *Val, DebugLoc DL) {
  487. Value *Ops[] = { Val };
  488. Type *Tys[] = { Val->getType() };
  489. Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
  490. Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
  491. CallInst *CI = IRBuilder.CreateCall(Func, Ops);
  492. CI->setDebugLoc(DL);
  493. return CI;
  494. }
  495. /// recognize - detect population count idiom in a non-countable loop. If
  496. /// detected, transform the relevant code to popcount intrinsic function
  497. /// call, and return true; otherwise, return false.
  498. bool NclPopcountRecognize::recognize() {
  499. if (!LIR.getTargetTransformInfo())
  500. return false;
  501. LIR.getScalarEvolution();
  502. if (!preliminaryScreen())
  503. return false;
  504. Instruction *CntInst;
  505. PHINode *CntPhi;
  506. Value *Val;
  507. if (!detectIdiom(CntInst, CntPhi, Val))
  508. return false;
  509. transform(CntInst, CntPhi, Val);
  510. return true;
  511. }
  512. //===----------------------------------------------------------------------===//
  513. //
  514. // Implementation of LoopIdiomRecognize
  515. //
  516. //===----------------------------------------------------------------------===//
  517. bool LoopIdiomRecognize::runOnCountableLoop() {
  518. const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
  519. assert(!isa<SCEVCouldNotCompute>(BECount) &&
  520. "runOnCountableLoop() called on a loop without a predictable"
  521. "backedge-taken count");
  522. // If this loop executes exactly one time, then it should be peeled, not
  523. // optimized by this pass.
  524. if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
  525. if (BECst->getValue()->getValue() == 0)
  526. return false;
  527. // set DT
  528. (void)getDominatorTree();
  529. LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  530. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  531. // set TLI
  532. (void)getTargetLibraryInfo();
  533. SmallVector<BasicBlock*, 8> ExitBlocks;
  534. CurLoop->getUniqueExitBlocks(ExitBlocks);
  535. DEBUG(dbgs() << "loop-idiom Scanning: F["
  536. << CurLoop->getHeader()->getParent()->getName()
  537. << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
  538. bool MadeChange = false;
  539. // Scan all the blocks in the loop that are not in subloops.
  540. for (auto *BB : CurLoop->getBlocks()) {
  541. // Ignore blocks in subloops.
  542. if (LI.getLoopFor(BB) != CurLoop)
  543. continue;
  544. MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
  545. }
  546. return MadeChange;
  547. }
  548. bool LoopIdiomRecognize::runOnNoncountableLoop() {
  549. NclPopcountRecognize Popcount(*this);
  550. if (Popcount.recognize())
  551. return true;
  552. return false;
  553. }
  554. bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
  555. if (skipOptnoneFunction(L))
  556. return false;
  557. CurLoop = L;
  558. // If the loop could not be converted to canonical form, it must have an
  559. // indirectbr in it, just give up.
  560. if (!L->getLoopPreheader())
  561. return false;
  562. // Disable loop idiom recognition if the function's name is a common idiom.
  563. StringRef Name = L->getHeader()->getParent()->getName();
  564. if (Name == "memset" || Name == "memcpy")
  565. return false;
  566. SE = &getAnalysis<ScalarEvolution>();
  567. if (SE->hasLoopInvariantBackedgeTakenCount(L))
  568. return runOnCountableLoop();
  569. return runOnNoncountableLoop();
  570. }
  571. /// runOnLoopBlock - Process the specified block, which lives in a counted loop
  572. /// with the specified backedge count. This block is known to be in the current
  573. /// loop and not in any subloops.
  574. bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
  575. SmallVectorImpl<BasicBlock*> &ExitBlocks) {
  576. // We can only promote stores in this block if they are unconditionally
  577. // executed in the loop. For a block to be unconditionally executed, it has
  578. // to dominate all the exit blocks of the loop. Verify this now.
  579. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
  580. if (!DT->dominates(BB, ExitBlocks[i]))
  581. return false;
  582. bool MadeChange = false;
  583. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
  584. Instruction *Inst = I++;
  585. // Look for store instructions, which may be optimized to memset/memcpy.
  586. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  587. WeakVH InstPtr(I);
  588. if (!processLoopStore(SI, BECount)) continue;
  589. MadeChange = true;
  590. // If processing the store invalidated our iterator, start over from the
  591. // top of the block.
  592. if (!InstPtr)
  593. I = BB->begin();
  594. continue;
  595. }
  596. // Look for memset instructions, which may be optimized to a larger memset.
  597. if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
  598. WeakVH InstPtr(I);
  599. if (!processLoopMemSet(MSI, BECount)) continue;
  600. MadeChange = true;
  601. // If processing the memset invalidated our iterator, start over from the
  602. // top of the block.
  603. if (!InstPtr)
  604. I = BB->begin();
  605. continue;
  606. }
  607. }
  608. return MadeChange;
  609. }
  610. /// processLoopStore - See if this store can be promoted to a memset or memcpy.
  611. bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
  612. if (!SI->isSimple()) return false;
  613. Value *StoredVal = SI->getValueOperand();
  614. Value *StorePtr = SI->getPointerOperand();
  615. // Reject stores that are so large that they overflow an unsigned.
  616. auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
  617. uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
  618. if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
  619. return false;
  620. // See if the pointer expression is an AddRec like {base,+,1} on the current
  621. // loop, which indicates a strided store. If we have something else, it's a
  622. // random store we can't handle.
  623. const SCEVAddRecExpr *StoreEv =
  624. dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
  625. if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
  626. return false;
  627. // Check to see if the stride matches the size of the store. If so, then we
  628. // know that every byte is touched in the loop.
  629. unsigned StoreSize = (unsigned)SizeInBits >> 3;
  630. const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
  631. if (!Stride || StoreSize != Stride->getValue()->getValue()) {
  632. // TODO: Could also handle negative stride here someday, that will require
  633. // the validity check in mayLoopAccessLocation to be updated though.
  634. // Enable this to print exact negative strides.
  635. #if 0 // HLSL Change - suppress '0 &&' warning
  636. if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
  637. dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
  638. dbgs() << "BB: " << *SI->getParent();
  639. }
  640. #endif // HLSL Change - suppress '0 &&' warning
  641. return false;
  642. }
  643. // See if we can optimize just this store in isolation.
  644. if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
  645. StoredVal, SI, StoreEv, BECount))
  646. return true;
  647. // If the stored value is a strided load in the same loop with the same stride
  648. // this this may be transformable into a memcpy. This kicks in for stuff like
  649. // for (i) A[i] = B[i];
  650. if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
  651. const SCEVAddRecExpr *LoadEv =
  652. dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
  653. if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
  654. StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
  655. if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
  656. return true;
  657. }
  658. //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
  659. return false;
  660. }
  661. /// processLoopMemSet - See if this memset can be promoted to a large memset.
  662. bool LoopIdiomRecognize::
  663. processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
  664. // We can only handle non-volatile memsets with a constant size.
  665. if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
  666. // If we're not allowed to hack on memset, we fail.
  667. if (!TLI->has(LibFunc::memset))
  668. return false;
  669. Value *Pointer = MSI->getDest();
  670. // See if the pointer expression is an AddRec like {base,+,1} on the current
  671. // loop, which indicates a strided store. If we have something else, it's a
  672. // random store we can't handle.
  673. const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
  674. if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
  675. return false;
  676. // Reject memsets that are so large that they overflow an unsigned.
  677. uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
  678. if ((SizeInBytes >> 32) != 0)
  679. return false;
  680. // Check to see if the stride matches the size of the memset. If so, then we
  681. // know that every byte is touched in the loop.
  682. const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
  683. // TODO: Could also handle negative stride here someday, that will require the
  684. // validity check in mayLoopAccessLocation to be updated though.
  685. if (!Stride || MSI->getLength() != Stride->getValue())
  686. return false;
  687. return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
  688. MSI->getAlignment(), MSI->getValue(),
  689. MSI, Ev, BECount);
  690. }
  691. /// mayLoopAccessLocation - Return true if the specified loop might access the
  692. /// specified pointer location, which is a loop-strided access. The 'Access'
  693. /// argument specifies what the verboten forms of access are (read or write).
  694. static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
  695. Loop *L, const SCEV *BECount,
  696. unsigned StoreSize, AliasAnalysis &AA,
  697. Instruction *IgnoredStore) {
  698. // Get the location that may be stored across the loop. Since the access is
  699. // strided positively through memory, we say that the modified location starts
  700. // at the pointer and has infinite size.
  701. uint64_t AccessSize = MemoryLocation::UnknownSize;
  702. // If the loop iterates a fixed number of times, we can refine the access size
  703. // to be exactly the size of the memset, which is (BECount+1)*StoreSize
  704. if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
  705. AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
  706. // TODO: For this to be really effective, we have to dive into the pointer
  707. // operand in the store. Store to &A[i] of 100 will always return may alias
  708. // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
  709. // which will then no-alias a store to &A[100].
  710. MemoryLocation StoreLoc(Ptr, AccessSize);
  711. for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
  712. ++BI)
  713. for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
  714. if (&*I != IgnoredStore &&
  715. (AA.getModRefInfo(I, StoreLoc) & Access))
  716. return true;
  717. return false;
  718. }
  719. /// getMemSetPatternValue - If a strided store of the specified value is safe to
  720. /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
  721. /// be passed in. Otherwise, return null.
  722. ///
  723. /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
  724. /// just replicate their input array and then pass on to memset_pattern16.
  725. static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
  726. // If the value isn't a constant, we can't promote it to being in a constant
  727. // array. We could theoretically do a store to an alloca or something, but
  728. // that doesn't seem worthwhile.
  729. Constant *C = dyn_cast<Constant>(V);
  730. if (!C) return nullptr;
  731. // Only handle simple values that are a power of two bytes in size.
  732. uint64_t Size = DL.getTypeSizeInBits(V->getType());
  733. if (Size == 0 || (Size & 7) || (Size & (Size-1)))
  734. return nullptr;
  735. // Don't care enough about darwin/ppc to implement this.
  736. if (DL.isBigEndian())
  737. return nullptr;
  738. // Convert to size in bytes.
  739. Size /= 8;
  740. // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
  741. // if the top and bottom are the same (e.g. for vectors and large integers).
  742. if (Size > 16) return nullptr;
  743. // If the constant is exactly 16 bytes, just use it.
  744. if (Size == 16) return C;
  745. // Otherwise, we'll use an array of the constants.
  746. unsigned ArraySize = 16/Size;
  747. ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
  748. return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
  749. }
  750. /// processLoopStridedStore - We see a strided store of some value. If we can
  751. /// transform this into a memset or memset_pattern in the loop preheader, do so.
  752. bool LoopIdiomRecognize::
  753. processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
  754. unsigned StoreAlignment, Value *StoredVal,
  755. Instruction *TheStore, const SCEVAddRecExpr *Ev,
  756. const SCEV *BECount) {
  757. // If the stored value is a byte-wise value (like i32 -1), then it may be
  758. // turned into a memset of i8 -1, assuming that all the consecutive bytes
  759. // are stored. A store of i32 0x01020304 can never be turned into a memset,
  760. // but it can be turned into memset_pattern if the target supports it.
  761. Value *SplatValue = isBytewiseValue(StoredVal);
  762. Constant *PatternValue = nullptr;
  763. auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
  764. unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
  765. // If we're allowed to form a memset, and the stored value would be acceptable
  766. // for memset, use it.
  767. if (SplatValue && TLI->has(LibFunc::memset) &&
  768. // Verify that the stored value is loop invariant. If not, we can't
  769. // promote the memset.
  770. CurLoop->isLoopInvariant(SplatValue)) {
  771. // Keep and use SplatValue.
  772. PatternValue = nullptr;
  773. } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
  774. (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
  775. // Don't create memset_pattern16s with address spaces.
  776. // It looks like we can use PatternValue!
  777. SplatValue = nullptr;
  778. } else {
  779. // Otherwise, this isn't an idiom we can transform. For example, we can't
  780. // do anything with a 3-byte store.
  781. return false;
  782. }
  783. // The trip count of the loop and the base pointer of the addrec SCEV is
  784. // guaranteed to be loop invariant, which means that it should dominate the
  785. // header. This allows us to insert code for it in the preheader.
  786. BasicBlock *Preheader = CurLoop->getLoopPreheader();
  787. IRBuilder<> Builder(Preheader->getTerminator());
  788. SCEVExpander Expander(*SE, DL, "loop-idiom");
  789. Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
  790. // Okay, we have a strided store "p[i]" of a splattable value. We can turn
  791. // this into a memset in the loop preheader now if we want. However, this
  792. // would be unsafe to do if there is anything else in the loop that may read
  793. // or write to the aliased location. Check for any overlap by generating the
  794. // base pointer and checking the region.
  795. Value *BasePtr =
  796. Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
  797. Preheader->getTerminator());
  798. if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
  799. CurLoop, BECount,
  800. StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
  801. Expander.clear();
  802. // If we generated new code for the base pointer, clean up.
  803. RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
  804. return false;
  805. }
  806. // Okay, everything looks good, insert the memset.
  807. // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
  808. // pointer size if it isn't already.
  809. Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
  810. BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
  811. const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
  812. SCEV::FlagNUW);
  813. if (StoreSize != 1) {
  814. NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
  815. SCEV::FlagNUW);
  816. }
  817. Value *NumBytes =
  818. Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
  819. CallInst *NewCall;
  820. if (SplatValue) {
  821. NewCall = Builder.CreateMemSet(BasePtr,
  822. SplatValue,
  823. NumBytes,
  824. StoreAlignment);
  825. } else {
  826. // Everything is emitted in default address space
  827. Type *Int8PtrTy = DestInt8PtrTy;
  828. Module *M = TheStore->getParent()->getParent()->getParent();
  829. Value *MSP = M->getOrInsertFunction("memset_pattern16",
  830. Builder.getVoidTy(),
  831. Int8PtrTy,
  832. Int8PtrTy,
  833. IntPtr,
  834. (void*)nullptr);
  835. // Otherwise we should form a memset_pattern16. PatternValue is known to be
  836. // an constant array of 16-bytes. Plop the value into a mergable global.
  837. GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
  838. GlobalValue::PrivateLinkage,
  839. PatternValue, ".memset_pattern");
  840. GV->setUnnamedAddr(true); // Ok to merge these.
  841. GV->setAlignment(16);
  842. Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
  843. NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
  844. }
  845. DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
  846. << " from store to: " << *Ev << " at: " << *TheStore << "\n");
  847. NewCall->setDebugLoc(TheStore->getDebugLoc());
  848. // Okay, the memset has been formed. Zap the original store and anything that
  849. // feeds into it.
  850. deleteDeadInstruction(TheStore, TLI);
  851. ++NumMemSet;
  852. return true;
  853. }
  854. /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
  855. /// same-strided load.
  856. bool LoopIdiomRecognize::
  857. processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
  858. const SCEVAddRecExpr *StoreEv,
  859. const SCEVAddRecExpr *LoadEv,
  860. const SCEV *BECount) {
  861. // If we're not allowed to form memcpy, we fail.
  862. if (!TLI->has(LibFunc::memcpy))
  863. return false;
  864. LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
  865. // The trip count of the loop and the base pointer of the addrec SCEV is
  866. // guaranteed to be loop invariant, which means that it should dominate the
  867. // header. This allows us to insert code for it in the preheader.
  868. BasicBlock *Preheader = CurLoop->getLoopPreheader();
  869. IRBuilder<> Builder(Preheader->getTerminator());
  870. const DataLayout &DL = Preheader->getModule()->getDataLayout();
  871. SCEVExpander Expander(*SE, DL, "loop-idiom");
  872. // Okay, we have a strided store "p[i]" of a loaded value. We can turn
  873. // this into a memcpy in the loop preheader now if we want. However, this
  874. // would be unsafe to do if there is anything else in the loop that may read
  875. // or write the memory region we're storing to. This includes the load that
  876. // feeds the stores. Check for an alias by generating the base address and
  877. // checking everything.
  878. Value *StoreBasePtr =
  879. Expander.expandCodeFor(StoreEv->getStart(),
  880. Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
  881. Preheader->getTerminator());
  882. if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
  883. CurLoop, BECount, StoreSize,
  884. getAnalysis<AliasAnalysis>(), SI)) {
  885. Expander.clear();
  886. // If we generated new code for the base pointer, clean up.
  887. RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
  888. return false;
  889. }
  890. // For a memcpy, we have to make sure that the input array is not being
  891. // mutated by the loop.
  892. Value *LoadBasePtr =
  893. Expander.expandCodeFor(LoadEv->getStart(),
  894. Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
  895. Preheader->getTerminator());
  896. if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
  897. StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
  898. Expander.clear();
  899. // If we generated new code for the base pointer, clean up.
  900. RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
  901. RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
  902. return false;
  903. }
  904. // Okay, everything is safe, we can transform this!
  905. // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
  906. // pointer size if it isn't already.
  907. Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
  908. BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
  909. const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
  910. SCEV::FlagNUW);
  911. if (StoreSize != 1)
  912. NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
  913. SCEV::FlagNUW);
  914. Value *NumBytes =
  915. Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
  916. CallInst *NewCall =
  917. Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
  918. std::min(SI->getAlignment(), LI->getAlignment()));
  919. NewCall->setDebugLoc(SI->getDebugLoc());
  920. DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
  921. << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
  922. << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
  923. // Okay, the memset has been formed. Zap the original store and anything that
  924. // feeds into it.
  925. deleteDeadInstruction(SI, TLI);
  926. ++NumMemCpy;
  927. return true;
  928. }