GVN.cpp 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868
  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/DXIL/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. #if 0 // HLSL Change: Don't support bitcasting to different sizes.
  818. /// This function is called when we have a
  819. /// memdep query of a load that ends up being a clobbering memory write (store,
  820. /// memset, memcpy, memmove). This means that the write *may* provide bits used
  821. /// by the load but we can't be sure because the pointers don't mustalias.
  822. ///
  823. /// Check this case to see if there is anything more we can do before we give
  824. /// up. This returns -1 if we have to give up, or a byte number in the stored
  825. /// value of the piece that feeds the load.
  826. static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
  827. Value *WritePtr,
  828. uint64_t WriteSizeInBits,
  829. const DataLayout &DL) {
  830. // If the loaded or stored value is a first class array or struct, don't try
  831. // to transform them. We need to be able to bitcast to integer.
  832. if (LoadTy->isStructTy() || LoadTy->isArrayTy())
  833. return -1;
  834. int64_t StoreOffset = 0, LoadOffset = 0;
  835. Value *StoreBase =
  836. GetPointerBaseWithConstantOffset(WritePtr, StoreOffset, DL);
  837. Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, DL);
  838. if (StoreBase != LoadBase)
  839. return -1;
  840. // If the load and store are to the exact same address, they should have been
  841. // a must alias. AA must have gotten confused.
  842. // FIXME: Study to see if/when this happens. One case is forwarding a memset
  843. // to a load from the base of the memset.
  844. #if 0
  845. if (LoadOffset == StoreOffset) {
  846. dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
  847. << "Base = " << *StoreBase << "\n"
  848. << "Store Ptr = " << *WritePtr << "\n"
  849. << "Store Offs = " << StoreOffset << "\n"
  850. << "Load Ptr = " << *LoadPtr << "\n";
  851. abort();
  852. }
  853. #endif
  854. // If the load and store don't overlap at all, the store doesn't provide
  855. // anything to the load. In this case, they really don't alias at all, AA
  856. // must have gotten confused.
  857. uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy);
  858. if ((WriteSizeInBits & 7) | (LoadSize & 7))
  859. return -1;
  860. uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
  861. LoadSize >>= 3;
  862. bool isAAFailure = false;
  863. if (StoreOffset < LoadOffset)
  864. isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
  865. else
  866. isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
  867. if (isAAFailure) {
  868. #if 0
  869. dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
  870. << "Base = " << *StoreBase << "\n"
  871. << "Store Ptr = " << *WritePtr << "\n"
  872. << "Store Offs = " << StoreOffset << "\n"
  873. << "Load Ptr = " << *LoadPtr << "\n";
  874. abort();
  875. #endif
  876. return -1;
  877. }
  878. // If the Load isn't completely contained within the stored bits, we don't
  879. // have all the bits to feed it. We could do something crazy in the future
  880. // (issue a smaller load then merge the bits in) but this seems unlikely to be
  881. // valuable.
  882. if (StoreOffset > LoadOffset ||
  883. StoreOffset+StoreSize < LoadOffset+LoadSize)
  884. return -1;
  885. // Okay, we can do this transformation. Return the number of bytes into the
  886. // store that the load is.
  887. return LoadOffset-StoreOffset;
  888. return -1;
  889. }
  890. #endif // HLSL Change: Don't support bitcasting to different sizes.
  891. /// This function is called when we have a
  892. /// memdep query of a load that ends up being a clobbering store.
  893. static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
  894. StoreInst *DepSI) {
  895. #if 0 // HLSL Change: Don't support bitcasting to different sizes.
  896. // Cannot handle reading from store of first-class aggregate yet.
  897. if (DepSI->getValueOperand()->getType()->isStructTy() ||
  898. DepSI->getValueOperand()->getType()->isArrayTy())
  899. return -1;
  900. const DataLayout &DL = DepSI->getModule()->getDataLayout();
  901. Value *StorePtr = DepSI->getPointerOperand();
  902. uint64_t StoreSize =DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
  903. return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
  904. StorePtr, StoreSize, DL);
  905. #endif // HLSL Change: Don't support bitcasting to different sizes.
  906. return -1;
  907. }
  908. /// This function is called when we have a
  909. /// memdep query of a load that ends up being clobbered by another load. See if
  910. /// the other load can feed into the second load.
  911. static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
  912. LoadInst *DepLI, const DataLayout &DL){
  913. #if 0 // HLSL Change: Don't support bitcasting to different sizes.
  914. // Cannot handle reading from store of first-class aggregate yet.
  915. if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
  916. return -1;
  917. Value *DepPtr = DepLI->getPointerOperand();
  918. uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
  919. int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
  920. if (R != -1) return R;
  921. // If we have a load/load clobber an DepLI can be widened to cover this load,
  922. // then we should widen it!
  923. int64_t LoadOffs = 0;
  924. const Value *LoadBase =
  925. GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL);
  926. unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
  927. unsigned Size = MemoryDependenceAnalysis::getLoadLoadClobberFullWidthSize(
  928. LoadBase, LoadOffs, LoadSize, DepLI);
  929. if (Size == 0) return -1;
  930. return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, DL);
  931. #endif
  932. return -1;
  933. }
  934. static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
  935. MemIntrinsic *MI,
  936. const DataLayout &DL) {
  937. #if 0 // HLSL Change: Don't support bitcasting to different sizes.
  938. // If the mem operation is a non-constant size, we can't handle it.
  939. ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
  940. if (!SizeCst) return -1;
  941. uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
  942. // If this is memset, we just need to see if the offset is valid in the size
  943. // of the memset..
  944. if (MI->getIntrinsicID() == Intrinsic::memset)
  945. return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
  946. MemSizeInBits, DL);
  947. // If we have a memcpy/memmove, the only case we can handle is if this is a
  948. // copy from constant memory. In that case, we can read directly from the
  949. // constant memory.
  950. MemTransferInst *MTI = cast<MemTransferInst>(MI);
  951. Constant *Src = dyn_cast<Constant>(MTI->getSource());
  952. if (!Src) return -1;
  953. GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, DL));
  954. if (!GV || !GV->isConstant()) return -1;
  955. // See if the access is within the bounds of the transfer.
  956. int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
  957. MI->getDest(), MemSizeInBits, DL);
  958. if (Offset == -1)
  959. return Offset;
  960. unsigned AS = Src->getType()->getPointerAddressSpace();
  961. // Otherwise, see if we can constant fold a load from the constant with the
  962. // offset applied as appropriate.
  963. Src = ConstantExpr::getBitCast(Src,
  964. Type::getInt8PtrTy(Src->getContext(), AS));
  965. Constant *OffsetCst =
  966. ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
  967. Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
  968. OffsetCst);
  969. Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
  970. if (ConstantFoldLoadFromConstPtr(Src, DL))
  971. return Offset;
  972. #endif
  973. return -1;
  974. }
  975. /// This function is called when we have a
  976. /// memdep query of a load that ends up being a clobbering store. This means
  977. /// that the store provides bits used by the load but we the pointers don't
  978. /// mustalias. Check this case to see if there is anything more we can do
  979. /// before we give up.
  980. static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
  981. Type *LoadTy,
  982. Instruction *InsertPt, const DataLayout &DL){
  983. LLVMContext &Ctx = SrcVal->getType()->getContext();
  984. uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
  985. uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
  986. IRBuilder<> Builder(InsertPt);
  987. // Compute which bits of the stored value are being used by the load. Convert
  988. // to an integer type to start with.
  989. if (SrcVal->getType()->getScalarType()->isPointerTy())
  990. SrcVal = Builder.CreatePtrToInt(SrcVal,
  991. DL.getIntPtrType(SrcVal->getType()));
  992. if (!SrcVal->getType()->isIntegerTy())
  993. SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
  994. // Shift the bits to the least significant depending on endianness.
  995. unsigned ShiftAmt;
  996. if (DL.isLittleEndian())
  997. ShiftAmt = Offset*8;
  998. else
  999. ShiftAmt = (StoreSize-LoadSize-Offset)*8;
  1000. if (ShiftAmt)
  1001. SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
  1002. if (LoadSize != StoreSize)
  1003. SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
  1004. return CoerceAvailableValueToLoadType(SrcVal, LoadTy, Builder, DL);
  1005. }
  1006. /// This function is called when we have a
  1007. /// memdep query of a load that ends up being a clobbering load. This means
  1008. /// that the load *may* provide bits used by the load but we can't be sure
  1009. /// because the pointers don't mustalias. Check this case to see if there is
  1010. /// anything more we can do before we give up.
  1011. static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
  1012. Type *LoadTy, Instruction *InsertPt,
  1013. GVN &gvn) {
  1014. const DataLayout &DL = SrcVal->getModule()->getDataLayout();
  1015. // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
  1016. // widen SrcVal out to a larger load.
  1017. unsigned SrcValSize = DL.getTypeStoreSize(SrcVal->getType());
  1018. unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
  1019. if (Offset+LoadSize > SrcValSize) {
  1020. assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
  1021. assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
  1022. // If we have a load/load clobber an DepLI can be widened to cover this
  1023. // load, then we should widen it to the next power of 2 size big enough!
  1024. unsigned NewLoadSize = Offset+LoadSize;
  1025. if (!isPowerOf2_32(NewLoadSize))
  1026. NewLoadSize = NextPowerOf2(NewLoadSize);
  1027. Value *PtrVal = SrcVal->getPointerOperand();
  1028. // Insert the new load after the old load. This ensures that subsequent
  1029. // memdep queries will find the new load. We can't easily remove the old
  1030. // load completely because it is already in the value numbering table.
  1031. IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
  1032. Type *DestPTy =
  1033. IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
  1034. DestPTy = PointerType::get(DestPTy,
  1035. PtrVal->getType()->getPointerAddressSpace());
  1036. Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
  1037. PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
  1038. LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
  1039. NewLoad->takeName(SrcVal);
  1040. NewLoad->setAlignment(SrcVal->getAlignment());
  1041. DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
  1042. DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
  1043. // Replace uses of the original load with the wider load. On a big endian
  1044. // system, we need to shift down to get the relevant bits.
  1045. Value *RV = NewLoad;
  1046. if (DL.isBigEndian())
  1047. RV = Builder.CreateLShr(RV,
  1048. NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
  1049. RV = Builder.CreateTrunc(RV, SrcVal->getType());
  1050. SrcVal->replaceAllUsesWith(RV);
  1051. // We would like to use gvn.markInstructionForDeletion here, but we can't
  1052. // because the load is already memoized into the leader map table that GVN
  1053. // tracks. It is potentially possible to remove the load from the table,
  1054. // but then there all of the operations based on it would need to be
  1055. // rehashed. Just leave the dead load around.
  1056. gvn.getMemDep().removeInstruction(SrcVal);
  1057. SrcVal = NewLoad;
  1058. }
  1059. return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
  1060. }
  1061. /// This function is called when we have a
  1062. /// memdep query of a load that ends up being a clobbering mem intrinsic.
  1063. static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
  1064. Type *LoadTy, Instruction *InsertPt,
  1065. const DataLayout &DL){
  1066. LLVMContext &Ctx = LoadTy->getContext();
  1067. uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
  1068. IRBuilder<> Builder(InsertPt);
  1069. // We know that this method is only called when the mem transfer fully
  1070. // provides the bits for the load.
  1071. if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
  1072. // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
  1073. // independently of what the offset is.
  1074. Value *Val = MSI->getValue();
  1075. if (LoadSize != 1)
  1076. Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
  1077. Value *OneElt = Val;
  1078. // Splat the value out to the right number of bits.
  1079. for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
  1080. // If we can double the number of bytes set, do it.
  1081. if (NumBytesSet*2 <= LoadSize) {
  1082. Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
  1083. Val = Builder.CreateOr(Val, ShVal);
  1084. NumBytesSet <<= 1;
  1085. continue;
  1086. }
  1087. // Otherwise insert one byte at a time.
  1088. Value *ShVal = Builder.CreateShl(Val, 1*8);
  1089. Val = Builder.CreateOr(OneElt, ShVal);
  1090. ++NumBytesSet;
  1091. }
  1092. return CoerceAvailableValueToLoadType(Val, LoadTy, Builder, DL);
  1093. }
  1094. // Otherwise, this is a memcpy/memmove from a constant global.
  1095. MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
  1096. Constant *Src = cast<Constant>(MTI->getSource());
  1097. unsigned AS = Src->getType()->getPointerAddressSpace();
  1098. // Otherwise, see if we can constant fold a load from the constant with the
  1099. // offset applied as appropriate.
  1100. Src = ConstantExpr::getBitCast(Src,
  1101. Type::getInt8PtrTy(Src->getContext(), AS));
  1102. Constant *OffsetCst =
  1103. ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
  1104. Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
  1105. OffsetCst);
  1106. Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
  1107. return ConstantFoldLoadFromConstPtr(Src, DL);
  1108. }
  1109. /// Given a set of loads specified by ValuesPerBlock,
  1110. /// construct SSA form, allowing us to eliminate LI. This returns the value
  1111. /// that should be used at LI's definition site.
  1112. static Value *ConstructSSAForLoadSet(LoadInst *LI,
  1113. SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
  1114. GVN &gvn) {
  1115. // Check for the fully redundant, dominating load case. In this case, we can
  1116. // just use the dominating value directly.
  1117. if (ValuesPerBlock.size() == 1 &&
  1118. gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
  1119. LI->getParent())) {
  1120. assert(!ValuesPerBlock[0].isUndefValue() && "Dead BB dominate this block");
  1121. return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
  1122. }
  1123. // Otherwise, we have to construct SSA form.
  1124. SmallVector<PHINode*, 8> NewPHIs;
  1125. SSAUpdater SSAUpdate(&NewPHIs);
  1126. SSAUpdate.Initialize(LI->getType(), LI->getName());
  1127. for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
  1128. const AvailableValueInBlock &AV = ValuesPerBlock[i];
  1129. BasicBlock *BB = AV.BB;
  1130. if (SSAUpdate.HasValueForBlock(BB))
  1131. continue;
  1132. SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn));
  1133. }
  1134. // Perform PHI construction.
  1135. Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
  1136. // If new PHI nodes were created, notify alias analysis.
  1137. if (V->getType()->getScalarType()->isPointerTy()) {
  1138. AliasAnalysis *AA = gvn.getAliasAnalysis();
  1139. // Scan the new PHIs and inform alias analysis that we've added potentially
  1140. // escaping uses to any values that are operands to these PHIs.
  1141. for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
  1142. PHINode *P = NewPHIs[i];
  1143. for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
  1144. unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
  1145. AA->addEscapingUse(P->getOperandUse(jj));
  1146. }
  1147. }
  1148. }
  1149. return V;
  1150. }
  1151. Value *AvailableValueInBlock::MaterializeAdjustedValue(LoadInst *LI,
  1152. GVN &gvn) const {
  1153. Value *Res;
  1154. Type *LoadTy = LI->getType();
  1155. const DataLayout &DL = LI->getModule()->getDataLayout();
  1156. if (isSimpleValue()) {
  1157. Res = getSimpleValue();
  1158. if (Res->getType() != LoadTy) {
  1159. Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(), DL);
  1160. DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
  1161. << *getSimpleValue() << '\n'
  1162. << *Res << '\n' << "\n\n\n");
  1163. }
  1164. } else if (isCoercedLoadValue()) {
  1165. LoadInst *Load = getCoercedLoadValue();
  1166. if (Load->getType() == LoadTy && Offset == 0) {
  1167. Res = Load;
  1168. } else {
  1169. Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
  1170. gvn);
  1171. DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
  1172. << *getCoercedLoadValue() << '\n'
  1173. << *Res << '\n' << "\n\n\n");
  1174. }
  1175. } else if (isMemIntrinValue()) {
  1176. Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
  1177. BB->getTerminator(), DL);
  1178. DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
  1179. << " " << *getMemIntrinValue() << '\n'
  1180. << *Res << '\n' << "\n\n\n");
  1181. } else {
  1182. assert(isUndefValue() && "Should be UndefVal");
  1183. DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
  1184. return UndefValue::get(LoadTy);
  1185. }
  1186. return Res;
  1187. }
  1188. static bool isLifetimeStart(const Instruction *Inst) {
  1189. if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
  1190. return II->getIntrinsicID() == Intrinsic::lifetime_start;
  1191. return false;
  1192. }
  1193. void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
  1194. AvailValInBlkVect &ValuesPerBlock,
  1195. UnavailBlkVect &UnavailableBlocks) {
  1196. // Filter out useless results (non-locals, etc). Keep track of the blocks
  1197. // where we have a value available in repl, also keep track of whether we see
  1198. // dependencies that produce an unknown value for the load (such as a call
  1199. // that could potentially clobber the load).
  1200. unsigned NumDeps = Deps.size();
  1201. const DataLayout &DL = LI->getModule()->getDataLayout();
  1202. for (unsigned i = 0, e = NumDeps; i != e; ++i) {
  1203. BasicBlock *DepBB = Deps[i].getBB();
  1204. MemDepResult DepInfo = Deps[i].getResult();
  1205. if (DeadBlocks.count(DepBB)) {
  1206. // Dead dependent mem-op disguise as a load evaluating the same value
  1207. // as the load in question.
  1208. ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
  1209. continue;
  1210. }
  1211. if (!DepInfo.isDef() && !DepInfo.isClobber()) {
  1212. UnavailableBlocks.push_back(DepBB);
  1213. continue;
  1214. }
  1215. if (DepInfo.isClobber()) {
  1216. // The address being loaded in this non-local block may not be the same as
  1217. // the pointer operand of the load if PHI translation occurs. Make sure
  1218. // to consider the right address.
  1219. Value *Address = Deps[i].getAddress();
  1220. // If the dependence is to a store that writes to a superset of the bits
  1221. // read by the load, we can extract the bits we need for the load from the
  1222. // stored value.
  1223. if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
  1224. if (Address) {
  1225. int Offset =
  1226. AnalyzeLoadFromClobberingStore(LI->getType(), Address, DepSI);
  1227. if (Offset != -1) {
  1228. ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
  1229. DepSI->getValueOperand(),
  1230. Offset));
  1231. continue;
  1232. }
  1233. }
  1234. }
  1235. // Check to see if we have something like this:
  1236. // load i32* P
  1237. // load i8* (P+1)
  1238. // if we have this, replace the later with an extraction from the former.
  1239. if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
  1240. // If this is a clobber and L is the first instruction in its block, then
  1241. // we have the first instruction in the entry block.
  1242. if (DepLI != LI && Address) {
  1243. int Offset =
  1244. AnalyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL);
  1245. if (Offset != -1) {
  1246. ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
  1247. Offset));
  1248. continue;
  1249. }
  1250. }
  1251. }
  1252. // If the clobbering value is a memset/memcpy/memmove, see if we can
  1253. // forward a value on from it.
  1254. if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
  1255. if (Address) {
  1256. int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
  1257. DepMI, DL);
  1258. if (Offset != -1) {
  1259. ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
  1260. Offset));
  1261. continue;
  1262. }
  1263. }
  1264. }
  1265. UnavailableBlocks.push_back(DepBB);
  1266. continue;
  1267. }
  1268. // DepInfo.isDef() here
  1269. Instruction *DepInst = DepInfo.getInst();
  1270. // Loading the allocation -> undef.
  1271. if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
  1272. // Loading immediately after lifetime begin -> undef.
  1273. isLifetimeStart(DepInst)) {
  1274. ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
  1275. UndefValue::get(LI->getType())));
  1276. continue;
  1277. }
  1278. // Loading from calloc (which zero initializes memory) -> zero
  1279. if (isCallocLikeFn(DepInst, TLI)) {
  1280. ValuesPerBlock.push_back(AvailableValueInBlock::get(
  1281. DepBB, Constant::getNullValue(LI->getType())));
  1282. continue;
  1283. }
  1284. if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
  1285. // Reject loads and stores that are to the same address but are of
  1286. // different types if we have to.
  1287. if (S->getValueOperand()->getType() != LI->getType()) {
  1288. // If the stored value is larger or equal to the loaded value, we can
  1289. // reuse it.
  1290. if (!CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
  1291. LI->getType(), DL)) {
  1292. UnavailableBlocks.push_back(DepBB);
  1293. continue;
  1294. }
  1295. }
  1296. ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
  1297. S->getValueOperand()));
  1298. continue;
  1299. }
  1300. if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
  1301. // If the types mismatch and we can't handle it, reject reuse of the load.
  1302. if (LD->getType() != LI->getType()) {
  1303. // If the stored value is larger or equal to the loaded value, we can
  1304. // reuse it.
  1305. if (!CanCoerceMustAliasedValueToLoad(LD, LI->getType(), DL)) {
  1306. UnavailableBlocks.push_back(DepBB);
  1307. continue;
  1308. }
  1309. }
  1310. ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
  1311. continue;
  1312. }
  1313. UnavailableBlocks.push_back(DepBB);
  1314. }
  1315. }
  1316. bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
  1317. UnavailBlkVect &UnavailableBlocks) {
  1318. // Okay, we have *some* definitions of the value. This means that the value
  1319. // is available in some of our (transitive) predecessors. Lets think about
  1320. // doing PRE of this load. This will involve inserting a new load into the
  1321. // predecessor when it's not available. We could do this in general, but
  1322. // prefer to not increase code size. As such, we only do this when we know
  1323. // that we only have to insert *one* load (which means we're basically moving
  1324. // the load, not inserting a new one).
  1325. SmallPtrSet<BasicBlock *, 4> Blockers;
  1326. for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
  1327. Blockers.insert(UnavailableBlocks[i]);
  1328. // Let's find the first basic block with more than one predecessor. Walk
  1329. // backwards through predecessors if needed.
  1330. BasicBlock *LoadBB = LI->getParent();
  1331. BasicBlock *TmpBB = LoadBB;
  1332. while (TmpBB->getSinglePredecessor()) {
  1333. TmpBB = TmpBB->getSinglePredecessor();
  1334. if (TmpBB == LoadBB) // Infinite (unreachable) loop.
  1335. return false;
  1336. if (Blockers.count(TmpBB))
  1337. return false;
  1338. // If any of these blocks has more than one successor (i.e. if the edge we
  1339. // just traversed was critical), then there are other paths through this
  1340. // block along which the load may not be anticipated. Hoisting the load
  1341. // above this block would be adding the load to execution paths along
  1342. // which it was not previously executed.
  1343. if (TmpBB->getTerminator()->getNumSuccessors() != 1)
  1344. return false;
  1345. }
  1346. assert(TmpBB);
  1347. LoadBB = TmpBB;
  1348. // Check to see how many predecessors have the loaded value fully
  1349. // available.
  1350. MapVector<BasicBlock *, Value *> PredLoads;
  1351. DenseMap<BasicBlock*, char> FullyAvailableBlocks;
  1352. for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
  1353. FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
  1354. for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
  1355. FullyAvailableBlocks[UnavailableBlocks[i]] = false;
  1356. SmallVector<BasicBlock *, 4> CriticalEdgePred;
  1357. for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
  1358. PI != E; ++PI) {
  1359. BasicBlock *Pred = *PI;
  1360. if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
  1361. continue;
  1362. }
  1363. if (Pred->getTerminator()->getNumSuccessors() != 1) {
  1364. if (isa<IndirectBrInst>(Pred->getTerminator())) {
  1365. DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
  1366. << Pred->getName() << "': " << *LI << '\n');
  1367. return false;
  1368. }
  1369. if (LoadBB->isLandingPad()) {
  1370. DEBUG(dbgs()
  1371. << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
  1372. << Pred->getName() << "': " << *LI << '\n');
  1373. return false;
  1374. }
  1375. CriticalEdgePred.push_back(Pred);
  1376. } else {
  1377. // Only add the predecessors that will not be split for now.
  1378. PredLoads[Pred] = nullptr;
  1379. }
  1380. }
  1381. // Decide whether PRE is profitable for this load.
  1382. unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
  1383. assert(NumUnavailablePreds != 0 &&
  1384. "Fully available value should already be eliminated!");
  1385. // If this load is unavailable in multiple predecessors, reject it.
  1386. // FIXME: If we could restructure the CFG, we could make a common pred with
  1387. // all the preds that don't have an available LI and insert a new load into
  1388. // that one block.
  1389. if (NumUnavailablePreds != 1)
  1390. return false;
  1391. // Split critical edges, and update the unavailable predecessors accordingly.
  1392. for (BasicBlock *OrigPred : CriticalEdgePred) {
  1393. BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
  1394. assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
  1395. PredLoads[NewPred] = nullptr;
  1396. DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
  1397. << LoadBB->getName() << '\n');
  1398. }
  1399. // Check if the load can safely be moved to all the unavailable predecessors.
  1400. bool CanDoPRE = true;
  1401. const DataLayout &DL = LI->getModule()->getDataLayout();
  1402. SmallVector<Instruction*, 8> NewInsts;
  1403. for (auto &PredLoad : PredLoads) {
  1404. BasicBlock *UnavailablePred = PredLoad.first;
  1405. // Do PHI translation to get its value in the predecessor if necessary. The
  1406. // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
  1407. // If all preds have a single successor, then we know it is safe to insert
  1408. // the load on the pred (?!?), so we can insert code to materialize the
  1409. // pointer if it is not available.
  1410. PHITransAddr Address(LI->getPointerOperand(), DL, AC);
  1411. Value *LoadPtr = nullptr;
  1412. LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
  1413. *DT, NewInsts);
  1414. // If we couldn't find or insert a computation of this phi translated value,
  1415. // we fail PRE.
  1416. if (!LoadPtr) {
  1417. DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
  1418. << *LI->getPointerOperand() << "\n");
  1419. CanDoPRE = false;
  1420. break;
  1421. }
  1422. PredLoad.second = LoadPtr;
  1423. }
  1424. if (!CanDoPRE) {
  1425. while (!NewInsts.empty()) {
  1426. Instruction *I = NewInsts.pop_back_val();
  1427. if (MD) MD->removeInstruction(I);
  1428. I->eraseFromParent();
  1429. }
  1430. // HINT: Don't revert the edge-splitting as following transformation may
  1431. // also need to split these critical edges.
  1432. return !CriticalEdgePred.empty();
  1433. }
  1434. // Okay, we can eliminate this load by inserting a reload in the predecessor
  1435. // and using PHI construction to get the value in the other predecessors, do
  1436. // it.
  1437. DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
  1438. DEBUG(if (!NewInsts.empty())
  1439. dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
  1440. << *NewInsts.back() << '\n');
  1441. // Assign value numbers to the new instructions.
  1442. for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
  1443. // FIXME: We really _ought_ to insert these value numbers into their
  1444. // parent's availability map. However, in doing so, we risk getting into
  1445. // ordering issues. If a block hasn't been processed yet, we would be
  1446. // marking a value as AVAIL-IN, which isn't what we intend.
  1447. VN.lookup_or_add(NewInsts[i]);
  1448. }
  1449. for (const auto &PredLoad : PredLoads) {
  1450. BasicBlock *UnavailablePred = PredLoad.first;
  1451. Value *LoadPtr = PredLoad.second;
  1452. Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
  1453. LI->getAlignment(),
  1454. UnavailablePred->getTerminator());
  1455. // Transfer the old load's AA tags to the new load.
  1456. AAMDNodes Tags;
  1457. LI->getAAMetadata(Tags);
  1458. if (Tags)
  1459. NewLoad->setAAMetadata(Tags);
  1460. // Transfer DebugLoc.
  1461. NewLoad->setDebugLoc(LI->getDebugLoc());
  1462. // Add the newly created load.
  1463. ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
  1464. NewLoad));
  1465. MD->invalidateCachedPointerInfo(LoadPtr);
  1466. DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
  1467. }
  1468. // Perform PHI construction.
  1469. Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
  1470. LI->replaceAllUsesWith(V);
  1471. if (isa<PHINode>(V))
  1472. V->takeName(LI);
  1473. if (Instruction *I = dyn_cast<Instruction>(V))
  1474. I->setDebugLoc(LI->getDebugLoc());
  1475. if (V->getType()->getScalarType()->isPointerTy())
  1476. MD->invalidateCachedPointerInfo(V);
  1477. markInstructionForDeletion(LI);
  1478. ++NumPRELoad;
  1479. return true;
  1480. }
  1481. /// Attempt to eliminate a load whose dependencies are
  1482. /// non-local by performing PHI construction.
  1483. bool GVN::processNonLocalLoad(LoadInst *LI) {
  1484. // Step 1: Find the non-local dependencies of the load.
  1485. LoadDepVect Deps;
  1486. MD->getNonLocalPointerDependency(LI, Deps);
  1487. // If we had to process more than one hundred blocks to find the
  1488. // dependencies, this load isn't worth worrying about. Optimizing
  1489. // it will be too expensive.
  1490. unsigned NumDeps = Deps.size();
  1491. if (NumDeps > 100)
  1492. return false;
  1493. // If we had a phi translation failure, we'll have a single entry which is a
  1494. // clobber in the current block. Reject this early.
  1495. if (NumDeps == 1 &&
  1496. !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
  1497. DEBUG(
  1498. dbgs() << "GVN: non-local load ";
  1499. LI->printAsOperand(dbgs());
  1500. dbgs() << " has unknown dependencies\n";
  1501. );
  1502. return false;
  1503. }
  1504. // If this load follows a GEP, see if we can PRE the indices before analyzing.
  1505. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) {
  1506. for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(),
  1507. OE = GEP->idx_end();
  1508. OI != OE; ++OI)
  1509. if (Instruction *I = dyn_cast<Instruction>(OI->get()))
  1510. performScalarPRE(I);
  1511. }
  1512. // Step 2: Analyze the availability of the load
  1513. AvailValInBlkVect ValuesPerBlock;
  1514. UnavailBlkVect UnavailableBlocks;
  1515. AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
  1516. // If we have no predecessors that produce a known value for this load, exit
  1517. // early.
  1518. if (ValuesPerBlock.empty())
  1519. return false;
  1520. // Step 3: Eliminate fully redundancy.
  1521. //
  1522. // If all of the instructions we depend on produce a known value for this
  1523. // load, then it is fully redundant and we can use PHI insertion to compute
  1524. // its value. Insert PHIs and remove the fully redundant value now.
  1525. if (UnavailableBlocks.empty()) {
  1526. DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
  1527. // Perform PHI construction.
  1528. Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
  1529. LI->replaceAllUsesWith(V);
  1530. if (isa<PHINode>(V))
  1531. V->takeName(LI);
  1532. if (Instruction *I = dyn_cast<Instruction>(V))
  1533. I->setDebugLoc(LI->getDebugLoc());
  1534. if (V->getType()->getScalarType()->isPointerTy())
  1535. MD->invalidateCachedPointerInfo(V);
  1536. markInstructionForDeletion(LI);
  1537. ++NumGVNLoad;
  1538. return true;
  1539. }
  1540. // Step 4: Eliminate partial redundancy.
  1541. if (!EnablePRE || !EnableLoadPRE)
  1542. return false;
  1543. return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
  1544. }
  1545. static void patchReplacementInstruction(Instruction *I, Value *Repl) {
  1546. // Patch the replacement so that it is not more restrictive than the value
  1547. // being replaced.
  1548. BinaryOperator *Op = dyn_cast<BinaryOperator>(I);
  1549. BinaryOperator *ReplOp = dyn_cast<BinaryOperator>(Repl);
  1550. if (Op && ReplOp)
  1551. ReplOp->andIRFlags(Op);
  1552. if (Instruction *ReplInst = dyn_cast<Instruction>(Repl)) {
  1553. // FIXME: If both the original and replacement value are part of the
  1554. // same control-flow region (meaning that the execution of one
  1555. // guarentees the executation of the other), then we can combine the
  1556. // noalias scopes here and do better than the general conservative
  1557. // answer used in combineMetadata().
  1558. // In general, GVN unifies expressions over different control-flow
  1559. // regions, and so we need a conservative combination of the noalias
  1560. // scopes.
  1561. static const unsigned KnownIDs[] = {
  1562. LLVMContext::MD_tbaa,
  1563. LLVMContext::MD_alias_scope,
  1564. LLVMContext::MD_noalias,
  1565. LLVMContext::MD_range,
  1566. LLVMContext::MD_fpmath,
  1567. LLVMContext::MD_invariant_load,
  1568. };
  1569. combineMetadata(ReplInst, I, KnownIDs);
  1570. }
  1571. }
  1572. static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
  1573. patchReplacementInstruction(I, Repl);
  1574. I->replaceAllUsesWith(Repl);
  1575. }
  1576. /// Attempt to eliminate a load, first by eliminating it
  1577. /// locally, and then attempting non-local elimination if that fails.
  1578. bool GVN::processLoad(LoadInst *L) {
  1579. if (!MD)
  1580. return false;
  1581. if (!L->isSimple())
  1582. return false;
  1583. if (L->use_empty()) {
  1584. markInstructionForDeletion(L);
  1585. return true;
  1586. }
  1587. // ... to a pointer that has been loaded from before...
  1588. MemDepResult Dep = MD->getDependency(L);
  1589. const DataLayout &DL = L->getModule()->getDataLayout();
  1590. // If we have a clobber and target data is around, see if this is a clobber
  1591. // that we can fix up through code synthesis.
  1592. if (Dep.isClobber()) {
  1593. // Check to see if we have something like this:
  1594. // store i32 123, i32* %P
  1595. // %A = bitcast i32* %P to i8*
  1596. // %B = gep i8* %A, i32 1
  1597. // %C = load i8* %B
  1598. //
  1599. // We could do that by recognizing if the clobber instructions are obviously
  1600. // a common base + constant offset, and if the previous store (or memset)
  1601. // completely covers this load. This sort of thing can happen in bitfield
  1602. // access code.
  1603. Value *AvailVal = nullptr;
  1604. if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
  1605. int Offset = AnalyzeLoadFromClobberingStore(
  1606. L->getType(), L->getPointerOperand(), DepSI);
  1607. if (Offset != -1)
  1608. AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
  1609. L->getType(), L, DL);
  1610. }
  1611. // Check to see if we have something like this:
  1612. // load i32* P
  1613. // load i8* (P+1)
  1614. // if we have this, replace the later with an extraction from the former.
  1615. if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
  1616. // If this is a clobber and L is the first instruction in its block, then
  1617. // we have the first instruction in the entry block.
  1618. if (DepLI == L)
  1619. return false;
  1620. int Offset = AnalyzeLoadFromClobberingLoad(
  1621. L->getType(), L->getPointerOperand(), DepLI, DL);
  1622. if (Offset != -1)
  1623. AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
  1624. }
  1625. // If the clobbering value is a memset/memcpy/memmove, see if we can forward
  1626. // a value on from it.
  1627. if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
  1628. int Offset = AnalyzeLoadFromClobberingMemInst(
  1629. L->getType(), L->getPointerOperand(), DepMI, DL);
  1630. if (Offset != -1)
  1631. AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, DL);
  1632. }
  1633. if (AvailVal) {
  1634. DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
  1635. << *AvailVal << '\n' << *L << "\n\n\n");
  1636. // Replace the load!
  1637. L->replaceAllUsesWith(AvailVal);
  1638. if (AvailVal->getType()->getScalarType()->isPointerTy())
  1639. MD->invalidateCachedPointerInfo(AvailVal);
  1640. markInstructionForDeletion(L);
  1641. ++NumGVNLoad;
  1642. return true;
  1643. }
  1644. }
  1645. // If the value isn't available, don't do anything!
  1646. if (Dep.isClobber()) {
  1647. DEBUG(
  1648. // fast print dep, using operator<< on instruction is too slow.
  1649. dbgs() << "GVN: load ";
  1650. L->printAsOperand(dbgs());
  1651. Instruction *I = Dep.getInst();
  1652. dbgs() << " is clobbered by " << *I << '\n';
  1653. );
  1654. return false;
  1655. }
  1656. // If it is defined in another block, try harder.
  1657. if (Dep.isNonLocal())
  1658. return processNonLocalLoad(L);
  1659. if (!Dep.isDef()) {
  1660. DEBUG(
  1661. // fast print dep, using operator<< on instruction is too slow.
  1662. dbgs() << "GVN: load ";
  1663. L->printAsOperand(dbgs());
  1664. dbgs() << " has unknown dependence\n";
  1665. );
  1666. return false;
  1667. }
  1668. Instruction *DepInst = Dep.getInst();
  1669. if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
  1670. Value *StoredVal = DepSI->getValueOperand();
  1671. // The store and load are to a must-aliased pointer, but they may not
  1672. // actually have the same type. See if we know how to reuse the stored
  1673. // value (depending on its type).
  1674. if (StoredVal->getType() != L->getType()) {
  1675. IRBuilder<> Builder(L);
  1676. StoredVal =
  1677. CoerceAvailableValueToLoadType(StoredVal, L->getType(), Builder, DL);
  1678. if (!StoredVal)
  1679. return false;
  1680. DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
  1681. << '\n' << *L << "\n\n\n");
  1682. }
  1683. // Remove it!
  1684. L->replaceAllUsesWith(StoredVal);
  1685. if (StoredVal->getType()->getScalarType()->isPointerTy())
  1686. MD->invalidateCachedPointerInfo(StoredVal);
  1687. markInstructionForDeletion(L);
  1688. ++NumGVNLoad;
  1689. return true;
  1690. }
  1691. if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
  1692. Value *AvailableVal = DepLI;
  1693. // The loads are of a must-aliased pointer, but they may not actually have
  1694. // the same type. See if we know how to reuse the previously loaded value
  1695. // (depending on its type).
  1696. if (DepLI->getType() != L->getType()) {
  1697. IRBuilder<> Builder(L);
  1698. AvailableVal =
  1699. CoerceAvailableValueToLoadType(DepLI, L->getType(), Builder, DL);
  1700. if (!AvailableVal)
  1701. return false;
  1702. DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
  1703. << "\n" << *L << "\n\n\n");
  1704. }
  1705. // Remove it!
  1706. patchAndReplaceAllUsesWith(L, AvailableVal);
  1707. if (DepLI->getType()->getScalarType()->isPointerTy())
  1708. MD->invalidateCachedPointerInfo(DepLI);
  1709. markInstructionForDeletion(L);
  1710. ++NumGVNLoad;
  1711. return true;
  1712. }
  1713. // If this load really doesn't depend on anything, then we must be loading an
  1714. // undef value. This can happen when loading for a fresh allocation with no
  1715. // intervening stores, for example.
  1716. if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
  1717. L->replaceAllUsesWith(UndefValue::get(L->getType()));
  1718. markInstructionForDeletion(L);
  1719. ++NumGVNLoad;
  1720. return true;
  1721. }
  1722. // If this load occurs either right after a lifetime begin,
  1723. // then the loaded value is undefined.
  1724. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
  1725. if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
  1726. L->replaceAllUsesWith(UndefValue::get(L->getType()));
  1727. markInstructionForDeletion(L);
  1728. ++NumGVNLoad;
  1729. return true;
  1730. }
  1731. }
  1732. // If this load follows a calloc (which zero initializes memory),
  1733. // then the loaded value is zero
  1734. if (isCallocLikeFn(DepInst, TLI)) {
  1735. L->replaceAllUsesWith(Constant::getNullValue(L->getType()));
  1736. markInstructionForDeletion(L);
  1737. ++NumGVNLoad;
  1738. return true;
  1739. }
  1740. return false;
  1741. }
  1742. // In order to find a leader for a given value number at a
  1743. // specific basic block, we first obtain the list of all Values for that number,
  1744. // and then scan the list to find one whose block dominates the block in
  1745. // question. This is fast because dominator tree queries consist of only
  1746. // a few comparisons of DFS numbers.
  1747. Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
  1748. LeaderTableEntry Vals = LeaderTable[num];
  1749. if (!Vals.Val) return nullptr;
  1750. Value *Val = nullptr;
  1751. if (DT->dominates(Vals.BB, BB)) {
  1752. Val = Vals.Val;
  1753. if (isa<Constant>(Val)) return Val;
  1754. }
  1755. LeaderTableEntry* Next = Vals.Next;
  1756. while (Next) {
  1757. if (DT->dominates(Next->BB, BB)) {
  1758. if (isa<Constant>(Next->Val)) return Next->Val;
  1759. if (!Val) Val = Next->Val;
  1760. }
  1761. Next = Next->Next;
  1762. }
  1763. return Val;
  1764. }
  1765. /// There is an edge from 'Src' to 'Dst'. Return
  1766. /// true if every path from the entry block to 'Dst' passes via this edge. In
  1767. /// particular 'Dst' must not be reachable via another edge from 'Src'.
  1768. static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
  1769. DominatorTree *DT) {
  1770. // While in theory it is interesting to consider the case in which Dst has
  1771. // more than one predecessor, because Dst might be part of a loop which is
  1772. // only reachable from Src, in practice it is pointless since at the time
  1773. // GVN runs all such loops have preheaders, which means that Dst will have
  1774. // been changed to have only one predecessor, namely Src.
  1775. const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
  1776. const BasicBlock *Src = E.getStart();
  1777. assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
  1778. (void)Src;
  1779. return Pred != nullptr;
  1780. }
  1781. /// The given values are known to be equal in every block
  1782. /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
  1783. /// 'RHS' everywhere in the scope. Returns whether a change was made.
  1784. bool GVN::propagateEquality(Value *LHS, Value *RHS,
  1785. const BasicBlockEdge &Root) {
  1786. SmallVector<std::pair<Value*, Value*>, 4> Worklist;
  1787. Worklist.push_back(std::make_pair(LHS, RHS));
  1788. bool Changed = false;
  1789. // For speed, compute a conservative fast approximation to
  1790. // DT->dominates(Root, Root.getEnd());
  1791. bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
  1792. while (!Worklist.empty()) {
  1793. std::pair<Value*, Value*> Item = Worklist.pop_back_val();
  1794. LHS = Item.first; RHS = Item.second;
  1795. if (LHS == RHS) continue;
  1796. assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
  1797. // Don't try to propagate equalities between constants.
  1798. if (isa<Constant>(LHS) && isa<Constant>(RHS)) continue;
  1799. // Prefer a constant on the right-hand side, or an Argument if no constants.
  1800. if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
  1801. std::swap(LHS, RHS);
  1802. assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
  1803. // If there is no obvious reason to prefer the left-hand side over the
  1804. // right-hand side, ensure the longest lived term is on the right-hand side,
  1805. // so the shortest lived term will be replaced by the longest lived.
  1806. // This tends to expose more simplifications.
  1807. uint32_t LVN = VN.lookup_or_add(LHS);
  1808. if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
  1809. (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
  1810. // Move the 'oldest' value to the right-hand side, using the value number
  1811. // as a proxy for age.
  1812. uint32_t RVN = VN.lookup_or_add(RHS);
  1813. if (LVN < RVN) {
  1814. std::swap(LHS, RHS);
  1815. LVN = RVN;
  1816. }
  1817. }
  1818. // If value numbering later sees that an instruction in the scope is equal
  1819. // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
  1820. // the invariant that instructions only occur in the leader table for their
  1821. // own value number (this is used by removeFromLeaderTable), do not do this
  1822. // if RHS is an instruction (if an instruction in the scope is morphed into
  1823. // LHS then it will be turned into RHS by the next GVN iteration anyway, so
  1824. // using the leader table is about compiling faster, not optimizing better).
  1825. // The leader table only tracks basic blocks, not edges. Only add to if we
  1826. // have the simple case where the edge dominates the end.
  1827. if (RootDominatesEnd && !isa<Instruction>(RHS))
  1828. addToLeaderTable(LVN, RHS, Root.getEnd());
  1829. // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
  1830. // LHS always has at least one use that is not dominated by Root, this will
  1831. // never do anything if LHS has only one use.
  1832. if (!LHS->hasOneUse()) {
  1833. unsigned NumReplacements = replaceDominatedUsesWith(LHS, RHS, *DT, Root);
  1834. Changed |= NumReplacements > 0;
  1835. NumGVNEqProp += NumReplacements;
  1836. }
  1837. // Now try to deduce additional equalities from this one. For example, if
  1838. // the known equality was "(A != B)" == "false" then it follows that A and B
  1839. // are equal in the scope. Only boolean equalities with an explicit true or
  1840. // false RHS are currently supported.
  1841. if (!RHS->getType()->isIntegerTy(1))
  1842. // Not a boolean equality - bail out.
  1843. continue;
  1844. ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
  1845. if (!CI)
  1846. // RHS neither 'true' nor 'false' - bail out.
  1847. continue;
  1848. // Whether RHS equals 'true'. Otherwise it equals 'false'.
  1849. bool isKnownTrue = CI->isAllOnesValue();
  1850. bool isKnownFalse = !isKnownTrue;
  1851. // If "A && B" is known true then both A and B are known true. If "A || B"
  1852. // is known false then both A and B are known false.
  1853. Value *A, *B;
  1854. if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
  1855. (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
  1856. Worklist.push_back(std::make_pair(A, RHS));
  1857. Worklist.push_back(std::make_pair(B, RHS));
  1858. continue;
  1859. }
  1860. // If we are propagating an equality like "(A == B)" == "true" then also
  1861. // propagate the equality A == B. When propagating a comparison such as
  1862. // "(A >= B)" == "true", replace all instances of "A < B" with "false".
  1863. if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
  1864. Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
  1865. // If "A == B" is known true, or "A != B" is known false, then replace
  1866. // A with B everywhere in the scope.
  1867. if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
  1868. (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
  1869. Worklist.push_back(std::make_pair(Op0, Op1));
  1870. // Handle the floating point versions of equality comparisons too.
  1871. if ((isKnownTrue && Cmp->getPredicate() == CmpInst::FCMP_OEQ) ||
  1872. (isKnownFalse && Cmp->getPredicate() == CmpInst::FCMP_UNE)) {
  1873. // Floating point -0.0 and 0.0 compare equal, so we can only
  1874. // propagate values if we know that we have a constant and that
  1875. // its value is non-zero.
  1876. // FIXME: We should do this optimization if 'no signed zeros' is
  1877. // applicable via an instruction-level fast-math-flag or some other
  1878. // indicator that relaxed FP semantics are being used.
  1879. if (isa<ConstantFP>(Op1) && !cast<ConstantFP>(Op1)->isZero())
  1880. Worklist.push_back(std::make_pair(Op0, Op1));
  1881. }
  1882. // If "A >= B" is known true, replace "A < B" with false everywhere.
  1883. CmpInst::Predicate NotPred = Cmp->getInversePredicate();
  1884. Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
  1885. // Since we don't have the instruction "A < B" immediately to hand, work
  1886. // out the value number that it would have and use that to find an
  1887. // appropriate instruction (if any).
  1888. uint32_t NextNum = VN.getNextUnusedValueNumber();
  1889. uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
  1890. // If the number we were assigned was brand new then there is no point in
  1891. // looking for an instruction realizing it: there cannot be one!
  1892. if (Num < NextNum) {
  1893. Value *NotCmp = findLeader(Root.getEnd(), Num);
  1894. if (NotCmp && isa<Instruction>(NotCmp)) {
  1895. unsigned NumReplacements =
  1896. replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root);
  1897. Changed |= NumReplacements > 0;
  1898. NumGVNEqProp += NumReplacements;
  1899. }
  1900. }
  1901. // Ensure that any instruction in scope that gets the "A < B" value number
  1902. // is replaced with false.
  1903. // The leader table only tracks basic blocks, not edges. Only add to if we
  1904. // have the simple case where the edge dominates the end.
  1905. if (RootDominatesEnd)
  1906. addToLeaderTable(Num, NotVal, Root.getEnd());
  1907. continue;
  1908. }
  1909. }
  1910. return Changed;
  1911. }
  1912. /// When calculating availability, handle an instruction
  1913. /// by inserting it into the appropriate sets
  1914. bool GVN::processInstruction(Instruction *I) {
  1915. // Ignore dbg info intrinsics.
  1916. if (isa<DbgInfoIntrinsic>(I))
  1917. return false;
  1918. // If the instruction can be easily simplified then do so now in preference
  1919. // to value numbering it. Value numbering often exposes redundancies, for
  1920. // example if it determines that %y is equal to %x then the instruction
  1921. // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
  1922. const DataLayout &DL = I->getModule()->getDataLayout();
  1923. if (Value *V = SimplifyInstruction(I, DL, TLI, DT, AC)) {
  1924. I->replaceAllUsesWith(V);
  1925. if (MD && V->getType()->getScalarType()->isPointerTy())
  1926. MD->invalidateCachedPointerInfo(V);
  1927. markInstructionForDeletion(I);
  1928. ++NumGVNSimpl;
  1929. return true;
  1930. }
  1931. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  1932. if (processLoad(LI))
  1933. return true;
  1934. unsigned Num = VN.lookup_or_add(LI);
  1935. addToLeaderTable(Num, LI, LI->getParent());
  1936. return false;
  1937. }
  1938. // For conditional branches, we can perform simple conditional propagation on
  1939. // the condition value itself.
  1940. if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
  1941. if (!BI->isConditional())
  1942. return false;
  1943. if (isa<Constant>(BI->getCondition()))
  1944. return processFoldableCondBr(BI);
  1945. Value *BranchCond = BI->getCondition();
  1946. BasicBlock *TrueSucc = BI->getSuccessor(0);
  1947. BasicBlock *FalseSucc = BI->getSuccessor(1);
  1948. // Avoid multiple edges early.
  1949. if (TrueSucc == FalseSucc)
  1950. return false;
  1951. BasicBlock *Parent = BI->getParent();
  1952. bool Changed = false;
  1953. Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
  1954. BasicBlockEdge TrueE(Parent, TrueSucc);
  1955. Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
  1956. Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
  1957. BasicBlockEdge FalseE(Parent, FalseSucc);
  1958. Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
  1959. return Changed;
  1960. }
  1961. // For switches, propagate the case values into the case destinations.
  1962. if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
  1963. Value *SwitchCond = SI->getCondition();
  1964. BasicBlock *Parent = SI->getParent();
  1965. bool Changed = false;
  1966. // Remember how many outgoing edges there are to every successor.
  1967. SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
  1968. for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
  1969. ++SwitchEdges[SI->getSuccessor(i)];
  1970. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  1971. i != e; ++i) {
  1972. BasicBlock *Dst = i.getCaseSuccessor();
  1973. // If there is only a single edge, propagate the case value into it.
  1974. if (SwitchEdges.lookup(Dst) == 1) {
  1975. BasicBlockEdge E(Parent, Dst);
  1976. Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E);
  1977. }
  1978. }
  1979. return Changed;
  1980. }
  1981. // Instructions with void type don't return a value, so there's
  1982. // no point in trying to find redundancies in them.
  1983. if (I->getType()->isVoidTy()) return false;
  1984. uint32_t NextNum = VN.getNextUnusedValueNumber();
  1985. unsigned Num = VN.lookup_or_add(I);
  1986. // Allocations are always uniquely numbered, so we can save time and memory
  1987. // by fast failing them.
  1988. if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
  1989. addToLeaderTable(Num, I, I->getParent());
  1990. return false;
  1991. }
  1992. // If the number we were assigned was a brand new VN, then we don't
  1993. // need to do a lookup to see if the number already exists
  1994. // somewhere in the domtree: it can't!
  1995. if (Num >= NextNum) {
  1996. addToLeaderTable(Num, I, I->getParent());
  1997. return false;
  1998. }
  1999. // Perform fast-path value-number based elimination of values inherited from
  2000. // dominators.
  2001. Value *repl = findLeader(I->getParent(), Num);
  2002. if (!repl) {
  2003. // Failure, just remember this instance for future use.
  2004. addToLeaderTable(Num, I, I->getParent());
  2005. return false;
  2006. }
  2007. // Remove it!
  2008. patchAndReplaceAllUsesWith(I, repl);
  2009. if (MD && repl->getType()->getScalarType()->isPointerTy())
  2010. MD->invalidateCachedPointerInfo(repl);
  2011. markInstructionForDeletion(I);
  2012. return true;
  2013. }
  2014. /// runOnFunction - This is the main transformation entry point for a function.
  2015. bool GVN::runOnFunction(Function& F) {
  2016. if (skipOptnoneFunction(F))
  2017. return false;
  2018. if (!NoLoads)
  2019. MD = &getAnalysis<MemoryDependenceAnalysis>();
  2020. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  2021. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  2022. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  2023. VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
  2024. VN.setMemDep(MD);
  2025. VN.setDomTree(DT);
  2026. bool Changed = false;
  2027. bool ShouldContinue = true;
  2028. // Merge unconditional branches, allowing PRE to catch more
  2029. // optimization opportunities.
  2030. for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
  2031. BasicBlock *BB = FI++;
  2032. bool removedBlock = MergeBlockIntoPredecessor(
  2033. BB, DT, /* LoopInfo */ nullptr, VN.getAliasAnalysis(), MD);
  2034. if (removedBlock) ++NumGVNBlocks;
  2035. Changed |= removedBlock;
  2036. }
  2037. unsigned Iteration = 0;
  2038. while (ShouldContinue) {
  2039. DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
  2040. ShouldContinue = iterateOnFunction(F);
  2041. Changed |= ShouldContinue;
  2042. ++Iteration;
  2043. }
  2044. if (EnablePRE) {
  2045. // Fabricate val-num for dead-code in order to suppress assertion in
  2046. // performPRE().
  2047. assignValNumForDeadCode();
  2048. bool PREChanged = true;
  2049. while (PREChanged) {
  2050. PREChanged = performPRE(F);
  2051. Changed |= PREChanged;
  2052. }
  2053. }
  2054. // FIXME: Should perform GVN again after PRE does something. PRE can move
  2055. // computations into blocks where they become fully redundant. Note that
  2056. // we can't do this until PRE's critical edge splitting updates memdep.
  2057. // Actually, when this happens, we should just fully integrate PRE into GVN.
  2058. cleanupGlobalSets();
  2059. // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
  2060. // iteration.
  2061. DeadBlocks.clear();
  2062. return Changed;
  2063. }
  2064. bool GVN::processBlock(BasicBlock *BB) {
  2065. // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
  2066. // (and incrementing BI before processing an instruction).
  2067. assert(InstrsToErase.empty() &&
  2068. "We expect InstrsToErase to be empty across iterations");
  2069. if (DeadBlocks.count(BB))
  2070. return false;
  2071. bool ChangedFunction = false;
  2072. for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
  2073. BI != BE;) {
  2074. ChangedFunction |= processInstruction(BI);
  2075. if (InstrsToErase.empty()) {
  2076. ++BI;
  2077. continue;
  2078. }
  2079. // If we need some instructions deleted, do it now.
  2080. NumGVNInstr += InstrsToErase.size();
  2081. // Avoid iterator invalidation.
  2082. bool AtStart = BI == BB->begin();
  2083. if (!AtStart)
  2084. --BI;
  2085. for (SmallVectorImpl<Instruction *>::iterator I = InstrsToErase.begin(),
  2086. E = InstrsToErase.end(); I != E; ++I) {
  2087. DEBUG(dbgs() << "GVN removed: " << **I << '\n');
  2088. if (MD) MD->removeInstruction(*I);
  2089. DEBUG(verifyRemoved(*I));
  2090. (*I)->eraseFromParent();
  2091. }
  2092. InstrsToErase.clear();
  2093. if (AtStart)
  2094. BI = BB->begin();
  2095. else
  2096. ++BI;
  2097. }
  2098. return ChangedFunction;
  2099. }
  2100. // Instantiate an expression in a predecessor that lacked it.
  2101. bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
  2102. unsigned int ValNo) {
  2103. // Because we are going top-down through the block, all value numbers
  2104. // will be available in the predecessor by the time we need them. Any
  2105. // that weren't originally present will have been instantiated earlier
  2106. // in this loop.
  2107. bool success = true;
  2108. for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) {
  2109. Value *Op = Instr->getOperand(i);
  2110. if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
  2111. continue;
  2112. if (Value *V = findLeader(Pred, VN.lookup(Op))) {
  2113. Instr->setOperand(i, V);
  2114. } else {
  2115. success = false;
  2116. break;
  2117. }
  2118. }
  2119. // Fail out if we encounter an operand that is not available in
  2120. // the PRE predecessor. This is typically because of loads which
  2121. // are not value numbered precisely.
  2122. if (!success)
  2123. return false;
  2124. Instr->insertBefore(Pred->getTerminator());
  2125. Instr->setName(Instr->getName() + ".pre");
  2126. Instr->setDebugLoc(Instr->getDebugLoc());
  2127. VN.add(Instr, ValNo);
  2128. // Update the availability map to include the new instruction.
  2129. addToLeaderTable(ValNo, Instr, Pred);
  2130. return true;
  2131. }
  2132. bool GVN::performScalarPRE(Instruction *CurInst) {
  2133. SmallVector<std::pair<Value*, BasicBlock*>, 8> predMap;
  2134. if (isa<AllocaInst>(CurInst) || isa<TerminatorInst>(CurInst) ||
  2135. isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
  2136. CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
  2137. isa<DbgInfoIntrinsic>(CurInst))
  2138. return false;
  2139. // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
  2140. // sinking the compare again, and it would force the code generator to
  2141. // move the i1 from processor flags or predicate registers into a general
  2142. // purpose register.
  2143. if (isa<CmpInst>(CurInst))
  2144. return false;
  2145. // HLSL Change Begin - Don't do PRE on pointer which may generate phi of
  2146. // pointers.
  2147. if (dyn_cast<PointerType>(CurInst->getType())) {
  2148. return false;
  2149. }
  2150. // HLSL Change End
  2151. // We don't currently value number ANY inline asm calls.
  2152. if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
  2153. if (CallI->isInlineAsm())
  2154. return false;
  2155. uint32_t ValNo = VN.lookup(CurInst);
  2156. // Look for the predecessors for PRE opportunities. We're
  2157. // only trying to solve the basic diamond case, where
  2158. // a value is computed in the successor and one predecessor,
  2159. // but not the other. We also explicitly disallow cases
  2160. // where the successor is its own predecessor, because they're
  2161. // more complicated to get right.
  2162. unsigned NumWith = 0;
  2163. unsigned NumWithout = 0;
  2164. BasicBlock *PREPred = nullptr;
  2165. BasicBlock *CurrentBlock = CurInst->getParent();
  2166. predMap.clear();
  2167. for (pred_iterator PI = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
  2168. PI != PE; ++PI) {
  2169. BasicBlock *P = *PI;
  2170. // We're not interested in PRE where the block is its
  2171. // own predecessor, or in blocks with predecessors
  2172. // that are not reachable.
  2173. if (P == CurrentBlock) {
  2174. NumWithout = 2;
  2175. break;
  2176. } else if (!DT->isReachableFromEntry(P)) {
  2177. NumWithout = 2;
  2178. break;
  2179. }
  2180. Value *predV = findLeader(P, ValNo);
  2181. if (!predV) {
  2182. predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
  2183. PREPred = P;
  2184. ++NumWithout;
  2185. } else if (predV == CurInst) {
  2186. /* CurInst dominates this predecessor. */
  2187. NumWithout = 2;
  2188. break;
  2189. } else {
  2190. predMap.push_back(std::make_pair(predV, P));
  2191. ++NumWith;
  2192. }
  2193. }
  2194. // Don't do PRE when it might increase code size, i.e. when
  2195. // we would need to insert instructions in more than one pred.
  2196. if (NumWithout > 1 || NumWith == 0)
  2197. return false;
  2198. // We may have a case where all predecessors have the instruction,
  2199. // and we just need to insert a phi node. Otherwise, perform
  2200. // insertion.
  2201. Instruction *PREInstr = nullptr;
  2202. if (NumWithout != 0) {
  2203. // Don't do PRE across indirect branch.
  2204. if (isa<IndirectBrInst>(PREPred->getTerminator()))
  2205. return false;
  2206. // We can't do PRE safely on a critical edge, so instead we schedule
  2207. // the edge to be split and perform the PRE the next time we iterate
  2208. // on the function.
  2209. unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
  2210. if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
  2211. toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
  2212. return false;
  2213. }
  2214. // We need to insert somewhere, so let's give it a shot
  2215. PREInstr = CurInst->clone();
  2216. if (!performScalarPREInsertion(PREInstr, PREPred, ValNo)) {
  2217. // If we failed insertion, make sure we remove the instruction.
  2218. DEBUG(verifyRemoved(PREInstr));
  2219. delete PREInstr;
  2220. return false;
  2221. }
  2222. }
  2223. // Either we should have filled in the PRE instruction, or we should
  2224. // not have needed insertions.
  2225. assert (PREInstr != nullptr || NumWithout == 0);
  2226. ++NumGVNPRE;
  2227. // Create a PHI to make the value available in this block.
  2228. PHINode *Phi =
  2229. PHINode::Create(CurInst->getType(), predMap.size(),
  2230. CurInst->getName() + ".pre-phi", CurrentBlock->begin());
  2231. for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
  2232. if (Value *V = predMap[i].first)
  2233. Phi->addIncoming(V, predMap[i].second);
  2234. else
  2235. Phi->addIncoming(PREInstr, PREPred);
  2236. }
  2237. VN.add(Phi, ValNo);
  2238. addToLeaderTable(ValNo, Phi, CurrentBlock);
  2239. Phi->setDebugLoc(CurInst->getDebugLoc());
  2240. CurInst->replaceAllUsesWith(Phi);
  2241. if (Phi->getType()->getScalarType()->isPointerTy()) {
  2242. // Because we have added a PHI-use of the pointer value, it has now
  2243. // "escaped" from alias analysis' perspective. We need to inform
  2244. // AA of this.
  2245. for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee; ++ii) {
  2246. unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
  2247. VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
  2248. }
  2249. if (MD)
  2250. MD->invalidateCachedPointerInfo(Phi);
  2251. }
  2252. VN.erase(CurInst);
  2253. removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
  2254. DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
  2255. if (MD)
  2256. MD->removeInstruction(CurInst);
  2257. DEBUG(verifyRemoved(CurInst));
  2258. CurInst->eraseFromParent();
  2259. ++NumGVNInstr;
  2260. return true;
  2261. }
  2262. /// Perform a purely local form of PRE that looks for diamond
  2263. /// control flow patterns and attempts to perform simple PRE at the join point.
  2264. bool GVN::performPRE(Function &F) {
  2265. bool Changed = false;
  2266. for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
  2267. // Nothing to PRE in the entry block.
  2268. if (CurrentBlock == &F.getEntryBlock())
  2269. continue;
  2270. // Don't perform PRE on a landing pad.
  2271. if (CurrentBlock->isLandingPad())
  2272. continue;
  2273. for (BasicBlock::iterator BI = CurrentBlock->begin(),
  2274. BE = CurrentBlock->end();
  2275. BI != BE;) {
  2276. Instruction *CurInst = BI++;
  2277. Changed = performScalarPRE(CurInst);
  2278. }
  2279. }
  2280. if (splitCriticalEdges())
  2281. Changed = true;
  2282. return Changed;
  2283. }
  2284. /// Split the critical edge connecting the given two blocks, and return
  2285. /// the block inserted to the critical edge.
  2286. BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
  2287. BasicBlock *BB = SplitCriticalEdge(
  2288. Pred, Succ, CriticalEdgeSplittingOptions(getAliasAnalysis(), DT));
  2289. if (MD)
  2290. MD->invalidateCachedPredecessors();
  2291. return BB;
  2292. }
  2293. /// Split critical edges found during the previous
  2294. /// iteration that may enable further optimization.
  2295. bool GVN::splitCriticalEdges() {
  2296. if (toSplit.empty())
  2297. return false;
  2298. do {
  2299. std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
  2300. SplitCriticalEdge(Edge.first, Edge.second,
  2301. CriticalEdgeSplittingOptions(getAliasAnalysis(), DT));
  2302. } while (!toSplit.empty());
  2303. if (MD) MD->invalidateCachedPredecessors();
  2304. return true;
  2305. }
  2306. /// Executes one iteration of GVN
  2307. bool GVN::iterateOnFunction(Function &F) {
  2308. cleanupGlobalSets();
  2309. // Top-down walk of the dominator tree
  2310. bool Changed = false;
  2311. // Save the blocks this function have before transformation begins. GVN may
  2312. // split critical edge, and hence may invalidate the RPO/DT iterator.
  2313. //
  2314. std::vector<BasicBlock *> BBVect;
  2315. BBVect.reserve(256);
  2316. // Needed for value numbering with phi construction to work.
  2317. ReversePostOrderTraversal<Function *> RPOT(&F);
  2318. for (ReversePostOrderTraversal<Function *>::rpo_iterator RI = RPOT.begin(),
  2319. RE = RPOT.end();
  2320. RI != RE; ++RI)
  2321. BBVect.push_back(*RI);
  2322. for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
  2323. I != E; I++)
  2324. Changed |= processBlock(*I);
  2325. return Changed;
  2326. }
  2327. void GVN::cleanupGlobalSets() {
  2328. VN.clear();
  2329. LeaderTable.clear();
  2330. TableAllocator.Reset();
  2331. }
  2332. /// Verify that the specified instruction does not occur in our
  2333. /// internal data structures.
  2334. void GVN::verifyRemoved(const Instruction *Inst) const {
  2335. VN.verifyRemoved(Inst);
  2336. // Walk through the value number scope to make sure the instruction isn't
  2337. // ferreted away in it.
  2338. for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
  2339. I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
  2340. const LeaderTableEntry *Node = &I->second;
  2341. assert(Node->Val != Inst && "Inst still in value numbering scope!");
  2342. while (Node->Next) {
  2343. Node = Node->Next;
  2344. assert(Node->Val != Inst && "Inst still in value numbering scope!");
  2345. }
  2346. }
  2347. }
  2348. /// BB is declared dead, which implied other blocks become dead as well. This
  2349. /// function is to add all these blocks to "DeadBlocks". For the dead blocks'
  2350. /// live successors, update their phi nodes by replacing the operands
  2351. /// corresponding to dead blocks with UndefVal.
  2352. void GVN::addDeadBlock(BasicBlock *BB) {
  2353. SmallVector<BasicBlock *, 4> NewDead;
  2354. SmallSetVector<BasicBlock *, 4> DF;
  2355. NewDead.push_back(BB);
  2356. while (!NewDead.empty()) {
  2357. BasicBlock *D = NewDead.pop_back_val();
  2358. if (DeadBlocks.count(D))
  2359. continue;
  2360. // All blocks dominated by D are dead.
  2361. SmallVector<BasicBlock *, 8> Dom;
  2362. DT->getDescendants(D, Dom);
  2363. DeadBlocks.insert(Dom.begin(), Dom.end());
  2364. // Figure out the dominance-frontier(D).
  2365. for (SmallVectorImpl<BasicBlock *>::iterator I = Dom.begin(),
  2366. E = Dom.end(); I != E; I++) {
  2367. BasicBlock *B = *I;
  2368. for (succ_iterator SI = succ_begin(B), SE = succ_end(B); SI != SE; SI++) {
  2369. BasicBlock *S = *SI;
  2370. if (DeadBlocks.count(S))
  2371. continue;
  2372. bool AllPredDead = true;
  2373. for (pred_iterator PI = pred_begin(S), PE = pred_end(S); PI != PE; PI++)
  2374. if (!DeadBlocks.count(*PI)) {
  2375. AllPredDead = false;
  2376. break;
  2377. }
  2378. if (!AllPredDead) {
  2379. // S could be proved dead later on. That is why we don't update phi
  2380. // operands at this moment.
  2381. DF.insert(S);
  2382. } else {
  2383. // While S is not dominated by D, it is dead by now. This could take
  2384. // place if S already have a dead predecessor before D is declared
  2385. // dead.
  2386. NewDead.push_back(S);
  2387. }
  2388. }
  2389. }
  2390. }
  2391. // For the dead blocks' live successors, update their phi nodes by replacing
  2392. // the operands corresponding to dead blocks with UndefVal.
  2393. for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
  2394. I != E; I++) {
  2395. BasicBlock *B = *I;
  2396. if (DeadBlocks.count(B))
  2397. continue;
  2398. SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
  2399. for (SmallVectorImpl<BasicBlock *>::iterator PI = Preds.begin(),
  2400. PE = Preds.end(); PI != PE; PI++) {
  2401. BasicBlock *P = *PI;
  2402. if (!DeadBlocks.count(P))
  2403. continue;
  2404. if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
  2405. if (BasicBlock *S = splitCriticalEdges(P, B))
  2406. DeadBlocks.insert(P = S);
  2407. }
  2408. for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
  2409. PHINode &Phi = cast<PHINode>(*II);
  2410. Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
  2411. UndefValue::get(Phi.getType()));
  2412. }
  2413. }
  2414. }
  2415. }
  2416. // If the given branch is recognized as a foldable branch (i.e. conditional
  2417. // branch with constant condition), it will perform following analyses and
  2418. // transformation.
  2419. // 1) If the dead out-coming edge is a critical-edge, split it. Let
  2420. // R be the target of the dead out-coming edge.
  2421. // 1) Identify the set of dead blocks implied by the branch's dead outcoming
  2422. // edge. The result of this step will be {X| X is dominated by R}
  2423. // 2) Identify those blocks which haves at least one dead prodecessor. The
  2424. // result of this step will be dominance-frontier(R).
  2425. // 3) Update the PHIs in DF(R) by replacing the operands corresponding to
  2426. // dead blocks with "UndefVal" in an hope these PHIs will optimized away.
  2427. //
  2428. // Return true iff *NEW* dead code are found.
  2429. bool GVN::processFoldableCondBr(BranchInst *BI) {
  2430. if (!BI || BI->isUnconditional())
  2431. return false;
  2432. // If a branch has two identical successors, we cannot declare either dead.
  2433. if (BI->getSuccessor(0) == BI->getSuccessor(1))
  2434. return false;
  2435. ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
  2436. if (!Cond)
  2437. return false;
  2438. BasicBlock *DeadRoot = Cond->getZExtValue() ?
  2439. BI->getSuccessor(1) : BI->getSuccessor(0);
  2440. if (DeadBlocks.count(DeadRoot))
  2441. return false;
  2442. if (!DeadRoot->getSinglePredecessor())
  2443. DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
  2444. addDeadBlock(DeadRoot);
  2445. return true;
  2446. }
  2447. // performPRE() will trigger assert if it comes across an instruction without
  2448. // associated val-num. As it normally has far more live instructions than dead
  2449. // instructions, it makes more sense just to "fabricate" a val-number for the
  2450. // dead code than checking if instruction involved is dead or not.
  2451. void GVN::assignValNumForDeadCode() {
  2452. for (SetVector<BasicBlock *>::iterator I = DeadBlocks.begin(),
  2453. E = DeadBlocks.end(); I != E; I++) {
  2454. BasicBlock *BB = *I;
  2455. for (BasicBlock::iterator II = BB->begin(), EE = BB->end();
  2456. II != EE; II++) {
  2457. Instruction *Inst = &*II;
  2458. unsigned ValNum = VN.lookup_or_add(Inst);
  2459. addToLeaderTable(ValNum, Inst, BB);
  2460. }
  2461. }
  2462. }