EarlyCSE.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762
  1. //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass performs a simple dominator tree walk that eliminates trivially
  10. // redundant instructions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar/EarlyCSE.h"
  14. #include "llvm/ADT/DenseMapInfo.h"
  15. #include "llvm/ADT/Hashing.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/ScopedHashTable.h"
  18. #include "llvm/ADT/SetVector.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/AssumptionCache.h"
  22. #include "llvm/Analysis/GlobalsModRef.h"
  23. #include "llvm/Analysis/GuardUtils.h"
  24. #include "llvm/Analysis/InstructionSimplify.h"
  25. #include "llvm/Analysis/MemorySSA.h"
  26. #include "llvm/Analysis/MemorySSAUpdater.h"
  27. #include "llvm/Analysis/TargetLibraryInfo.h"
  28. #include "llvm/Analysis/TargetTransformInfo.h"
  29. #include "llvm/Analysis/ValueTracking.h"
  30. #include "llvm/IR/BasicBlock.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/Dominators.h"
  34. #include "llvm/IR/Function.h"
  35. #include "llvm/IR/InstrTypes.h"
  36. #include "llvm/IR/Instruction.h"
  37. #include "llvm/IR/Instructions.h"
  38. #include "llvm/IR/IntrinsicInst.h"
  39. #include "llvm/IR/Intrinsics.h"
  40. #include "llvm/IR/LLVMContext.h"
  41. #include "llvm/IR/PassManager.h"
  42. #include "llvm/IR/PatternMatch.h"
  43. #include "llvm/IR/Type.h"
  44. #include "llvm/IR/Use.h"
  45. #include "llvm/IR/Value.h"
  46. #include "llvm/InitializePasses.h"
  47. #include "llvm/Pass.h"
  48. #include "llvm/Support/Allocator.h"
  49. #include "llvm/Support/AtomicOrdering.h"
  50. #include "llvm/Support/Casting.h"
  51. #include "llvm/Support/Debug.h"
  52. #include "llvm/Support/DebugCounter.h"
  53. #include "llvm/Support/RecyclingAllocator.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include "llvm/Transforms/Scalar.h"
  56. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  57. #include "llvm/Transforms/Utils/GuardUtils.h"
  58. #include "llvm/Transforms/Utils/Local.h"
  59. #include <cassert>
  60. #include <deque>
  61. #include <memory>
  62. #include <utility>
  63. using namespace llvm;
  64. using namespace llvm::PatternMatch;
  65. #define DEBUG_TYPE "early-cse"
  66. STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
  67. STATISTIC(NumCSE, "Number of instructions CSE'd");
  68. STATISTIC(NumCSECVP, "Number of compare instructions CVP'd");
  69. STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
  70. STATISTIC(NumCSECall, "Number of call instructions CSE'd");
  71. STATISTIC(NumDSE, "Number of trivial dead stores removed");
  72. DEBUG_COUNTER(CSECounter, "early-cse",
  73. "Controls which instructions are removed");
  74. static cl::opt<unsigned> EarlyCSEMssaOptCap(
  75. "earlycse-mssa-optimization-cap", cl::init(500), cl::Hidden,
  76. cl::desc("Enable imprecision in EarlyCSE in pathological cases, in exchange "
  77. "for faster compile. Caps the MemorySSA clobbering calls."));
  78. static cl::opt<bool> EarlyCSEDebugHash(
  79. "earlycse-debug-hash", cl::init(false), cl::Hidden,
  80. cl::desc("Perform extra assertion checking to verify that SimpleValue's hash "
  81. "function is well-behaved w.r.t. its isEqual predicate"));
  82. //===----------------------------------------------------------------------===//
  83. // SimpleValue
  84. //===----------------------------------------------------------------------===//
  85. namespace {
  86. /// Struct representing the available values in the scoped hash table.
  87. struct SimpleValue {
  88. Instruction *Inst;
  89. SimpleValue(Instruction *I) : Inst(I) {
  90. assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
  91. }
  92. bool isSentinel() const {
  93. return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
  94. Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
  95. }
  96. static bool canHandle(Instruction *Inst) {
  97. // This can only handle non-void readnone functions.
  98. // Also handled are constrained intrinsic that look like the types
  99. // of instruction handled below (UnaryOperator, etc.).
  100. if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
  101. if (Function *F = CI->getCalledFunction()) {
  102. switch ((Intrinsic::ID)F->getIntrinsicID()) {
  103. case Intrinsic::experimental_constrained_fadd:
  104. case Intrinsic::experimental_constrained_fsub:
  105. case Intrinsic::experimental_constrained_fmul:
  106. case Intrinsic::experimental_constrained_fdiv:
  107. case Intrinsic::experimental_constrained_frem:
  108. case Intrinsic::experimental_constrained_fptosi:
  109. case Intrinsic::experimental_constrained_sitofp:
  110. case Intrinsic::experimental_constrained_fptoui:
  111. case Intrinsic::experimental_constrained_uitofp:
  112. case Intrinsic::experimental_constrained_fcmp:
  113. case Intrinsic::experimental_constrained_fcmps: {
  114. auto *CFP = cast<ConstrainedFPIntrinsic>(CI);
  115. return CFP->isDefaultFPEnvironment();
  116. }
  117. }
  118. }
  119. return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
  120. }
  121. return isa<CastInst>(Inst) || isa<UnaryOperator>(Inst) ||
  122. isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
  123. isa<CmpInst>(Inst) || isa<SelectInst>(Inst) ||
  124. isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
  125. isa<ShuffleVectorInst>(Inst) || isa<ExtractValueInst>(Inst) ||
  126. isa<InsertValueInst>(Inst) || isa<FreezeInst>(Inst);
  127. }
  128. };
  129. } // end anonymous namespace
  130. namespace llvm {
  131. template <> struct DenseMapInfo<SimpleValue> {
  132. static inline SimpleValue getEmptyKey() {
  133. return DenseMapInfo<Instruction *>::getEmptyKey();
  134. }
  135. static inline SimpleValue getTombstoneKey() {
  136. return DenseMapInfo<Instruction *>::getTombstoneKey();
  137. }
  138. static unsigned getHashValue(SimpleValue Val);
  139. static bool isEqual(SimpleValue LHS, SimpleValue RHS);
  140. };
  141. } // end namespace llvm
  142. /// Match a 'select' including an optional 'not's of the condition.
  143. static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond, Value *&A,
  144. Value *&B,
  145. SelectPatternFlavor &Flavor) {
  146. // Return false if V is not even a select.
  147. if (!match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))))
  148. return false;
  149. // Look through a 'not' of the condition operand by swapping A/B.
  150. Value *CondNot;
  151. if (match(Cond, m_Not(m_Value(CondNot)))) {
  152. Cond = CondNot;
  153. std::swap(A, B);
  154. }
  155. // Match canonical forms of min/max. We are not using ValueTracking's
  156. // more powerful matchSelectPattern() because it may rely on instruction flags
  157. // such as "nsw". That would be incompatible with the current hashing
  158. // mechanism that may remove flags to increase the likelihood of CSE.
  159. Flavor = SPF_UNKNOWN;
  160. CmpInst::Predicate Pred;
  161. if (!match(Cond, m_ICmp(Pred, m_Specific(A), m_Specific(B)))) {
  162. // Check for commuted variants of min/max by swapping predicate.
  163. // If we do not match the standard or commuted patterns, this is not a
  164. // recognized form of min/max, but it is still a select, so return true.
  165. if (!match(Cond, m_ICmp(Pred, m_Specific(B), m_Specific(A))))
  166. return true;
  167. Pred = ICmpInst::getSwappedPredicate(Pred);
  168. }
  169. switch (Pred) {
  170. case CmpInst::ICMP_UGT: Flavor = SPF_UMAX; break;
  171. case CmpInst::ICMP_ULT: Flavor = SPF_UMIN; break;
  172. case CmpInst::ICMP_SGT: Flavor = SPF_SMAX; break;
  173. case CmpInst::ICMP_SLT: Flavor = SPF_SMIN; break;
  174. // Non-strict inequalities.
  175. case CmpInst::ICMP_ULE: Flavor = SPF_UMIN; break;
  176. case CmpInst::ICMP_UGE: Flavor = SPF_UMAX; break;
  177. case CmpInst::ICMP_SLE: Flavor = SPF_SMIN; break;
  178. case CmpInst::ICMP_SGE: Flavor = SPF_SMAX; break;
  179. default: break;
  180. }
  181. return true;
  182. }
  183. static unsigned getHashValueImpl(SimpleValue Val) {
  184. Instruction *Inst = Val.Inst;
  185. // Hash in all of the operands as pointers.
  186. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
  187. Value *LHS = BinOp->getOperand(0);
  188. Value *RHS = BinOp->getOperand(1);
  189. if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
  190. std::swap(LHS, RHS);
  191. return hash_combine(BinOp->getOpcode(), LHS, RHS);
  192. }
  193. if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
  194. // Compares can be commuted by swapping the comparands and
  195. // updating the predicate. Choose the form that has the
  196. // comparands in sorted order, or in the case of a tie, the
  197. // one with the lower predicate.
  198. Value *LHS = CI->getOperand(0);
  199. Value *RHS = CI->getOperand(1);
  200. CmpInst::Predicate Pred = CI->getPredicate();
  201. CmpInst::Predicate SwappedPred = CI->getSwappedPredicate();
  202. if (std::tie(LHS, Pred) > std::tie(RHS, SwappedPred)) {
  203. std::swap(LHS, RHS);
  204. Pred = SwappedPred;
  205. }
  206. return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
  207. }
  208. // Hash general selects to allow matching commuted true/false operands.
  209. SelectPatternFlavor SPF;
  210. Value *Cond, *A, *B;
  211. if (matchSelectWithOptionalNotCond(Inst, Cond, A, B, SPF)) {
  212. // Hash min/max (cmp + select) to allow for commuted operands.
  213. // Min/max may also have non-canonical compare predicate (eg, the compare for
  214. // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
  215. // compare.
  216. // TODO: We should also detect FP min/max.
  217. if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
  218. SPF == SPF_UMIN || SPF == SPF_UMAX) {
  219. if (A > B)
  220. std::swap(A, B);
  221. return hash_combine(Inst->getOpcode(), SPF, A, B);
  222. }
  223. // Hash general selects to allow matching commuted true/false operands.
  224. // If we do not have a compare as the condition, just hash in the condition.
  225. CmpInst::Predicate Pred;
  226. Value *X, *Y;
  227. if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y))))
  228. return hash_combine(Inst->getOpcode(), Cond, A, B);
  229. // Similar to cmp normalization (above) - canonicalize the predicate value:
  230. // select (icmp Pred, X, Y), A, B --> select (icmp InvPred, X, Y), B, A
  231. if (CmpInst::getInversePredicate(Pred) < Pred) {
  232. Pred = CmpInst::getInversePredicate(Pred);
  233. std::swap(A, B);
  234. }
  235. return hash_combine(Inst->getOpcode(), Pred, X, Y, A, B);
  236. }
  237. if (CastInst *CI = dyn_cast<CastInst>(Inst))
  238. return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
  239. if (FreezeInst *FI = dyn_cast<FreezeInst>(Inst))
  240. return hash_combine(FI->getOpcode(), FI->getOperand(0));
  241. if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
  242. return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
  243. hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
  244. if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
  245. return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
  246. IVI->getOperand(1),
  247. hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
  248. assert((isa<CallInst>(Inst) || isa<GetElementPtrInst>(Inst) ||
  249. isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
  250. isa<ShuffleVectorInst>(Inst) || isa<UnaryOperator>(Inst) ||
  251. isa<FreezeInst>(Inst)) &&
  252. "Invalid/unknown instruction");
  253. // Handle intrinsics with commutative operands.
  254. // TODO: Extend this to handle intrinsics with >2 operands where the 1st
  255. // 2 operands are commutative.
  256. auto *II = dyn_cast<IntrinsicInst>(Inst);
  257. if (II && II->isCommutative() && II->arg_size() == 2) {
  258. Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
  259. if (LHS > RHS)
  260. std::swap(LHS, RHS);
  261. return hash_combine(II->getOpcode(), LHS, RHS);
  262. }
  263. // gc.relocate is 'special' call: its second and third operands are
  264. // not real values, but indices into statepoint's argument list.
  265. // Get values they point to.
  266. if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(Inst))
  267. return hash_combine(GCR->getOpcode(), GCR->getOperand(0),
  268. GCR->getBasePtr(), GCR->getDerivedPtr());
  269. // Mix in the opcode.
  270. return hash_combine(
  271. Inst->getOpcode(),
  272. hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
  273. }
  274. unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
  275. #ifndef NDEBUG
  276. // If -earlycse-debug-hash was specified, return a constant -- this
  277. // will force all hashing to collide, so we'll exhaustively search
  278. // the table for a match, and the assertion in isEqual will fire if
  279. // there's a bug causing equal keys to hash differently.
  280. if (EarlyCSEDebugHash)
  281. return 0;
  282. #endif
  283. return getHashValueImpl(Val);
  284. }
  285. static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS) {
  286. Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
  287. if (LHS.isSentinel() || RHS.isSentinel())
  288. return LHSI == RHSI;
  289. if (LHSI->getOpcode() != RHSI->getOpcode())
  290. return false;
  291. if (LHSI->isIdenticalToWhenDefined(RHSI))
  292. return true;
  293. // If we're not strictly identical, we still might be a commutable instruction
  294. if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
  295. if (!LHSBinOp->isCommutative())
  296. return false;
  297. assert(isa<BinaryOperator>(RHSI) &&
  298. "same opcode, but different instruction type?");
  299. BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
  300. // Commuted equality
  301. return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
  302. LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
  303. }
  304. if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
  305. assert(isa<CmpInst>(RHSI) &&
  306. "same opcode, but different instruction type?");
  307. CmpInst *RHSCmp = cast<CmpInst>(RHSI);
  308. // Commuted equality
  309. return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
  310. LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
  311. LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
  312. }
  313. // TODO: Extend this for >2 args by matching the trailing N-2 args.
  314. auto *LII = dyn_cast<IntrinsicInst>(LHSI);
  315. auto *RII = dyn_cast<IntrinsicInst>(RHSI);
  316. if (LII && RII && LII->getIntrinsicID() == RII->getIntrinsicID() &&
  317. LII->isCommutative() && LII->arg_size() == 2) {
  318. return LII->getArgOperand(0) == RII->getArgOperand(1) &&
  319. LII->getArgOperand(1) == RII->getArgOperand(0);
  320. }
  321. // See comment above in `getHashValue()`.
  322. if (const GCRelocateInst *GCR1 = dyn_cast<GCRelocateInst>(LHSI))
  323. if (const GCRelocateInst *GCR2 = dyn_cast<GCRelocateInst>(RHSI))
  324. return GCR1->getOperand(0) == GCR2->getOperand(0) &&
  325. GCR1->getBasePtr() == GCR2->getBasePtr() &&
  326. GCR1->getDerivedPtr() == GCR2->getDerivedPtr();
  327. // Min/max can occur with commuted operands, non-canonical predicates,
  328. // and/or non-canonical operands.
  329. // Selects can be non-trivially equivalent via inverted conditions and swaps.
  330. SelectPatternFlavor LSPF, RSPF;
  331. Value *CondL, *CondR, *LHSA, *RHSA, *LHSB, *RHSB;
  332. if (matchSelectWithOptionalNotCond(LHSI, CondL, LHSA, LHSB, LSPF) &&
  333. matchSelectWithOptionalNotCond(RHSI, CondR, RHSA, RHSB, RSPF)) {
  334. if (LSPF == RSPF) {
  335. // TODO: We should also detect FP min/max.
  336. if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
  337. LSPF == SPF_UMIN || LSPF == SPF_UMAX)
  338. return ((LHSA == RHSA && LHSB == RHSB) ||
  339. (LHSA == RHSB && LHSB == RHSA));
  340. // select Cond, A, B <--> select not(Cond), B, A
  341. if (CondL == CondR && LHSA == RHSA && LHSB == RHSB)
  342. return true;
  343. }
  344. // If the true/false operands are swapped and the conditions are compares
  345. // with inverted predicates, the selects are equal:
  346. // select (icmp Pred, X, Y), A, B <--> select (icmp InvPred, X, Y), B, A
  347. //
  348. // This also handles patterns with a double-negation in the sense of not +
  349. // inverse, because we looked through a 'not' in the matching function and
  350. // swapped A/B:
  351. // select (cmp Pred, X, Y), A, B <--> select (not (cmp InvPred, X, Y)), B, A
  352. //
  353. // This intentionally does NOT handle patterns with a double-negation in
  354. // the sense of not + not, because doing so could result in values
  355. // comparing
  356. // as equal that hash differently in the min/max cases like:
  357. // select (cmp slt, X, Y), X, Y <--> select (not (not (cmp slt, X, Y))), X, Y
  358. // ^ hashes as min ^ would not hash as min
  359. // In the context of the EarlyCSE pass, however, such cases never reach
  360. // this code, as we simplify the double-negation before hashing the second
  361. // select (and so still succeed at CSEing them).
  362. if (LHSA == RHSB && LHSB == RHSA) {
  363. CmpInst::Predicate PredL, PredR;
  364. Value *X, *Y;
  365. if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) &&
  366. match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) &&
  367. CmpInst::getInversePredicate(PredL) == PredR)
  368. return true;
  369. }
  370. }
  371. return false;
  372. }
  373. bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
  374. // These comparisons are nontrivial, so assert that equality implies
  375. // hash equality (DenseMap demands this as an invariant).
  376. bool Result = isEqualImpl(LHS, RHS);
  377. assert(!Result || (LHS.isSentinel() && LHS.Inst == RHS.Inst) ||
  378. getHashValueImpl(LHS) == getHashValueImpl(RHS));
  379. return Result;
  380. }
  381. //===----------------------------------------------------------------------===//
  382. // CallValue
  383. //===----------------------------------------------------------------------===//
  384. namespace {
  385. /// Struct representing the available call values in the scoped hash
  386. /// table.
  387. struct CallValue {
  388. Instruction *Inst;
  389. CallValue(Instruction *I) : Inst(I) {
  390. assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
  391. }
  392. bool isSentinel() const {
  393. return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
  394. Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
  395. }
  396. static bool canHandle(Instruction *Inst) {
  397. // Don't value number anything that returns void.
  398. if (Inst->getType()->isVoidTy())
  399. return false;
  400. CallInst *CI = dyn_cast<CallInst>(Inst);
  401. if (!CI || !CI->onlyReadsMemory())
  402. return false;
  403. return true;
  404. }
  405. };
  406. } // end anonymous namespace
  407. namespace llvm {
  408. template <> struct DenseMapInfo<CallValue> {
  409. static inline CallValue getEmptyKey() {
  410. return DenseMapInfo<Instruction *>::getEmptyKey();
  411. }
  412. static inline CallValue getTombstoneKey() {
  413. return DenseMapInfo<Instruction *>::getTombstoneKey();
  414. }
  415. static unsigned getHashValue(CallValue Val);
  416. static bool isEqual(CallValue LHS, CallValue RHS);
  417. };
  418. } // end namespace llvm
  419. unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
  420. Instruction *Inst = Val.Inst;
  421. // Hash all of the operands as pointers and mix in the opcode.
  422. return hash_combine(
  423. Inst->getOpcode(),
  424. hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
  425. }
  426. bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
  427. Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
  428. if (LHS.isSentinel() || RHS.isSentinel())
  429. return LHSI == RHSI;
  430. return LHSI->isIdenticalTo(RHSI);
  431. }
  432. //===----------------------------------------------------------------------===//
  433. // EarlyCSE implementation
  434. //===----------------------------------------------------------------------===//
  435. namespace {
  436. /// A simple and fast domtree-based CSE pass.
  437. ///
  438. /// This pass does a simple depth-first walk over the dominator tree,
  439. /// eliminating trivially redundant instructions and using instsimplify to
  440. /// canonicalize things as it goes. It is intended to be fast and catch obvious
  441. /// cases so that instcombine and other passes are more effective. It is
  442. /// expected that a later pass of GVN will catch the interesting/hard cases.
  443. class EarlyCSE {
  444. public:
  445. const TargetLibraryInfo &TLI;
  446. const TargetTransformInfo &TTI;
  447. DominatorTree &DT;
  448. AssumptionCache &AC;
  449. const SimplifyQuery SQ;
  450. MemorySSA *MSSA;
  451. std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
  452. using AllocatorTy =
  453. RecyclingAllocator<BumpPtrAllocator,
  454. ScopedHashTableVal<SimpleValue, Value *>>;
  455. using ScopedHTType =
  456. ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
  457. AllocatorTy>;
  458. /// A scoped hash table of the current values of all of our simple
  459. /// scalar expressions.
  460. ///
  461. /// As we walk down the domtree, we look to see if instructions are in this:
  462. /// if so, we replace them with what we find, otherwise we insert them so
  463. /// that dominated values can succeed in their lookup.
  464. ScopedHTType AvailableValues;
  465. /// A scoped hash table of the current values of previously encountered
  466. /// memory locations.
  467. ///
  468. /// This allows us to get efficient access to dominating loads or stores when
  469. /// we have a fully redundant load. In addition to the most recent load, we
  470. /// keep track of a generation count of the read, which is compared against
  471. /// the current generation count. The current generation count is incremented
  472. /// after every possibly writing memory operation, which ensures that we only
  473. /// CSE loads with other loads that have no intervening store. Ordering
  474. /// events (such as fences or atomic instructions) increment the generation
  475. /// count as well; essentially, we model these as writes to all possible
  476. /// locations. Note that atomic and/or volatile loads and stores can be
  477. /// present the table; it is the responsibility of the consumer to inspect
  478. /// the atomicity/volatility if needed.
  479. struct LoadValue {
  480. Instruction *DefInst = nullptr;
  481. unsigned Generation = 0;
  482. int MatchingId = -1;
  483. bool IsAtomic = false;
  484. LoadValue() = default;
  485. LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
  486. bool IsAtomic)
  487. : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
  488. IsAtomic(IsAtomic) {}
  489. };
  490. using LoadMapAllocator =
  491. RecyclingAllocator<BumpPtrAllocator,
  492. ScopedHashTableVal<Value *, LoadValue>>;
  493. using LoadHTType =
  494. ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
  495. LoadMapAllocator>;
  496. LoadHTType AvailableLoads;
  497. // A scoped hash table mapping memory locations (represented as typed
  498. // addresses) to generation numbers at which that memory location became
  499. // (henceforth indefinitely) invariant.
  500. using InvariantMapAllocator =
  501. RecyclingAllocator<BumpPtrAllocator,
  502. ScopedHashTableVal<MemoryLocation, unsigned>>;
  503. using InvariantHTType =
  504. ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
  505. InvariantMapAllocator>;
  506. InvariantHTType AvailableInvariants;
  507. /// A scoped hash table of the current values of read-only call
  508. /// values.
  509. ///
  510. /// It uses the same generation count as loads.
  511. using CallHTType =
  512. ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
  513. CallHTType AvailableCalls;
  514. /// This is the current generation of the memory value.
  515. unsigned CurrentGeneration = 0;
  516. /// Set up the EarlyCSE runner for a particular function.
  517. EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
  518. const TargetTransformInfo &TTI, DominatorTree &DT,
  519. AssumptionCache &AC, MemorySSA *MSSA)
  520. : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
  521. MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {}
  522. bool run();
  523. private:
  524. unsigned ClobberCounter = 0;
  525. // Almost a POD, but needs to call the constructors for the scoped hash
  526. // tables so that a new scope gets pushed on. These are RAII so that the
  527. // scope gets popped when the NodeScope is destroyed.
  528. class NodeScope {
  529. public:
  530. NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
  531. InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls)
  532. : Scope(AvailableValues), LoadScope(AvailableLoads),
  533. InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {}
  534. NodeScope(const NodeScope &) = delete;
  535. NodeScope &operator=(const NodeScope &) = delete;
  536. private:
  537. ScopedHTType::ScopeTy Scope;
  538. LoadHTType::ScopeTy LoadScope;
  539. InvariantHTType::ScopeTy InvariantScope;
  540. CallHTType::ScopeTy CallScope;
  541. };
  542. // Contains all the needed information to create a stack for doing a depth
  543. // first traversal of the tree. This includes scopes for values, loads, and
  544. // calls as well as the generation. There is a child iterator so that the
  545. // children do not need to be store separately.
  546. class StackNode {
  547. public:
  548. StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
  549. InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
  550. unsigned cg, DomTreeNode *n, DomTreeNode::const_iterator child,
  551. DomTreeNode::const_iterator end)
  552. : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
  553. EndIter(end),
  554. Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
  555. AvailableCalls)
  556. {}
  557. StackNode(const StackNode &) = delete;
  558. StackNode &operator=(const StackNode &) = delete;
  559. // Accessors.
  560. unsigned currentGeneration() const { return CurrentGeneration; }
  561. unsigned childGeneration() const { return ChildGeneration; }
  562. void childGeneration(unsigned generation) { ChildGeneration = generation; }
  563. DomTreeNode *node() { return Node; }
  564. DomTreeNode::const_iterator childIter() const { return ChildIter; }
  565. DomTreeNode *nextChild() {
  566. DomTreeNode *child = *ChildIter;
  567. ++ChildIter;
  568. return child;
  569. }
  570. DomTreeNode::const_iterator end() const { return EndIter; }
  571. bool isProcessed() const { return Processed; }
  572. void process() { Processed = true; }
  573. private:
  574. unsigned CurrentGeneration;
  575. unsigned ChildGeneration;
  576. DomTreeNode *Node;
  577. DomTreeNode::const_iterator ChildIter;
  578. DomTreeNode::const_iterator EndIter;
  579. NodeScope Scopes;
  580. bool Processed = false;
  581. };
  582. /// Wrapper class to handle memory instructions, including loads,
  583. /// stores and intrinsic loads and stores defined by the target.
  584. class ParseMemoryInst {
  585. public:
  586. ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
  587. : Inst(Inst) {
  588. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  589. IntrID = II->getIntrinsicID();
  590. if (TTI.getTgtMemIntrinsic(II, Info))
  591. return;
  592. if (isHandledNonTargetIntrinsic(IntrID)) {
  593. switch (IntrID) {
  594. case Intrinsic::masked_load:
  595. Info.PtrVal = Inst->getOperand(0);
  596. Info.MatchingId = Intrinsic::masked_load;
  597. Info.ReadMem = true;
  598. Info.WriteMem = false;
  599. Info.IsVolatile = false;
  600. break;
  601. case Intrinsic::masked_store:
  602. Info.PtrVal = Inst->getOperand(1);
  603. // Use the ID of masked load as the "matching id". This will
  604. // prevent matching non-masked loads/stores with masked ones
  605. // (which could be done), but at the moment, the code here
  606. // does not support matching intrinsics with non-intrinsics,
  607. // so keep the MatchingIds specific to masked instructions
  608. // for now (TODO).
  609. Info.MatchingId = Intrinsic::masked_load;
  610. Info.ReadMem = false;
  611. Info.WriteMem = true;
  612. Info.IsVolatile = false;
  613. break;
  614. }
  615. }
  616. }
  617. }
  618. Instruction *get() { return Inst; }
  619. const Instruction *get() const { return Inst; }
  620. bool isLoad() const {
  621. if (IntrID != 0)
  622. return Info.ReadMem;
  623. return isa<LoadInst>(Inst);
  624. }
  625. bool isStore() const {
  626. if (IntrID != 0)
  627. return Info.WriteMem;
  628. return isa<StoreInst>(Inst);
  629. }
  630. bool isAtomic() const {
  631. if (IntrID != 0)
  632. return Info.Ordering != AtomicOrdering::NotAtomic;
  633. return Inst->isAtomic();
  634. }
  635. bool isUnordered() const {
  636. if (IntrID != 0)
  637. return Info.isUnordered();
  638. if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  639. return LI->isUnordered();
  640. } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  641. return SI->isUnordered();
  642. }
  643. // Conservative answer
  644. return !Inst->isAtomic();
  645. }
  646. bool isVolatile() const {
  647. if (IntrID != 0)
  648. return Info.IsVolatile;
  649. if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  650. return LI->isVolatile();
  651. } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  652. return SI->isVolatile();
  653. }
  654. // Conservative answer
  655. return true;
  656. }
  657. bool isInvariantLoad() const {
  658. if (auto *LI = dyn_cast<LoadInst>(Inst))
  659. return LI->hasMetadata(LLVMContext::MD_invariant_load);
  660. return false;
  661. }
  662. bool isValid() const { return getPointerOperand() != nullptr; }
  663. // For regular (non-intrinsic) loads/stores, this is set to -1. For
  664. // intrinsic loads/stores, the id is retrieved from the corresponding
  665. // field in the MemIntrinsicInfo structure. That field contains
  666. // non-negative values only.
  667. int getMatchingId() const {
  668. if (IntrID != 0)
  669. return Info.MatchingId;
  670. return -1;
  671. }
  672. Value *getPointerOperand() const {
  673. if (IntrID != 0)
  674. return Info.PtrVal;
  675. return getLoadStorePointerOperand(Inst);
  676. }
  677. bool mayReadFromMemory() const {
  678. if (IntrID != 0)
  679. return Info.ReadMem;
  680. return Inst->mayReadFromMemory();
  681. }
  682. bool mayWriteToMemory() const {
  683. if (IntrID != 0)
  684. return Info.WriteMem;
  685. return Inst->mayWriteToMemory();
  686. }
  687. private:
  688. Intrinsic::ID IntrID = 0;
  689. MemIntrinsicInfo Info;
  690. Instruction *Inst;
  691. };
  692. // This function is to prevent accidentally passing a non-target
  693. // intrinsic ID to TargetTransformInfo.
  694. static bool isHandledNonTargetIntrinsic(Intrinsic::ID ID) {
  695. switch (ID) {
  696. case Intrinsic::masked_load:
  697. case Intrinsic::masked_store:
  698. return true;
  699. }
  700. return false;
  701. }
  702. static bool isHandledNonTargetIntrinsic(const Value *V) {
  703. if (auto *II = dyn_cast<IntrinsicInst>(V))
  704. return isHandledNonTargetIntrinsic(II->getIntrinsicID());
  705. return false;
  706. }
  707. bool processNode(DomTreeNode *Node);
  708. bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI,
  709. const BasicBlock *BB, const BasicBlock *Pred);
  710. Value *getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
  711. unsigned CurrentGeneration);
  712. bool overridingStores(const ParseMemoryInst &Earlier,
  713. const ParseMemoryInst &Later);
  714. Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
  715. // TODO: We could insert relevant casts on type mismatch here.
  716. if (auto *LI = dyn_cast<LoadInst>(Inst))
  717. return LI->getType() == ExpectedType ? LI : nullptr;
  718. else if (auto *SI = dyn_cast<StoreInst>(Inst)) {
  719. Value *V = SI->getValueOperand();
  720. return V->getType() == ExpectedType ? V : nullptr;
  721. }
  722. assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
  723. auto *II = cast<IntrinsicInst>(Inst);
  724. if (isHandledNonTargetIntrinsic(II->getIntrinsicID()))
  725. return getOrCreateResultNonTargetMemIntrinsic(II, ExpectedType);
  726. return TTI.getOrCreateResultFromMemIntrinsic(II, ExpectedType);
  727. }
  728. Value *getOrCreateResultNonTargetMemIntrinsic(IntrinsicInst *II,
  729. Type *ExpectedType) const {
  730. switch (II->getIntrinsicID()) {
  731. case Intrinsic::masked_load:
  732. return II;
  733. case Intrinsic::masked_store:
  734. return II->getOperand(0);
  735. }
  736. return nullptr;
  737. }
  738. /// Return true if the instruction is known to only operate on memory
  739. /// provably invariant in the given "generation".
  740. bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
  741. bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
  742. Instruction *EarlierInst, Instruction *LaterInst);
  743. bool isNonTargetIntrinsicMatch(const IntrinsicInst *Earlier,
  744. const IntrinsicInst *Later) {
  745. auto IsSubmask = [](const Value *Mask0, const Value *Mask1) {
  746. // Is Mask0 a submask of Mask1?
  747. if (Mask0 == Mask1)
  748. return true;
  749. if (isa<UndefValue>(Mask0) || isa<UndefValue>(Mask1))
  750. return false;
  751. auto *Vec0 = dyn_cast<ConstantVector>(Mask0);
  752. auto *Vec1 = dyn_cast<ConstantVector>(Mask1);
  753. if (!Vec0 || !Vec1)
  754. return false;
  755. assert(Vec0->getType() == Vec1->getType() &&
  756. "Masks should have the same type");
  757. for (int i = 0, e = Vec0->getNumOperands(); i != e; ++i) {
  758. Constant *Elem0 = Vec0->getOperand(i);
  759. Constant *Elem1 = Vec1->getOperand(i);
  760. auto *Int0 = dyn_cast<ConstantInt>(Elem0);
  761. if (Int0 && Int0->isZero())
  762. continue;
  763. auto *Int1 = dyn_cast<ConstantInt>(Elem1);
  764. if (Int1 && !Int1->isZero())
  765. continue;
  766. if (isa<UndefValue>(Elem0) || isa<UndefValue>(Elem1))
  767. return false;
  768. if (Elem0 == Elem1)
  769. continue;
  770. return false;
  771. }
  772. return true;
  773. };
  774. auto PtrOp = [](const IntrinsicInst *II) {
  775. if (II->getIntrinsicID() == Intrinsic::masked_load)
  776. return II->getOperand(0);
  777. if (II->getIntrinsicID() == Intrinsic::masked_store)
  778. return II->getOperand(1);
  779. llvm_unreachable("Unexpected IntrinsicInst");
  780. };
  781. auto MaskOp = [](const IntrinsicInst *II) {
  782. if (II->getIntrinsicID() == Intrinsic::masked_load)
  783. return II->getOperand(2);
  784. if (II->getIntrinsicID() == Intrinsic::masked_store)
  785. return II->getOperand(3);
  786. llvm_unreachable("Unexpected IntrinsicInst");
  787. };
  788. auto ThruOp = [](const IntrinsicInst *II) {
  789. if (II->getIntrinsicID() == Intrinsic::masked_load)
  790. return II->getOperand(3);
  791. llvm_unreachable("Unexpected IntrinsicInst");
  792. };
  793. if (PtrOp(Earlier) != PtrOp(Later))
  794. return false;
  795. Intrinsic::ID IDE = Earlier->getIntrinsicID();
  796. Intrinsic::ID IDL = Later->getIntrinsicID();
  797. // We could really use specific intrinsic classes for masked loads
  798. // and stores in IntrinsicInst.h.
  799. if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_load) {
  800. // Trying to replace later masked load with the earlier one.
  801. // Check that the pointers are the same, and
  802. // - masks and pass-throughs are the same, or
  803. // - replacee's pass-through is "undef" and replacer's mask is a
  804. // super-set of the replacee's mask.
  805. if (MaskOp(Earlier) == MaskOp(Later) && ThruOp(Earlier) == ThruOp(Later))
  806. return true;
  807. if (!isa<UndefValue>(ThruOp(Later)))
  808. return false;
  809. return IsSubmask(MaskOp(Later), MaskOp(Earlier));
  810. }
  811. if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_load) {
  812. // Trying to replace a load of a stored value with the store's value.
  813. // Check that the pointers are the same, and
  814. // - load's mask is a subset of store's mask, and
  815. // - load's pass-through is "undef".
  816. if (!IsSubmask(MaskOp(Later), MaskOp(Earlier)))
  817. return false;
  818. return isa<UndefValue>(ThruOp(Later));
  819. }
  820. if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_store) {
  821. // Trying to remove a store of the loaded value.
  822. // Check that the pointers are the same, and
  823. // - store's mask is a subset of the load's mask.
  824. return IsSubmask(MaskOp(Later), MaskOp(Earlier));
  825. }
  826. if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_store) {
  827. // Trying to remove a dead store (earlier).
  828. // Check that the pointers are the same,
  829. // - the to-be-removed store's mask is a subset of the other store's
  830. // mask.
  831. return IsSubmask(MaskOp(Earlier), MaskOp(Later));
  832. }
  833. return false;
  834. }
  835. void removeMSSA(Instruction &Inst) {
  836. if (!MSSA)
  837. return;
  838. if (VerifyMemorySSA)
  839. MSSA->verifyMemorySSA();
  840. // Removing a store here can leave MemorySSA in an unoptimized state by
  841. // creating MemoryPhis that have identical arguments and by creating
  842. // MemoryUses whose defining access is not an actual clobber. The phi case
  843. // is handled by MemorySSA when passing OptimizePhis = true to
  844. // removeMemoryAccess. The non-optimized MemoryUse case is lazily updated
  845. // by MemorySSA's getClobberingMemoryAccess.
  846. MSSAUpdater->removeMemoryAccess(&Inst, true);
  847. }
  848. };
  849. } // end anonymous namespace
  850. /// Determine if the memory referenced by LaterInst is from the same heap
  851. /// version as EarlierInst.
  852. /// This is currently called in two scenarios:
  853. ///
  854. /// load p
  855. /// ...
  856. /// load p
  857. ///
  858. /// and
  859. ///
  860. /// x = load p
  861. /// ...
  862. /// store x, p
  863. ///
  864. /// in both cases we want to verify that there are no possible writes to the
  865. /// memory referenced by p between the earlier and later instruction.
  866. bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
  867. unsigned LaterGeneration,
  868. Instruction *EarlierInst,
  869. Instruction *LaterInst) {
  870. // Check the simple memory generation tracking first.
  871. if (EarlierGeneration == LaterGeneration)
  872. return true;
  873. if (!MSSA)
  874. return false;
  875. // If MemorySSA has determined that one of EarlierInst or LaterInst does not
  876. // read/write memory, then we can safely return true here.
  877. // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
  878. // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
  879. // by also checking the MemorySSA MemoryAccess on the instruction. Initial
  880. // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
  881. // with the default optimization pipeline.
  882. auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
  883. if (!EarlierMA)
  884. return true;
  885. auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
  886. if (!LaterMA)
  887. return true;
  888. // Since we know LaterDef dominates LaterInst and EarlierInst dominates
  889. // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
  890. // EarlierInst and LaterInst and neither can any other write that potentially
  891. // clobbers LaterInst.
  892. MemoryAccess *LaterDef;
  893. if (ClobberCounter < EarlyCSEMssaOptCap) {
  894. LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
  895. ClobberCounter++;
  896. } else
  897. LaterDef = LaterMA->getDefiningAccess();
  898. return MSSA->dominates(LaterDef, EarlierMA);
  899. }
  900. bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
  901. // A location loaded from with an invariant_load is assumed to *never* change
  902. // within the visible scope of the compilation.
  903. if (auto *LI = dyn_cast<LoadInst>(I))
  904. if (LI->hasMetadata(LLVMContext::MD_invariant_load))
  905. return true;
  906. auto MemLocOpt = MemoryLocation::getOrNone(I);
  907. if (!MemLocOpt)
  908. // "target" intrinsic forms of loads aren't currently known to
  909. // MemoryLocation::get. TODO
  910. return false;
  911. MemoryLocation MemLoc = *MemLocOpt;
  912. if (!AvailableInvariants.count(MemLoc))
  913. return false;
  914. // Is the generation at which this became invariant older than the
  915. // current one?
  916. return AvailableInvariants.lookup(MemLoc) <= GenAt;
  917. }
  918. bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
  919. const BranchInst *BI, const BasicBlock *BB,
  920. const BasicBlock *Pred) {
  921. assert(BI->isConditional() && "Should be a conditional branch!");
  922. assert(BI->getCondition() == CondInst && "Wrong condition?");
  923. assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
  924. auto *TorF = (BI->getSuccessor(0) == BB)
  925. ? ConstantInt::getTrue(BB->getContext())
  926. : ConstantInt::getFalse(BB->getContext());
  927. auto MatchBinOp = [](Instruction *I, unsigned Opcode, Value *&LHS,
  928. Value *&RHS) {
  929. if (Opcode == Instruction::And &&
  930. match(I, m_LogicalAnd(m_Value(LHS), m_Value(RHS))))
  931. return true;
  932. else if (Opcode == Instruction::Or &&
  933. match(I, m_LogicalOr(m_Value(LHS), m_Value(RHS))))
  934. return true;
  935. return false;
  936. };
  937. // If the condition is AND operation, we can propagate its operands into the
  938. // true branch. If it is OR operation, we can propagate them into the false
  939. // branch.
  940. unsigned PropagateOpcode =
  941. (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
  942. bool MadeChanges = false;
  943. SmallVector<Instruction *, 4> WorkList;
  944. SmallPtrSet<Instruction *, 4> Visited;
  945. WorkList.push_back(CondInst);
  946. while (!WorkList.empty()) {
  947. Instruction *Curr = WorkList.pop_back_val();
  948. AvailableValues.insert(Curr, TorF);
  949. LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
  950. << Curr->getName() << "' as " << *TorF << " in "
  951. << BB->getName() << "\n");
  952. if (!DebugCounter::shouldExecute(CSECounter)) {
  953. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  954. } else {
  955. // Replace all dominated uses with the known value.
  956. if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
  957. BasicBlockEdge(Pred, BB))) {
  958. NumCSECVP += Count;
  959. MadeChanges = true;
  960. }
  961. }
  962. Value *LHS, *RHS;
  963. if (MatchBinOp(Curr, PropagateOpcode, LHS, RHS))
  964. for (auto &Op : { LHS, RHS })
  965. if (Instruction *OPI = dyn_cast<Instruction>(Op))
  966. if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
  967. WorkList.push_back(OPI);
  968. }
  969. return MadeChanges;
  970. }
  971. Value *EarlyCSE::getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
  972. unsigned CurrentGeneration) {
  973. if (InVal.DefInst == nullptr)
  974. return nullptr;
  975. if (InVal.MatchingId != MemInst.getMatchingId())
  976. return nullptr;
  977. // We don't yet handle removing loads with ordering of any kind.
  978. if (MemInst.isVolatile() || !MemInst.isUnordered())
  979. return nullptr;
  980. // We can't replace an atomic load with one which isn't also atomic.
  981. if (MemInst.isLoad() && !InVal.IsAtomic && MemInst.isAtomic())
  982. return nullptr;
  983. // The value V returned from this function is used differently depending
  984. // on whether MemInst is a load or a store. If it's a load, we will replace
  985. // MemInst with V, if it's a store, we will check if V is the same as the
  986. // available value.
  987. bool MemInstMatching = !MemInst.isLoad();
  988. Instruction *Matching = MemInstMatching ? MemInst.get() : InVal.DefInst;
  989. Instruction *Other = MemInstMatching ? InVal.DefInst : MemInst.get();
  990. // For stores check the result values before checking memory generation
  991. // (otherwise isSameMemGeneration may crash).
  992. Value *Result = MemInst.isStore()
  993. ? getOrCreateResult(Matching, Other->getType())
  994. : nullptr;
  995. if (MemInst.isStore() && InVal.DefInst != Result)
  996. return nullptr;
  997. // Deal with non-target memory intrinsics.
  998. bool MatchingNTI = isHandledNonTargetIntrinsic(Matching);
  999. bool OtherNTI = isHandledNonTargetIntrinsic(Other);
  1000. if (OtherNTI != MatchingNTI)
  1001. return nullptr;
  1002. if (OtherNTI && MatchingNTI) {
  1003. if (!isNonTargetIntrinsicMatch(cast<IntrinsicInst>(InVal.DefInst),
  1004. cast<IntrinsicInst>(MemInst.get())))
  1005. return nullptr;
  1006. }
  1007. if (!isOperatingOnInvariantMemAt(MemInst.get(), InVal.Generation) &&
  1008. !isSameMemGeneration(InVal.Generation, CurrentGeneration, InVal.DefInst,
  1009. MemInst.get()))
  1010. return nullptr;
  1011. if (!Result)
  1012. Result = getOrCreateResult(Matching, Other->getType());
  1013. return Result;
  1014. }
  1015. bool EarlyCSE::overridingStores(const ParseMemoryInst &Earlier,
  1016. const ParseMemoryInst &Later) {
  1017. // Can we remove Earlier store because of Later store?
  1018. assert(Earlier.isUnordered() && !Earlier.isVolatile() &&
  1019. "Violated invariant");
  1020. if (Earlier.getPointerOperand() != Later.getPointerOperand())
  1021. return false;
  1022. if (Earlier.getMatchingId() != Later.getMatchingId())
  1023. return false;
  1024. // At the moment, we don't remove ordered stores, but do remove
  1025. // unordered atomic stores. There's no special requirement (for
  1026. // unordered atomics) about removing atomic stores only in favor of
  1027. // other atomic stores since we were going to execute the non-atomic
  1028. // one anyway and the atomic one might never have become visible.
  1029. if (!Earlier.isUnordered() || !Later.isUnordered())
  1030. return false;
  1031. // Deal with non-target memory intrinsics.
  1032. bool ENTI = isHandledNonTargetIntrinsic(Earlier.get());
  1033. bool LNTI = isHandledNonTargetIntrinsic(Later.get());
  1034. if (ENTI && LNTI)
  1035. return isNonTargetIntrinsicMatch(cast<IntrinsicInst>(Earlier.get()),
  1036. cast<IntrinsicInst>(Later.get()));
  1037. // Because of the check above, at least one of them is false.
  1038. // For now disallow matching intrinsics with non-intrinsics,
  1039. // so assume that the stores match if neither is an intrinsic.
  1040. return ENTI == LNTI;
  1041. }
  1042. bool EarlyCSE::processNode(DomTreeNode *Node) {
  1043. bool Changed = false;
  1044. BasicBlock *BB = Node->getBlock();
  1045. // If this block has a single predecessor, then the predecessor is the parent
  1046. // of the domtree node and all of the live out memory values are still current
  1047. // in this block. If this block has multiple predecessors, then they could
  1048. // have invalidated the live-out memory values of our parent value. For now,
  1049. // just be conservative and invalidate memory if this block has multiple
  1050. // predecessors.
  1051. if (!BB->getSinglePredecessor())
  1052. ++CurrentGeneration;
  1053. // If this node has a single predecessor which ends in a conditional branch,
  1054. // we can infer the value of the branch condition given that we took this
  1055. // path. We need the single predecessor to ensure there's not another path
  1056. // which reaches this block where the condition might hold a different
  1057. // value. Since we're adding this to the scoped hash table (like any other
  1058. // def), it will have been popped if we encounter a future merge block.
  1059. if (BasicBlock *Pred = BB->getSinglePredecessor()) {
  1060. auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
  1061. if (BI && BI->isConditional()) {
  1062. auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
  1063. if (CondInst && SimpleValue::canHandle(CondInst))
  1064. Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
  1065. }
  1066. }
  1067. /// LastStore - Keep track of the last non-volatile store that we saw... for
  1068. /// as long as there in no instruction that reads memory. If we see a store
  1069. /// to the same location, we delete the dead store. This zaps trivial dead
  1070. /// stores which can occur in bitfield code among other things.
  1071. Instruction *LastStore = nullptr;
  1072. // See if any instructions in the block can be eliminated. If so, do it. If
  1073. // not, add them to AvailableValues.
  1074. for (Instruction &Inst : make_early_inc_range(BB->getInstList())) {
  1075. // Dead instructions should just be removed.
  1076. if (isInstructionTriviallyDead(&Inst, &TLI)) {
  1077. LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << Inst << '\n');
  1078. if (!DebugCounter::shouldExecute(CSECounter)) {
  1079. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1080. continue;
  1081. }
  1082. salvageKnowledge(&Inst, &AC);
  1083. salvageDebugInfo(Inst);
  1084. removeMSSA(Inst);
  1085. Inst.eraseFromParent();
  1086. Changed = true;
  1087. ++NumSimplify;
  1088. continue;
  1089. }
  1090. // Skip assume intrinsics, they don't really have side effects (although
  1091. // they're marked as such to ensure preservation of control dependencies),
  1092. // and this pass will not bother with its removal. However, we should mark
  1093. // its condition as true for all dominated blocks.
  1094. if (auto *Assume = dyn_cast<AssumeInst>(&Inst)) {
  1095. auto *CondI = dyn_cast<Instruction>(Assume->getArgOperand(0));
  1096. if (CondI && SimpleValue::canHandle(CondI)) {
  1097. LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << Inst
  1098. << '\n');
  1099. AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
  1100. } else
  1101. LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << Inst << '\n');
  1102. continue;
  1103. }
  1104. // Likewise, noalias intrinsics don't actually write.
  1105. if (match(&Inst,
  1106. m_Intrinsic<Intrinsic::experimental_noalias_scope_decl>())) {
  1107. LLVM_DEBUG(dbgs() << "EarlyCSE skipping noalias intrinsic: " << Inst
  1108. << '\n');
  1109. continue;
  1110. }
  1111. // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
  1112. if (match(&Inst, m_Intrinsic<Intrinsic::sideeffect>())) {
  1113. LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << Inst << '\n');
  1114. continue;
  1115. }
  1116. // Skip pseudoprobe intrinsics, for the same reason as assume intrinsics.
  1117. if (match(&Inst, m_Intrinsic<Intrinsic::pseudoprobe>())) {
  1118. LLVM_DEBUG(dbgs() << "EarlyCSE skipping pseudoprobe: " << Inst << '\n');
  1119. continue;
  1120. }
  1121. // We can skip all invariant.start intrinsics since they only read memory,
  1122. // and we can forward values across it. For invariant starts without
  1123. // invariant ends, we can use the fact that the invariantness never ends to
  1124. // start a scope in the current generaton which is true for all future
  1125. // generations. Also, we dont need to consume the last store since the
  1126. // semantics of invariant.start allow us to perform DSE of the last
  1127. // store, if there was a store following invariant.start. Consider:
  1128. //
  1129. // store 30, i8* p
  1130. // invariant.start(p)
  1131. // store 40, i8* p
  1132. // We can DSE the store to 30, since the store 40 to invariant location p
  1133. // causes undefined behaviour.
  1134. if (match(&Inst, m_Intrinsic<Intrinsic::invariant_start>())) {
  1135. // If there are any uses, the scope might end.
  1136. if (!Inst.use_empty())
  1137. continue;
  1138. MemoryLocation MemLoc =
  1139. MemoryLocation::getForArgument(&cast<CallInst>(Inst), 1, TLI);
  1140. // Don't start a scope if we already have a better one pushed
  1141. if (!AvailableInvariants.count(MemLoc))
  1142. AvailableInvariants.insert(MemLoc, CurrentGeneration);
  1143. continue;
  1144. }
  1145. if (isGuard(&Inst)) {
  1146. if (auto *CondI =
  1147. dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0))) {
  1148. if (SimpleValue::canHandle(CondI)) {
  1149. // Do we already know the actual value of this condition?
  1150. if (auto *KnownCond = AvailableValues.lookup(CondI)) {
  1151. // Is the condition known to be true?
  1152. if (isa<ConstantInt>(KnownCond) &&
  1153. cast<ConstantInt>(KnownCond)->isOne()) {
  1154. LLVM_DEBUG(dbgs()
  1155. << "EarlyCSE removing guard: " << Inst << '\n');
  1156. salvageKnowledge(&Inst, &AC);
  1157. removeMSSA(Inst);
  1158. Inst.eraseFromParent();
  1159. Changed = true;
  1160. continue;
  1161. } else
  1162. // Use the known value if it wasn't true.
  1163. cast<CallInst>(Inst).setArgOperand(0, KnownCond);
  1164. }
  1165. // The condition we're on guarding here is true for all dominated
  1166. // locations.
  1167. AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
  1168. }
  1169. }
  1170. // Guard intrinsics read all memory, but don't write any memory.
  1171. // Accordingly, don't update the generation but consume the last store (to
  1172. // avoid an incorrect DSE).
  1173. LastStore = nullptr;
  1174. continue;
  1175. }
  1176. // If the instruction can be simplified (e.g. X+0 = X) then replace it with
  1177. // its simpler value.
  1178. if (Value *V = SimplifyInstruction(&Inst, SQ)) {
  1179. LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << Inst << " to: " << *V
  1180. << '\n');
  1181. if (!DebugCounter::shouldExecute(CSECounter)) {
  1182. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1183. } else {
  1184. bool Killed = false;
  1185. if (!Inst.use_empty()) {
  1186. Inst.replaceAllUsesWith(V);
  1187. Changed = true;
  1188. }
  1189. if (isInstructionTriviallyDead(&Inst, &TLI)) {
  1190. salvageKnowledge(&Inst, &AC);
  1191. removeMSSA(Inst);
  1192. Inst.eraseFromParent();
  1193. Changed = true;
  1194. Killed = true;
  1195. }
  1196. if (Changed)
  1197. ++NumSimplify;
  1198. if (Killed)
  1199. continue;
  1200. }
  1201. }
  1202. // If this is a simple instruction that we can value number, process it.
  1203. if (SimpleValue::canHandle(&Inst)) {
  1204. // See if the instruction has an available value. If so, use it.
  1205. if (Value *V = AvailableValues.lookup(&Inst)) {
  1206. LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << Inst << " to: " << *V
  1207. << '\n');
  1208. if (!DebugCounter::shouldExecute(CSECounter)) {
  1209. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1210. continue;
  1211. }
  1212. if (auto *I = dyn_cast<Instruction>(V)) {
  1213. // If I being poison triggers UB, there is no need to drop those
  1214. // flags. Otherwise, only retain flags present on both I and Inst.
  1215. // TODO: Currently some fast-math flags are not treated as
  1216. // poison-generating even though they should. Until this is fixed,
  1217. // always retain flags present on both I and Inst for floating point
  1218. // instructions.
  1219. if (isa<FPMathOperator>(I) || (I->hasPoisonGeneratingFlags() && !programUndefinedIfPoison(I)))
  1220. I->andIRFlags(&Inst);
  1221. }
  1222. Inst.replaceAllUsesWith(V);
  1223. salvageKnowledge(&Inst, &AC);
  1224. removeMSSA(Inst);
  1225. Inst.eraseFromParent();
  1226. Changed = true;
  1227. ++NumCSE;
  1228. continue;
  1229. }
  1230. // Otherwise, just remember that this value is available.
  1231. AvailableValues.insert(&Inst, &Inst);
  1232. continue;
  1233. }
  1234. ParseMemoryInst MemInst(&Inst, TTI);
  1235. // If this is a non-volatile load, process it.
  1236. if (MemInst.isValid() && MemInst.isLoad()) {
  1237. // (conservatively) we can't peak past the ordering implied by this
  1238. // operation, but we can add this load to our set of available values
  1239. if (MemInst.isVolatile() || !MemInst.isUnordered()) {
  1240. LastStore = nullptr;
  1241. ++CurrentGeneration;
  1242. }
  1243. if (MemInst.isInvariantLoad()) {
  1244. // If we pass an invariant load, we know that memory location is
  1245. // indefinitely constant from the moment of first dereferenceability.
  1246. // We conservatively treat the invariant_load as that moment. If we
  1247. // pass a invariant load after already establishing a scope, don't
  1248. // restart it since we want to preserve the earliest point seen.
  1249. auto MemLoc = MemoryLocation::get(&Inst);
  1250. if (!AvailableInvariants.count(MemLoc))
  1251. AvailableInvariants.insert(MemLoc, CurrentGeneration);
  1252. }
  1253. // If we have an available version of this load, and if it is the right
  1254. // generation or the load is known to be from an invariant location,
  1255. // replace this instruction.
  1256. //
  1257. // If either the dominating load or the current load are invariant, then
  1258. // we can assume the current load loads the same value as the dominating
  1259. // load.
  1260. LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
  1261. if (Value *Op = getMatchingValue(InVal, MemInst, CurrentGeneration)) {
  1262. LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << Inst
  1263. << " to: " << *InVal.DefInst << '\n');
  1264. if (!DebugCounter::shouldExecute(CSECounter)) {
  1265. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1266. continue;
  1267. }
  1268. if (!Inst.use_empty())
  1269. Inst.replaceAllUsesWith(Op);
  1270. salvageKnowledge(&Inst, &AC);
  1271. removeMSSA(Inst);
  1272. Inst.eraseFromParent();
  1273. Changed = true;
  1274. ++NumCSELoad;
  1275. continue;
  1276. }
  1277. // Otherwise, remember that we have this instruction.
  1278. AvailableLoads.insert(MemInst.getPointerOperand(),
  1279. LoadValue(&Inst, CurrentGeneration,
  1280. MemInst.getMatchingId(),
  1281. MemInst.isAtomic()));
  1282. LastStore = nullptr;
  1283. continue;
  1284. }
  1285. // If this instruction may read from memory or throw (and potentially read
  1286. // from memory in the exception handler), forget LastStore. Load/store
  1287. // intrinsics will indicate both a read and a write to memory. The target
  1288. // may override this (e.g. so that a store intrinsic does not read from
  1289. // memory, and thus will be treated the same as a regular store for
  1290. // commoning purposes).
  1291. if ((Inst.mayReadFromMemory() || Inst.mayThrow()) &&
  1292. !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
  1293. LastStore = nullptr;
  1294. // If this is a read-only call, process it.
  1295. if (CallValue::canHandle(&Inst)) {
  1296. // If we have an available version of this call, and if it is the right
  1297. // generation, replace this instruction.
  1298. std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(&Inst);
  1299. if (InVal.first != nullptr &&
  1300. isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
  1301. &Inst)) {
  1302. LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << Inst
  1303. << " to: " << *InVal.first << '\n');
  1304. if (!DebugCounter::shouldExecute(CSECounter)) {
  1305. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1306. continue;
  1307. }
  1308. if (!Inst.use_empty())
  1309. Inst.replaceAllUsesWith(InVal.first);
  1310. salvageKnowledge(&Inst, &AC);
  1311. removeMSSA(Inst);
  1312. Inst.eraseFromParent();
  1313. Changed = true;
  1314. ++NumCSECall;
  1315. continue;
  1316. }
  1317. // Otherwise, remember that we have this instruction.
  1318. AvailableCalls.insert(&Inst, std::make_pair(&Inst, CurrentGeneration));
  1319. continue;
  1320. }
  1321. // A release fence requires that all stores complete before it, but does
  1322. // not prevent the reordering of following loads 'before' the fence. As a
  1323. // result, we don't need to consider it as writing to memory and don't need
  1324. // to advance the generation. We do need to prevent DSE across the fence,
  1325. // but that's handled above.
  1326. if (auto *FI = dyn_cast<FenceInst>(&Inst))
  1327. if (FI->getOrdering() == AtomicOrdering::Release) {
  1328. assert(Inst.mayReadFromMemory() && "relied on to prevent DSE above");
  1329. continue;
  1330. }
  1331. // write back DSE - If we write back the same value we just loaded from
  1332. // the same location and haven't passed any intervening writes or ordering
  1333. // operations, we can remove the write. The primary benefit is in allowing
  1334. // the available load table to remain valid and value forward past where
  1335. // the store originally was.
  1336. if (MemInst.isValid() && MemInst.isStore()) {
  1337. LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
  1338. if (InVal.DefInst &&
  1339. InVal.DefInst == getMatchingValue(InVal, MemInst, CurrentGeneration)) {
  1340. // It is okay to have a LastStore to a different pointer here if MemorySSA
  1341. // tells us that the load and store are from the same memory generation.
  1342. // In that case, LastStore should keep its present value since we're
  1343. // removing the current store.
  1344. assert((!LastStore ||
  1345. ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
  1346. MemInst.getPointerOperand() ||
  1347. MSSA) &&
  1348. "can't have an intervening store if not using MemorySSA!");
  1349. LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << Inst << '\n');
  1350. if (!DebugCounter::shouldExecute(CSECounter)) {
  1351. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1352. continue;
  1353. }
  1354. salvageKnowledge(&Inst, &AC);
  1355. removeMSSA(Inst);
  1356. Inst.eraseFromParent();
  1357. Changed = true;
  1358. ++NumDSE;
  1359. // We can avoid incrementing the generation count since we were able
  1360. // to eliminate this store.
  1361. continue;
  1362. }
  1363. }
  1364. // Okay, this isn't something we can CSE at all. Check to see if it is
  1365. // something that could modify memory. If so, our available memory values
  1366. // cannot be used so bump the generation count.
  1367. if (Inst.mayWriteToMemory()) {
  1368. ++CurrentGeneration;
  1369. if (MemInst.isValid() && MemInst.isStore()) {
  1370. // We do a trivial form of DSE if there are two stores to the same
  1371. // location with no intervening loads. Delete the earlier store.
  1372. if (LastStore) {
  1373. if (overridingStores(ParseMemoryInst(LastStore, TTI), MemInst)) {
  1374. LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
  1375. << " due to: " << Inst << '\n');
  1376. if (!DebugCounter::shouldExecute(CSECounter)) {
  1377. LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
  1378. } else {
  1379. salvageKnowledge(&Inst, &AC);
  1380. removeMSSA(*LastStore);
  1381. LastStore->eraseFromParent();
  1382. Changed = true;
  1383. ++NumDSE;
  1384. LastStore = nullptr;
  1385. }
  1386. }
  1387. // fallthrough - we can exploit information about this store
  1388. }
  1389. // Okay, we just invalidated anything we knew about loaded values. Try
  1390. // to salvage *something* by remembering that the stored value is a live
  1391. // version of the pointer. It is safe to forward from volatile stores
  1392. // to non-volatile loads, so we don't have to check for volatility of
  1393. // the store.
  1394. AvailableLoads.insert(MemInst.getPointerOperand(),
  1395. LoadValue(&Inst, CurrentGeneration,
  1396. MemInst.getMatchingId(),
  1397. MemInst.isAtomic()));
  1398. // Remember that this was the last unordered store we saw for DSE. We
  1399. // don't yet handle DSE on ordered or volatile stores since we don't
  1400. // have a good way to model the ordering requirement for following
  1401. // passes once the store is removed. We could insert a fence, but
  1402. // since fences are slightly stronger than stores in their ordering,
  1403. // it's not clear this is a profitable transform. Another option would
  1404. // be to merge the ordering with that of the post dominating store.
  1405. if (MemInst.isUnordered() && !MemInst.isVolatile())
  1406. LastStore = &Inst;
  1407. else
  1408. LastStore = nullptr;
  1409. }
  1410. }
  1411. }
  1412. return Changed;
  1413. }
  1414. bool EarlyCSE::run() {
  1415. // Note, deque is being used here because there is significant performance
  1416. // gains over vector when the container becomes very large due to the
  1417. // specific access patterns. For more information see the mailing list
  1418. // discussion on this:
  1419. // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
  1420. std::deque<StackNode *> nodesToProcess;
  1421. bool Changed = false;
  1422. // Process the root node.
  1423. nodesToProcess.push_back(new StackNode(
  1424. AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
  1425. CurrentGeneration, DT.getRootNode(),
  1426. DT.getRootNode()->begin(), DT.getRootNode()->end()));
  1427. assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it.");
  1428. // Process the stack.
  1429. while (!nodesToProcess.empty()) {
  1430. // Grab the first item off the stack. Set the current generation, remove
  1431. // the node from the stack, and process it.
  1432. StackNode *NodeToProcess = nodesToProcess.back();
  1433. // Initialize class members.
  1434. CurrentGeneration = NodeToProcess->currentGeneration();
  1435. // Check if the node needs to be processed.
  1436. if (!NodeToProcess->isProcessed()) {
  1437. // Process the node.
  1438. Changed |= processNode(NodeToProcess->node());
  1439. NodeToProcess->childGeneration(CurrentGeneration);
  1440. NodeToProcess->process();
  1441. } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
  1442. // Push the next child onto the stack.
  1443. DomTreeNode *child = NodeToProcess->nextChild();
  1444. nodesToProcess.push_back(
  1445. new StackNode(AvailableValues, AvailableLoads, AvailableInvariants,
  1446. AvailableCalls, NodeToProcess->childGeneration(),
  1447. child, child->begin(), child->end()));
  1448. } else {
  1449. // It has been processed, and there are no more children to process,
  1450. // so delete it and pop it off the stack.
  1451. delete NodeToProcess;
  1452. nodesToProcess.pop_back();
  1453. }
  1454. } // while (!nodes...)
  1455. return Changed;
  1456. }
  1457. PreservedAnalyses EarlyCSEPass::run(Function &F,
  1458. FunctionAnalysisManager &AM) {
  1459. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  1460. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  1461. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  1462. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  1463. auto *MSSA =
  1464. UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
  1465. EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
  1466. if (!CSE.run())
  1467. return PreservedAnalyses::all();
  1468. PreservedAnalyses PA;
  1469. PA.preserveSet<CFGAnalyses>();
  1470. if (UseMemorySSA)
  1471. PA.preserve<MemorySSAAnalysis>();
  1472. return PA;
  1473. }
  1474. void EarlyCSEPass::printPipeline(
  1475. raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
  1476. static_cast<PassInfoMixin<EarlyCSEPass> *>(this)->printPipeline(
  1477. OS, MapClassName2PassName);
  1478. OS << "<";
  1479. if (UseMemorySSA)
  1480. OS << "memssa";
  1481. OS << ">";
  1482. }
  1483. namespace {
  1484. /// A simple and fast domtree-based CSE pass.
  1485. ///
  1486. /// This pass does a simple depth-first walk over the dominator tree,
  1487. /// eliminating trivially redundant instructions and using instsimplify to
  1488. /// canonicalize things as it goes. It is intended to be fast and catch obvious
  1489. /// cases so that instcombine and other passes are more effective. It is
  1490. /// expected that a later pass of GVN will catch the interesting/hard cases.
  1491. template<bool UseMemorySSA>
  1492. class EarlyCSELegacyCommonPass : public FunctionPass {
  1493. public:
  1494. static char ID;
  1495. EarlyCSELegacyCommonPass() : FunctionPass(ID) {
  1496. if (UseMemorySSA)
  1497. initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
  1498. else
  1499. initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
  1500. }
  1501. bool runOnFunction(Function &F) override {
  1502. if (skipFunction(F))
  1503. return false;
  1504. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  1505. auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  1506. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1507. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1508. auto *MSSA =
  1509. UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
  1510. EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
  1511. return CSE.run();
  1512. }
  1513. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1514. AU.addRequired<AssumptionCacheTracker>();
  1515. AU.addRequired<DominatorTreeWrapperPass>();
  1516. AU.addRequired<TargetLibraryInfoWrapperPass>();
  1517. AU.addRequired<TargetTransformInfoWrapperPass>();
  1518. if (UseMemorySSA) {
  1519. AU.addRequired<AAResultsWrapperPass>();
  1520. AU.addRequired<MemorySSAWrapperPass>();
  1521. AU.addPreserved<MemorySSAWrapperPass>();
  1522. }
  1523. AU.addPreserved<GlobalsAAWrapperPass>();
  1524. AU.addPreserved<AAResultsWrapperPass>();
  1525. AU.setPreservesCFG();
  1526. }
  1527. };
  1528. } // end anonymous namespace
  1529. using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
  1530. template<>
  1531. char EarlyCSELegacyPass::ID = 0;
  1532. INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
  1533. false)
  1534. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  1535. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1536. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1537. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  1538. INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
  1539. using EarlyCSEMemSSALegacyPass =
  1540. EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
  1541. template<>
  1542. char EarlyCSEMemSSALegacyPass::ID = 0;
  1543. FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
  1544. if (UseMemorySSA)
  1545. return new EarlyCSEMemSSALegacyPass();
  1546. else
  1547. return new EarlyCSELegacyPass();
  1548. }
  1549. INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
  1550. "Early CSE w/ MemorySSA", false, false)
  1551. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  1552. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1553. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  1554. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1555. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  1556. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  1557. INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
  1558. "Early CSE w/ MemorySSA", false, false)