MergedLoadStoreMotion.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. //===- MergedLoadStoreMotion.cpp - merge and hoist/sink load/stores -------===//
  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. //! \file
  11. //! \brief This pass performs merges of loads and stores on both sides of a
  12. // diamond (hammock). It hoists the loads and sinks the stores.
  13. //
  14. // The algorithm iteratively hoists two loads to the same address out of a
  15. // diamond (hammock) and merges them into a single load in the header. Similar
  16. // it sinks and merges two stores to the tail block (footer). The algorithm
  17. // iterates over the instructions of one side of the diamond and attempts to
  18. // find a matching load/store on the other side. It hoists / sinks when it
  19. // thinks it safe to do so. This optimization helps with eg. hiding load
  20. // latencies, triggering if-conversion, and reducing static code size.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. //
  24. //
  25. // Example:
  26. // Diamond shaped code before merge:
  27. //
  28. // header:
  29. // br %cond, label %if.then, label %if.else
  30. // + +
  31. // + +
  32. // + +
  33. // if.then: if.else:
  34. // %lt = load %addr_l %le = load %addr_l
  35. // <use %lt> <use %le>
  36. // <...> <...>
  37. // store %st, %addr_s store %se, %addr_s
  38. // br label %if.end br label %if.end
  39. // + +
  40. // + +
  41. // + +
  42. // if.end ("footer"):
  43. // <...>
  44. //
  45. // Diamond shaped code after merge:
  46. //
  47. // header:
  48. // %l = load %addr_l
  49. // br %cond, label %if.then, label %if.else
  50. // + +
  51. // + +
  52. // + +
  53. // if.then: if.else:
  54. // <use %l> <use %l>
  55. // <...> <...>
  56. // br label %if.end br label %if.end
  57. // + +
  58. // + +
  59. // + +
  60. // if.end ("footer"):
  61. // %s.sink = phi [%st, if.then], [%se, if.else]
  62. // <...>
  63. // store %s.sink, %addr_s
  64. // <...>
  65. //
  66. //
  67. //===----------------------- TODO -----------------------------------------===//
  68. //
  69. // 1) Generalize to regions other than diamonds
  70. // 2) Be more aggressive merging memory operations
  71. // Note that both changes require register pressure control
  72. //
  73. //===----------------------------------------------------------------------===//
  74. #include "llvm/Transforms/Scalar.h"
  75. #include "llvm/ADT/SetVector.h"
  76. #include "llvm/ADT/SmallPtrSet.h"
  77. #include "llvm/ADT/Statistic.h"
  78. #include "llvm/Analysis/AliasAnalysis.h"
  79. #include "llvm/Analysis/CFG.h"
  80. #include "llvm/Analysis/Loads.h"
  81. #include "llvm/Analysis/MemoryBuiltins.h"
  82. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  83. #include "llvm/Analysis/TargetLibraryInfo.h"
  84. #include "llvm/IR/Metadata.h"
  85. #include "llvm/IR/PatternMatch.h"
  86. #include "llvm/Support/Allocator.h"
  87. #include "llvm/Support/CommandLine.h"
  88. #include "llvm/Support/Debug.h"
  89. #include "llvm/Support/raw_ostream.h"
  90. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  91. #include "llvm/Transforms/Utils/SSAUpdater.h"
  92. #include <vector>
  93. using namespace llvm;
  94. #define DEBUG_TYPE "mldst-motion"
  95. //===----------------------------------------------------------------------===//
  96. // MergedLoadStoreMotion Pass
  97. //===----------------------------------------------------------------------===//
  98. namespace {
  99. class MergedLoadStoreMotion : public FunctionPass {
  100. AliasAnalysis *AA;
  101. MemoryDependenceAnalysis *MD;
  102. public:
  103. static char ID; // Pass identification, replacement for typeid
  104. explicit MergedLoadStoreMotion(void)
  105. : FunctionPass(ID), MD(nullptr), MagicCompileTimeControl(250) {
  106. initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry());
  107. }
  108. bool runOnFunction(Function &F) override;
  109. private:
  110. // This transformation requires dominator postdominator info
  111. void getAnalysisUsage(AnalysisUsage &AU) const override {
  112. AU.addRequired<TargetLibraryInfoWrapperPass>();
  113. AU.addRequired<AliasAnalysis>();
  114. AU.addPreserved<MemoryDependenceAnalysis>();
  115. AU.addPreserved<AliasAnalysis>();
  116. }
  117. // Helper routines
  118. ///
  119. /// \brief Remove instruction from parent and update memory dependence
  120. /// analysis.
  121. ///
  122. void removeInstruction(Instruction *Inst);
  123. BasicBlock *getDiamondTail(BasicBlock *BB);
  124. bool isDiamondHead(BasicBlock *BB);
  125. // Routines for hoisting loads
  126. bool isLoadHoistBarrierInRange(const Instruction& Start,
  127. const Instruction& End,
  128. LoadInst* LI);
  129. LoadInst *canHoistFromBlock(BasicBlock *BB, LoadInst *LI);
  130. void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
  131. Instruction *ElseInst);
  132. bool isSafeToHoist(Instruction *I) const;
  133. bool hoistLoad(BasicBlock *BB, LoadInst *HoistCand, LoadInst *ElseInst);
  134. bool mergeLoads(BasicBlock *BB);
  135. // Routines for sinking stores
  136. StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
  137. PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
  138. bool isStoreSinkBarrierInRange(const Instruction &Start,
  139. const Instruction &End, MemoryLocation Loc);
  140. bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
  141. bool mergeStores(BasicBlock *BB);
  142. // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
  143. // where Size0 and Size1 are the #instructions on the two sides of
  144. // the diamond. The constant chosen here is arbitrary. Compiler Time
  145. // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
  146. const int MagicCompileTimeControl;
  147. };
  148. char MergedLoadStoreMotion::ID = 0;
  149. }
  150. ///
  151. /// \brief createMergedLoadStoreMotionPass - The public interface to this file.
  152. ///
  153. FunctionPass *llvm::createMergedLoadStoreMotionPass() {
  154. return new MergedLoadStoreMotion();
  155. }
  156. INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
  157. "MergedLoadStoreMotion", false, false)
  158. INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
  159. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  160. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  161. INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
  162. "MergedLoadStoreMotion", false, false)
  163. ///
  164. /// \brief Remove instruction from parent and update memory dependence analysis.
  165. ///
  166. void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
  167. // Notify the memory dependence analysis.
  168. if (MD) {
  169. MD->removeInstruction(Inst);
  170. if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  171. MD->invalidateCachedPointerInfo(LI->getPointerOperand());
  172. if (Inst->getType()->getScalarType()->isPointerTy()) {
  173. MD->invalidateCachedPointerInfo(Inst);
  174. }
  175. }
  176. Inst->eraseFromParent();
  177. }
  178. ///
  179. /// \brief Return tail block of a diamond.
  180. ///
  181. BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
  182. assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
  183. BranchInst *BI = (BranchInst *)(BB->getTerminator());
  184. BasicBlock *Succ0 = BI->getSuccessor(0);
  185. BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
  186. return Tail;
  187. }
  188. ///
  189. /// \brief True when BB is the head of a diamond (hammock)
  190. ///
  191. bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
  192. if (!BB)
  193. return false;
  194. if (!isa<BranchInst>(BB->getTerminator()))
  195. return false;
  196. if (BB->getTerminator()->getNumSuccessors() != 2)
  197. return false;
  198. BranchInst *BI = (BranchInst *)(BB->getTerminator());
  199. BasicBlock *Succ0 = BI->getSuccessor(0);
  200. BasicBlock *Succ1 = BI->getSuccessor(1);
  201. if (!Succ0->getSinglePredecessor() ||
  202. Succ0->getTerminator()->getNumSuccessors() != 1)
  203. return false;
  204. if (!Succ1->getSinglePredecessor() ||
  205. Succ1->getTerminator()->getNumSuccessors() != 1)
  206. return false;
  207. BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
  208. // Ignore triangles.
  209. if (Succ1->getTerminator()->getSuccessor(0) != Tail)
  210. return false;
  211. return true;
  212. }
  213. ///
  214. /// \brief True when instruction is a hoist barrier for a load
  215. ///
  216. /// Whenever an instruction could possibly modify the value
  217. /// being loaded or protect against the load from happening
  218. /// it is considered a hoist barrier.
  219. ///
  220. bool MergedLoadStoreMotion::isLoadHoistBarrierInRange(const Instruction& Start,
  221. const Instruction& End,
  222. LoadInst* LI) {
  223. MemoryLocation Loc = MemoryLocation::get(LI);
  224. return AA->canInstructionRangeModRef(Start, End, Loc, AliasAnalysis::Mod);
  225. }
  226. ///
  227. /// \brief Decide if a load can be hoisted
  228. ///
  229. /// When there is a load in \p BB to the same address as \p LI
  230. /// and it can be hoisted from \p BB, return that load.
  231. /// Otherwise return Null.
  232. ///
  233. LoadInst *MergedLoadStoreMotion::canHoistFromBlock(BasicBlock *BB1,
  234. LoadInst *Load0) {
  235. for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
  236. ++BBI) {
  237. Instruction *Inst = BBI;
  238. // Only merge and hoist loads when their result in used only in BB
  239. if (!isa<LoadInst>(Inst) || Inst->isUsedOutsideOfBlock(BB1))
  240. continue;
  241. LoadInst *Load1 = dyn_cast<LoadInst>(Inst);
  242. BasicBlock *BB0 = Load0->getParent();
  243. MemoryLocation Loc0 = MemoryLocation::get(Load0);
  244. MemoryLocation Loc1 = MemoryLocation::get(Load1);
  245. if (AA->isMustAlias(Loc0, Loc1) && Load0->isSameOperationAs(Load1) &&
  246. !isLoadHoistBarrierInRange(BB1->front(), *Load1, Load1) &&
  247. !isLoadHoistBarrierInRange(BB0->front(), *Load0, Load0)) {
  248. return Load1;
  249. }
  250. }
  251. return nullptr;
  252. }
  253. ///
  254. /// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into
  255. /// \p BB
  256. ///
  257. /// BB is the head of a diamond
  258. ///
  259. void MergedLoadStoreMotion::hoistInstruction(BasicBlock *BB,
  260. Instruction *HoistCand,
  261. Instruction *ElseInst) {
  262. DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
  263. dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
  264. dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
  265. // Hoist the instruction.
  266. assert(HoistCand->getParent() != BB);
  267. // Intersect optional metadata.
  268. HoistCand->intersectOptionalDataWith(ElseInst);
  269. HoistCand->dropUnknownMetadata();
  270. // Prepend point for instruction insert
  271. Instruction *HoistPt = BB->getTerminator();
  272. // Merged instruction
  273. Instruction *HoistedInst = HoistCand->clone();
  274. // Hoist instruction.
  275. HoistedInst->insertBefore(HoistPt);
  276. HoistCand->replaceAllUsesWith(HoistedInst);
  277. removeInstruction(HoistCand);
  278. // Replace the else block instruction.
  279. ElseInst->replaceAllUsesWith(HoistedInst);
  280. removeInstruction(ElseInst);
  281. }
  282. ///
  283. /// \brief Return true if no operand of \p I is defined in I's parent block
  284. ///
  285. bool MergedLoadStoreMotion::isSafeToHoist(Instruction *I) const {
  286. BasicBlock *Parent = I->getParent();
  287. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  288. Instruction *Instr = dyn_cast<Instruction>(I->getOperand(i));
  289. if (Instr && Instr->getParent() == Parent)
  290. return false;
  291. }
  292. return true;
  293. }
  294. ///
  295. /// \brief Merge two equivalent loads and GEPs and hoist into diamond head
  296. ///
  297. bool MergedLoadStoreMotion::hoistLoad(BasicBlock *BB, LoadInst *L0,
  298. LoadInst *L1) {
  299. // Only one definition?
  300. Instruction *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
  301. Instruction *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
  302. if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
  303. A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
  304. A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
  305. isa<GetElementPtrInst>(A0)) {
  306. DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
  307. dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
  308. dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
  309. hoistInstruction(BB, A0, A1);
  310. hoistInstruction(BB, L0, L1);
  311. return true;
  312. } else
  313. return false;
  314. }
  315. ///
  316. /// \brief Try to hoist two loads to same address into diamond header
  317. ///
  318. /// Starting from a diamond head block, iterate over the instructions in one
  319. /// successor block and try to match a load in the second successor.
  320. ///
  321. bool MergedLoadStoreMotion::mergeLoads(BasicBlock *BB) {
  322. bool MergedLoads = false;
  323. assert(isDiamondHead(BB));
  324. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  325. BasicBlock *Succ0 = BI->getSuccessor(0);
  326. BasicBlock *Succ1 = BI->getSuccessor(1);
  327. // #Instructions in Succ1 for Compile Time Control
  328. int Size1 = Succ1->size();
  329. int NLoads = 0;
  330. for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
  331. BBI != BBE;) {
  332. Instruction *I = BBI;
  333. ++BBI;
  334. // Only move non-simple (atomic, volatile) loads.
  335. LoadInst *L0 = dyn_cast<LoadInst>(I);
  336. if (!L0 || !L0->isSimple() || L0->isUsedOutsideOfBlock(Succ0))
  337. continue;
  338. ++NLoads;
  339. if (NLoads * Size1 >= MagicCompileTimeControl)
  340. break;
  341. if (LoadInst *L1 = canHoistFromBlock(Succ1, L0)) {
  342. bool Res = hoistLoad(BB, L0, L1);
  343. MergedLoads |= Res;
  344. // Don't attempt to hoist above loads that had not been hoisted.
  345. if (!Res)
  346. break;
  347. }
  348. }
  349. return MergedLoads;
  350. }
  351. ///
  352. /// \brief True when instruction is a sink barrier for a store
  353. /// located in Loc
  354. ///
  355. /// Whenever an instruction could possibly read or modify the
  356. /// value being stored or protect against the store from
  357. /// happening it is considered a sink barrier.
  358. ///
  359. bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
  360. const Instruction &End,
  361. MemoryLocation Loc) {
  362. return AA->canInstructionRangeModRef(Start, End, Loc, AliasAnalysis::ModRef);
  363. }
  364. ///
  365. /// \brief Check if \p BB contains a store to the same address as \p SI
  366. ///
  367. /// \return The store in \p when it is safe to sink. Otherwise return Null.
  368. ///
  369. StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
  370. StoreInst *Store0) {
  371. DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
  372. BasicBlock *BB0 = Store0->getParent();
  373. for (BasicBlock::reverse_iterator RBI = BB1->rbegin(), RBE = BB1->rend();
  374. RBI != RBE; ++RBI) {
  375. Instruction *Inst = &*RBI;
  376. if (!isa<StoreInst>(Inst))
  377. continue;
  378. StoreInst *Store1 = cast<StoreInst>(Inst);
  379. MemoryLocation Loc0 = MemoryLocation::get(Store0);
  380. MemoryLocation Loc1 = MemoryLocation::get(Store1);
  381. if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
  382. !isStoreSinkBarrierInRange(*(std::next(BasicBlock::iterator(Store1))),
  383. BB1->back(), Loc1) &&
  384. !isStoreSinkBarrierInRange(*(std::next(BasicBlock::iterator(Store0))),
  385. BB0->back(), Loc0)) {
  386. return Store1;
  387. }
  388. }
  389. return nullptr;
  390. }
  391. ///
  392. /// \brief Create a PHI node in BB for the operands of S0 and S1
  393. ///
  394. PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
  395. StoreInst *S1) {
  396. // Create a phi if the values mismatch.
  397. PHINode *NewPN = 0;
  398. Value *Opd1 = S0->getValueOperand();
  399. Value *Opd2 = S1->getValueOperand();
  400. if (Opd1 != Opd2) {
  401. NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
  402. BB->begin());
  403. NewPN->addIncoming(Opd1, S0->getParent());
  404. NewPN->addIncoming(Opd2, S1->getParent());
  405. if (NewPN->getType()->getScalarType()->isPointerTy()) {
  406. // AA needs to be informed when a PHI-use of the pointer value is added
  407. for (unsigned I = 0, E = NewPN->getNumIncomingValues(); I != E; ++I) {
  408. unsigned J = PHINode::getOperandNumForIncomingValue(I);
  409. AA->addEscapingUse(NewPN->getOperandUse(J));
  410. }
  411. if (MD)
  412. MD->invalidateCachedPointerInfo(NewPN);
  413. }
  414. }
  415. return NewPN;
  416. }
  417. ///
  418. /// \brief Merge two stores to same address and sink into \p BB
  419. ///
  420. /// Also sinks GEP instruction computing the store address
  421. ///
  422. bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
  423. StoreInst *S1) {
  424. // Only one definition?
  425. Instruction *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
  426. Instruction *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
  427. if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
  428. (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
  429. (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
  430. DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
  431. dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
  432. dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
  433. // Hoist the instruction.
  434. BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
  435. // Intersect optional metadata.
  436. S0->intersectOptionalDataWith(S1);
  437. S0->dropUnknownMetadata();
  438. // Create the new store to be inserted at the join point.
  439. StoreInst *SNew = (StoreInst *)(S0->clone());
  440. Instruction *ANew = A0->clone();
  441. SNew->insertBefore(InsertPt);
  442. ANew->insertBefore(SNew);
  443. assert(S0->getParent() == A0->getParent());
  444. assert(S1->getParent() == A1->getParent());
  445. PHINode *NewPN = getPHIOperand(BB, S0, S1);
  446. // New PHI operand? Use it.
  447. if (NewPN)
  448. SNew->setOperand(0, NewPN);
  449. removeInstruction(S0);
  450. removeInstruction(S1);
  451. A0->replaceAllUsesWith(ANew);
  452. removeInstruction(A0);
  453. A1->replaceAllUsesWith(ANew);
  454. removeInstruction(A1);
  455. return true;
  456. }
  457. return false;
  458. }
  459. ///
  460. /// \brief True when two stores are equivalent and can sink into the footer
  461. ///
  462. /// Starting from a diamond tail block, iterate over the instructions in one
  463. /// predecessor block and try to match a store in the second predecessor.
  464. ///
  465. bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
  466. bool MergedStores = false;
  467. assert(T && "Footer of a diamond cannot be empty");
  468. pred_iterator PI = pred_begin(T), E = pred_end(T);
  469. assert(PI != E);
  470. BasicBlock *Pred0 = *PI;
  471. ++PI;
  472. BasicBlock *Pred1 = *PI;
  473. ++PI;
  474. // tail block of a diamond/hammock?
  475. if (Pred0 == Pred1)
  476. return false; // No.
  477. if (PI != E)
  478. return false; // No. More than 2 predecessors.
  479. // #Instructions in Succ1 for Compile Time Control
  480. int Size1 = Pred1->size();
  481. int NStores = 0;
  482. for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
  483. RBI != RBE;) {
  484. Instruction *I = &*RBI;
  485. ++RBI;
  486. // Sink move non-simple (atomic, volatile) stores
  487. if (!isa<StoreInst>(I))
  488. continue;
  489. StoreInst *S0 = (StoreInst *)I;
  490. if (!S0->isSimple())
  491. continue;
  492. ++NStores;
  493. if (NStores * Size1 >= MagicCompileTimeControl)
  494. break;
  495. if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
  496. bool Res = sinkStore(T, S0, S1);
  497. MergedStores |= Res;
  498. // Don't attempt to sink below stores that had to stick around
  499. // But after removal of a store and some of its feeding
  500. // instruction search again from the beginning since the iterator
  501. // is likely stale at this point.
  502. if (!Res)
  503. break;
  504. else {
  505. RBI = Pred0->rbegin();
  506. RBE = Pred0->rend();
  507. DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
  508. }
  509. }
  510. }
  511. return MergedStores;
  512. }
  513. ///
  514. /// \brief Run the transformation for each function
  515. ///
  516. bool MergedLoadStoreMotion::runOnFunction(Function &F) {
  517. MD = getAnalysisIfAvailable<MemoryDependenceAnalysis>();
  518. AA = &getAnalysis<AliasAnalysis>();
  519. bool Changed = false;
  520. DEBUG(dbgs() << "Instruction Merger\n");
  521. // Merge unconditional branches, allowing PRE to catch more
  522. // optimization opportunities.
  523. for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
  524. BasicBlock *BB = FI++;
  525. // Hoist equivalent loads and sink stores
  526. // outside diamonds when possible
  527. if (isDiamondHead(BB)) {
  528. Changed |= mergeLoads(BB);
  529. Changed |= mergeStores(getDiamondTail(BB));
  530. }
  531. }
  532. return Changed;
  533. }