GVN.cpp 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855
  1. //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass performs global value numbering to eliminate fully redundant
  11. // instructions. It also performs simple dead load elimination.
  12. //
  13. // Note that this pass does the value numbering itself; it does not use the
  14. // ValueNumbering analysis passes.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Transforms/Scalar.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/DepthFirstIterator.h"
  20. #include "llvm/ADT/Hashing.h"
  21. #include "llvm/ADT/MapVector.h"
  22. #include "llvm/ADT/PostOrderIterator.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/Analysis/AliasAnalysis.h"
  27. #include "llvm/Analysis/AssumptionCache.h"
  28. #include "llvm/Analysis/CFG.h"
  29. #include "llvm/Analysis/ConstantFolding.h"
  30. #include "llvm/Analysis/InstructionSimplify.h"
  31. #include "llvm/Analysis/Loads.h"
  32. #include "llvm/Analysis/MemoryBuiltins.h"
  33. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  34. #include "llvm/Analysis/PHITransAddr.h"
  35. #include "llvm/Analysis/TargetLibraryInfo.h"
  36. #include "llvm/Analysis/ValueTracking.h"
  37. #include "llvm/IR/DataLayout.h"
  38. #include "llvm/IR/Dominators.h"
  39. #include "llvm/IR/GlobalVariable.h"
  40. #include "llvm/IR/IRBuilder.h"
  41. #include "llvm/IR/IntrinsicInst.h"
  42. #include "llvm/IR/LLVMContext.h"
  43. #include "llvm/IR/Metadata.h"
  44. #include "llvm/IR/PatternMatch.h"
  45. #include "llvm/Support/Allocator.h"
  46. #include "llvm/Support/CommandLine.h"
  47. #include "llvm/Support/Debug.h"
  48. #include "llvm/Support/raw_ostream.h"
  49. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  50. #include "llvm/Transforms/Utils/Local.h"
  51. #include "llvm/Transforms/Utils/SSAUpdater.h"
  52. #include <vector>
  53. #include "dxc/HLSL/DxilConstants.h" // HLSL Change
  54. using namespace llvm;
  55. using namespace PatternMatch;
  56. #define DEBUG_TYPE "gvn"
  57. STATISTIC(NumGVNInstr, "Number of instructions deleted");
  58. STATISTIC(NumGVNLoad, "Number of loads deleted");
  59. STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
  60. STATISTIC(NumGVNBlocks, "Number of blocks merged");
  61. STATISTIC(NumGVNSimpl, "Number of instructions simplified");
  62. STATISTIC(NumGVNEqProp, "Number of equalities propagated");
  63. STATISTIC(NumPRELoad, "Number of loads PRE'd");
  64. #if 0 // HLSL Change Starts - option pending
  65. static cl::opt<bool> EnablePRE("enable-pre",
  66. cl::init(true), cl::Hidden);
  67. static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
  68. // Maximum allowed recursion depth.
  69. static cl::opt<uint32_t>
  70. MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
  71. cl::desc("Max recurse depth (default = 1000)"));
  72. #else
  73. static const bool EnablePRE = true;
  74. static const bool EnableLoadPRE = true;
  75. static const uint32_t MaxRecurseDepth = 1000;
  76. #endif // HLSL Change Ends
  77. //===----------------------------------------------------------------------===//
  78. // ValueTable Class
  79. //===----------------------------------------------------------------------===//
  80. /// This class holds the mapping between values and value numbers. It is used
  81. /// as an efficient mechanism to determine the expression-wise equivalence of
  82. /// two values.
  83. namespace {
  84. struct Expression {
  85. uint32_t opcode;
  86. Type *type;
  87. SmallVector<uint32_t, 4> varargs;
  88. Expression(uint32_t o = ~2U) : opcode(o) { }
  89. bool operator==(const Expression &other) const {
  90. if (opcode != other.opcode)
  91. return false;
  92. if (opcode == ~0U || opcode == ~1U)
  93. return true;
  94. if (type != other.type)
  95. return false;
  96. if (varargs != other.varargs)
  97. return false;
  98. return true;
  99. }
  100. friend hash_code hash_value(const Expression &Value) {
  101. return hash_combine(Value.opcode, Value.type,
  102. hash_combine_range(Value.varargs.begin(),
  103. Value.varargs.end()));
  104. }
  105. };
  106. class ValueTable {
  107. DenseMap<Value*, uint32_t> valueNumbering;
  108. DenseMap<Expression, uint32_t> expressionNumbering;
  109. AliasAnalysis *AA;
  110. MemoryDependenceAnalysis *MD;
  111. DominatorTree *DT;
  112. uint32_t nextValueNumber;
  113. Expression create_expression(Instruction* I);
  114. Expression create_cmp_expression(unsigned Opcode,
  115. CmpInst::Predicate Predicate,
  116. Value *LHS, Value *RHS);
  117. Expression create_extractvalue_expression(ExtractValueInst* EI);
  118. uint32_t lookup_or_add_call(CallInst* C);
  119. public:
  120. ValueTable() : nextValueNumber(1) { }
  121. uint32_t lookup_or_add(Value *V);
  122. uint32_t lookup(Value *V) const;
  123. uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
  124. Value *LHS, Value *RHS);
  125. void add(Value *V, uint32_t num);
  126. void clear();
  127. void erase(Value *v);
  128. void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
  129. AliasAnalysis *getAliasAnalysis() const { return AA; }
  130. void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
  131. void setDomTree(DominatorTree* D) { DT = D; }
  132. uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
  133. void verifyRemoved(const Value *) const;
  134. };
  135. }
  136. namespace llvm {
  137. template <> struct DenseMapInfo<Expression> {
  138. static inline Expression getEmptyKey() {
  139. return ~0U;
  140. }
  141. static inline Expression getTombstoneKey() {
  142. return ~1U;
  143. }
  144. static unsigned getHashValue(const Expression e) {
  145. using llvm::hash_value;
  146. return static_cast<unsigned>(hash_value(e));
  147. }
  148. static bool isEqual(const Expression &LHS, const Expression &RHS) {
  149. return LHS == RHS;
  150. }
  151. };
  152. }
  153. //===----------------------------------------------------------------------===//
  154. // ValueTable Internal Functions
  155. //===----------------------------------------------------------------------===//
  156. Expression ValueTable::create_expression(Instruction *I) {
  157. Expression e;
  158. e.type = I->getType();
  159. e.opcode = I->getOpcode();
  160. for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
  161. OI != OE; ++OI)
  162. e.varargs.push_back(lookup_or_add(*OI));
  163. if (I->isCommutative()) {
  164. // Ensure that commutative instructions that only differ by a permutation
  165. // of their operands get the same value number by sorting the operand value
  166. // numbers. Since all commutative instructions have two operands it is more
  167. // efficient to sort by hand rather than using, say, std::sort.
  168. assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
  169. if (e.varargs[0] > e.varargs[1])
  170. std::swap(e.varargs[0], e.varargs[1]);
  171. }
  172. if (CmpInst *C = dyn_cast<CmpInst>(I)) {
  173. // Sort the operand value numbers so x<y and y>x get the same value number.
  174. CmpInst::Predicate Predicate = C->getPredicate();
  175. if (e.varargs[0] > e.varargs[1]) {
  176. std::swap(e.varargs[0], e.varargs[1]);
  177. Predicate = CmpInst::getSwappedPredicate(Predicate);
  178. }
  179. e.opcode = (C->getOpcode() << 8) | Predicate;
  180. } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
  181. for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
  182. II != IE; ++II)
  183. e.varargs.push_back(*II);
  184. }
  185. return e;
  186. }
  187. Expression ValueTable::create_cmp_expression(unsigned Opcode,
  188. CmpInst::Predicate Predicate,
  189. Value *LHS, Value *RHS) {
  190. assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
  191. "Not a comparison!");
  192. Expression e;
  193. e.type = CmpInst::makeCmpResultType(LHS->getType());
  194. e.varargs.push_back(lookup_or_add(LHS));
  195. e.varargs.push_back(lookup_or_add(RHS));
  196. // Sort the operand value numbers so x<y and y>x get the same value number.
  197. if (e.varargs[0] > e.varargs[1]) {
  198. std::swap(e.varargs[0], e.varargs[1]);
  199. Predicate = CmpInst::getSwappedPredicate(Predicate);
  200. }
  201. e.opcode = (Opcode << 8) | Predicate;
  202. return e;
  203. }
  204. Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
  205. assert(EI && "Not an ExtractValueInst?");
  206. Expression e;
  207. e.type = EI->getType();
  208. e.opcode = 0;
  209. IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
  210. if (I != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
  211. // EI might be an extract from one of our recognised intrinsics. If it
  212. // is we'll synthesize a semantically equivalent expression instead on
  213. // an extract value expression.
  214. switch (I->getIntrinsicID()) {
  215. case Intrinsic::sadd_with_overflow:
  216. case Intrinsic::uadd_with_overflow:
  217. e.opcode = Instruction::Add;
  218. break;
  219. case Intrinsic::ssub_with_overflow:
  220. case Intrinsic::usub_with_overflow:
  221. e.opcode = Instruction::Sub;
  222. break;
  223. case Intrinsic::smul_with_overflow:
  224. case Intrinsic::umul_with_overflow:
  225. e.opcode = Instruction::Mul;
  226. break;
  227. default:
  228. break;
  229. }
  230. if (e.opcode != 0) {
  231. // Intrinsic recognized. Grab its args to finish building the expression.
  232. assert(I->getNumArgOperands() == 2 &&
  233. "Expect two args for recognised intrinsics.");
  234. e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
  235. e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
  236. return e;
  237. }
  238. }
  239. // Not a recognised intrinsic. Fall back to producing an extract value
  240. // expression.
  241. e.opcode = EI->getOpcode();
  242. for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
  243. OI != OE; ++OI)
  244. e.varargs.push_back(lookup_or_add(*OI));
  245. for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
  246. II != IE; ++II)
  247. e.varargs.push_back(*II);
  248. return e;
  249. }
  250. //===----------------------------------------------------------------------===//
  251. // ValueTable External Functions
  252. //===----------------------------------------------------------------------===//
  253. /// add - Insert a value into the table with a specified value number.
  254. void ValueTable::add(Value *V, uint32_t num) {
  255. valueNumbering.insert(std::make_pair(V, num));
  256. }
  257. uint32_t ValueTable::lookup_or_add_call(CallInst *C) {
  258. if (AA->doesNotAccessMemory(C)) {
  259. Expression exp = create_expression(C);
  260. uint32_t &e = expressionNumbering[exp];
  261. if (!e) e = nextValueNumber++;
  262. valueNumbering[C] = e;
  263. return e;
  264. } else if (AA->onlyReadsMemory(C)) {
  265. Expression exp = create_expression(C);
  266. uint32_t &e = expressionNumbering[exp];
  267. if (!e) {
  268. e = nextValueNumber++;
  269. valueNumbering[C] = e;
  270. return e;
  271. }
  272. if (!MD) {
  273. e = nextValueNumber++;
  274. valueNumbering[C] = e;
  275. return e;
  276. }
  277. MemDepResult local_dep = MD->getDependency(C);
  278. if (!local_dep.isDef() && !local_dep.isNonLocal()) {
  279. valueNumbering[C] = nextValueNumber;
  280. return nextValueNumber++;
  281. }
  282. if (local_dep.isDef()) {
  283. CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
  284. if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
  285. valueNumbering[C] = nextValueNumber;
  286. return nextValueNumber++;
  287. }
  288. for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
  289. uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
  290. uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
  291. if (c_vn != cd_vn) {
  292. valueNumbering[C] = nextValueNumber;
  293. return nextValueNumber++;
  294. }
  295. }
  296. uint32_t v = lookup_or_add(local_cdep);
  297. valueNumbering[C] = v;
  298. return v;
  299. }
  300. // Non-local case.
  301. const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
  302. MD->getNonLocalCallDependency(CallSite(C));
  303. // FIXME: Move the checking logic to MemDep!
  304. CallInst* cdep = nullptr;
  305. // Check to see if we have a single dominating call instruction that is
  306. // identical to C.
  307. for (unsigned i = 0, e = deps.size(); i != e; ++i) {
  308. const NonLocalDepEntry *I = &deps[i];
  309. if (I->getResult().isNonLocal())
  310. continue;
  311. // We don't handle non-definitions. If we already have a call, reject
  312. // instruction dependencies.
  313. if (!I->getResult().isDef() || cdep != nullptr) {
  314. cdep = nullptr;
  315. break;
  316. }
  317. CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
  318. // FIXME: All duplicated with non-local case.
  319. if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
  320. cdep = NonLocalDepCall;
  321. continue;
  322. }
  323. cdep = nullptr;
  324. break;
  325. }
  326. if (!cdep) {
  327. valueNumbering[C] = nextValueNumber;
  328. return nextValueNumber++;
  329. }
  330. if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
  331. valueNumbering[C] = nextValueNumber;
  332. return nextValueNumber++;
  333. }
  334. for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
  335. uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
  336. uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
  337. if (c_vn != cd_vn) {
  338. valueNumbering[C] = nextValueNumber;
  339. return nextValueNumber++;
  340. }
  341. }
  342. uint32_t v = lookup_or_add(cdep);
  343. valueNumbering[C] = v;
  344. return v;
  345. } else {
  346. valueNumbering[C] = nextValueNumber;
  347. return nextValueNumber++;
  348. }
  349. }
  350. /// lookup_or_add - Returns the value number for the specified value, assigning
  351. /// it a new number if it did not have one before.
  352. uint32_t ValueTable::lookup_or_add(Value *V) {
  353. DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
  354. if (VI != valueNumbering.end())
  355. return VI->second;
  356. if (!isa<Instruction>(V)) {
  357. valueNumbering[V] = nextValueNumber;
  358. return nextValueNumber++;
  359. }
  360. Instruction* I = cast<Instruction>(V);
  361. Expression exp;
  362. switch (I->getOpcode()) {
  363. case Instruction::Call:
  364. return lookup_or_add_call(cast<CallInst>(I));
  365. case Instruction::Add:
  366. case Instruction::FAdd:
  367. case Instruction::Sub:
  368. case Instruction::FSub:
  369. case Instruction::Mul:
  370. case Instruction::FMul:
  371. case Instruction::UDiv:
  372. case Instruction::SDiv:
  373. case Instruction::FDiv:
  374. case Instruction::URem:
  375. case Instruction::SRem:
  376. case Instruction::FRem:
  377. case Instruction::Shl:
  378. case Instruction::LShr:
  379. case Instruction::AShr:
  380. case Instruction::And:
  381. case Instruction::Or:
  382. case Instruction::Xor:
  383. case Instruction::ICmp:
  384. case Instruction::FCmp:
  385. case Instruction::Trunc:
  386. case Instruction::ZExt:
  387. case Instruction::SExt:
  388. case Instruction::FPToUI:
  389. case Instruction::FPToSI:
  390. case Instruction::UIToFP:
  391. case Instruction::SIToFP:
  392. case Instruction::FPTrunc:
  393. case Instruction::FPExt:
  394. case Instruction::PtrToInt:
  395. case Instruction::IntToPtr:
  396. case Instruction::BitCast:
  397. case Instruction::Select:
  398. case Instruction::ExtractElement:
  399. case Instruction::InsertElement:
  400. case Instruction::ShuffleVector:
  401. case Instruction::InsertValue:
  402. case Instruction::GetElementPtr:
  403. exp = create_expression(I);
  404. break;
  405. case Instruction::ExtractValue:
  406. exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
  407. break;
  408. default:
  409. valueNumbering[V] = nextValueNumber;
  410. return nextValueNumber++;
  411. }
  412. uint32_t& e = expressionNumbering[exp];
  413. if (!e) e = nextValueNumber++;
  414. valueNumbering[V] = e;
  415. return e;
  416. }
  417. /// Returns the value number of the specified value. Fails if
  418. /// the value has not yet been numbered.
  419. uint32_t ValueTable::lookup(Value *V) const {
  420. DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
  421. assert(VI != valueNumbering.end() && "Value not numbered?");
  422. return VI->second;
  423. }
  424. /// Returns the value number of the given comparison,
  425. /// assigning it a new number if it did not have one before. Useful when
  426. /// we deduced the result of a comparison, but don't immediately have an
  427. /// instruction realizing that comparison to hand.
  428. uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
  429. CmpInst::Predicate Predicate,
  430. Value *LHS, Value *RHS) {
  431. Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
  432. uint32_t& e = expressionNumbering[exp];
  433. if (!e) e = nextValueNumber++;
  434. return e;
  435. }
  436. /// Remove all entries from the ValueTable.
  437. void ValueTable::clear() {
  438. valueNumbering.clear();
  439. expressionNumbering.clear();
  440. nextValueNumber = 1;
  441. }
  442. /// Remove a value from the value numbering.
  443. void ValueTable::erase(Value *V) {
  444. valueNumbering.erase(V);
  445. }
  446. /// verifyRemoved - Verify that the value is removed from all internal data
  447. /// structures.
  448. void ValueTable::verifyRemoved(const Value *V) const {
  449. for (DenseMap<Value*, uint32_t>::const_iterator
  450. I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
  451. assert(I->first != V && "Inst still occurs in value numbering map!");
  452. }
  453. }
  454. //===----------------------------------------------------------------------===//
  455. // GVN Pass
  456. //===----------------------------------------------------------------------===//
  457. namespace {
  458. class GVN;
  459. struct AvailableValueInBlock {
  460. /// BB - The basic block in question.
  461. BasicBlock *BB;
  462. enum ValType {
  463. SimpleVal, // A simple offsetted value that is accessed.
  464. LoadVal, // A value produced by a load.
  465. MemIntrin, // A memory intrinsic which is loaded from.
  466. UndefVal // A UndefValue representing a value from dead block (which
  467. // is not yet physically removed from the CFG).
  468. };
  469. /// V - The value that is live out of the block.
  470. PointerIntPair<Value *, 2, ValType> Val;
  471. /// Offset - The byte offset in Val that is interesting for the load query.
  472. unsigned Offset;
  473. static AvailableValueInBlock get(BasicBlock *BB, Value *V,
  474. unsigned Offset = 0) {
  475. AvailableValueInBlock Res;
  476. Res.BB = BB;
  477. Res.Val.setPointer(V);
  478. Res.Val.setInt(SimpleVal);
  479. Res.Offset = Offset;
  480. return Res;
  481. }
  482. static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
  483. unsigned Offset = 0) {
  484. AvailableValueInBlock Res;
  485. Res.BB = BB;
  486. Res.Val.setPointer(MI);
  487. Res.Val.setInt(MemIntrin);
  488. Res.Offset = Offset;
  489. return Res;
  490. }
  491. static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
  492. unsigned Offset = 0) {
  493. AvailableValueInBlock Res;
  494. Res.BB = BB;
  495. Res.Val.setPointer(LI);
  496. Res.Val.setInt(LoadVal);
  497. Res.Offset = Offset;
  498. return Res;
  499. }
  500. static AvailableValueInBlock getUndef(BasicBlock *BB) {
  501. AvailableValueInBlock Res;
  502. Res.BB = BB;
  503. Res.Val.setPointer(nullptr);
  504. Res.Val.setInt(UndefVal);
  505. Res.Offset = 0;
  506. return Res;
  507. }
  508. bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
  509. bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
  510. bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
  511. bool isUndefValue() const { return Val.getInt() == UndefVal; }
  512. Value *getSimpleValue() const {
  513. assert(isSimpleValue() && "Wrong accessor");
  514. return Val.getPointer();
  515. }
  516. LoadInst *getCoercedLoadValue() const {
  517. assert(isCoercedLoadValue() && "Wrong accessor");
  518. return cast<LoadInst>(Val.getPointer());
  519. }
  520. MemIntrinsic *getMemIntrinValue() const {
  521. assert(isMemIntrinValue() && "Wrong accessor");
  522. return cast<MemIntrinsic>(Val.getPointer());
  523. }
  524. /// Emit code into this block to adjust the value defined here to the
  525. /// specified type. This handles various coercion cases.
  526. Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const;
  527. };
  528. class GVN : public FunctionPass {
  529. bool NoLoads;
  530. MemoryDependenceAnalysis *MD;
  531. DominatorTree *DT;
  532. const TargetLibraryInfo *TLI;
  533. AssumptionCache *AC;
  534. SetVector<BasicBlock *> DeadBlocks;
  535. ValueTable VN;
  536. /// A mapping from value numbers to lists of Value*'s that
  537. /// have that value number. Use findLeader to query it.
  538. struct LeaderTableEntry {
  539. Value *Val;
  540. const BasicBlock *BB;
  541. LeaderTableEntry *Next;
  542. };
  543. DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
  544. BumpPtrAllocator TableAllocator;
  545. SmallVector<Instruction*, 8> InstrsToErase;
  546. typedef SmallVector<NonLocalDepResult, 64> LoadDepVect;
  547. typedef SmallVector<AvailableValueInBlock, 64> AvailValInBlkVect;
  548. typedef SmallVector<BasicBlock*, 64> UnavailBlkVect;
  549. public:
  550. static char ID; // Pass identification, replacement for typeid
  551. explicit GVN(bool noloads = false)
  552. : FunctionPass(ID), NoLoads(noloads), MD(nullptr) {
  553. initializeGVNPass(*PassRegistry::getPassRegistry());
  554. }
  555. bool runOnFunction(Function &F) override;
  556. /// This removes the specified instruction from
  557. /// our various maps and marks it for deletion.
  558. void markInstructionForDeletion(Instruction *I) {
  559. VN.erase(I);
  560. InstrsToErase.push_back(I);
  561. }
  562. DominatorTree &getDominatorTree() const { return *DT; }
  563. AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
  564. MemoryDependenceAnalysis &getMemDep() const { return *MD; }
  565. private:
  566. /// Push a new Value to the LeaderTable onto the list for its value number.
  567. void addToLeaderTable(uint32_t N, Value *V, const BasicBlock *BB) {
  568. LeaderTableEntry &Curr = LeaderTable[N];
  569. if (!Curr.Val) {
  570. Curr.Val = V;
  571. Curr.BB = BB;
  572. return;
  573. }
  574. LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
  575. Node->Val = V;
  576. Node->BB = BB;
  577. Node->Next = Curr.Next;
  578. Curr.Next = Node;
  579. }
  580. /// Scan the list of values corresponding to a given
  581. /// value number, and remove the given instruction if encountered.
  582. void removeFromLeaderTable(uint32_t N, Instruction *I, BasicBlock *BB) {
  583. LeaderTableEntry* Prev = nullptr;
  584. LeaderTableEntry* Curr = &LeaderTable[N];
  585. while (Curr && (Curr->Val != I || Curr->BB != BB)) {
  586. Prev = Curr;
  587. Curr = Curr->Next;
  588. }
  589. if (!Curr)
  590. return;
  591. if (Prev) {
  592. Prev->Next = Curr->Next;
  593. } else {
  594. if (!Curr->Next) {
  595. Curr->Val = nullptr;
  596. Curr->BB = nullptr;
  597. } else {
  598. LeaderTableEntry* Next = Curr->Next;
  599. Curr->Val = Next->Val;
  600. Curr->BB = Next->BB;
  601. Curr->Next = Next->Next;
  602. }
  603. }
  604. }
  605. // List of critical edges to be split between iterations.
  606. SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
  607. // This transformation requires dominator postdominator info
  608. void getAnalysisUsage(AnalysisUsage &AU) const override {
  609. AU.addRequired<AssumptionCacheTracker>();
  610. AU.addRequired<DominatorTreeWrapperPass>();
  611. AU.addRequired<TargetLibraryInfoWrapperPass>();
  612. if (!NoLoads)
  613. AU.addRequired<MemoryDependenceAnalysis>();
  614. AU.addRequired<AliasAnalysis>();
  615. AU.addPreserved<DominatorTreeWrapperPass>();
  616. AU.addPreserved<AliasAnalysis>();
  617. }
  618. // Helper fuctions of redundant load elimination
  619. bool processLoad(LoadInst *L);
  620. bool processNonLocalLoad(LoadInst *L);
  621. void AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
  622. AvailValInBlkVect &ValuesPerBlock,
  623. UnavailBlkVect &UnavailableBlocks);
  624. bool PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
  625. UnavailBlkVect &UnavailableBlocks);
  626. // Other helper routines
  627. bool processInstruction(Instruction *I);
  628. bool processBlock(BasicBlock *BB);
  629. void dump(DenseMap<uint32_t, Value*> &d);
  630. bool iterateOnFunction(Function &F);
  631. bool performPRE(Function &F);
  632. bool performScalarPRE(Instruction *I);
  633. bool performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
  634. unsigned int ValNo);
  635. Value *findLeader(const BasicBlock *BB, uint32_t num);
  636. void cleanupGlobalSets();
  637. void verifyRemoved(const Instruction *I) const;
  638. bool splitCriticalEdges();
  639. BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
  640. bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root);
  641. bool processFoldableCondBr(BranchInst *BI);
  642. void addDeadBlock(BasicBlock *BB);
  643. void assignValNumForDeadCode();
  644. };
  645. char GVN::ID = 0;
  646. }
  647. // The public interface to this file...
  648. FunctionPass *llvm::createGVNPass(bool NoLoads) {
  649. return new GVN(NoLoads);
  650. }
  651. INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
  652. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  653. INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
  654. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  655. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  656. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  657. INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
  658. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  659. void GVN::dump(DenseMap<uint32_t, Value*>& d) {
  660. errs() << "{\n";
  661. for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
  662. E = d.end(); I != E; ++I) {
  663. errs() << I->first << "\n";
  664. I->second->dump();
  665. }
  666. errs() << "}\n";
  667. }
  668. #endif
  669. /// Return true if we can prove that the value
  670. /// we're analyzing is fully available in the specified block. As we go, keep
  671. /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
  672. /// map is actually a tri-state map with the following values:
  673. /// 0) we know the block *is not* fully available.
  674. /// 1) we know the block *is* fully available.
  675. /// 2) we do not know whether the block is fully available or not, but we are
  676. /// currently speculating that it will be.
  677. /// 3) we are speculating for this block and have used that to speculate for
  678. /// other blocks.
  679. static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
  680. DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
  681. uint32_t RecurseDepth) {
  682. if (RecurseDepth > MaxRecurseDepth)
  683. return false;
  684. // Optimistically assume that the block is fully available and check to see
  685. // if we already know about this block in one lookup.
  686. std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
  687. FullyAvailableBlocks.insert(std::make_pair(BB, 2));
  688. // If the entry already existed for this block, return the precomputed value.
  689. if (!IV.second) {
  690. // If this is a speculative "available" value, mark it as being used for
  691. // speculation of other blocks.
  692. if (IV.first->second == 2)
  693. IV.first->second = 3;
  694. return IV.first->second != 0;
  695. }
  696. // Otherwise, see if it is fully available in all predecessors.
  697. pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
  698. // If this block has no predecessors, it isn't live-in here.
  699. if (PI == PE)
  700. goto SpeculationFailure;
  701. for (; PI != PE; ++PI)
  702. // If the value isn't fully available in one of our predecessors, then it
  703. // isn't fully available in this block either. Undo our previous
  704. // optimistic assumption and bail out.
  705. if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
  706. goto SpeculationFailure;
  707. return true;
  708. // If we get here, we found out that this is not, after
  709. // all, a fully-available block. We have a problem if we speculated on this and
  710. // used the speculation to mark other blocks as available.
  711. SpeculationFailure:
  712. char &BBVal = FullyAvailableBlocks[BB];
  713. // If we didn't speculate on this, just return with it set to false.
  714. if (BBVal == 2) {
  715. BBVal = 0;
  716. return false;
  717. }
  718. // If we did speculate on this value, we could have blocks set to 1 that are
  719. // incorrect. Walk the (transitive) successors of this block and mark them as
  720. // 0 if set to one.
  721. SmallVector<BasicBlock*, 32> BBWorklist;
  722. BBWorklist.push_back(BB);
  723. do {
  724. BasicBlock *Entry = BBWorklist.pop_back_val();
  725. // Note that this sets blocks to 0 (unavailable) if they happen to not
  726. // already be in FullyAvailableBlocks. This is safe.
  727. char &EntryVal = FullyAvailableBlocks[Entry];
  728. if (EntryVal == 0) continue; // Already unavailable.
  729. // Mark as unavailable.
  730. EntryVal = 0;
  731. BBWorklist.append(succ_begin(Entry), succ_end(Entry));
  732. } while (!BBWorklist.empty());
  733. return false;
  734. }
  735. /// Return true if CoerceAvailableValueToLoadType will succeed.
  736. static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
  737. Type *LoadTy,
  738. const DataLayout &DL) {
  739. // If the loaded or stored value is an first class array or struct, don't try
  740. // to transform them. We need to be able to bitcast to integer.
  741. if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
  742. StoredVal->getType()->isStructTy() ||
  743. StoredVal->getType()->isArrayTy())
  744. return false;
  745. // The store has to be at least as big as the load.
  746. if (DL.getTypeSizeInBits(StoredVal->getType()) <
  747. DL.getTypeSizeInBits(LoadTy))
  748. return false;
  749. return true;
  750. }
  751. /// If we saw a store of a value to memory, and
  752. /// then a load from a must-aliased pointer of a different type, try to coerce
  753. /// the stored value. LoadedTy is the type of the load we want to replace.
  754. /// IRB is IRBuilder used to insert new instructions.
  755. ///
  756. /// If we can't do it, return null.
  757. static Value *CoerceAvailableValueToLoadType(Value *StoredVal, Type *LoadedTy,
  758. IRBuilder<> &IRB,
  759. const DataLayout &DL) {
  760. if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL))
  761. return nullptr;
  762. // If this is already the right type, just return it.
  763. Type *StoredValTy = StoredVal->getType();
  764. uint64_t StoreSize = DL.getTypeSizeInBits(StoredValTy);
  765. uint64_t LoadSize = DL.getTypeSizeInBits(LoadedTy);
  766. // If the store and reload are the same size, we can always reuse it.
  767. if (StoreSize == LoadSize) {
  768. // Pointer to Pointer -> use bitcast.
  769. if (StoredValTy->getScalarType()->isPointerTy() &&
  770. LoadedTy->getScalarType()->isPointerTy())
  771. return IRB.CreateBitCast(StoredVal, LoadedTy);
  772. // Convert source pointers to integers, which can be bitcast.
  773. if (StoredValTy->getScalarType()->isPointerTy()) {
  774. StoredValTy = DL.getIntPtrType(StoredValTy);
  775. StoredVal = IRB.CreatePtrToInt(StoredVal, StoredValTy);
  776. }
  777. Type *TypeToCastTo = LoadedTy;
  778. if (TypeToCastTo->getScalarType()->isPointerTy())
  779. TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
  780. if (StoredValTy != TypeToCastTo)
  781. StoredVal = IRB.CreateBitCast(StoredVal, TypeToCastTo);
  782. // Cast to pointer if the load needs a pointer type.
  783. if (LoadedTy->getScalarType()->isPointerTy())
  784. StoredVal = IRB.CreateIntToPtr(StoredVal, LoadedTy);
  785. return StoredVal;
  786. }
  787. // If the loaded value is smaller than the available value, then we can
  788. // extract out a piece from it. If the available value is too small, then we
  789. // can't do anything.
  790. assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
  791. // Convert source pointers to integers, which can be manipulated.
  792. if (StoredValTy->getScalarType()->isPointerTy()) {
  793. StoredValTy = DL.getIntPtrType(StoredValTy);
  794. StoredVal = IRB.CreatePtrToInt(StoredVal, StoredValTy);
  795. }
  796. // Convert vectors and fp to integer, which can be manipulated.
  797. if (!StoredValTy->isIntegerTy()) {
  798. StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
  799. StoredVal = IRB.CreateBitCast(StoredVal, StoredValTy);
  800. }
  801. // If this is a big-endian system, we need to shift the value down to the low
  802. // bits so that a truncate will work.
  803. if (DL.isBigEndian()) {
  804. StoredVal = IRB.CreateLShr(StoredVal, StoreSize - LoadSize, "tmp");
  805. }
  806. // Truncate the integer to the right size now.
  807. Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
  808. StoredVal = IRB.CreateTrunc(StoredVal, NewIntTy, "trunc");
  809. if (LoadedTy == NewIntTy)
  810. return StoredVal;
  811. // If the result is a pointer, inttoptr.
  812. if (LoadedTy->getScalarType()->isPointerTy())
  813. return IRB.CreateIntToPtr(StoredVal, LoadedTy, "inttoptr");
  814. // Otherwise, bitcast.
  815. return IRB.CreateBitCast(StoredVal, LoadedTy, "bitcast");
  816. }
  817. /// This function is called when we have a
  818. /// memdep query of a load that ends up being a clobbering memory write (store,
  819. /// memset, memcpy, memmove). This means that the write *may* provide bits used
  820. /// by the load but we can't be sure because the pointers don't mustalias.
  821. ///
  822. /// Check this case to see if there is anything more we can do before we give
  823. /// up. This returns -1 if we have to give up, or a byte number in the stored
  824. /// value of the piece that feeds the load.
  825. static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
  826. Value *WritePtr,
  827. uint64_t WriteSizeInBits,
  828. const DataLayout &DL) {
  829. // If the loaded or stored value is a first class array or struct, don't try
  830. // to transform them. We need to be able to bitcast to integer.
  831. if (LoadTy->isStructTy() || LoadTy->isArrayTy())
  832. return -1;
  833. int64_t StoreOffset = 0, LoadOffset = 0;
  834. Value *StoreBase =
  835. GetPointerBaseWithConstantOffset(WritePtr, StoreOffset, DL);
  836. Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, DL);
  837. if (StoreBase != LoadBase)
  838. return -1;
  839. // If the load and store are to the exact same address, they should have been
  840. // a must alias. AA must have gotten confused.
  841. // FIXME: Study to see if/when this happens. One case is forwarding a memset
  842. // to a load from the base of the memset.
  843. #if 0
  844. if (LoadOffset == StoreOffset) {
  845. dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
  846. << "Base = " << *StoreBase << "\n"
  847. << "Store Ptr = " << *WritePtr << "\n"
  848. << "Store Offs = " << StoreOffset << "\n"
  849. << "Load Ptr = " << *LoadPtr << "\n";
  850. abort();
  851. }
  852. #endif
  853. // If the load and store don't overlap at all, the store doesn't provide
  854. // anything to the load. In this case, they really don't alias at all, AA
  855. // must have gotten confused.
  856. uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy);
  857. if ((WriteSizeInBits & 7) | (LoadSize & 7))
  858. return -1;
  859. uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
  860. LoadSize >>= 3;
  861. bool isAAFailure = false;
  862. if (StoreOffset < LoadOffset)
  863. isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
  864. else
  865. isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
  866. if (isAAFailure) {
  867. #if 0
  868. dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
  869. << "Base = " << *StoreBase << "\n"
  870. << "Store Ptr = " << *WritePtr << "\n"
  871. << "Store Offs = " << StoreOffset << "\n"
  872. << "Load Ptr = " << *LoadPtr << "\n";
  873. abort();
  874. #endif
  875. return -1;
  876. }
  877. // If the Load isn't completely contained within the stored bits, we don't
  878. // have all the bits to feed it. We could do something crazy in the future
  879. // (issue a smaller load then merge the bits in) but this seems unlikely to be
  880. // valuable.
  881. if (StoreOffset > LoadOffset ||
  882. StoreOffset+StoreSize < LoadOffset+LoadSize)
  883. return -1;
  884. // Okay, we can do this transformation. Return the number of bytes into the
  885. // store that the load is.
  886. return LoadOffset-StoreOffset;
  887. }
  888. /// This function is called when we have a
  889. /// memdep query of a load that ends up being a clobbering store.
  890. static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
  891. StoreInst *DepSI) {
  892. // Cannot handle reading from store of first-class aggregate yet.
  893. if (DepSI->getValueOperand()->getType()->isStructTy() ||
  894. DepSI->getValueOperand()->getType()->isArrayTy())
  895. return -1;
  896. const DataLayout &DL = DepSI->getModule()->getDataLayout();
  897. Value *StorePtr = DepSI->getPointerOperand();
  898. uint64_t StoreSize =DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
  899. return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
  900. StorePtr, StoreSize, DL);
  901. }
  902. /// This function is called when we have a
  903. /// memdep query of a load that ends up being clobbered by another load. See if
  904. /// the other load can feed into the second load.
  905. static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
  906. LoadInst *DepLI, const DataLayout &DL){
  907. // Cannot handle reading from store of first-class aggregate yet.
  908. if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
  909. return -1;
  910. Value *DepPtr = DepLI->getPointerOperand();
  911. uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
  912. int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
  913. if (R != -1) return R;
  914. // If we have a load/load clobber an DepLI can be widened to cover this load,
  915. // then we should widen it!
  916. int64_t LoadOffs = 0;
  917. const Value *LoadBase =
  918. GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL);
  919. unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
  920. unsigned Size = MemoryDependenceAnalysis::getLoadLoadClobberFullWidthSize(
  921. LoadBase, LoadOffs, LoadSize, DepLI);
  922. if (Size == 0) return -1;
  923. return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, DL);
  924. }
  925. static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
  926. MemIntrinsic *MI,
  927. const DataLayout &DL) {
  928. // If the mem operation is a non-constant size, we can't handle it.
  929. ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
  930. if (!SizeCst) return -1;
  931. uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
  932. // If this is memset, we just need to see if the offset is valid in the size
  933. // of the memset..
  934. if (MI->getIntrinsicID() == Intrinsic::memset)
  935. return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
  936. MemSizeInBits, DL);
  937. // If we have a memcpy/memmove, the only case we can handle is if this is a
  938. // copy from constant memory. In that case, we can read directly from the
  939. // constant memory.
  940. MemTransferInst *MTI = cast<MemTransferInst>(MI);
  941. Constant *Src = dyn_cast<Constant>(MTI->getSource());
  942. if (!Src) return -1;
  943. GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, DL));
  944. if (!GV || !GV->isConstant()) return -1;
  945. // See if the access is within the bounds of the transfer.
  946. int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
  947. MI->getDest(), MemSizeInBits, DL);
  948. if (Offset == -1)
  949. return Offset;
  950. unsigned AS = Src->getType()->getPointerAddressSpace();
  951. // Otherwise, see if we can constant fold a load from the constant with the
  952. // offset applied as appropriate.
  953. Src = ConstantExpr::getBitCast(Src,
  954. Type::getInt8PtrTy(Src->getContext(), AS));
  955. Constant *OffsetCst =
  956. ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
  957. Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
  958. OffsetCst);
  959. Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
  960. if (ConstantFoldLoadFromConstPtr(Src, DL))
  961. return Offset;
  962. return -1;
  963. }
  964. /// This function is called when we have a
  965. /// memdep query of a load that ends up being a clobbering store. This means
  966. /// that the store provides bits used by the load but we the pointers don't
  967. /// mustalias. Check this case to see if there is anything more we can do
  968. /// before we give up.
  969. static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
  970. Type *LoadTy,
  971. Instruction *InsertPt, const DataLayout &DL){
  972. LLVMContext &Ctx = SrcVal->getType()->getContext();
  973. uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
  974. uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
  975. IRBuilder<> Builder(InsertPt);
  976. // Compute which bits of the stored value are being used by the load. Convert
  977. // to an integer type to start with.
  978. if (SrcVal->getType()->getScalarType()->isPointerTy())
  979. SrcVal = Builder.CreatePtrToInt(SrcVal,
  980. DL.getIntPtrType(SrcVal->getType()));
  981. if (!SrcVal->getType()->isIntegerTy())
  982. SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
  983. // Shift the bits to the least significant depending on endianness.
  984. unsigned ShiftAmt;
  985. if (DL.isLittleEndian())
  986. ShiftAmt = Offset*8;
  987. else
  988. ShiftAmt = (StoreSize-LoadSize-Offset)*8;
  989. if (ShiftAmt)
  990. SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
  991. if (LoadSize != StoreSize)
  992. SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
  993. return CoerceAvailableValueToLoadType(SrcVal, LoadTy, Builder, DL);
  994. }
  995. /// This function is called when we have a
  996. /// memdep query of a load that ends up being a clobbering load. This means
  997. /// that the load *may* provide bits used by the load but we can't be sure
  998. /// because the pointers don't mustalias. Check this case to see if there is
  999. /// anything more we can do before we give up.
  1000. static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
  1001. Type *LoadTy, Instruction *InsertPt,
  1002. GVN &gvn) {
  1003. const DataLayout &DL = SrcVal->getModule()->getDataLayout();
  1004. // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
  1005. // widen SrcVal out to a larger load.
  1006. unsigned SrcValSize = DL.getTypeStoreSize(SrcVal->getType());
  1007. unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
  1008. if (Offset+LoadSize > SrcValSize) {
  1009. assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
  1010. assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
  1011. // If we have a load/load clobber an DepLI can be widened to cover this
  1012. // load, then we should widen it to the next power of 2 size big enough!
  1013. unsigned NewLoadSize = Offset+LoadSize;
  1014. if (!isPowerOf2_32(NewLoadSize))
  1015. NewLoadSize = NextPowerOf2(NewLoadSize);
  1016. Value *PtrVal = SrcVal->getPointerOperand();
  1017. // Insert the new load after the old load. This ensures that subsequent
  1018. // memdep queries will find the new load. We can't easily remove the old
  1019. // load completely because it is already in the value numbering table.
  1020. IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
  1021. Type *DestPTy =
  1022. IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
  1023. DestPTy = PointerType::get(DestPTy,
  1024. PtrVal->getType()->getPointerAddressSpace());
  1025. Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
  1026. PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
  1027. LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
  1028. NewLoad->takeName(SrcVal);
  1029. NewLoad->setAlignment(SrcVal->getAlignment());
  1030. DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
  1031. DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
  1032. // Replace uses of the original load with the wider load. On a big endian
  1033. // system, we need to shift down to get the relevant bits.
  1034. Value *RV = NewLoad;
  1035. if (DL.isBigEndian())
  1036. RV = Builder.CreateLShr(RV,
  1037. NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
  1038. RV = Builder.CreateTrunc(RV, SrcVal->getType());
  1039. SrcVal->replaceAllUsesWith(RV);
  1040. // We would like to use gvn.markInstructionForDeletion here, but we can't
  1041. // because the load is already memoized into the leader map table that GVN
  1042. // tracks. It is potentially possible to remove the load from the table,
  1043. // but then there all of the operations based on it would need to be
  1044. // rehashed. Just leave the dead load around.
  1045. gvn.getMemDep().removeInstruction(SrcVal);
  1046. SrcVal = NewLoad;
  1047. }
  1048. return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
  1049. }
  1050. /// This function is called when we have a
  1051. /// memdep query of a load that ends up being a clobbering mem intrinsic.
  1052. static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
  1053. Type *LoadTy, Instruction *InsertPt,
  1054. const DataLayout &DL){
  1055. LLVMContext &Ctx = LoadTy->getContext();
  1056. uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
  1057. IRBuilder<> Builder(InsertPt);
  1058. // We know that this method is only called when the mem transfer fully
  1059. // provides the bits for the load.
  1060. if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
  1061. // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
  1062. // independently of what the offset is.
  1063. Value *Val = MSI->getValue();
  1064. if (LoadSize != 1)
  1065. Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
  1066. Value *OneElt = Val;
  1067. // Splat the value out to the right number of bits.
  1068. for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
  1069. // If we can double the number of bytes set, do it.
  1070. if (NumBytesSet*2 <= LoadSize) {
  1071. Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
  1072. Val = Builder.CreateOr(Val, ShVal);
  1073. NumBytesSet <<= 1;
  1074. continue;
  1075. }
  1076. // Otherwise insert one byte at a time.
  1077. Value *ShVal = Builder.CreateShl(Val, 1*8);
  1078. Val = Builder.CreateOr(OneElt, ShVal);
  1079. ++NumBytesSet;
  1080. }
  1081. return CoerceAvailableValueToLoadType(Val, LoadTy, Builder, DL);
  1082. }
  1083. // Otherwise, this is a memcpy/memmove from a constant global.
  1084. MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
  1085. Constant *Src = cast<Constant>(MTI->getSource());
  1086. unsigned AS = Src->getType()->getPointerAddressSpace();
  1087. // Otherwise, see if we can constant fold a load from the constant with the
  1088. // offset applied as appropriate.
  1089. Src = ConstantExpr::getBitCast(Src,
  1090. Type::getInt8PtrTy(Src->getContext(), AS));
  1091. Constant *OffsetCst =
  1092. ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
  1093. Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
  1094. OffsetCst);
  1095. Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
  1096. return ConstantFoldLoadFromConstPtr(Src, DL);
  1097. }
  1098. /// Given a set of loads specified by ValuesPerBlock,
  1099. /// construct SSA form, allowing us to eliminate LI. This returns the value
  1100. /// that should be used at LI's definition site.
  1101. static Value *ConstructSSAForLoadSet(LoadInst *LI,
  1102. SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
  1103. GVN &gvn) {
  1104. // Check for the fully redundant, dominating load case. In this case, we can
  1105. // just use the dominating value directly.
  1106. if (ValuesPerBlock.size() == 1 &&
  1107. gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
  1108. LI->getParent())) {
  1109. assert(!ValuesPerBlock[0].isUndefValue() && "Dead BB dominate this block");
  1110. return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
  1111. }
  1112. // Otherwise, we have to construct SSA form.
  1113. SmallVector<PHINode*, 8> NewPHIs;
  1114. SSAUpdater SSAUpdate(&NewPHIs);
  1115. SSAUpdate.Initialize(LI->getType(), LI->getName());
  1116. for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
  1117. const AvailableValueInBlock &AV = ValuesPerBlock[i];
  1118. BasicBlock *BB = AV.BB;
  1119. if (SSAUpdate.HasValueForBlock(BB))
  1120. continue;
  1121. SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn));
  1122. }
  1123. // Perform PHI construction.
  1124. Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
  1125. // If new PHI nodes were created, notify alias analysis.
  1126. if (V->getType()->getScalarType()->isPointerTy()) {
  1127. AliasAnalysis *AA = gvn.getAliasAnalysis();
  1128. // Scan the new PHIs and inform alias analysis that we've added potentially
  1129. // escaping uses to any values that are operands to these PHIs.
  1130. for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
  1131. PHINode *P = NewPHIs[i];
  1132. for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
  1133. unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
  1134. AA->addEscapingUse(P->getOperandUse(jj));
  1135. }
  1136. }
  1137. }
  1138. return V;
  1139. }
  1140. Value *AvailableValueInBlock::MaterializeAdjustedValue(LoadInst *LI,
  1141. GVN &gvn) const {
  1142. Value *Res;
  1143. Type *LoadTy = LI->getType();
  1144. const DataLayout &DL = LI->getModule()->getDataLayout();
  1145. if (isSimpleValue()) {
  1146. Res = getSimpleValue();
  1147. if (Res->getType() != LoadTy) {
  1148. Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(), DL);
  1149. DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
  1150. << *getSimpleValue() << '\n'
  1151. << *Res << '\n' << "\n\n\n");
  1152. }
  1153. } else if (isCoercedLoadValue()) {
  1154. LoadInst *Load = getCoercedLoadValue();
  1155. if (Load->getType() == LoadTy && Offset == 0) {
  1156. Res = Load;
  1157. } else {
  1158. Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
  1159. gvn);
  1160. DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
  1161. << *getCoercedLoadValue() << '\n'
  1162. << *Res << '\n' << "\n\n\n");
  1163. }
  1164. } else if (isMemIntrinValue()) {
  1165. Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
  1166. BB->getTerminator(), DL);
  1167. DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
  1168. << " " << *getMemIntrinValue() << '\n'
  1169. << *Res << '\n' << "\n\n\n");
  1170. } else {
  1171. assert(isUndefValue() && "Should be UndefVal");
  1172. DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
  1173. return UndefValue::get(LoadTy);
  1174. }
  1175. return Res;
  1176. }
  1177. static bool isLifetimeStart(const Instruction *Inst) {
  1178. if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
  1179. return II->getIntrinsicID() == Intrinsic::lifetime_start;
  1180. return false;
  1181. }
  1182. void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
  1183. AvailValInBlkVect &ValuesPerBlock,
  1184. UnavailBlkVect &UnavailableBlocks) {
  1185. // Filter out useless results (non-locals, etc). Keep track of the blocks
  1186. // where we have a value available in repl, also keep track of whether we see
  1187. // dependencies that produce an unknown value for the load (such as a call
  1188. // that could potentially clobber the load).
  1189. unsigned NumDeps = Deps.size();
  1190. const DataLayout &DL = LI->getModule()->getDataLayout();
  1191. for (unsigned i = 0, e = NumDeps; i != e; ++i) {
  1192. BasicBlock *DepBB = Deps[i].getBB();
  1193. MemDepResult DepInfo = Deps[i].getResult();
  1194. if (DeadBlocks.count(DepBB)) {
  1195. // Dead dependent mem-op disguise as a load evaluating the same value
  1196. // as the load in question.
  1197. ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
  1198. continue;
  1199. }
  1200. if (!DepInfo.isDef() && !DepInfo.isClobber()) {
  1201. UnavailableBlocks.push_back(DepBB);
  1202. continue;
  1203. }
  1204. if (DepInfo.isClobber()) {
  1205. // The address being loaded in this non-local block may not be the same as
  1206. // the pointer operand of the load if PHI translation occurs. Make sure
  1207. // to consider the right address.
  1208. Value *Address = Deps[i].getAddress();
  1209. // If the dependence is to a store that writes to a superset of the bits
  1210. // read by the load, we can extract the bits we need for the load from the
  1211. // stored value.
  1212. if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
  1213. if (Address) {
  1214. int Offset =
  1215. AnalyzeLoadFromClobberingStore(LI->getType(), Address, DepSI);
  1216. if (Offset != -1) {
  1217. ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
  1218. DepSI->getValueOperand(),
  1219. Offset));
  1220. continue;
  1221. }
  1222. }
  1223. }
  1224. // Check to see if we have something like this:
  1225. // load i32* P
  1226. // load i8* (P+1)
  1227. // if we have this, replace the later with an extraction from the former.
  1228. if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
  1229. // If this is a clobber and L is the first instruction in its block, then
  1230. // we have the first instruction in the entry block.
  1231. if (DepLI != LI && Address) {
  1232. int Offset =
  1233. AnalyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL);
  1234. if (Offset != -1) {
  1235. ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
  1236. Offset));
  1237. continue;
  1238. }
  1239. }
  1240. }
  1241. // If the clobbering value is a memset/memcpy/memmove, see if we can
  1242. // forward a value on from it.
  1243. if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
  1244. if (Address) {
  1245. int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
  1246. DepMI, DL);
  1247. if (Offset != -1) {
  1248. ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
  1249. Offset));
  1250. continue;
  1251. }
  1252. }
  1253. }
  1254. UnavailableBlocks.push_back(DepBB);
  1255. continue;
  1256. }
  1257. // DepInfo.isDef() here
  1258. Instruction *DepInst = DepInfo.getInst();
  1259. // Loading the allocation -> undef.
  1260. if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
  1261. // Loading immediately after lifetime begin -> undef.
  1262. isLifetimeStart(DepInst)) {
  1263. ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
  1264. UndefValue::get(LI->getType())));
  1265. continue;
  1266. }
  1267. // Loading from calloc (which zero initializes memory) -> zero
  1268. if (isCallocLikeFn(DepInst, TLI)) {
  1269. ValuesPerBlock.push_back(AvailableValueInBlock::get(
  1270. DepBB, Constant::getNullValue(LI->getType())));
  1271. continue;
  1272. }
  1273. if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
  1274. // Reject loads and stores that are to the same address but are of
  1275. // different types if we have to.
  1276. if (S->getValueOperand()->getType() != LI->getType()) {
  1277. // If the stored value is larger or equal to the loaded value, we can
  1278. // reuse it.
  1279. if (!CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
  1280. LI->getType(), DL)) {
  1281. UnavailableBlocks.push_back(DepBB);
  1282. continue;
  1283. }
  1284. }
  1285. ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
  1286. S->getValueOperand()));
  1287. continue;
  1288. }
  1289. if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
  1290. // If the types mismatch and we can't handle it, reject reuse of the load.
  1291. if (LD->getType() != LI->getType()) {
  1292. // If the stored value is larger or equal to the loaded value, we can
  1293. // reuse it.
  1294. if (!CanCoerceMustAliasedValueToLoad(LD, LI->getType(), DL)) {
  1295. UnavailableBlocks.push_back(DepBB);
  1296. continue;
  1297. }
  1298. }
  1299. ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
  1300. continue;
  1301. }
  1302. UnavailableBlocks.push_back(DepBB);
  1303. }
  1304. }
  1305. bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
  1306. UnavailBlkVect &UnavailableBlocks) {
  1307. // Okay, we have *some* definitions of the value. This means that the value
  1308. // is available in some of our (transitive) predecessors. Lets think about
  1309. // doing PRE of this load. This will involve inserting a new load into the
  1310. // predecessor when it's not available. We could do this in general, but
  1311. // prefer to not increase code size. As such, we only do this when we know
  1312. // that we only have to insert *one* load (which means we're basically moving
  1313. // the load, not inserting a new one).
  1314. SmallPtrSet<BasicBlock *, 4> Blockers;
  1315. for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
  1316. Blockers.insert(UnavailableBlocks[i]);
  1317. // Let's find the first basic block with more than one predecessor. Walk
  1318. // backwards through predecessors if needed.
  1319. BasicBlock *LoadBB = LI->getParent();
  1320. BasicBlock *TmpBB = LoadBB;
  1321. while (TmpBB->getSinglePredecessor()) {
  1322. TmpBB = TmpBB->getSinglePredecessor();
  1323. if (TmpBB == LoadBB) // Infinite (unreachable) loop.
  1324. return false;
  1325. if (Blockers.count(TmpBB))
  1326. return false;
  1327. // If any of these blocks has more than one successor (i.e. if the edge we
  1328. // just traversed was critical), then there are other paths through this
  1329. // block along which the load may not be anticipated. Hoisting the load
  1330. // above this block would be adding the load to execution paths along
  1331. // which it was not previously executed.
  1332. if (TmpBB->getTerminator()->getNumSuccessors() != 1)
  1333. return false;
  1334. }
  1335. assert(TmpBB);
  1336. LoadBB = TmpBB;
  1337. // Check to see how many predecessors have the loaded value fully
  1338. // available.
  1339. MapVector<BasicBlock *, Value *> PredLoads;
  1340. DenseMap<BasicBlock*, char> FullyAvailableBlocks;
  1341. for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
  1342. FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
  1343. for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
  1344. FullyAvailableBlocks[UnavailableBlocks[i]] = false;
  1345. SmallVector<BasicBlock *, 4> CriticalEdgePred;
  1346. for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
  1347. PI != E; ++PI) {
  1348. BasicBlock *Pred = *PI;
  1349. if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
  1350. continue;
  1351. }
  1352. if (Pred->getTerminator()->getNumSuccessors() != 1) {
  1353. if (isa<IndirectBrInst>(Pred->getTerminator())) {
  1354. DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
  1355. << Pred->getName() << "': " << *LI << '\n');
  1356. return false;
  1357. }
  1358. if (LoadBB->isLandingPad()) {
  1359. DEBUG(dbgs()
  1360. << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
  1361. << Pred->getName() << "': " << *LI << '\n');
  1362. return false;
  1363. }
  1364. CriticalEdgePred.push_back(Pred);
  1365. } else {
  1366. // Only add the predecessors that will not be split for now.
  1367. PredLoads[Pred] = nullptr;
  1368. }
  1369. }
  1370. // Decide whether PRE is profitable for this load.
  1371. unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
  1372. assert(NumUnavailablePreds != 0 &&
  1373. "Fully available value should already be eliminated!");
  1374. // If this load is unavailable in multiple predecessors, reject it.
  1375. // FIXME: If we could restructure the CFG, we could make a common pred with
  1376. // all the preds that don't have an available LI and insert a new load into
  1377. // that one block.
  1378. if (NumUnavailablePreds != 1)
  1379. return false;
  1380. // Split critical edges, and update the unavailable predecessors accordingly.
  1381. for (BasicBlock *OrigPred : CriticalEdgePred) {
  1382. BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
  1383. assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
  1384. PredLoads[NewPred] = nullptr;
  1385. DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
  1386. << LoadBB->getName() << '\n');
  1387. }
  1388. // Check if the load can safely be moved to all the unavailable predecessors.
  1389. bool CanDoPRE = true;
  1390. const DataLayout &DL = LI->getModule()->getDataLayout();
  1391. SmallVector<Instruction*, 8> NewInsts;
  1392. for (auto &PredLoad : PredLoads) {
  1393. BasicBlock *UnavailablePred = PredLoad.first;
  1394. // Do PHI translation to get its value in the predecessor if necessary. The
  1395. // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
  1396. // If all preds have a single successor, then we know it is safe to insert
  1397. // the load on the pred (?!?), so we can insert code to materialize the
  1398. // pointer if it is not available.
  1399. PHITransAddr Address(LI->getPointerOperand(), DL, AC);
  1400. Value *LoadPtr = nullptr;
  1401. LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
  1402. *DT, NewInsts);
  1403. // If we couldn't find or insert a computation of this phi translated value,
  1404. // we fail PRE.
  1405. if (!LoadPtr) {
  1406. DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
  1407. << *LI->getPointerOperand() << "\n");
  1408. CanDoPRE = false;
  1409. break;
  1410. }
  1411. PredLoad.second = LoadPtr;
  1412. }
  1413. if (!CanDoPRE) {
  1414. while (!NewInsts.empty()) {
  1415. Instruction *I = NewInsts.pop_back_val();
  1416. if (MD) MD->removeInstruction(I);
  1417. I->eraseFromParent();
  1418. }
  1419. // HINT: Don't revert the edge-splitting as following transformation may
  1420. // also need to split these critical edges.
  1421. return !CriticalEdgePred.empty();
  1422. }
  1423. // Okay, we can eliminate this load by inserting a reload in the predecessor
  1424. // and using PHI construction to get the value in the other predecessors, do
  1425. // it.
  1426. DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
  1427. DEBUG(if (!NewInsts.empty())
  1428. dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
  1429. << *NewInsts.back() << '\n');
  1430. // Assign value numbers to the new instructions.
  1431. for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
  1432. // FIXME: We really _ought_ to insert these value numbers into their
  1433. // parent's availability map. However, in doing so, we risk getting into
  1434. // ordering issues. If a block hasn't been processed yet, we would be
  1435. // marking a value as AVAIL-IN, which isn't what we intend.
  1436. VN.lookup_or_add(NewInsts[i]);
  1437. }
  1438. for (const auto &PredLoad : PredLoads) {
  1439. BasicBlock *UnavailablePred = PredLoad.first;
  1440. Value *LoadPtr = PredLoad.second;
  1441. Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
  1442. LI->getAlignment(),
  1443. UnavailablePred->getTerminator());
  1444. // Transfer the old load's AA tags to the new load.
  1445. AAMDNodes Tags;
  1446. LI->getAAMetadata(Tags);
  1447. if (Tags)
  1448. NewLoad->setAAMetadata(Tags);
  1449. // Transfer DebugLoc.
  1450. NewLoad->setDebugLoc(LI->getDebugLoc());
  1451. // Add the newly created load.
  1452. ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
  1453. NewLoad));
  1454. MD->invalidateCachedPointerInfo(LoadPtr);
  1455. DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
  1456. }
  1457. // Perform PHI construction.
  1458. Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
  1459. LI->replaceAllUsesWith(V);
  1460. if (isa<PHINode>(V))
  1461. V->takeName(LI);
  1462. if (Instruction *I = dyn_cast<Instruction>(V))
  1463. I->setDebugLoc(LI->getDebugLoc());
  1464. if (V->getType()->getScalarType()->isPointerTy())
  1465. MD->invalidateCachedPointerInfo(V);
  1466. markInstructionForDeletion(LI);
  1467. ++NumPRELoad;
  1468. return true;
  1469. }
  1470. /// Attempt to eliminate a load whose dependencies are
  1471. /// non-local by performing PHI construction.
  1472. bool GVN::processNonLocalLoad(LoadInst *LI) {
  1473. // Step 1: Find the non-local dependencies of the load.
  1474. LoadDepVect Deps;
  1475. MD->getNonLocalPointerDependency(LI, Deps);
  1476. // If we had to process more than one hundred blocks to find the
  1477. // dependencies, this load isn't worth worrying about. Optimizing
  1478. // it will be too expensive.
  1479. unsigned NumDeps = Deps.size();
  1480. if (NumDeps > 100)
  1481. return false;
  1482. // If we had a phi translation failure, we'll have a single entry which is a
  1483. // clobber in the current block. Reject this early.
  1484. if (NumDeps == 1 &&
  1485. !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
  1486. DEBUG(
  1487. dbgs() << "GVN: non-local load ";
  1488. LI->printAsOperand(dbgs());
  1489. dbgs() << " has unknown dependencies\n";
  1490. );
  1491. return false;
  1492. }
  1493. // If this load follows a GEP, see if we can PRE the indices before analyzing.
  1494. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) {
  1495. for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(),
  1496. OE = GEP->idx_end();
  1497. OI != OE; ++OI)
  1498. if (Instruction *I = dyn_cast<Instruction>(OI->get()))
  1499. performScalarPRE(I);
  1500. }
  1501. // Step 2: Analyze the availability of the load
  1502. AvailValInBlkVect ValuesPerBlock;
  1503. UnavailBlkVect UnavailableBlocks;
  1504. AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
  1505. // If we have no predecessors that produce a known value for this load, exit
  1506. // early.
  1507. if (ValuesPerBlock.empty())
  1508. return false;
  1509. // Step 3: Eliminate fully redundancy.
  1510. //
  1511. // If all of the instructions we depend on produce a known value for this
  1512. // load, then it is fully redundant and we can use PHI insertion to compute
  1513. // its value. Insert PHIs and remove the fully redundant value now.
  1514. if (UnavailableBlocks.empty()) {
  1515. DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
  1516. // Perform PHI construction.
  1517. Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
  1518. LI->replaceAllUsesWith(V);
  1519. if (isa<PHINode>(V))
  1520. V->takeName(LI);
  1521. if (Instruction *I = dyn_cast<Instruction>(V))
  1522. I->setDebugLoc(LI->getDebugLoc());
  1523. if (V->getType()->getScalarType()->isPointerTy())
  1524. MD->invalidateCachedPointerInfo(V);
  1525. markInstructionForDeletion(LI);
  1526. ++NumGVNLoad;
  1527. return true;
  1528. }
  1529. // Step 4: Eliminate partial redundancy.
  1530. if (!EnablePRE || !EnableLoadPRE)
  1531. return false;
  1532. return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
  1533. }
  1534. static void patchReplacementInstruction(Instruction *I, Value *Repl) {
  1535. // Patch the replacement so that it is not more restrictive than the value
  1536. // being replaced.
  1537. BinaryOperator *Op = dyn_cast<BinaryOperator>(I);
  1538. BinaryOperator *ReplOp = dyn_cast<BinaryOperator>(Repl);
  1539. if (Op && ReplOp)
  1540. ReplOp->andIRFlags(Op);
  1541. if (Instruction *ReplInst = dyn_cast<Instruction>(Repl)) {
  1542. // FIXME: If both the original and replacement value are part of the
  1543. // same control-flow region (meaning that the execution of one
  1544. // guarentees the executation of the other), then we can combine the
  1545. // noalias scopes here and do better than the general conservative
  1546. // answer used in combineMetadata().
  1547. // In general, GVN unifies expressions over different control-flow
  1548. // regions, and so we need a conservative combination of the noalias
  1549. // scopes.
  1550. static const unsigned KnownIDs[] = {
  1551. LLVMContext::MD_tbaa,
  1552. LLVMContext::MD_alias_scope,
  1553. LLVMContext::MD_noalias,
  1554. LLVMContext::MD_range,
  1555. LLVMContext::MD_fpmath,
  1556. LLVMContext::MD_invariant_load,
  1557. };
  1558. combineMetadata(ReplInst, I, KnownIDs);
  1559. }
  1560. }
  1561. static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
  1562. patchReplacementInstruction(I, Repl);
  1563. I->replaceAllUsesWith(Repl);
  1564. }
  1565. /// Attempt to eliminate a load, first by eliminating it
  1566. /// locally, and then attempting non-local elimination if that fails.
  1567. bool GVN::processLoad(LoadInst *L) {
  1568. if (!MD)
  1569. return false;
  1570. if (!L->isSimple())
  1571. return false;
  1572. if (L->use_empty()) {
  1573. markInstructionForDeletion(L);
  1574. return true;
  1575. }
  1576. // ... to a pointer that has been loaded from before...
  1577. MemDepResult Dep = MD->getDependency(L);
  1578. const DataLayout &DL = L->getModule()->getDataLayout();
  1579. // If we have a clobber and target data is around, see if this is a clobber
  1580. // that we can fix up through code synthesis.
  1581. if (Dep.isClobber()) {
  1582. // Check to see if we have something like this:
  1583. // store i32 123, i32* %P
  1584. // %A = bitcast i32* %P to i8*
  1585. // %B = gep i8* %A, i32 1
  1586. // %C = load i8* %B
  1587. //
  1588. // We could do that by recognizing if the clobber instructions are obviously
  1589. // a common base + constant offset, and if the previous store (or memset)
  1590. // completely covers this load. This sort of thing can happen in bitfield
  1591. // access code.
  1592. Value *AvailVal = nullptr;
  1593. if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
  1594. int Offset = AnalyzeLoadFromClobberingStore(
  1595. L->getType(), L->getPointerOperand(), DepSI);
  1596. if (Offset != -1)
  1597. AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
  1598. L->getType(), L, DL);
  1599. }
  1600. // Check to see if we have something like this:
  1601. // load i32* P
  1602. // load i8* (P+1)
  1603. // if we have this, replace the later with an extraction from the former.
  1604. if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
  1605. // If this is a clobber and L is the first instruction in its block, then
  1606. // we have the first instruction in the entry block.
  1607. if (DepLI == L)
  1608. return false;
  1609. int Offset = AnalyzeLoadFromClobberingLoad(
  1610. L->getType(), L->getPointerOperand(), DepLI, DL);
  1611. if (Offset != -1)
  1612. AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
  1613. }
  1614. // If the clobbering value is a memset/memcpy/memmove, see if we can forward
  1615. // a value on from it.
  1616. if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
  1617. int Offset = AnalyzeLoadFromClobberingMemInst(
  1618. L->getType(), L->getPointerOperand(), DepMI, DL);
  1619. if (Offset != -1)
  1620. AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, DL);
  1621. }
  1622. if (AvailVal) {
  1623. DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
  1624. << *AvailVal << '\n' << *L << "\n\n\n");
  1625. // Replace the load!
  1626. L->replaceAllUsesWith(AvailVal);
  1627. if (AvailVal->getType()->getScalarType()->isPointerTy())
  1628. MD->invalidateCachedPointerInfo(AvailVal);
  1629. markInstructionForDeletion(L);
  1630. ++NumGVNLoad;
  1631. return true;
  1632. }
  1633. }
  1634. // If the value isn't available, don't do anything!
  1635. if (Dep.isClobber()) {
  1636. DEBUG(
  1637. // fast print dep, using operator<< on instruction is too slow.
  1638. dbgs() << "GVN: load ";
  1639. L->printAsOperand(dbgs());
  1640. Instruction *I = Dep.getInst();
  1641. dbgs() << " is clobbered by " << *I << '\n';
  1642. );
  1643. return false;
  1644. }
  1645. // If it is defined in another block, try harder.
  1646. if (Dep.isNonLocal())
  1647. return processNonLocalLoad(L);
  1648. if (!Dep.isDef()) {
  1649. DEBUG(
  1650. // fast print dep, using operator<< on instruction is too slow.
  1651. dbgs() << "GVN: load ";
  1652. L->printAsOperand(dbgs());
  1653. dbgs() << " has unknown dependence\n";
  1654. );
  1655. return false;
  1656. }
  1657. Instruction *DepInst = Dep.getInst();
  1658. if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
  1659. Value *StoredVal = DepSI->getValueOperand();
  1660. // The store and load are to a must-aliased pointer, but they may not
  1661. // actually have the same type. See if we know how to reuse the stored
  1662. // value (depending on its type).
  1663. if (StoredVal->getType() != L->getType()) {
  1664. IRBuilder<> Builder(L);
  1665. StoredVal =
  1666. CoerceAvailableValueToLoadType(StoredVal, L->getType(), Builder, DL);
  1667. if (!StoredVal)
  1668. return false;
  1669. DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
  1670. << '\n' << *L << "\n\n\n");
  1671. }
  1672. // Remove it!
  1673. L->replaceAllUsesWith(StoredVal);
  1674. if (StoredVal->getType()->getScalarType()->isPointerTy())
  1675. MD->invalidateCachedPointerInfo(StoredVal);
  1676. markInstructionForDeletion(L);
  1677. ++NumGVNLoad;
  1678. return true;
  1679. }
  1680. if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
  1681. Value *AvailableVal = DepLI;
  1682. // The loads are of a must-aliased pointer, but they may not actually have
  1683. // the same type. See if we know how to reuse the previously loaded value
  1684. // (depending on its type).
  1685. if (DepLI->getType() != L->getType()) {
  1686. IRBuilder<> Builder(L);
  1687. AvailableVal =
  1688. CoerceAvailableValueToLoadType(DepLI, L->getType(), Builder, DL);
  1689. if (!AvailableVal)
  1690. return false;
  1691. DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
  1692. << "\n" << *L << "\n\n\n");
  1693. }
  1694. // Remove it!
  1695. patchAndReplaceAllUsesWith(L, AvailableVal);
  1696. if (DepLI->getType()->getScalarType()->isPointerTy())
  1697. MD->invalidateCachedPointerInfo(DepLI);
  1698. markInstructionForDeletion(L);
  1699. ++NumGVNLoad;
  1700. return true;
  1701. }
  1702. // If this load really doesn't depend on anything, then we must be loading an
  1703. // undef value. This can happen when loading for a fresh allocation with no
  1704. // intervening stores, for example.
  1705. if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
  1706. L->replaceAllUsesWith(UndefValue::get(L->getType()));
  1707. markInstructionForDeletion(L);
  1708. ++NumGVNLoad;
  1709. return true;
  1710. }
  1711. // If this load occurs either right after a lifetime begin,
  1712. // then the loaded value is undefined.
  1713. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
  1714. if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
  1715. L->replaceAllUsesWith(UndefValue::get(L->getType()));
  1716. markInstructionForDeletion(L);
  1717. ++NumGVNLoad;
  1718. return true;
  1719. }
  1720. }
  1721. // If this load follows a calloc (which zero initializes memory),
  1722. // then the loaded value is zero
  1723. if (isCallocLikeFn(DepInst, TLI)) {
  1724. L->replaceAllUsesWith(Constant::getNullValue(L->getType()));
  1725. markInstructionForDeletion(L);
  1726. ++NumGVNLoad;
  1727. return true;
  1728. }
  1729. return false;
  1730. }
  1731. // In order to find a leader for a given value number at a
  1732. // specific basic block, we first obtain the list of all Values for that number,
  1733. // and then scan the list to find one whose block dominates the block in
  1734. // question. This is fast because dominator tree queries consist of only
  1735. // a few comparisons of DFS numbers.
  1736. Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
  1737. LeaderTableEntry Vals = LeaderTable[num];
  1738. if (!Vals.Val) return nullptr;
  1739. Value *Val = nullptr;
  1740. if (DT->dominates(Vals.BB, BB)) {
  1741. Val = Vals.Val;
  1742. if (isa<Constant>(Val)) return Val;
  1743. }
  1744. LeaderTableEntry* Next = Vals.Next;
  1745. while (Next) {
  1746. if (DT->dominates(Next->BB, BB)) {
  1747. if (isa<Constant>(Next->Val)) return Next->Val;
  1748. if (!Val) Val = Next->Val;
  1749. }
  1750. Next = Next->Next;
  1751. }
  1752. return Val;
  1753. }
  1754. /// There is an edge from 'Src' to 'Dst'. Return
  1755. /// true if every path from the entry block to 'Dst' passes via this edge. In
  1756. /// particular 'Dst' must not be reachable via another edge from 'Src'.
  1757. static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
  1758. DominatorTree *DT) {
  1759. // While in theory it is interesting to consider the case in which Dst has
  1760. // more than one predecessor, because Dst might be part of a loop which is
  1761. // only reachable from Src, in practice it is pointless since at the time
  1762. // GVN runs all such loops have preheaders, which means that Dst will have
  1763. // been changed to have only one predecessor, namely Src.
  1764. const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
  1765. const BasicBlock *Src = E.getStart();
  1766. assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
  1767. (void)Src;
  1768. return Pred != nullptr;
  1769. }
  1770. /// The given values are known to be equal in every block
  1771. /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
  1772. /// 'RHS' everywhere in the scope. Returns whether a change was made.
  1773. bool GVN::propagateEquality(Value *LHS, Value *RHS,
  1774. const BasicBlockEdge &Root) {
  1775. SmallVector<std::pair<Value*, Value*>, 4> Worklist;
  1776. Worklist.push_back(std::make_pair(LHS, RHS));
  1777. bool Changed = false;
  1778. // For speed, compute a conservative fast approximation to
  1779. // DT->dominates(Root, Root.getEnd());
  1780. bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
  1781. while (!Worklist.empty()) {
  1782. std::pair<Value*, Value*> Item = Worklist.pop_back_val();
  1783. LHS = Item.first; RHS = Item.second;
  1784. if (LHS == RHS) continue;
  1785. assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
  1786. // Don't try to propagate equalities between constants.
  1787. if (isa<Constant>(LHS) && isa<Constant>(RHS)) continue;
  1788. // Prefer a constant on the right-hand side, or an Argument if no constants.
  1789. if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
  1790. std::swap(LHS, RHS);
  1791. assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
  1792. // If there is no obvious reason to prefer the left-hand side over the
  1793. // right-hand side, ensure the longest lived term is on the right-hand side,
  1794. // so the shortest lived term will be replaced by the longest lived.
  1795. // This tends to expose more simplifications.
  1796. uint32_t LVN = VN.lookup_or_add(LHS);
  1797. if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
  1798. (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
  1799. // Move the 'oldest' value to the right-hand side, using the value number
  1800. // as a proxy for age.
  1801. uint32_t RVN = VN.lookup_or_add(RHS);
  1802. if (LVN < RVN) {
  1803. std::swap(LHS, RHS);
  1804. LVN = RVN;
  1805. }
  1806. }
  1807. // If value numbering later sees that an instruction in the scope is equal
  1808. // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
  1809. // the invariant that instructions only occur in the leader table for their
  1810. // own value number (this is used by removeFromLeaderTable), do not do this
  1811. // if RHS is an instruction (if an instruction in the scope is morphed into
  1812. // LHS then it will be turned into RHS by the next GVN iteration anyway, so
  1813. // using the leader table is about compiling faster, not optimizing better).
  1814. // The leader table only tracks basic blocks, not edges. Only add to if we
  1815. // have the simple case where the edge dominates the end.
  1816. if (RootDominatesEnd && !isa<Instruction>(RHS))
  1817. addToLeaderTable(LVN, RHS, Root.getEnd());
  1818. // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
  1819. // LHS always has at least one use that is not dominated by Root, this will
  1820. // never do anything if LHS has only one use.
  1821. if (!LHS->hasOneUse()) {
  1822. unsigned NumReplacements = replaceDominatedUsesWith(LHS, RHS, *DT, Root);
  1823. Changed |= NumReplacements > 0;
  1824. NumGVNEqProp += NumReplacements;
  1825. }
  1826. // Now try to deduce additional equalities from this one. For example, if
  1827. // the known equality was "(A != B)" == "false" then it follows that A and B
  1828. // are equal in the scope. Only boolean equalities with an explicit true or
  1829. // false RHS are currently supported.
  1830. if (!RHS->getType()->isIntegerTy(1))
  1831. // Not a boolean equality - bail out.
  1832. continue;
  1833. ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
  1834. if (!CI)
  1835. // RHS neither 'true' nor 'false' - bail out.
  1836. continue;
  1837. // Whether RHS equals 'true'. Otherwise it equals 'false'.
  1838. bool isKnownTrue = CI->isAllOnesValue();
  1839. bool isKnownFalse = !isKnownTrue;
  1840. // If "A && B" is known true then both A and B are known true. If "A || B"
  1841. // is known false then both A and B are known false.
  1842. Value *A, *B;
  1843. if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
  1844. (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
  1845. Worklist.push_back(std::make_pair(A, RHS));
  1846. Worklist.push_back(std::make_pair(B, RHS));
  1847. continue;
  1848. }
  1849. // If we are propagating an equality like "(A == B)" == "true" then also
  1850. // propagate the equality A == B. When propagating a comparison such as
  1851. // "(A >= B)" == "true", replace all instances of "A < B" with "false".
  1852. if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
  1853. Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
  1854. // If "A == B" is known true, or "A != B" is known false, then replace
  1855. // A with B everywhere in the scope.
  1856. if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
  1857. (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
  1858. Worklist.push_back(std::make_pair(Op0, Op1));
  1859. // Handle the floating point versions of equality comparisons too.
  1860. if ((isKnownTrue && Cmp->getPredicate() == CmpInst::FCMP_OEQ) ||
  1861. (isKnownFalse && Cmp->getPredicate() == CmpInst::FCMP_UNE)) {
  1862. // Floating point -0.0 and 0.0 compare equal, so we can only
  1863. // propagate values if we know that we have a constant and that
  1864. // its value is non-zero.
  1865. // FIXME: We should do this optimization if 'no signed zeros' is
  1866. // applicable via an instruction-level fast-math-flag or some other
  1867. // indicator that relaxed FP semantics are being used.
  1868. if (isa<ConstantFP>(Op1) && !cast<ConstantFP>(Op1)->isZero())
  1869. Worklist.push_back(std::make_pair(Op0, Op1));
  1870. }
  1871. // If "A >= B" is known true, replace "A < B" with false everywhere.
  1872. CmpInst::Predicate NotPred = Cmp->getInversePredicate();
  1873. Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
  1874. // Since we don't have the instruction "A < B" immediately to hand, work
  1875. // out the value number that it would have and use that to find an
  1876. // appropriate instruction (if any).
  1877. uint32_t NextNum = VN.getNextUnusedValueNumber();
  1878. uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
  1879. // If the number we were assigned was brand new then there is no point in
  1880. // looking for an instruction realizing it: there cannot be one!
  1881. if (Num < NextNum) {
  1882. Value *NotCmp = findLeader(Root.getEnd(), Num);
  1883. if (NotCmp && isa<Instruction>(NotCmp)) {
  1884. unsigned NumReplacements =
  1885. replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root);
  1886. Changed |= NumReplacements > 0;
  1887. NumGVNEqProp += NumReplacements;
  1888. }
  1889. }
  1890. // Ensure that any instruction in scope that gets the "A < B" value number
  1891. // is replaced with false.
  1892. // The leader table only tracks basic blocks, not edges. Only add to if we
  1893. // have the simple case where the edge dominates the end.
  1894. if (RootDominatesEnd)
  1895. addToLeaderTable(Num, NotVal, Root.getEnd());
  1896. continue;
  1897. }
  1898. }
  1899. return Changed;
  1900. }
  1901. /// When calculating availability, handle an instruction
  1902. /// by inserting it into the appropriate sets
  1903. bool GVN::processInstruction(Instruction *I) {
  1904. // Ignore dbg info intrinsics.
  1905. if (isa<DbgInfoIntrinsic>(I))
  1906. return false;
  1907. // If the instruction can be easily simplified then do so now in preference
  1908. // to value numbering it. Value numbering often exposes redundancies, for
  1909. // example if it determines that %y is equal to %x then the instruction
  1910. // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
  1911. const DataLayout &DL = I->getModule()->getDataLayout();
  1912. if (Value *V = SimplifyInstruction(I, DL, TLI, DT, AC)) {
  1913. I->replaceAllUsesWith(V);
  1914. if (MD && V->getType()->getScalarType()->isPointerTy())
  1915. MD->invalidateCachedPointerInfo(V);
  1916. markInstructionForDeletion(I);
  1917. ++NumGVNSimpl;
  1918. return true;
  1919. }
  1920. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  1921. if (processLoad(LI))
  1922. return true;
  1923. unsigned Num = VN.lookup_or_add(LI);
  1924. addToLeaderTable(Num, LI, LI->getParent());
  1925. return false;
  1926. }
  1927. // For conditional branches, we can perform simple conditional propagation on
  1928. // the condition value itself.
  1929. if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
  1930. if (!BI->isConditional())
  1931. return false;
  1932. if (isa<Constant>(BI->getCondition()))
  1933. return processFoldableCondBr(BI);
  1934. Value *BranchCond = BI->getCondition();
  1935. BasicBlock *TrueSucc = BI->getSuccessor(0);
  1936. BasicBlock *FalseSucc = BI->getSuccessor(1);
  1937. // Avoid multiple edges early.
  1938. if (TrueSucc == FalseSucc)
  1939. return false;
  1940. BasicBlock *Parent = BI->getParent();
  1941. bool Changed = false;
  1942. Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
  1943. BasicBlockEdge TrueE(Parent, TrueSucc);
  1944. Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
  1945. Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
  1946. BasicBlockEdge FalseE(Parent, FalseSucc);
  1947. Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
  1948. return Changed;
  1949. }
  1950. // For switches, propagate the case values into the case destinations.
  1951. if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
  1952. Value *SwitchCond = SI->getCondition();
  1953. BasicBlock *Parent = SI->getParent();
  1954. bool Changed = false;
  1955. // Remember how many outgoing edges there are to every successor.
  1956. SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
  1957. for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
  1958. ++SwitchEdges[SI->getSuccessor(i)];
  1959. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  1960. i != e; ++i) {
  1961. BasicBlock *Dst = i.getCaseSuccessor();
  1962. // If there is only a single edge, propagate the case value into it.
  1963. if (SwitchEdges.lookup(Dst) == 1) {
  1964. BasicBlockEdge E(Parent, Dst);
  1965. Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E);
  1966. }
  1967. }
  1968. return Changed;
  1969. }
  1970. // Instructions with void type don't return a value, so there's
  1971. // no point in trying to find redundancies in them.
  1972. if (I->getType()->isVoidTy()) return false;
  1973. uint32_t NextNum = VN.getNextUnusedValueNumber();
  1974. unsigned Num = VN.lookup_or_add(I);
  1975. // Allocations are always uniquely numbered, so we can save time and memory
  1976. // by fast failing them.
  1977. if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
  1978. addToLeaderTable(Num, I, I->getParent());
  1979. return false;
  1980. }
  1981. // If the number we were assigned was a brand new VN, then we don't
  1982. // need to do a lookup to see if the number already exists
  1983. // somewhere in the domtree: it can't!
  1984. if (Num >= NextNum) {
  1985. addToLeaderTable(Num, I, I->getParent());
  1986. return false;
  1987. }
  1988. // Perform fast-path value-number based elimination of values inherited from
  1989. // dominators.
  1990. Value *repl = findLeader(I->getParent(), Num);
  1991. if (!repl) {
  1992. // Failure, just remember this instance for future use.
  1993. addToLeaderTable(Num, I, I->getParent());
  1994. return false;
  1995. }
  1996. // Remove it!
  1997. patchAndReplaceAllUsesWith(I, repl);
  1998. if (MD && repl->getType()->getScalarType()->isPointerTy())
  1999. MD->invalidateCachedPointerInfo(repl);
  2000. markInstructionForDeletion(I);
  2001. return true;
  2002. }
  2003. /// runOnFunction - This is the main transformation entry point for a function.
  2004. bool GVN::runOnFunction(Function& F) {
  2005. if (skipOptnoneFunction(F))
  2006. return false;
  2007. if (!NoLoads)
  2008. MD = &getAnalysis<MemoryDependenceAnalysis>();
  2009. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  2010. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  2011. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  2012. VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
  2013. VN.setMemDep(MD);
  2014. VN.setDomTree(DT);
  2015. bool Changed = false;
  2016. bool ShouldContinue = true;
  2017. // Merge unconditional branches, allowing PRE to catch more
  2018. // optimization opportunities.
  2019. for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
  2020. BasicBlock *BB = FI++;
  2021. bool removedBlock = MergeBlockIntoPredecessor(
  2022. BB, DT, /* LoopInfo */ nullptr, VN.getAliasAnalysis(), MD);
  2023. if (removedBlock) ++NumGVNBlocks;
  2024. Changed |= removedBlock;
  2025. }
  2026. unsigned Iteration = 0;
  2027. while (ShouldContinue) {
  2028. DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
  2029. ShouldContinue = iterateOnFunction(F);
  2030. Changed |= ShouldContinue;
  2031. ++Iteration;
  2032. }
  2033. if (EnablePRE) {
  2034. // Fabricate val-num for dead-code in order to suppress assertion in
  2035. // performPRE().
  2036. assignValNumForDeadCode();
  2037. bool PREChanged = true;
  2038. while (PREChanged) {
  2039. PREChanged = performPRE(F);
  2040. Changed |= PREChanged;
  2041. }
  2042. }
  2043. // FIXME: Should perform GVN again after PRE does something. PRE can move
  2044. // computations into blocks where they become fully redundant. Note that
  2045. // we can't do this until PRE's critical edge splitting updates memdep.
  2046. // Actually, when this happens, we should just fully integrate PRE into GVN.
  2047. cleanupGlobalSets();
  2048. // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
  2049. // iteration.
  2050. DeadBlocks.clear();
  2051. return Changed;
  2052. }
  2053. bool GVN::processBlock(BasicBlock *BB) {
  2054. // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
  2055. // (and incrementing BI before processing an instruction).
  2056. assert(InstrsToErase.empty() &&
  2057. "We expect InstrsToErase to be empty across iterations");
  2058. if (DeadBlocks.count(BB))
  2059. return false;
  2060. bool ChangedFunction = false;
  2061. for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
  2062. BI != BE;) {
  2063. ChangedFunction |= processInstruction(BI);
  2064. if (InstrsToErase.empty()) {
  2065. ++BI;
  2066. continue;
  2067. }
  2068. // If we need some instructions deleted, do it now.
  2069. NumGVNInstr += InstrsToErase.size();
  2070. // Avoid iterator invalidation.
  2071. bool AtStart = BI == BB->begin();
  2072. if (!AtStart)
  2073. --BI;
  2074. for (SmallVectorImpl<Instruction *>::iterator I = InstrsToErase.begin(),
  2075. E = InstrsToErase.end(); I != E; ++I) {
  2076. DEBUG(dbgs() << "GVN removed: " << **I << '\n');
  2077. if (MD) MD->removeInstruction(*I);
  2078. DEBUG(verifyRemoved(*I));
  2079. (*I)->eraseFromParent();
  2080. }
  2081. InstrsToErase.clear();
  2082. if (AtStart)
  2083. BI = BB->begin();
  2084. else
  2085. ++BI;
  2086. }
  2087. return ChangedFunction;
  2088. }
  2089. // Instantiate an expression in a predecessor that lacked it.
  2090. bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
  2091. unsigned int ValNo) {
  2092. // Because we are going top-down through the block, all value numbers
  2093. // will be available in the predecessor by the time we need them. Any
  2094. // that weren't originally present will have been instantiated earlier
  2095. // in this loop.
  2096. bool success = true;
  2097. for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) {
  2098. Value *Op = Instr->getOperand(i);
  2099. if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
  2100. continue;
  2101. if (Value *V = findLeader(Pred, VN.lookup(Op))) {
  2102. Instr->setOperand(i, V);
  2103. } else {
  2104. success = false;
  2105. break;
  2106. }
  2107. }
  2108. // Fail out if we encounter an operand that is not available in
  2109. // the PRE predecessor. This is typically because of loads which
  2110. // are not value numbered precisely.
  2111. if (!success)
  2112. return false;
  2113. Instr->insertBefore(Pred->getTerminator());
  2114. Instr->setName(Instr->getName() + ".pre");
  2115. Instr->setDebugLoc(Instr->getDebugLoc());
  2116. VN.add(Instr, ValNo);
  2117. // Update the availability map to include the new instruction.
  2118. addToLeaderTable(ValNo, Instr, Pred);
  2119. return true;
  2120. }
  2121. bool GVN::performScalarPRE(Instruction *CurInst) {
  2122. SmallVector<std::pair<Value*, BasicBlock*>, 8> predMap;
  2123. if (isa<AllocaInst>(CurInst) || isa<TerminatorInst>(CurInst) ||
  2124. isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
  2125. CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
  2126. isa<DbgInfoIntrinsic>(CurInst))
  2127. return false;
  2128. // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
  2129. // sinking the compare again, and it would force the code generator to
  2130. // move the i1 from processor flags or predicate registers into a general
  2131. // purpose register.
  2132. if (isa<CmpInst>(CurInst))
  2133. return false;
  2134. // HLSL Change Begin - Don't do PRE on pointer which may generate phi of
  2135. // pointers.
  2136. if (PointerType *PT = dyn_cast<PointerType>(CurInst->getType())) {
  2137. return false;
  2138. }
  2139. // HLSL Change End
  2140. // We don't currently value number ANY inline asm calls.
  2141. if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
  2142. if (CallI->isInlineAsm())
  2143. return false;
  2144. uint32_t ValNo = VN.lookup(CurInst);
  2145. // Look for the predecessors for PRE opportunities. We're
  2146. // only trying to solve the basic diamond case, where
  2147. // a value is computed in the successor and one predecessor,
  2148. // but not the other. We also explicitly disallow cases
  2149. // where the successor is its own predecessor, because they're
  2150. // more complicated to get right.
  2151. unsigned NumWith = 0;
  2152. unsigned NumWithout = 0;
  2153. BasicBlock *PREPred = nullptr;
  2154. BasicBlock *CurrentBlock = CurInst->getParent();
  2155. predMap.clear();
  2156. for (pred_iterator PI = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
  2157. PI != PE; ++PI) {
  2158. BasicBlock *P = *PI;
  2159. // We're not interested in PRE where the block is its
  2160. // own predecessor, or in blocks with predecessors
  2161. // that are not reachable.
  2162. if (P == CurrentBlock) {
  2163. NumWithout = 2;
  2164. break;
  2165. } else if (!DT->isReachableFromEntry(P)) {
  2166. NumWithout = 2;
  2167. break;
  2168. }
  2169. Value *predV = findLeader(P, ValNo);
  2170. if (!predV) {
  2171. predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
  2172. PREPred = P;
  2173. ++NumWithout;
  2174. } else if (predV == CurInst) {
  2175. /* CurInst dominates this predecessor. */
  2176. NumWithout = 2;
  2177. break;
  2178. } else {
  2179. predMap.push_back(std::make_pair(predV, P));
  2180. ++NumWith;
  2181. }
  2182. }
  2183. // Don't do PRE when it might increase code size, i.e. when
  2184. // we would need to insert instructions in more than one pred.
  2185. if (NumWithout > 1 || NumWith == 0)
  2186. return false;
  2187. // We may have a case where all predecessors have the instruction,
  2188. // and we just need to insert a phi node. Otherwise, perform
  2189. // insertion.
  2190. Instruction *PREInstr = nullptr;
  2191. if (NumWithout != 0) {
  2192. // Don't do PRE across indirect branch.
  2193. if (isa<IndirectBrInst>(PREPred->getTerminator()))
  2194. return false;
  2195. // We can't do PRE safely on a critical edge, so instead we schedule
  2196. // the edge to be split and perform the PRE the next time we iterate
  2197. // on the function.
  2198. unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
  2199. if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
  2200. toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
  2201. return false;
  2202. }
  2203. // We need to insert somewhere, so let's give it a shot
  2204. PREInstr = CurInst->clone();
  2205. if (!performScalarPREInsertion(PREInstr, PREPred, ValNo)) {
  2206. // If we failed insertion, make sure we remove the instruction.
  2207. DEBUG(verifyRemoved(PREInstr));
  2208. delete PREInstr;
  2209. return false;
  2210. }
  2211. }
  2212. // Either we should have filled in the PRE instruction, or we should
  2213. // not have needed insertions.
  2214. assert (PREInstr != nullptr || NumWithout == 0);
  2215. ++NumGVNPRE;
  2216. // Create a PHI to make the value available in this block.
  2217. PHINode *Phi =
  2218. PHINode::Create(CurInst->getType(), predMap.size(),
  2219. CurInst->getName() + ".pre-phi", CurrentBlock->begin());
  2220. for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
  2221. if (Value *V = predMap[i].first)
  2222. Phi->addIncoming(V, predMap[i].second);
  2223. else
  2224. Phi->addIncoming(PREInstr, PREPred);
  2225. }
  2226. VN.add(Phi, ValNo);
  2227. addToLeaderTable(ValNo, Phi, CurrentBlock);
  2228. Phi->setDebugLoc(CurInst->getDebugLoc());
  2229. CurInst->replaceAllUsesWith(Phi);
  2230. if (Phi->getType()->getScalarType()->isPointerTy()) {
  2231. // Because we have added a PHI-use of the pointer value, it has now
  2232. // "escaped" from alias analysis' perspective. We need to inform
  2233. // AA of this.
  2234. for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee; ++ii) {
  2235. unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
  2236. VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
  2237. }
  2238. if (MD)
  2239. MD->invalidateCachedPointerInfo(Phi);
  2240. }
  2241. VN.erase(CurInst);
  2242. removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
  2243. DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
  2244. if (MD)
  2245. MD->removeInstruction(CurInst);
  2246. DEBUG(verifyRemoved(CurInst));
  2247. CurInst->eraseFromParent();
  2248. ++NumGVNInstr;
  2249. return true;
  2250. }
  2251. /// Perform a purely local form of PRE that looks for diamond
  2252. /// control flow patterns and attempts to perform simple PRE at the join point.
  2253. bool GVN::performPRE(Function &F) {
  2254. bool Changed = false;
  2255. for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
  2256. // Nothing to PRE in the entry block.
  2257. if (CurrentBlock == &F.getEntryBlock())
  2258. continue;
  2259. // Don't perform PRE on a landing pad.
  2260. if (CurrentBlock->isLandingPad())
  2261. continue;
  2262. for (BasicBlock::iterator BI = CurrentBlock->begin(),
  2263. BE = CurrentBlock->end();
  2264. BI != BE;) {
  2265. Instruction *CurInst = BI++;
  2266. Changed = performScalarPRE(CurInst);
  2267. }
  2268. }
  2269. if (splitCriticalEdges())
  2270. Changed = true;
  2271. return Changed;
  2272. }
  2273. /// Split the critical edge connecting the given two blocks, and return
  2274. /// the block inserted to the critical edge.
  2275. BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
  2276. BasicBlock *BB = SplitCriticalEdge(
  2277. Pred, Succ, CriticalEdgeSplittingOptions(getAliasAnalysis(), DT));
  2278. if (MD)
  2279. MD->invalidateCachedPredecessors();
  2280. return BB;
  2281. }
  2282. /// Split critical edges found during the previous
  2283. /// iteration that may enable further optimization.
  2284. bool GVN::splitCriticalEdges() {
  2285. if (toSplit.empty())
  2286. return false;
  2287. do {
  2288. std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
  2289. SplitCriticalEdge(Edge.first, Edge.second,
  2290. CriticalEdgeSplittingOptions(getAliasAnalysis(), DT));
  2291. } while (!toSplit.empty());
  2292. if (MD) MD->invalidateCachedPredecessors();
  2293. return true;
  2294. }
  2295. /// Executes one iteration of GVN
  2296. bool GVN::iterateOnFunction(Function &F) {
  2297. cleanupGlobalSets();
  2298. // Top-down walk of the dominator tree
  2299. bool Changed = false;
  2300. // Save the blocks this function have before transformation begins. GVN may
  2301. // split critical edge, and hence may invalidate the RPO/DT iterator.
  2302. //
  2303. std::vector<BasicBlock *> BBVect;
  2304. BBVect.reserve(256);
  2305. // Needed for value numbering with phi construction to work.
  2306. ReversePostOrderTraversal<Function *> RPOT(&F);
  2307. for (ReversePostOrderTraversal<Function *>::rpo_iterator RI = RPOT.begin(),
  2308. RE = RPOT.end();
  2309. RI != RE; ++RI)
  2310. BBVect.push_back(*RI);
  2311. for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
  2312. I != E; I++)
  2313. Changed |= processBlock(*I);
  2314. return Changed;
  2315. }
  2316. void GVN::cleanupGlobalSets() {
  2317. VN.clear();
  2318. LeaderTable.clear();
  2319. TableAllocator.Reset();
  2320. }
  2321. /// Verify that the specified instruction does not occur in our
  2322. /// internal data structures.
  2323. void GVN::verifyRemoved(const Instruction *Inst) const {
  2324. VN.verifyRemoved(Inst);
  2325. // Walk through the value number scope to make sure the instruction isn't
  2326. // ferreted away in it.
  2327. for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
  2328. I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
  2329. const LeaderTableEntry *Node = &I->second;
  2330. assert(Node->Val != Inst && "Inst still in value numbering scope!");
  2331. while (Node->Next) {
  2332. Node = Node->Next;
  2333. assert(Node->Val != Inst && "Inst still in value numbering scope!");
  2334. }
  2335. }
  2336. }
  2337. /// BB is declared dead, which implied other blocks become dead as well. This
  2338. /// function is to add all these blocks to "DeadBlocks". For the dead blocks'
  2339. /// live successors, update their phi nodes by replacing the operands
  2340. /// corresponding to dead blocks with UndefVal.
  2341. void GVN::addDeadBlock(BasicBlock *BB) {
  2342. SmallVector<BasicBlock *, 4> NewDead;
  2343. SmallSetVector<BasicBlock *, 4> DF;
  2344. NewDead.push_back(BB);
  2345. while (!NewDead.empty()) {
  2346. BasicBlock *D = NewDead.pop_back_val();
  2347. if (DeadBlocks.count(D))
  2348. continue;
  2349. // All blocks dominated by D are dead.
  2350. SmallVector<BasicBlock *, 8> Dom;
  2351. DT->getDescendants(D, Dom);
  2352. DeadBlocks.insert(Dom.begin(), Dom.end());
  2353. // Figure out the dominance-frontier(D).
  2354. for (SmallVectorImpl<BasicBlock *>::iterator I = Dom.begin(),
  2355. E = Dom.end(); I != E; I++) {
  2356. BasicBlock *B = *I;
  2357. for (succ_iterator SI = succ_begin(B), SE = succ_end(B); SI != SE; SI++) {
  2358. BasicBlock *S = *SI;
  2359. if (DeadBlocks.count(S))
  2360. continue;
  2361. bool AllPredDead = true;
  2362. for (pred_iterator PI = pred_begin(S), PE = pred_end(S); PI != PE; PI++)
  2363. if (!DeadBlocks.count(*PI)) {
  2364. AllPredDead = false;
  2365. break;
  2366. }
  2367. if (!AllPredDead) {
  2368. // S could be proved dead later on. That is why we don't update phi
  2369. // operands at this moment.
  2370. DF.insert(S);
  2371. } else {
  2372. // While S is not dominated by D, it is dead by now. This could take
  2373. // place if S already have a dead predecessor before D is declared
  2374. // dead.
  2375. NewDead.push_back(S);
  2376. }
  2377. }
  2378. }
  2379. }
  2380. // For the dead blocks' live successors, update their phi nodes by replacing
  2381. // the operands corresponding to dead blocks with UndefVal.
  2382. for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
  2383. I != E; I++) {
  2384. BasicBlock *B = *I;
  2385. if (DeadBlocks.count(B))
  2386. continue;
  2387. SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
  2388. for (SmallVectorImpl<BasicBlock *>::iterator PI = Preds.begin(),
  2389. PE = Preds.end(); PI != PE; PI++) {
  2390. BasicBlock *P = *PI;
  2391. if (!DeadBlocks.count(P))
  2392. continue;
  2393. if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
  2394. if (BasicBlock *S = splitCriticalEdges(P, B))
  2395. DeadBlocks.insert(P = S);
  2396. }
  2397. for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
  2398. PHINode &Phi = cast<PHINode>(*II);
  2399. Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
  2400. UndefValue::get(Phi.getType()));
  2401. }
  2402. }
  2403. }
  2404. }
  2405. // If the given branch is recognized as a foldable branch (i.e. conditional
  2406. // branch with constant condition), it will perform following analyses and
  2407. // transformation.
  2408. // 1) If the dead out-coming edge is a critical-edge, split it. Let
  2409. // R be the target of the dead out-coming edge.
  2410. // 1) Identify the set of dead blocks implied by the branch's dead outcoming
  2411. // edge. The result of this step will be {X| X is dominated by R}
  2412. // 2) Identify those blocks which haves at least one dead prodecessor. The
  2413. // result of this step will be dominance-frontier(R).
  2414. // 3) Update the PHIs in DF(R) by replacing the operands corresponding to
  2415. // dead blocks with "UndefVal" in an hope these PHIs will optimized away.
  2416. //
  2417. // Return true iff *NEW* dead code are found.
  2418. bool GVN::processFoldableCondBr(BranchInst *BI) {
  2419. if (!BI || BI->isUnconditional())
  2420. return false;
  2421. // If a branch has two identical successors, we cannot declare either dead.
  2422. if (BI->getSuccessor(0) == BI->getSuccessor(1))
  2423. return false;
  2424. ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
  2425. if (!Cond)
  2426. return false;
  2427. BasicBlock *DeadRoot = Cond->getZExtValue() ?
  2428. BI->getSuccessor(1) : BI->getSuccessor(0);
  2429. if (DeadBlocks.count(DeadRoot))
  2430. return false;
  2431. if (!DeadRoot->getSinglePredecessor())
  2432. DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
  2433. addDeadBlock(DeadRoot);
  2434. return true;
  2435. }
  2436. // performPRE() will trigger assert if it comes across an instruction without
  2437. // associated val-num. As it normally has far more live instructions than dead
  2438. // instructions, it makes more sense just to "fabricate" a val-number for the
  2439. // dead code than checking if instruction involved is dead or not.
  2440. void GVN::assignValNumForDeadCode() {
  2441. for (SetVector<BasicBlock *>::iterator I = DeadBlocks.begin(),
  2442. E = DeadBlocks.end(); I != E; I++) {
  2443. BasicBlock *BB = *I;
  2444. for (BasicBlock::iterator II = BB->begin(), EE = BB->end();
  2445. II != EE; II++) {
  2446. Instruction *Inst = &*II;
  2447. unsigned ValNum = VN.lookup_or_add(Inst);
  2448. addToLeaderTable(ValNum, Inst, BB);
  2449. }
  2450. }
  2451. }