Local.cpp 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886
  1. //===- Local.cpp - Functions to perform local transformations -------------===//
  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 family of functions perform various local transformations to the
  11. // program.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/Local.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/DenseMapInfo.h"
  18. #include "llvm/ADT/DenseSet.h"
  19. #include "llvm/ADT/Hashing.h"
  20. #include "llvm/ADT/None.h"
  21. #include "llvm/ADT/Optional.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/ADT/TinyPtrVector.h"
  28. #include "llvm/Analysis/ConstantFolding.h"
  29. #include "llvm/Analysis/EHPersonalities.h"
  30. #include "llvm/Analysis/InstructionSimplify.h"
  31. #include "llvm/Analysis/LazyValueInfo.h"
  32. #include "llvm/Analysis/MemoryBuiltins.h"
  33. #include "llvm/Analysis/MemorySSAUpdater.h"
  34. #include "llvm/Analysis/TargetLibraryInfo.h"
  35. #include "llvm/Analysis/ValueTracking.h"
  36. #include "llvm/Analysis/VectorUtils.h"
  37. #include "llvm/BinaryFormat/Dwarf.h"
  38. #include "llvm/IR/Argument.h"
  39. #include "llvm/IR/Attributes.h"
  40. #include "llvm/IR/BasicBlock.h"
  41. #include "llvm/IR/CFG.h"
  42. #include "llvm/IR/CallSite.h"
  43. #include "llvm/IR/Constant.h"
  44. #include "llvm/IR/ConstantRange.h"
  45. #include "llvm/IR/Constants.h"
  46. #include "llvm/IR/DIBuilder.h"
  47. #include "llvm/IR/DataLayout.h"
  48. #include "llvm/IR/DebugInfoMetadata.h"
  49. #include "llvm/IR/DebugLoc.h"
  50. #include "llvm/IR/DerivedTypes.h"
  51. #include "llvm/IR/DomTreeUpdater.h"
  52. #include "llvm/IR/Dominators.h"
  53. #include "llvm/IR/Function.h"
  54. #include "llvm/IR/GetElementPtrTypeIterator.h"
  55. #include "llvm/IR/GlobalObject.h"
  56. #include "llvm/IR/IRBuilder.h"
  57. #include "llvm/IR/InstrTypes.h"
  58. #include "llvm/IR/Instruction.h"
  59. #include "llvm/IR/Instructions.h"
  60. #include "llvm/IR/IntrinsicInst.h"
  61. #include "llvm/IR/Intrinsics.h"
  62. #include "llvm/IR/LLVMContext.h"
  63. #include "llvm/IR/MDBuilder.h"
  64. #include "llvm/IR/Metadata.h"
  65. #include "llvm/IR/Module.h"
  66. #include "llvm/IR/Operator.h"
  67. #include "llvm/IR/PatternMatch.h"
  68. #include "llvm/IR/Type.h"
  69. #include "llvm/IR/Use.h"
  70. #include "llvm/IR/User.h"
  71. #include "llvm/IR/Value.h"
  72. #include "llvm/IR/ValueHandle.h"
  73. #include "llvm/Support/Casting.h"
  74. #include "llvm/Support/Debug.h"
  75. #include "llvm/Support/ErrorHandling.h"
  76. #include "llvm/Support/KnownBits.h"
  77. #include "llvm/Support/raw_ostream.h"
  78. #include "llvm/Transforms/Utils/ValueMapper.h"
  79. #include <algorithm>
  80. #include <cassert>
  81. #include <climits>
  82. #include <cstdint>
  83. #include <iterator>
  84. #include <map>
  85. #include <utility>
  86. using namespace llvm;
  87. using namespace llvm::PatternMatch;
  88. #define DEBUG_TYPE "local"
  89. STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
  90. //===----------------------------------------------------------------------===//
  91. // Local constant propagation.
  92. //
  93. /// ConstantFoldTerminator - If a terminator instruction is predicated on a
  94. /// constant value, convert it into an unconditional branch to the constant
  95. /// destination. This is a nontrivial operation because the successors of this
  96. /// basic block must have their PHI nodes updated.
  97. /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
  98. /// conditions and indirectbr addresses this might make dead if
  99. /// DeleteDeadConditions is true.
  100. bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
  101. const TargetLibraryInfo *TLI,
  102. DomTreeUpdater *DTU) {
  103. Instruction *T = BB->getTerminator();
  104. IRBuilder<> Builder(T);
  105. // Branch - See if we are conditional jumping on constant
  106. if (auto *BI = dyn_cast<BranchInst>(T)) {
  107. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  108. BasicBlock *Dest1 = BI->getSuccessor(0);
  109. BasicBlock *Dest2 = BI->getSuccessor(1);
  110. if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  111. // Are we branching on constant?
  112. // YES. Change to unconditional branch...
  113. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  114. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  115. // Let the basic block know that we are letting go of it. Based on this,
  116. // it will adjust it's PHI nodes.
  117. OldDest->removePredecessor(BB);
  118. // Replace the conditional branch with an unconditional one.
  119. Builder.CreateBr(Destination);
  120. BI->eraseFromParent();
  121. if (DTU)
  122. DTU->deleteEdgeRelaxed(BB, OldDest);
  123. return true;
  124. }
  125. if (Dest2 == Dest1) { // Conditional branch to same location?
  126. // This branch matches something like this:
  127. // br bool %cond, label %Dest, label %Dest
  128. // and changes it into: br label %Dest
  129. // Let the basic block know that we are letting go of one copy of it.
  130. assert(BI->getParent() && "Terminator not inserted in block!");
  131. Dest1->removePredecessor(BI->getParent());
  132. // Replace the conditional branch with an unconditional one.
  133. Builder.CreateBr(Dest1);
  134. Value *Cond = BI->getCondition();
  135. BI->eraseFromParent();
  136. if (DeleteDeadConditions)
  137. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  138. return true;
  139. }
  140. return false;
  141. }
  142. if (auto *SI = dyn_cast<SwitchInst>(T)) {
  143. // If we are switching on a constant, we can convert the switch to an
  144. // unconditional branch.
  145. auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
  146. BasicBlock *DefaultDest = SI->getDefaultDest();
  147. BasicBlock *TheOnlyDest = DefaultDest;
  148. // If the default is unreachable, ignore it when searching for TheOnlyDest.
  149. if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
  150. SI->getNumCases() > 0) {
  151. TheOnlyDest = SI->case_begin()->getCaseSuccessor();
  152. }
  153. // Figure out which case it goes to.
  154. for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
  155. // Found case matching a constant operand?
  156. if (i->getCaseValue() == CI) {
  157. TheOnlyDest = i->getCaseSuccessor();
  158. break;
  159. }
  160. // Check to see if this branch is going to the same place as the default
  161. // dest. If so, eliminate it as an explicit compare.
  162. if (i->getCaseSuccessor() == DefaultDest) {
  163. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  164. unsigned NCases = SI->getNumCases();
  165. // Fold the case metadata into the default if there will be any branches
  166. // left, unless the metadata doesn't match the switch.
  167. if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
  168. // Collect branch weights into a vector.
  169. SmallVector<uint32_t, 8> Weights;
  170. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  171. ++MD_i) {
  172. auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
  173. Weights.push_back(CI->getValue().getZExtValue());
  174. }
  175. // Merge weight of this case to the default weight.
  176. unsigned idx = i->getCaseIndex();
  177. Weights[0] += Weights[idx+1];
  178. // Remove weight for this case.
  179. std::swap(Weights[idx+1], Weights.back());
  180. Weights.pop_back();
  181. SI->setMetadata(LLVMContext::MD_prof,
  182. MDBuilder(BB->getContext()).
  183. createBranchWeights(Weights));
  184. }
  185. // Remove this entry.
  186. BasicBlock *ParentBB = SI->getParent();
  187. DefaultDest->removePredecessor(ParentBB);
  188. i = SI->removeCase(i);
  189. e = SI->case_end();
  190. if (DTU)
  191. DTU->deleteEdgeRelaxed(ParentBB, DefaultDest);
  192. continue;
  193. }
  194. // Otherwise, check to see if the switch only branches to one destination.
  195. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  196. // destinations.
  197. if (i->getCaseSuccessor() != TheOnlyDest)
  198. TheOnlyDest = nullptr;
  199. // Increment this iterator as we haven't removed the case.
  200. ++i;
  201. }
  202. if (CI && !TheOnlyDest) {
  203. // Branching on a constant, but not any of the cases, go to the default
  204. // successor.
  205. TheOnlyDest = SI->getDefaultDest();
  206. }
  207. // If we found a single destination that we can fold the switch into, do so
  208. // now.
  209. if (TheOnlyDest) {
  210. // Insert the new branch.
  211. Builder.CreateBr(TheOnlyDest);
  212. BasicBlock *BB = SI->getParent();
  213. std::vector <DominatorTree::UpdateType> Updates;
  214. if (DTU)
  215. Updates.reserve(SI->getNumSuccessors() - 1);
  216. // Remove entries from PHI nodes which we no longer branch to...
  217. for (BasicBlock *Succ : successors(SI)) {
  218. // Found case matching a constant operand?
  219. if (Succ == TheOnlyDest) {
  220. TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
  221. } else {
  222. Succ->removePredecessor(BB);
  223. if (DTU)
  224. Updates.push_back({DominatorTree::Delete, BB, Succ});
  225. }
  226. }
  227. // Delete the old switch.
  228. Value *Cond = SI->getCondition();
  229. SI->eraseFromParent();
  230. if (DeleteDeadConditions)
  231. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  232. if (DTU)
  233. DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
  234. return true;
  235. }
  236. if (SI->getNumCases() == 1) {
  237. // Otherwise, we can fold this switch into a conditional branch
  238. // instruction if it has only one non-default destination.
  239. auto FirstCase = *SI->case_begin();
  240. Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
  241. FirstCase.getCaseValue(), "cond");
  242. // Insert the new branch.
  243. BranchInst *NewBr = Builder.CreateCondBr(Cond,
  244. FirstCase.getCaseSuccessor(),
  245. SI->getDefaultDest());
  246. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  247. if (MD && MD->getNumOperands() == 3) {
  248. ConstantInt *SICase =
  249. mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
  250. ConstantInt *SIDef =
  251. mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
  252. assert(SICase && SIDef);
  253. // The TrueWeight should be the weight for the single case of SI.
  254. NewBr->setMetadata(LLVMContext::MD_prof,
  255. MDBuilder(BB->getContext()).
  256. createBranchWeights(SICase->getValue().getZExtValue(),
  257. SIDef->getValue().getZExtValue()));
  258. }
  259. // Update make.implicit metadata to the newly-created conditional branch.
  260. MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
  261. if (MakeImplicitMD)
  262. NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
  263. // Delete the old switch.
  264. SI->eraseFromParent();
  265. return true;
  266. }
  267. return false;
  268. }
  269. if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
  270. // indirectbr blockaddress(@F, @BB) -> br label @BB
  271. if (auto *BA =
  272. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  273. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  274. std::vector <DominatorTree::UpdateType> Updates;
  275. if (DTU)
  276. Updates.reserve(IBI->getNumDestinations() - 1);
  277. // Insert the new branch.
  278. Builder.CreateBr(TheOnlyDest);
  279. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  280. if (IBI->getDestination(i) == TheOnlyDest) {
  281. TheOnlyDest = nullptr;
  282. } else {
  283. BasicBlock *ParentBB = IBI->getParent();
  284. BasicBlock *DestBB = IBI->getDestination(i);
  285. DestBB->removePredecessor(ParentBB);
  286. if (DTU)
  287. Updates.push_back({DominatorTree::Delete, ParentBB, DestBB});
  288. }
  289. }
  290. Value *Address = IBI->getAddress();
  291. IBI->eraseFromParent();
  292. if (DeleteDeadConditions)
  293. RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
  294. // If we didn't find our destination in the IBI successor list, then we
  295. // have undefined behavior. Replace the unconditional branch with an
  296. // 'unreachable' instruction.
  297. if (TheOnlyDest) {
  298. BB->getTerminator()->eraseFromParent();
  299. new UnreachableInst(BB->getContext(), BB);
  300. }
  301. if (DTU)
  302. DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
  303. return true;
  304. }
  305. }
  306. return false;
  307. }
  308. //===----------------------------------------------------------------------===//
  309. // Local dead code elimination.
  310. //
  311. /// isInstructionTriviallyDead - Return true if the result produced by the
  312. /// instruction is not used, and the instruction has no side effects.
  313. ///
  314. bool llvm::isInstructionTriviallyDead(Instruction *I,
  315. const TargetLibraryInfo *TLI) {
  316. if (!I->use_empty())
  317. return false;
  318. return wouldInstructionBeTriviallyDead(I, TLI);
  319. }
  320. bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
  321. const TargetLibraryInfo *TLI) {
  322. if (I->isTerminator())
  323. return false;
  324. // We don't want the landingpad-like instructions removed by anything this
  325. // general.
  326. if (I->isEHPad())
  327. return false;
  328. // We don't want debug info removed by anything this general, unless
  329. // debug info is empty.
  330. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  331. if (DDI->getAddress())
  332. return false;
  333. return true;
  334. }
  335. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  336. if (DVI->getValue())
  337. return false;
  338. return true;
  339. }
  340. if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
  341. if (DLI->getLabel())
  342. return false;
  343. return true;
  344. }
  345. if (!I->mayHaveSideEffects())
  346. return true;
  347. // Special case intrinsics that "may have side effects" but can be deleted
  348. // when dead.
  349. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  350. // Safe to delete llvm.stacksave and launder.invariant.group if dead.
  351. if (II->getIntrinsicID() == Intrinsic::stacksave ||
  352. II->getIntrinsicID() == Intrinsic::launder_invariant_group)
  353. return true;
  354. // Lifetime intrinsics are dead when their right-hand is undef.
  355. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  356. II->getIntrinsicID() == Intrinsic::lifetime_end)
  357. return isa<UndefValue>(II->getArgOperand(1));
  358. // Assumptions are dead if their condition is trivially true. Guards on
  359. // true are operationally no-ops. In the future we can consider more
  360. // sophisticated tradeoffs for guards considering potential for check
  361. // widening, but for now we keep things simple.
  362. if (II->getIntrinsicID() == Intrinsic::assume ||
  363. II->getIntrinsicID() == Intrinsic::experimental_guard) {
  364. if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
  365. return !Cond->isZero();
  366. return false;
  367. }
  368. }
  369. if (isAllocLikeFn(I, TLI))
  370. return true;
  371. if (CallInst *CI = isFreeCall(I, TLI))
  372. if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
  373. return C->isNullValue() || isa<UndefValue>(C);
  374. if (CallSite CS = CallSite(I))
  375. if (isMathLibCallNoop(CS, TLI))
  376. return true;
  377. return false;
  378. }
  379. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  380. /// trivially dead instruction, delete it. If that makes any of its operands
  381. /// trivially dead, delete them too, recursively. Return true if any
  382. /// instructions were deleted.
  383. bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
  384. Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU) {
  385. Instruction *I = dyn_cast<Instruction>(V);
  386. if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
  387. return false;
  388. SmallVector<Instruction*, 16> DeadInsts;
  389. DeadInsts.push_back(I);
  390. RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU);
  391. return true;
  392. }
  393. void llvm::RecursivelyDeleteTriviallyDeadInstructions(
  394. SmallVectorImpl<Instruction *> &DeadInsts, const TargetLibraryInfo *TLI,
  395. MemorySSAUpdater *MSSAU) {
  396. // Process the dead instruction list until empty.
  397. while (!DeadInsts.empty()) {
  398. Instruction &I = *DeadInsts.pop_back_val();
  399. assert(I.use_empty() && "Instructions with uses are not dead.");
  400. assert(isInstructionTriviallyDead(&I, TLI) &&
  401. "Live instruction found in dead worklist!");
  402. // Don't lose the debug info while deleting the instructions.
  403. salvageDebugInfo(I);
  404. // Null out all of the instruction's operands to see if any operand becomes
  405. // dead as we go.
  406. for (Use &OpU : I.operands()) {
  407. Value *OpV = OpU.get();
  408. OpU.set(nullptr);
  409. if (!OpV->use_empty())
  410. continue;
  411. // If the operand is an instruction that became dead as we nulled out the
  412. // operand, and if it is 'trivially' dead, delete it in a future loop
  413. // iteration.
  414. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  415. if (isInstructionTriviallyDead(OpI, TLI))
  416. DeadInsts.push_back(OpI);
  417. }
  418. if (MSSAU)
  419. MSSAU->removeMemoryAccess(&I);
  420. I.eraseFromParent();
  421. }
  422. }
  423. bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
  424. SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
  425. findDbgUsers(DbgUsers, I);
  426. for (auto *DII : DbgUsers) {
  427. Value *Undef = UndefValue::get(I->getType());
  428. DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
  429. ValueAsMetadata::get(Undef)));
  430. }
  431. return !DbgUsers.empty();
  432. }
  433. /// areAllUsesEqual - Check whether the uses of a value are all the same.
  434. /// This is similar to Instruction::hasOneUse() except this will also return
  435. /// true when there are no uses or multiple uses that all refer to the same
  436. /// value.
  437. static bool areAllUsesEqual(Instruction *I) {
  438. Value::user_iterator UI = I->user_begin();
  439. Value::user_iterator UE = I->user_end();
  440. if (UI == UE)
  441. return true;
  442. User *TheUse = *UI;
  443. for (++UI; UI != UE; ++UI) {
  444. if (*UI != TheUse)
  445. return false;
  446. }
  447. return true;
  448. }
  449. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  450. /// dead PHI node, due to being a def-use chain of single-use nodes that
  451. /// either forms a cycle or is terminated by a trivially dead instruction,
  452. /// delete it. If that makes any of its operands trivially dead, delete them
  453. /// too, recursively. Return true if a change was made.
  454. bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
  455. const TargetLibraryInfo *TLI) {
  456. SmallPtrSet<Instruction*, 4> Visited;
  457. for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
  458. I = cast<Instruction>(*I->user_begin())) {
  459. if (I->use_empty())
  460. return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  461. // If we find an instruction more than once, we're on a cycle that
  462. // won't prove fruitful.
  463. if (!Visited.insert(I).second) {
  464. // Break the cycle and delete the instruction and its operands.
  465. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  466. (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  467. return true;
  468. }
  469. }
  470. return false;
  471. }
  472. static bool
  473. simplifyAndDCEInstruction(Instruction *I,
  474. SmallSetVector<Instruction *, 16> &WorkList,
  475. const DataLayout &DL,
  476. const TargetLibraryInfo *TLI) {
  477. if (isInstructionTriviallyDead(I, TLI)) {
  478. salvageDebugInfo(*I);
  479. // Null out all of the instruction's operands to see if any operand becomes
  480. // dead as we go.
  481. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  482. Value *OpV = I->getOperand(i);
  483. I->setOperand(i, nullptr);
  484. if (!OpV->use_empty() || I == OpV)
  485. continue;
  486. // If the operand is an instruction that became dead as we nulled out the
  487. // operand, and if it is 'trivially' dead, delete it in a future loop
  488. // iteration.
  489. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  490. if (isInstructionTriviallyDead(OpI, TLI))
  491. WorkList.insert(OpI);
  492. }
  493. I->eraseFromParent();
  494. return true;
  495. }
  496. if (Value *SimpleV = SimplifyInstruction(I, DL)) {
  497. // Add the users to the worklist. CAREFUL: an instruction can use itself,
  498. // in the case of a phi node.
  499. for (User *U : I->users()) {
  500. if (U != I) {
  501. WorkList.insert(cast<Instruction>(U));
  502. }
  503. }
  504. // Replace the instruction with its simplified value.
  505. bool Changed = false;
  506. if (!I->use_empty()) {
  507. I->replaceAllUsesWith(SimpleV);
  508. Changed = true;
  509. }
  510. if (isInstructionTriviallyDead(I, TLI)) {
  511. I->eraseFromParent();
  512. Changed = true;
  513. }
  514. return Changed;
  515. }
  516. return false;
  517. }
  518. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  519. /// simplify any instructions in it and recursively delete dead instructions.
  520. ///
  521. /// This returns true if it changed the code, note that it can delete
  522. /// instructions in other blocks as well in this block.
  523. bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
  524. const TargetLibraryInfo *TLI) {
  525. bool MadeChange = false;
  526. const DataLayout &DL = BB->getModule()->getDataLayout();
  527. #ifndef NDEBUG
  528. // In debug builds, ensure that the terminator of the block is never replaced
  529. // or deleted by these simplifications. The idea of simplification is that it
  530. // cannot introduce new instructions, and there is no way to replace the
  531. // terminator of a block without introducing a new instruction.
  532. AssertingVH<Instruction> TerminatorVH(&BB->back());
  533. #endif
  534. SmallSetVector<Instruction *, 16> WorkList;
  535. // Iterate over the original function, only adding insts to the worklist
  536. // if they actually need to be revisited. This avoids having to pre-init
  537. // the worklist with the entire function's worth of instructions.
  538. for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
  539. BI != E;) {
  540. assert(!BI->isTerminator());
  541. Instruction *I = &*BI;
  542. ++BI;
  543. // We're visiting this instruction now, so make sure it's not in the
  544. // worklist from an earlier visit.
  545. if (!WorkList.count(I))
  546. MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
  547. }
  548. while (!WorkList.empty()) {
  549. Instruction *I = WorkList.pop_back_val();
  550. MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
  551. }
  552. return MadeChange;
  553. }
  554. //===----------------------------------------------------------------------===//
  555. // Control Flow Graph Restructuring.
  556. //
  557. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  558. /// method is called when we're about to delete Pred as a predecessor of BB. If
  559. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  560. ///
  561. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  562. /// nodes that collapse into identity values. For example, if we have:
  563. /// x = phi(1, 0, 0, 0)
  564. /// y = and x, z
  565. ///
  566. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  567. /// recursively fold the and to 0.
  568. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
  569. DomTreeUpdater *DTU) {
  570. // This only adjusts blocks with PHI nodes.
  571. if (!isa<PHINode>(BB->begin()))
  572. return;
  573. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  574. // them down. This will leave us with single entry phi nodes and other phis
  575. // that can be removed.
  576. BB->removePredecessor(Pred, true);
  577. WeakTrackingVH PhiIt = &BB->front();
  578. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  579. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  580. Value *OldPhiIt = PhiIt;
  581. if (!recursivelySimplifyInstruction(PN))
  582. continue;
  583. // If recursive simplification ended up deleting the next PHI node we would
  584. // iterate to, then our iterator is invalid, restart scanning from the top
  585. // of the block.
  586. if (PhiIt != OldPhiIt) PhiIt = &BB->front();
  587. }
  588. if (DTU)
  589. DTU->deleteEdgeRelaxed(Pred, BB);
  590. }
  591. /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
  592. /// predecessor is known to have one successor (DestBB!). Eliminate the edge
  593. /// between them, moving the instructions in the predecessor into DestBB and
  594. /// deleting the predecessor block.
  595. void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
  596. DomTreeUpdater *DTU) {
  597. // If BB has single-entry PHI nodes, fold them.
  598. while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  599. Value *NewVal = PN->getIncomingValue(0);
  600. // Replace self referencing PHI with undef, it must be dead.
  601. if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
  602. PN->replaceAllUsesWith(NewVal);
  603. PN->eraseFromParent();
  604. }
  605. BasicBlock *PredBB = DestBB->getSinglePredecessor();
  606. assert(PredBB && "Block doesn't have a single predecessor!");
  607. bool ReplaceEntryBB = false;
  608. if (PredBB == &DestBB->getParent()->getEntryBlock())
  609. ReplaceEntryBB = true;
  610. // DTU updates: Collect all the edges that enter
  611. // PredBB. These dominator edges will be redirected to DestBB.
  612. SmallVector<DominatorTree::UpdateType, 32> Updates;
  613. if (DTU) {
  614. Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
  615. for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
  616. Updates.push_back({DominatorTree::Delete, *I, PredBB});
  617. // This predecessor of PredBB may already have DestBB as a successor.
  618. if (llvm::find(successors(*I), DestBB) == succ_end(*I))
  619. Updates.push_back({DominatorTree::Insert, *I, DestBB});
  620. }
  621. }
  622. // Zap anything that took the address of DestBB. Not doing this will give the
  623. // address an invalid value.
  624. if (DestBB->hasAddressTaken()) {
  625. BlockAddress *BA = BlockAddress::get(DestBB);
  626. Constant *Replacement =
  627. ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
  628. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  629. BA->getType()));
  630. BA->destroyConstant();
  631. }
  632. // Anything that branched to PredBB now branches to DestBB.
  633. PredBB->replaceAllUsesWith(DestBB);
  634. // Splice all the instructions from PredBB to DestBB.
  635. PredBB->getTerminator()->eraseFromParent();
  636. DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
  637. new UnreachableInst(PredBB->getContext(), PredBB);
  638. // If the PredBB is the entry block of the function, move DestBB up to
  639. // become the entry block after we erase PredBB.
  640. if (ReplaceEntryBB)
  641. DestBB->moveAfter(PredBB);
  642. if (DTU) {
  643. assert(PredBB->getInstList().size() == 1 &&
  644. isa<UnreachableInst>(PredBB->getTerminator()) &&
  645. "The successor list of PredBB isn't empty before "
  646. "applying corresponding DTU updates.");
  647. DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
  648. DTU->deleteBB(PredBB);
  649. // Recalculation of DomTree is needed when updating a forward DomTree and
  650. // the Entry BB is replaced.
  651. if (ReplaceEntryBB && DTU->hasDomTree()) {
  652. // The entry block was removed and there is no external interface for
  653. // the dominator tree to be notified of this change. In this corner-case
  654. // we recalculate the entire tree.
  655. DTU->recalculate(*(DestBB->getParent()));
  656. }
  657. }
  658. else {
  659. PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
  660. }
  661. }
  662. /// CanMergeValues - Return true if we can choose one of these values to use
  663. /// in place of the other. Note that we will always choose the non-undef
  664. /// value to keep.
  665. static bool CanMergeValues(Value *First, Value *Second) {
  666. return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
  667. }
  668. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  669. /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
  670. ///
  671. /// Assumption: Succ is the single successor for BB.
  672. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  673. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  674. LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
  675. << Succ->getName() << "\n");
  676. // Shortcut, if there is only a single predecessor it must be BB and merging
  677. // is always safe
  678. if (Succ->getSinglePredecessor()) return true;
  679. // Make a list of the predecessors of BB
  680. SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  681. // Look at all the phi nodes in Succ, to see if they present a conflict when
  682. // merging these blocks
  683. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  684. PHINode *PN = cast<PHINode>(I);
  685. // If the incoming value from BB is again a PHINode in
  686. // BB which has the same incoming value for *PI as PN does, we can
  687. // merge the phi nodes and then the blocks can still be merged
  688. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  689. if (BBPN && BBPN->getParent() == BB) {
  690. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  691. BasicBlock *IBB = PN->getIncomingBlock(PI);
  692. if (BBPreds.count(IBB) &&
  693. !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
  694. PN->getIncomingValue(PI))) {
  695. LLVM_DEBUG(dbgs()
  696. << "Can't fold, phi node " << PN->getName() << " in "
  697. << Succ->getName() << " is conflicting with "
  698. << BBPN->getName() << " with regard to common predecessor "
  699. << IBB->getName() << "\n");
  700. return false;
  701. }
  702. }
  703. } else {
  704. Value* Val = PN->getIncomingValueForBlock(BB);
  705. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  706. // See if the incoming value for the common predecessor is equal to the
  707. // one for BB, in which case this phi node will not prevent the merging
  708. // of the block.
  709. BasicBlock *IBB = PN->getIncomingBlock(PI);
  710. if (BBPreds.count(IBB) &&
  711. !CanMergeValues(Val, PN->getIncomingValue(PI))) {
  712. LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
  713. << " in " << Succ->getName()
  714. << " is conflicting with regard to common "
  715. << "predecessor " << IBB->getName() << "\n");
  716. return false;
  717. }
  718. }
  719. }
  720. }
  721. return true;
  722. }
  723. using PredBlockVector = SmallVector<BasicBlock *, 16>;
  724. using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
  725. /// Determines the value to use as the phi node input for a block.
  726. ///
  727. /// Select between \p OldVal any value that we know flows from \p BB
  728. /// to a particular phi on the basis of which one (if either) is not
  729. /// undef. Update IncomingValues based on the selected value.
  730. ///
  731. /// \param OldVal The value we are considering selecting.
  732. /// \param BB The block that the value flows in from.
  733. /// \param IncomingValues A map from block-to-value for other phi inputs
  734. /// that we have examined.
  735. ///
  736. /// \returns the selected value.
  737. static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
  738. IncomingValueMap &IncomingValues) {
  739. if (!isa<UndefValue>(OldVal)) {
  740. assert((!IncomingValues.count(BB) ||
  741. IncomingValues.find(BB)->second == OldVal) &&
  742. "Expected OldVal to match incoming value from BB!");
  743. IncomingValues.insert(std::make_pair(BB, OldVal));
  744. return OldVal;
  745. }
  746. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  747. if (It != IncomingValues.end()) return It->second;
  748. return OldVal;
  749. }
  750. /// Create a map from block to value for the operands of a
  751. /// given phi.
  752. ///
  753. /// Create a map from block to value for each non-undef value flowing
  754. /// into \p PN.
  755. ///
  756. /// \param PN The phi we are collecting the map for.
  757. /// \param IncomingValues [out] The map from block to value for this phi.
  758. static void gatherIncomingValuesToPhi(PHINode *PN,
  759. IncomingValueMap &IncomingValues) {
  760. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  761. BasicBlock *BB = PN->getIncomingBlock(i);
  762. Value *V = PN->getIncomingValue(i);
  763. if (!isa<UndefValue>(V))
  764. IncomingValues.insert(std::make_pair(BB, V));
  765. }
  766. }
  767. /// Replace the incoming undef values to a phi with the values
  768. /// from a block-to-value map.
  769. ///
  770. /// \param PN The phi we are replacing the undefs in.
  771. /// \param IncomingValues A map from block to value.
  772. static void replaceUndefValuesInPhi(PHINode *PN,
  773. const IncomingValueMap &IncomingValues) {
  774. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  775. Value *V = PN->getIncomingValue(i);
  776. if (!isa<UndefValue>(V)) continue;
  777. BasicBlock *BB = PN->getIncomingBlock(i);
  778. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  779. if (It == IncomingValues.end()) continue;
  780. PN->setIncomingValue(i, It->second);
  781. }
  782. }
  783. /// Replace a value flowing from a block to a phi with
  784. /// potentially multiple instances of that value flowing from the
  785. /// block's predecessors to the phi.
  786. ///
  787. /// \param BB The block with the value flowing into the phi.
  788. /// \param BBPreds The predecessors of BB.
  789. /// \param PN The phi that we are updating.
  790. static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
  791. const PredBlockVector &BBPreds,
  792. PHINode *PN) {
  793. Value *OldVal = PN->removeIncomingValue(BB, false);
  794. assert(OldVal && "No entry in PHI for Pred BB!");
  795. IncomingValueMap IncomingValues;
  796. // We are merging two blocks - BB, and the block containing PN - and
  797. // as a result we need to redirect edges from the predecessors of BB
  798. // to go to the block containing PN, and update PN
  799. // accordingly. Since we allow merging blocks in the case where the
  800. // predecessor and successor blocks both share some predecessors,
  801. // and where some of those common predecessors might have undef
  802. // values flowing into PN, we want to rewrite those values to be
  803. // consistent with the non-undef values.
  804. gatherIncomingValuesToPhi(PN, IncomingValues);
  805. // If this incoming value is one of the PHI nodes in BB, the new entries
  806. // in the PHI node are the entries from the old PHI.
  807. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  808. PHINode *OldValPN = cast<PHINode>(OldVal);
  809. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
  810. // Note that, since we are merging phi nodes and BB and Succ might
  811. // have common predecessors, we could end up with a phi node with
  812. // identical incoming branches. This will be cleaned up later (and
  813. // will trigger asserts if we try to clean it up now, without also
  814. // simplifying the corresponding conditional branch).
  815. BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
  816. Value *PredVal = OldValPN->getIncomingValue(i);
  817. Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
  818. IncomingValues);
  819. // And add a new incoming value for this predecessor for the
  820. // newly retargeted branch.
  821. PN->addIncoming(Selected, PredBB);
  822. }
  823. } else {
  824. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
  825. // Update existing incoming values in PN for this
  826. // predecessor of BB.
  827. BasicBlock *PredBB = BBPreds[i];
  828. Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
  829. IncomingValues);
  830. // And add a new incoming value for this predecessor for the
  831. // newly retargeted branch.
  832. PN->addIncoming(Selected, PredBB);
  833. }
  834. }
  835. replaceUndefValuesInPhi(PN, IncomingValues);
  836. }
  837. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  838. /// unconditional branch, and contains no instructions other than PHI nodes,
  839. /// potential side-effect free intrinsics and the branch. If possible,
  840. /// eliminate BB by rewriting all the predecessors to branch to the successor
  841. /// block and return true. If we can't transform, return false.
  842. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
  843. DomTreeUpdater *DTU) {
  844. assert(BB != &BB->getParent()->getEntryBlock() &&
  845. "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
  846. // We can't eliminate infinite loops.
  847. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  848. if (BB == Succ) return false;
  849. // Check to see if merging these blocks would cause conflicts for any of the
  850. // phi nodes in BB or Succ. If not, we can safely merge.
  851. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  852. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  853. // has uses which will not disappear when the PHI nodes are merged. It is
  854. // possible to handle such cases, but difficult: it requires checking whether
  855. // BB dominates Succ, which is non-trivial to calculate in the case where
  856. // Succ has multiple predecessors. Also, it requires checking whether
  857. // constructing the necessary self-referential PHI node doesn't introduce any
  858. // conflicts; this isn't too difficult, but the previous code for doing this
  859. // was incorrect.
  860. //
  861. // Note that if this check finds a live use, BB dominates Succ, so BB is
  862. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  863. // folding the branch isn't profitable in that case anyway.
  864. if (!Succ->getSinglePredecessor()) {
  865. BasicBlock::iterator BBI = BB->begin();
  866. while (isa<PHINode>(*BBI)) {
  867. for (Use &U : BBI->uses()) {
  868. if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
  869. if (PN->getIncomingBlock(U) != BB)
  870. return false;
  871. } else {
  872. return false;
  873. }
  874. }
  875. ++BBI;
  876. }
  877. }
  878. LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
  879. SmallVector<DominatorTree::UpdateType, 32> Updates;
  880. if (DTU) {
  881. Updates.push_back({DominatorTree::Delete, BB, Succ});
  882. // All predecessors of BB will be moved to Succ.
  883. for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
  884. Updates.push_back({DominatorTree::Delete, *I, BB});
  885. // This predecessor of BB may already have Succ as a successor.
  886. if (llvm::find(successors(*I), Succ) == succ_end(*I))
  887. Updates.push_back({DominatorTree::Insert, *I, Succ});
  888. }
  889. }
  890. if (isa<PHINode>(Succ->begin())) {
  891. // If there is more than one pred of succ, and there are PHI nodes in
  892. // the successor, then we need to add incoming edges for the PHI nodes
  893. //
  894. const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
  895. // Loop over all of the PHI nodes in the successor of BB.
  896. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  897. PHINode *PN = cast<PHINode>(I);
  898. redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
  899. }
  900. }
  901. if (Succ->getSinglePredecessor()) {
  902. // BB is the only predecessor of Succ, so Succ will end up with exactly
  903. // the same predecessors BB had.
  904. // Copy over any phi, debug or lifetime instruction.
  905. BB->getTerminator()->eraseFromParent();
  906. Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
  907. BB->getInstList());
  908. } else {
  909. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  910. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  911. assert(PN->use_empty() && "There shouldn't be any uses here!");
  912. PN->eraseFromParent();
  913. }
  914. }
  915. // If the unconditional branch we replaced contains llvm.loop metadata, we
  916. // add the metadata to the branch instructions in the predecessors.
  917. unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
  918. Instruction *TI = BB->getTerminator();
  919. if (TI)
  920. if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
  921. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  922. BasicBlock *Pred = *PI;
  923. Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
  924. }
  925. // Everything that jumped to BB now goes to Succ.
  926. BB->replaceAllUsesWith(Succ);
  927. if (!Succ->hasName()) Succ->takeName(BB);
  928. // Clear the successor list of BB to match updates applying to DTU later.
  929. if (BB->getTerminator())
  930. BB->getInstList().pop_back();
  931. new UnreachableInst(BB->getContext(), BB);
  932. assert(succ_empty(BB) && "The successor list of BB isn't empty before "
  933. "applying corresponding DTU updates.");
  934. if (DTU) {
  935. DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
  936. DTU->deleteBB(BB);
  937. } else {
  938. BB->eraseFromParent(); // Delete the old basic block.
  939. }
  940. return true;
  941. }
  942. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  943. /// nodes in this block. This doesn't try to be clever about PHI nodes
  944. /// which differ only in the order of the incoming values, but instcombine
  945. /// orders them so it usually won't matter.
  946. bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
  947. // This implementation doesn't currently consider undef operands
  948. // specially. Theoretically, two phis which are identical except for
  949. // one having an undef where the other doesn't could be collapsed.
  950. struct PHIDenseMapInfo {
  951. static PHINode *getEmptyKey() {
  952. return DenseMapInfo<PHINode *>::getEmptyKey();
  953. }
  954. static PHINode *getTombstoneKey() {
  955. return DenseMapInfo<PHINode *>::getTombstoneKey();
  956. }
  957. static unsigned getHashValue(PHINode *PN) {
  958. // Compute a hash value on the operands. Instcombine will likely have
  959. // sorted them, which helps expose duplicates, but we have to check all
  960. // the operands to be safe in case instcombine hasn't run.
  961. return static_cast<unsigned>(hash_combine(
  962. hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
  963. hash_combine_range(PN->block_begin(), PN->block_end())));
  964. }
  965. static bool isEqual(PHINode *LHS, PHINode *RHS) {
  966. if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
  967. RHS == getEmptyKey() || RHS == getTombstoneKey())
  968. return LHS == RHS;
  969. return LHS->isIdenticalTo(RHS);
  970. }
  971. };
  972. // Set of unique PHINodes.
  973. DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
  974. // Examine each PHI.
  975. bool Changed = false;
  976. for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
  977. auto Inserted = PHISet.insert(PN);
  978. if (!Inserted.second) {
  979. // A duplicate. Replace this PHI with its duplicate.
  980. PN->replaceAllUsesWith(*Inserted.first);
  981. PN->eraseFromParent();
  982. Changed = true;
  983. // The RAUW can change PHIs that we already visited. Start over from the
  984. // beginning.
  985. PHISet.clear();
  986. I = BB->begin();
  987. }
  988. }
  989. return Changed;
  990. }
  991. /// enforceKnownAlignment - If the specified pointer points to an object that
  992. /// we control, modify the object's alignment to PrefAlign. This isn't
  993. /// often possible though. If alignment is important, a more reliable approach
  994. /// is to simply align all global variables and allocation instructions to
  995. /// their preferred alignment from the beginning.
  996. static unsigned enforceKnownAlignment(Value *V, unsigned Align,
  997. unsigned PrefAlign,
  998. const DataLayout &DL) {
  999. assert(PrefAlign > Align);
  1000. V = V->stripPointerCasts();
  1001. if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1002. // TODO: ideally, computeKnownBits ought to have used
  1003. // AllocaInst::getAlignment() in its computation already, making
  1004. // the below max redundant. But, as it turns out,
  1005. // stripPointerCasts recurses through infinite layers of bitcasts,
  1006. // while computeKnownBits is not allowed to traverse more than 6
  1007. // levels.
  1008. Align = std::max(AI->getAlignment(), Align);
  1009. if (PrefAlign <= Align)
  1010. return Align;
  1011. // If the preferred alignment is greater than the natural stack alignment
  1012. // then don't round up. This avoids dynamic stack realignment.
  1013. if (DL.exceedsNaturalStackAlignment(PrefAlign))
  1014. return Align;
  1015. AI->setAlignment(PrefAlign);
  1016. return PrefAlign;
  1017. }
  1018. if (auto *GO = dyn_cast<GlobalObject>(V)) {
  1019. // TODO: as above, this shouldn't be necessary.
  1020. Align = std::max(GO->getAlignment(), Align);
  1021. if (PrefAlign <= Align)
  1022. return Align;
  1023. // If there is a large requested alignment and we can, bump up the alignment
  1024. // of the global. If the memory we set aside for the global may not be the
  1025. // memory used by the final program then it is impossible for us to reliably
  1026. // enforce the preferred alignment.
  1027. if (!GO->canIncreaseAlignment())
  1028. return Align;
  1029. GO->setAlignment(PrefAlign);
  1030. return PrefAlign;
  1031. }
  1032. return Align;
  1033. }
  1034. unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
  1035. const DataLayout &DL,
  1036. const Instruction *CxtI,
  1037. AssumptionCache *AC,
  1038. const DominatorTree *DT) {
  1039. assert(V->getType()->isPointerTy() &&
  1040. "getOrEnforceKnownAlignment expects a pointer!");
  1041. KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
  1042. unsigned TrailZ = Known.countMinTrailingZeros();
  1043. // Avoid trouble with ridiculously large TrailZ values, such as
  1044. // those computed from a null pointer.
  1045. TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
  1046. unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
  1047. // LLVM doesn't support alignments larger than this currently.
  1048. Align = std::min(Align, +Value::MaximumAlignment);
  1049. if (PrefAlign > Align)
  1050. Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
  1051. // We don't need to make any adjustment.
  1052. return Align;
  1053. }
  1054. ///===---------------------------------------------------------------------===//
  1055. /// Dbg Intrinsic utilities
  1056. ///
  1057. /// See if there is a dbg.value intrinsic for DIVar before I.
  1058. static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
  1059. Instruction *I) {
  1060. // Since we can't guarantee that the original dbg.declare instrinsic
  1061. // is removed by LowerDbgDeclare(), we need to make sure that we are
  1062. // not inserting the same dbg.value intrinsic over and over.
  1063. BasicBlock::InstListType::iterator PrevI(I);
  1064. if (PrevI != I->getParent()->getInstList().begin()) {
  1065. --PrevI;
  1066. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
  1067. if (DVI->getValue() == I->getOperand(0) &&
  1068. DVI->getVariable() == DIVar &&
  1069. DVI->getExpression() == DIExpr)
  1070. return true;
  1071. }
  1072. return false;
  1073. }
  1074. /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
  1075. static bool PhiHasDebugValue(DILocalVariable *DIVar,
  1076. DIExpression *DIExpr,
  1077. PHINode *APN) {
  1078. // Since we can't guarantee that the original dbg.declare instrinsic
  1079. // is removed by LowerDbgDeclare(), we need to make sure that we are
  1080. // not inserting the same dbg.value intrinsic over and over.
  1081. SmallVector<DbgValueInst *, 1> DbgValues;
  1082. findDbgValues(DbgValues, APN);
  1083. for (auto *DVI : DbgValues) {
  1084. assert(DVI->getValue() == APN);
  1085. if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
  1086. return true;
  1087. }
  1088. return false;
  1089. }
  1090. /// Check if the alloc size of \p ValTy is large enough to cover the variable
  1091. /// (or fragment of the variable) described by \p DII.
  1092. ///
  1093. /// This is primarily intended as a helper for the different
  1094. /// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
  1095. /// converted describes an alloca'd variable, so we need to use the
  1096. /// alloc size of the value when doing the comparison. E.g. an i1 value will be
  1097. /// identified as covering an n-bit fragment, if the store size of i1 is at
  1098. /// least n bits.
  1099. static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
  1100. const DataLayout &DL = DII->getModule()->getDataLayout();
  1101. uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy);
  1102. if (auto FragmentSize = DII->getFragmentSizeInBits())
  1103. return ValueSize >= *FragmentSize;
  1104. // We can't always calculate the size of the DI variable (e.g. if it is a
  1105. // VLA). Try to use the size of the alloca that the dbg intrinsic describes
  1106. // intead.
  1107. if (DII->isAddressOfVariable())
  1108. if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
  1109. if (auto FragmentSize = AI->getAllocationSizeInBits(DL))
  1110. return ValueSize >= *FragmentSize;
  1111. // Could not determine size of variable. Conservatively return false.
  1112. return false;
  1113. }
  1114. /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
  1115. /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
  1116. void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
  1117. StoreInst *SI, DIBuilder &Builder) {
  1118. assert(DII->isAddressOfVariable());
  1119. auto *DIVar = DII->getVariable();
  1120. assert(DIVar && "Missing variable");
  1121. auto *DIExpr = DII->getExpression();
  1122. Value *DV = SI->getOperand(0);
  1123. if (!valueCoversEntireFragment(SI->getValueOperand()->getType(), DII)) {
  1124. // FIXME: If storing to a part of the variable described by the dbg.declare,
  1125. // then we want to insert a dbg.value for the corresponding fragment.
  1126. LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
  1127. << *DII << '\n');
  1128. // For now, when there is a store to parts of the variable (but we do not
  1129. // know which part) we insert an dbg.value instrinsic to indicate that we
  1130. // know nothing about the variable's content.
  1131. DV = UndefValue::get(DV->getType());
  1132. if (!LdStHasDebugValue(DIVar, DIExpr, SI))
  1133. Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
  1134. SI);
  1135. return;
  1136. }
  1137. if (!LdStHasDebugValue(DIVar, DIExpr, SI))
  1138. Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
  1139. SI);
  1140. }
  1141. /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
  1142. /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
  1143. void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
  1144. LoadInst *LI, DIBuilder &Builder) {
  1145. auto *DIVar = DII->getVariable();
  1146. auto *DIExpr = DII->getExpression();
  1147. assert(DIVar && "Missing variable");
  1148. if (LdStHasDebugValue(DIVar, DIExpr, LI))
  1149. return;
  1150. if (!valueCoversEntireFragment(LI->getType(), DII)) {
  1151. // FIXME: If only referring to a part of the variable described by the
  1152. // dbg.declare, then we want to insert a dbg.value for the corresponding
  1153. // fragment.
  1154. LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
  1155. << *DII << '\n');
  1156. return;
  1157. }
  1158. // We are now tracking the loaded value instead of the address. In the
  1159. // future if multi-location support is added to the IR, it might be
  1160. // preferable to keep tracking both the loaded value and the original
  1161. // address in case the alloca can not be elided.
  1162. Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
  1163. LI, DIVar, DIExpr, DII->getDebugLoc(), (Instruction *)nullptr);
  1164. DbgValue->insertAfter(LI);
  1165. }
  1166. /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
  1167. /// llvm.dbg.declare or llvm.dbg.addr intrinsic.
  1168. void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
  1169. PHINode *APN, DIBuilder &Builder) {
  1170. auto *DIVar = DII->getVariable();
  1171. auto *DIExpr = DII->getExpression();
  1172. assert(DIVar && "Missing variable");
  1173. if (PhiHasDebugValue(DIVar, DIExpr, APN))
  1174. return;
  1175. if (!valueCoversEntireFragment(APN->getType(), DII)) {
  1176. // FIXME: If only referring to a part of the variable described by the
  1177. // dbg.declare, then we want to insert a dbg.value for the corresponding
  1178. // fragment.
  1179. LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
  1180. << *DII << '\n');
  1181. return;
  1182. }
  1183. BasicBlock *BB = APN->getParent();
  1184. auto InsertionPt = BB->getFirstInsertionPt();
  1185. // The block may be a catchswitch block, which does not have a valid
  1186. // insertion point.
  1187. // FIXME: Insert dbg.value markers in the successors when appropriate.
  1188. if (InsertionPt != BB->end())
  1189. Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, DII->getDebugLoc(),
  1190. &*InsertionPt);
  1191. }
  1192. /// Determine whether this alloca is either a VLA or an array.
  1193. static bool isArray(AllocaInst *AI) {
  1194. return AI->isArrayAllocation() ||
  1195. AI->getType()->getElementType()->isArrayTy();
  1196. }
  1197. /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
  1198. /// of llvm.dbg.value intrinsics.
  1199. bool llvm::LowerDbgDeclare(Function &F) {
  1200. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  1201. SmallVector<DbgDeclareInst *, 4> Dbgs;
  1202. for (auto &FI : F)
  1203. for (Instruction &BI : FI)
  1204. if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
  1205. Dbgs.push_back(DDI);
  1206. if (Dbgs.empty())
  1207. return false;
  1208. for (auto &I : Dbgs) {
  1209. DbgDeclareInst *DDI = I;
  1210. AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
  1211. // If this is an alloca for a scalar variable, insert a dbg.value
  1212. // at each load and store to the alloca and erase the dbg.declare.
  1213. // The dbg.values allow tracking a variable even if it is not
  1214. // stored on the stack, while the dbg.declare can only describe
  1215. // the stack slot (and at a lexical-scope granularity). Later
  1216. // passes will attempt to elide the stack slot.
  1217. if (!AI || isArray(AI))
  1218. continue;
  1219. // A volatile load/store means that the alloca can't be elided anyway.
  1220. if (llvm::any_of(AI->users(), [](User *U) -> bool {
  1221. if (LoadInst *LI = dyn_cast<LoadInst>(U))
  1222. return LI->isVolatile();
  1223. if (StoreInst *SI = dyn_cast<StoreInst>(U))
  1224. return SI->isVolatile();
  1225. return false;
  1226. }))
  1227. continue;
  1228. for (auto &AIUse : AI->uses()) {
  1229. User *U = AIUse.getUser();
  1230. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  1231. if (AIUse.getOperandNo() == 1)
  1232. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  1233. } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1234. ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
  1235. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  1236. // This is a call by-value or some other instruction that takes a
  1237. // pointer to the variable. Insert a *value* intrinsic that describes
  1238. // the variable by dereferencing the alloca.
  1239. auto *DerefExpr =
  1240. DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
  1241. DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
  1242. DDI->getDebugLoc(), CI);
  1243. }
  1244. }
  1245. DDI->eraseFromParent();
  1246. }
  1247. return true;
  1248. }
  1249. /// Propagate dbg.value intrinsics through the newly inserted PHIs.
  1250. void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
  1251. SmallVectorImpl<PHINode *> &InsertedPHIs) {
  1252. assert(BB && "No BasicBlock to clone dbg.value(s) from.");
  1253. if (InsertedPHIs.size() == 0)
  1254. return;
  1255. // Map existing PHI nodes to their dbg.values.
  1256. ValueToValueMapTy DbgValueMap;
  1257. for (auto &I : *BB) {
  1258. if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
  1259. if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
  1260. DbgValueMap.insert({Loc, DbgII});
  1261. }
  1262. }
  1263. if (DbgValueMap.size() == 0)
  1264. return;
  1265. // Then iterate through the new PHIs and look to see if they use one of the
  1266. // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
  1267. // propagate the info through the new PHI.
  1268. LLVMContext &C = BB->getContext();
  1269. for (auto PHI : InsertedPHIs) {
  1270. BasicBlock *Parent = PHI->getParent();
  1271. // Avoid inserting an intrinsic into an EH block.
  1272. if (Parent->getFirstNonPHI()->isEHPad())
  1273. continue;
  1274. auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
  1275. for (auto VI : PHI->operand_values()) {
  1276. auto V = DbgValueMap.find(VI);
  1277. if (V != DbgValueMap.end()) {
  1278. auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
  1279. Instruction *NewDbgII = DbgII->clone();
  1280. NewDbgII->setOperand(0, PhiMAV);
  1281. auto InsertionPt = Parent->getFirstInsertionPt();
  1282. assert(InsertionPt != Parent->end() && "Ill-formed basic block");
  1283. NewDbgII->insertBefore(&*InsertionPt);
  1284. }
  1285. }
  1286. }
  1287. }
  1288. /// Finds all intrinsics declaring local variables as living in the memory that
  1289. /// 'V' points to. This may include a mix of dbg.declare and
  1290. /// dbg.addr intrinsics.
  1291. TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
  1292. // This function is hot. Check whether the value has any metadata to avoid a
  1293. // DenseMap lookup.
  1294. if (!V->isUsedByMetadata())
  1295. return {};
  1296. auto *L = LocalAsMetadata::getIfExists(V);
  1297. if (!L)
  1298. return {};
  1299. auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
  1300. if (!MDV)
  1301. return {};
  1302. TinyPtrVector<DbgVariableIntrinsic *> Declares;
  1303. for (User *U : MDV->users()) {
  1304. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
  1305. if (DII->isAddressOfVariable())
  1306. Declares.push_back(DII);
  1307. }
  1308. return Declares;
  1309. }
  1310. void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
  1311. // This function is hot. Check whether the value has any metadata to avoid a
  1312. // DenseMap lookup.
  1313. if (!V->isUsedByMetadata())
  1314. return;
  1315. if (auto *L = LocalAsMetadata::getIfExists(V))
  1316. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
  1317. for (User *U : MDV->users())
  1318. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  1319. DbgValues.push_back(DVI);
  1320. }
  1321. void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
  1322. Value *V) {
  1323. // This function is hot. Check whether the value has any metadata to avoid a
  1324. // DenseMap lookup.
  1325. if (!V->isUsedByMetadata())
  1326. return;
  1327. if (auto *L = LocalAsMetadata::getIfExists(V))
  1328. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
  1329. for (User *U : MDV->users())
  1330. if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
  1331. DbgUsers.push_back(DII);
  1332. }
  1333. bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
  1334. Instruction *InsertBefore, DIBuilder &Builder,
  1335. bool DerefBefore, int Offset, bool DerefAfter) {
  1336. auto DbgAddrs = FindDbgAddrUses(Address);
  1337. for (DbgVariableIntrinsic *DII : DbgAddrs) {
  1338. DebugLoc Loc = DII->getDebugLoc();
  1339. auto *DIVar = DII->getVariable();
  1340. auto *DIExpr = DII->getExpression();
  1341. assert(DIVar && "Missing variable");
  1342. DIExpr = DIExpression::prepend(DIExpr, DerefBefore, Offset, DerefAfter);
  1343. // Insert llvm.dbg.declare immediately before InsertBefore, and remove old
  1344. // llvm.dbg.declare.
  1345. Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
  1346. if (DII == InsertBefore)
  1347. InsertBefore = InsertBefore->getNextNode();
  1348. DII->eraseFromParent();
  1349. }
  1350. return !DbgAddrs.empty();
  1351. }
  1352. bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  1353. DIBuilder &Builder, bool DerefBefore,
  1354. int Offset, bool DerefAfter) {
  1355. return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
  1356. DerefBefore, Offset, DerefAfter);
  1357. }
  1358. static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
  1359. DIBuilder &Builder, int Offset) {
  1360. DebugLoc Loc = DVI->getDebugLoc();
  1361. auto *DIVar = DVI->getVariable();
  1362. auto *DIExpr = DVI->getExpression();
  1363. assert(DIVar && "Missing variable");
  1364. // This is an alloca-based llvm.dbg.value. The first thing it should do with
  1365. // the alloca pointer is dereference it. Otherwise we don't know how to handle
  1366. // it and give up.
  1367. if (!DIExpr || DIExpr->getNumElements() < 1 ||
  1368. DIExpr->getElement(0) != dwarf::DW_OP_deref)
  1369. return;
  1370. // Insert the offset immediately after the first deref.
  1371. // We could just change the offset argument of dbg.value, but it's unsigned...
  1372. if (Offset) {
  1373. SmallVector<uint64_t, 4> Ops;
  1374. Ops.push_back(dwarf::DW_OP_deref);
  1375. DIExpression::appendOffset(Ops, Offset);
  1376. Ops.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
  1377. DIExpr = Builder.createExpression(Ops);
  1378. }
  1379. Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
  1380. DVI->eraseFromParent();
  1381. }
  1382. void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  1383. DIBuilder &Builder, int Offset) {
  1384. if (auto *L = LocalAsMetadata::getIfExists(AI))
  1385. if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
  1386. for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
  1387. Use &U = *UI++;
  1388. if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
  1389. replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
  1390. }
  1391. }
  1392. /// Wrap \p V in a ValueAsMetadata instance.
  1393. static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
  1394. return MetadataAsValue::get(C, ValueAsMetadata::get(V));
  1395. }
  1396. bool llvm::salvageDebugInfo(Instruction &I) {
  1397. SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
  1398. findDbgUsers(DbgUsers, &I);
  1399. if (DbgUsers.empty())
  1400. return false;
  1401. auto &M = *I.getModule();
  1402. auto &DL = M.getDataLayout();
  1403. auto &Ctx = I.getContext();
  1404. auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
  1405. auto doSalvage = [&](DbgVariableIntrinsic *DII, SmallVectorImpl<uint64_t> &Ops) {
  1406. auto *DIExpr = DII->getExpression();
  1407. if (!Ops.empty()) {
  1408. // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
  1409. // are implicitly pointing out the value as a DWARF memory location
  1410. // description.
  1411. bool WithStackValue = isa<DbgValueInst>(DII);
  1412. DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
  1413. }
  1414. DII->setOperand(0, wrapMD(I.getOperand(0)));
  1415. DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
  1416. LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
  1417. };
  1418. auto applyOffset = [&](DbgVariableIntrinsic *DII, uint64_t Offset) {
  1419. SmallVector<uint64_t, 8> Ops;
  1420. DIExpression::appendOffset(Ops, Offset);
  1421. doSalvage(DII, Ops);
  1422. };
  1423. auto applyOps = [&](DbgVariableIntrinsic *DII,
  1424. std::initializer_list<uint64_t> Opcodes) {
  1425. SmallVector<uint64_t, 8> Ops(Opcodes);
  1426. doSalvage(DII, Ops);
  1427. };
  1428. if (auto *CI = dyn_cast<CastInst>(&I)) {
  1429. if (!CI->isNoopCast(DL))
  1430. return false;
  1431. // No-op casts are irrelevant for debug info.
  1432. MetadataAsValue *CastSrc = wrapMD(I.getOperand(0));
  1433. for (auto *DII : DbgUsers) {
  1434. DII->setOperand(0, CastSrc);
  1435. LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
  1436. }
  1437. return true;
  1438. } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  1439. unsigned BitWidth =
  1440. M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
  1441. // Rewrite a constant GEP into a DIExpression. Since we are performing
  1442. // arithmetic to compute the variable's *value* in the DIExpression, we
  1443. // need to mark the expression with a DW_OP_stack_value.
  1444. APInt Offset(BitWidth, 0);
  1445. if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset))
  1446. for (auto *DII : DbgUsers)
  1447. applyOffset(DII, Offset.getSExtValue());
  1448. return true;
  1449. } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
  1450. // Rewrite binary operations with constant integer operands.
  1451. auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
  1452. if (!ConstInt || ConstInt->getBitWidth() > 64)
  1453. return false;
  1454. uint64_t Val = ConstInt->getSExtValue();
  1455. for (auto *DII : DbgUsers) {
  1456. switch (BI->getOpcode()) {
  1457. case Instruction::Add:
  1458. applyOffset(DII, Val);
  1459. break;
  1460. case Instruction::Sub:
  1461. applyOffset(DII, -int64_t(Val));
  1462. break;
  1463. case Instruction::Mul:
  1464. applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
  1465. break;
  1466. case Instruction::SDiv:
  1467. applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
  1468. break;
  1469. case Instruction::SRem:
  1470. applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
  1471. break;
  1472. case Instruction::Or:
  1473. applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
  1474. break;
  1475. case Instruction::And:
  1476. applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
  1477. break;
  1478. case Instruction::Xor:
  1479. applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
  1480. break;
  1481. case Instruction::Shl:
  1482. applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
  1483. break;
  1484. case Instruction::LShr:
  1485. applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
  1486. break;
  1487. case Instruction::AShr:
  1488. applyOps(DII, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
  1489. break;
  1490. default:
  1491. // TODO: Salvage constants from each kind of binop we know about.
  1492. return false;
  1493. }
  1494. }
  1495. return true;
  1496. } else if (isa<LoadInst>(&I)) {
  1497. MetadataAsValue *AddrMD = wrapMD(I.getOperand(0));
  1498. for (auto *DII : DbgUsers) {
  1499. // Rewrite the load into DW_OP_deref.
  1500. auto *DIExpr = DII->getExpression();
  1501. DIExpr = DIExpression::prepend(DIExpr, DIExpression::WithDeref);
  1502. DII->setOperand(0, AddrMD);
  1503. DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
  1504. LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
  1505. }
  1506. return true;
  1507. }
  1508. return false;
  1509. }
  1510. /// A replacement for a dbg.value expression.
  1511. using DbgValReplacement = Optional<DIExpression *>;
  1512. /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
  1513. /// possibly moving/deleting users to prevent use-before-def. Returns true if
  1514. /// changes are made.
  1515. static bool rewriteDebugUsers(
  1516. Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
  1517. function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
  1518. // Find debug users of From.
  1519. SmallVector<DbgVariableIntrinsic *, 1> Users;
  1520. findDbgUsers(Users, &From);
  1521. if (Users.empty())
  1522. return false;
  1523. // Prevent use-before-def of To.
  1524. bool Changed = false;
  1525. SmallPtrSet<DbgVariableIntrinsic *, 1> DeleteOrSalvage;
  1526. if (isa<Instruction>(&To)) {
  1527. bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
  1528. for (auto *DII : Users) {
  1529. // It's common to see a debug user between From and DomPoint. Move it
  1530. // after DomPoint to preserve the variable update without any reordering.
  1531. if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
  1532. LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n');
  1533. DII->moveAfter(&DomPoint);
  1534. Changed = true;
  1535. // Users which otherwise aren't dominated by the replacement value must
  1536. // be salvaged or deleted.
  1537. } else if (!DT.dominates(&DomPoint, DII)) {
  1538. DeleteOrSalvage.insert(DII);
  1539. }
  1540. }
  1541. }
  1542. // Update debug users without use-before-def risk.
  1543. for (auto *DII : Users) {
  1544. if (DeleteOrSalvage.count(DII))
  1545. continue;
  1546. LLVMContext &Ctx = DII->getContext();
  1547. DbgValReplacement DVR = RewriteExpr(*DII);
  1548. if (!DVR)
  1549. continue;
  1550. DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
  1551. DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
  1552. LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n');
  1553. Changed = true;
  1554. }
  1555. if (!DeleteOrSalvage.empty()) {
  1556. // Try to salvage the remaining debug users.
  1557. Changed |= salvageDebugInfo(From);
  1558. // Delete the debug users which weren't salvaged.
  1559. for (auto *DII : DeleteOrSalvage) {
  1560. if (DII->getVariableLocation() == &From) {
  1561. LLVM_DEBUG(dbgs() << "Erased UseBeforeDef: " << *DII << '\n');
  1562. DII->eraseFromParent();
  1563. Changed = true;
  1564. }
  1565. }
  1566. }
  1567. return Changed;
  1568. }
  1569. /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
  1570. /// losslessly preserve the bits and semantics of the value. This predicate is
  1571. /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
  1572. ///
  1573. /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
  1574. /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
  1575. /// and also does not allow lossless pointer <-> integer conversions.
  1576. static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
  1577. Type *ToTy) {
  1578. // Trivially compatible types.
  1579. if (FromTy == ToTy)
  1580. return true;
  1581. // Handle compatible pointer <-> integer conversions.
  1582. if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
  1583. bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
  1584. bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
  1585. !DL.isNonIntegralPointerType(ToTy);
  1586. return SameSize && LosslessConversion;
  1587. }
  1588. // TODO: This is not exhaustive.
  1589. return false;
  1590. }
  1591. bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
  1592. Instruction &DomPoint, DominatorTree &DT) {
  1593. // Exit early if From has no debug users.
  1594. if (!From.isUsedByMetadata())
  1595. return false;
  1596. assert(&From != &To && "Can't replace something with itself");
  1597. Type *FromTy = From.getType();
  1598. Type *ToTy = To.getType();
  1599. auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
  1600. return DII.getExpression();
  1601. };
  1602. // Handle no-op conversions.
  1603. Module &M = *From.getModule();
  1604. const DataLayout &DL = M.getDataLayout();
  1605. if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
  1606. return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
  1607. // Handle integer-to-integer widening and narrowing.
  1608. // FIXME: Use DW_OP_convert when it's available everywhere.
  1609. if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
  1610. uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
  1611. uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
  1612. assert(FromBits != ToBits && "Unexpected no-op conversion");
  1613. // When the width of the result grows, assume that a debugger will only
  1614. // access the low `FromBits` bits when inspecting the source variable.
  1615. if (FromBits < ToBits)
  1616. return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
  1617. // The width of the result has shrunk. Use sign/zero extension to describe
  1618. // the source variable's high bits.
  1619. auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
  1620. DILocalVariable *Var = DII.getVariable();
  1621. // Without knowing signedness, sign/zero extension isn't possible.
  1622. auto Signedness = Var->getSignedness();
  1623. if (!Signedness)
  1624. return None;
  1625. bool Signed = *Signedness == DIBasicType::Signedness::Signed;
  1626. if (!Signed) {
  1627. // In the unsigned case, assume that a debugger will initialize the
  1628. // high bits to 0 and do a no-op conversion.
  1629. return Identity(DII);
  1630. } else {
  1631. // In the signed case, the high bits are given by sign extension, i.e:
  1632. // (To >> (ToBits - 1)) * ((2 ^ FromBits) - 1)
  1633. // Calculate the high bits and OR them together with the low bits.
  1634. SmallVector<uint64_t, 8> Ops({dwarf::DW_OP_dup, dwarf::DW_OP_constu,
  1635. (ToBits - 1), dwarf::DW_OP_shr,
  1636. dwarf::DW_OP_lit0, dwarf::DW_OP_not,
  1637. dwarf::DW_OP_mul, dwarf::DW_OP_or});
  1638. return DIExpression::appendToStack(DII.getExpression(), Ops);
  1639. }
  1640. };
  1641. return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
  1642. }
  1643. // TODO: Floating-point conversions, vectors.
  1644. return false;
  1645. }
  1646. unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
  1647. unsigned NumDeadInst = 0;
  1648. // Delete the instructions backwards, as it has a reduced likelihood of
  1649. // having to update as many def-use and use-def chains.
  1650. Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
  1651. while (EndInst != &BB->front()) {
  1652. // Delete the next to last instruction.
  1653. Instruction *Inst = &*--EndInst->getIterator();
  1654. if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
  1655. Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
  1656. if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
  1657. EndInst = Inst;
  1658. continue;
  1659. }
  1660. if (!isa<DbgInfoIntrinsic>(Inst))
  1661. ++NumDeadInst;
  1662. Inst->eraseFromParent();
  1663. }
  1664. return NumDeadInst;
  1665. }
  1666. unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
  1667. bool PreserveLCSSA, DomTreeUpdater *DTU) {
  1668. BasicBlock *BB = I->getParent();
  1669. std::vector <DominatorTree::UpdateType> Updates;
  1670. // Loop over all of the successors, removing BB's entry from any PHI
  1671. // nodes.
  1672. if (DTU)
  1673. Updates.reserve(BB->getTerminator()->getNumSuccessors());
  1674. for (BasicBlock *Successor : successors(BB)) {
  1675. Successor->removePredecessor(BB, PreserveLCSSA);
  1676. if (DTU)
  1677. Updates.push_back({DominatorTree::Delete, BB, Successor});
  1678. }
  1679. // Insert a call to llvm.trap right before this. This turns the undefined
  1680. // behavior into a hard fail instead of falling through into random code.
  1681. if (UseLLVMTrap) {
  1682. Function *TrapFn =
  1683. Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
  1684. CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
  1685. CallTrap->setDebugLoc(I->getDebugLoc());
  1686. }
  1687. auto *UI = new UnreachableInst(I->getContext(), I);
  1688. UI->setDebugLoc(I->getDebugLoc());
  1689. // All instructions after this are dead.
  1690. unsigned NumInstrsRemoved = 0;
  1691. BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
  1692. while (BBI != BBE) {
  1693. if (!BBI->use_empty())
  1694. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  1695. BB->getInstList().erase(BBI++);
  1696. ++NumInstrsRemoved;
  1697. }
  1698. if (DTU)
  1699. DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
  1700. return NumInstrsRemoved;
  1701. }
  1702. /// changeToCall - Convert the specified invoke into a normal call.
  1703. static void changeToCall(InvokeInst *II, DomTreeUpdater *DTU = nullptr) {
  1704. SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
  1705. SmallVector<OperandBundleDef, 1> OpBundles;
  1706. II->getOperandBundlesAsDefs(OpBundles);
  1707. CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
  1708. "", II);
  1709. NewCall->takeName(II);
  1710. NewCall->setCallingConv(II->getCallingConv());
  1711. NewCall->setAttributes(II->getAttributes());
  1712. NewCall->setDebugLoc(II->getDebugLoc());
  1713. NewCall->copyMetadata(*II);
  1714. II->replaceAllUsesWith(NewCall);
  1715. // Follow the call by a branch to the normal destination.
  1716. BasicBlock *NormalDestBB = II->getNormalDest();
  1717. BranchInst::Create(NormalDestBB, II);
  1718. // Update PHI nodes in the unwind destination
  1719. BasicBlock *BB = II->getParent();
  1720. BasicBlock *UnwindDestBB = II->getUnwindDest();
  1721. UnwindDestBB->removePredecessor(BB);
  1722. II->eraseFromParent();
  1723. if (DTU)
  1724. DTU->deleteEdgeRelaxed(BB, UnwindDestBB);
  1725. }
  1726. BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
  1727. BasicBlock *UnwindEdge) {
  1728. BasicBlock *BB = CI->getParent();
  1729. // Convert this function call into an invoke instruction. First, split the
  1730. // basic block.
  1731. BasicBlock *Split =
  1732. BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
  1733. // Delete the unconditional branch inserted by splitBasicBlock
  1734. BB->getInstList().pop_back();
  1735. // Create the new invoke instruction.
  1736. SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
  1737. SmallVector<OperandBundleDef, 1> OpBundles;
  1738. CI->getOperandBundlesAsDefs(OpBundles);
  1739. // Note: we're round tripping operand bundles through memory here, and that
  1740. // can potentially be avoided with a cleverer API design that we do not have
  1741. // as of this time.
  1742. InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge,
  1743. InvokeArgs, OpBundles, CI->getName(), BB);
  1744. II->setDebugLoc(CI->getDebugLoc());
  1745. II->setCallingConv(CI->getCallingConv());
  1746. II->setAttributes(CI->getAttributes());
  1747. // Make sure that anything using the call now uses the invoke! This also
  1748. // updates the CallGraph if present, because it uses a WeakTrackingVH.
  1749. CI->replaceAllUsesWith(II);
  1750. // Delete the original call
  1751. Split->getInstList().pop_front();
  1752. return Split;
  1753. }
  1754. static bool markAliveBlocks(Function &F,
  1755. SmallPtrSetImpl<BasicBlock *> &Reachable,
  1756. DomTreeUpdater *DTU = nullptr) {
  1757. SmallVector<BasicBlock*, 128> Worklist;
  1758. BasicBlock *BB = &F.front();
  1759. Worklist.push_back(BB);
  1760. Reachable.insert(BB);
  1761. bool Changed = false;
  1762. do {
  1763. BB = Worklist.pop_back_val();
  1764. // Do a quick scan of the basic block, turning any obviously unreachable
  1765. // instructions into LLVM unreachable insts. The instruction combining pass
  1766. // canonicalizes unreachable insts into stores to null or undef.
  1767. for (Instruction &I : *BB) {
  1768. if (auto *CI = dyn_cast<CallInst>(&I)) {
  1769. Value *Callee = CI->getCalledValue();
  1770. // Handle intrinsic calls.
  1771. if (Function *F = dyn_cast<Function>(Callee)) {
  1772. auto IntrinsicID = F->getIntrinsicID();
  1773. // Assumptions that are known to be false are equivalent to
  1774. // unreachable. Also, if the condition is undefined, then we make the
  1775. // choice most beneficial to the optimizer, and choose that to also be
  1776. // unreachable.
  1777. if (IntrinsicID == Intrinsic::assume) {
  1778. if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
  1779. // Don't insert a call to llvm.trap right before the unreachable.
  1780. changeToUnreachable(CI, false, false, DTU);
  1781. Changed = true;
  1782. break;
  1783. }
  1784. } else if (IntrinsicID == Intrinsic::experimental_guard) {
  1785. // A call to the guard intrinsic bails out of the current
  1786. // compilation unit if the predicate passed to it is false. If the
  1787. // predicate is a constant false, then we know the guard will bail
  1788. // out of the current compile unconditionally, so all code following
  1789. // it is dead.
  1790. //
  1791. // Note: unlike in llvm.assume, it is not "obviously profitable" for
  1792. // guards to treat `undef` as `false` since a guard on `undef` can
  1793. // still be useful for widening.
  1794. if (match(CI->getArgOperand(0), m_Zero()))
  1795. if (!isa<UnreachableInst>(CI->getNextNode())) {
  1796. changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
  1797. false, DTU);
  1798. Changed = true;
  1799. break;
  1800. }
  1801. }
  1802. } else if ((isa<ConstantPointerNull>(Callee) &&
  1803. !NullPointerIsDefined(CI->getFunction())) ||
  1804. isa<UndefValue>(Callee)) {
  1805. changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
  1806. Changed = true;
  1807. break;
  1808. }
  1809. if (CI->doesNotReturn()) {
  1810. // If we found a call to a no-return function, insert an unreachable
  1811. // instruction after it. Make sure there isn't *already* one there
  1812. // though.
  1813. if (!isa<UnreachableInst>(CI->getNextNode())) {
  1814. // Don't insert a call to llvm.trap right before the unreachable.
  1815. changeToUnreachable(CI->getNextNode(), false, false, DTU);
  1816. Changed = true;
  1817. }
  1818. break;
  1819. }
  1820. } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
  1821. // Store to undef and store to null are undefined and used to signal
  1822. // that they should be changed to unreachable by passes that can't
  1823. // modify the CFG.
  1824. // Don't touch volatile stores.
  1825. if (SI->isVolatile()) continue;
  1826. Value *Ptr = SI->getOperand(1);
  1827. if (isa<UndefValue>(Ptr) ||
  1828. (isa<ConstantPointerNull>(Ptr) &&
  1829. !NullPointerIsDefined(SI->getFunction(),
  1830. SI->getPointerAddressSpace()))) {
  1831. changeToUnreachable(SI, true, false, DTU);
  1832. Changed = true;
  1833. break;
  1834. }
  1835. }
  1836. }
  1837. Instruction *Terminator = BB->getTerminator();
  1838. if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
  1839. // Turn invokes that call 'nounwind' functions into ordinary calls.
  1840. Value *Callee = II->getCalledValue();
  1841. if ((isa<ConstantPointerNull>(Callee) &&
  1842. !NullPointerIsDefined(BB->getParent())) ||
  1843. isa<UndefValue>(Callee)) {
  1844. changeToUnreachable(II, true, false, DTU);
  1845. Changed = true;
  1846. } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
  1847. if (II->use_empty() && II->onlyReadsMemory()) {
  1848. // jump to the normal destination branch.
  1849. BasicBlock *NormalDestBB = II->getNormalDest();
  1850. BasicBlock *UnwindDestBB = II->getUnwindDest();
  1851. BranchInst::Create(NormalDestBB, II);
  1852. UnwindDestBB->removePredecessor(II->getParent());
  1853. II->eraseFromParent();
  1854. if (DTU)
  1855. DTU->deleteEdgeRelaxed(BB, UnwindDestBB);
  1856. } else
  1857. changeToCall(II, DTU);
  1858. Changed = true;
  1859. }
  1860. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
  1861. // Remove catchpads which cannot be reached.
  1862. struct CatchPadDenseMapInfo {
  1863. static CatchPadInst *getEmptyKey() {
  1864. return DenseMapInfo<CatchPadInst *>::getEmptyKey();
  1865. }
  1866. static CatchPadInst *getTombstoneKey() {
  1867. return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
  1868. }
  1869. static unsigned getHashValue(CatchPadInst *CatchPad) {
  1870. return static_cast<unsigned>(hash_combine_range(
  1871. CatchPad->value_op_begin(), CatchPad->value_op_end()));
  1872. }
  1873. static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
  1874. if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
  1875. RHS == getEmptyKey() || RHS == getTombstoneKey())
  1876. return LHS == RHS;
  1877. return LHS->isIdenticalTo(RHS);
  1878. }
  1879. };
  1880. // Set of unique CatchPads.
  1881. SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
  1882. CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
  1883. HandlerSet;
  1884. detail::DenseSetEmpty Empty;
  1885. for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
  1886. E = CatchSwitch->handler_end();
  1887. I != E; ++I) {
  1888. BasicBlock *HandlerBB = *I;
  1889. auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
  1890. if (!HandlerSet.insert({CatchPad, Empty}).second) {
  1891. CatchSwitch->removeHandler(I);
  1892. --I;
  1893. --E;
  1894. Changed = true;
  1895. }
  1896. }
  1897. }
  1898. Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
  1899. for (BasicBlock *Successor : successors(BB))
  1900. if (Reachable.insert(Successor).second)
  1901. Worklist.push_back(Successor);
  1902. } while (!Worklist.empty());
  1903. return Changed;
  1904. }
  1905. void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
  1906. Instruction *TI = BB->getTerminator();
  1907. if (auto *II = dyn_cast<InvokeInst>(TI)) {
  1908. changeToCall(II, DTU);
  1909. return;
  1910. }
  1911. Instruction *NewTI;
  1912. BasicBlock *UnwindDest;
  1913. if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
  1914. NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
  1915. UnwindDest = CRI->getUnwindDest();
  1916. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
  1917. auto *NewCatchSwitch = CatchSwitchInst::Create(
  1918. CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
  1919. CatchSwitch->getName(), CatchSwitch);
  1920. for (BasicBlock *PadBB : CatchSwitch->handlers())
  1921. NewCatchSwitch->addHandler(PadBB);
  1922. NewTI = NewCatchSwitch;
  1923. UnwindDest = CatchSwitch->getUnwindDest();
  1924. } else {
  1925. llvm_unreachable("Could not find unwind successor");
  1926. }
  1927. NewTI->takeName(TI);
  1928. NewTI->setDebugLoc(TI->getDebugLoc());
  1929. UnwindDest->removePredecessor(BB);
  1930. TI->replaceAllUsesWith(NewTI);
  1931. TI->eraseFromParent();
  1932. if (DTU)
  1933. DTU->deleteEdgeRelaxed(BB, UnwindDest);
  1934. }
  1935. /// removeUnreachableBlocks - Remove blocks that are not reachable, even
  1936. /// if they are in a dead cycle. Return true if a change was made, false
  1937. /// otherwise. If `LVI` is passed, this function preserves LazyValueInfo
  1938. /// after modifying the CFG.
  1939. bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI,
  1940. DomTreeUpdater *DTU,
  1941. MemorySSAUpdater *MSSAU) {
  1942. SmallPtrSet<BasicBlock*, 16> Reachable;
  1943. bool Changed = markAliveBlocks(F, Reachable, DTU);
  1944. // If there are unreachable blocks in the CFG...
  1945. if (Reachable.size() == F.size())
  1946. return Changed;
  1947. assert(Reachable.size() < F.size());
  1948. NumRemoved += F.size()-Reachable.size();
  1949. SmallPtrSet<BasicBlock *, 16> DeadBlockSet;
  1950. for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ++I) {
  1951. auto *BB = &*I;
  1952. if (Reachable.count(BB))
  1953. continue;
  1954. DeadBlockSet.insert(BB);
  1955. }
  1956. if (MSSAU)
  1957. MSSAU->removeBlocks(DeadBlockSet);
  1958. // Loop over all of the basic blocks that are not reachable, dropping all of
  1959. // their internal references. Update DTU and LVI if available.
  1960. std::vector<DominatorTree::UpdateType> Updates;
  1961. for (auto *BB : DeadBlockSet) {
  1962. for (BasicBlock *Successor : successors(BB)) {
  1963. if (!DeadBlockSet.count(Successor))
  1964. Successor->removePredecessor(BB);
  1965. if (DTU)
  1966. Updates.push_back({DominatorTree::Delete, BB, Successor});
  1967. }
  1968. if (LVI)
  1969. LVI->eraseBlock(BB);
  1970. BB->dropAllReferences();
  1971. }
  1972. for (Function::iterator I = ++F.begin(); I != F.end();) {
  1973. auto *BB = &*I;
  1974. if (Reachable.count(BB)) {
  1975. ++I;
  1976. continue;
  1977. }
  1978. if (DTU) {
  1979. // Remove the terminator of BB to clear the successor list of BB.
  1980. if (BB->getTerminator())
  1981. BB->getInstList().pop_back();
  1982. new UnreachableInst(BB->getContext(), BB);
  1983. assert(succ_empty(BB) && "The successor list of BB isn't empty before "
  1984. "applying corresponding DTU updates.");
  1985. ++I;
  1986. } else {
  1987. I = F.getBasicBlockList().erase(I);
  1988. }
  1989. }
  1990. if (DTU) {
  1991. DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
  1992. bool Deleted = false;
  1993. for (auto *BB : DeadBlockSet) {
  1994. if (DTU->isBBPendingDeletion(BB))
  1995. --NumRemoved;
  1996. else
  1997. Deleted = true;
  1998. DTU->deleteBB(BB);
  1999. }
  2000. if (!Deleted)
  2001. return false;
  2002. }
  2003. return true;
  2004. }
  2005. void llvm::combineMetadata(Instruction *K, const Instruction *J,
  2006. ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
  2007. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  2008. K->dropUnknownNonDebugMetadata(KnownIDs);
  2009. K->getAllMetadataOtherThanDebugLoc(Metadata);
  2010. for (const auto &MD : Metadata) {
  2011. unsigned Kind = MD.first;
  2012. MDNode *JMD = J->getMetadata(Kind);
  2013. MDNode *KMD = MD.second;
  2014. switch (Kind) {
  2015. default:
  2016. K->setMetadata(Kind, nullptr); // Remove unknown metadata
  2017. break;
  2018. case LLVMContext::MD_dbg:
  2019. llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
  2020. case LLVMContext::MD_tbaa:
  2021. K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
  2022. break;
  2023. case LLVMContext::MD_alias_scope:
  2024. K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
  2025. break;
  2026. case LLVMContext::MD_noalias:
  2027. case LLVMContext::MD_mem_parallel_loop_access:
  2028. K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
  2029. break;
  2030. case LLVMContext::MD_access_group:
  2031. K->setMetadata(LLVMContext::MD_access_group,
  2032. intersectAccessGroups(K, J));
  2033. break;
  2034. case LLVMContext::MD_range:
  2035. // If K does move, use most generic range. Otherwise keep the range of
  2036. // K.
  2037. if (DoesKMove)
  2038. // FIXME: If K does move, we should drop the range info and nonnull.
  2039. // Currently this function is used with DoesKMove in passes
  2040. // doing hoisting/sinking and the current behavior of using the
  2041. // most generic range is correct in those cases.
  2042. K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
  2043. break;
  2044. case LLVMContext::MD_fpmath:
  2045. K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
  2046. break;
  2047. case LLVMContext::MD_invariant_load:
  2048. // Only set the !invariant.load if it is present in both instructions.
  2049. K->setMetadata(Kind, JMD);
  2050. break;
  2051. case LLVMContext::MD_nonnull:
  2052. // If K does move, keep nonull if it is present in both instructions.
  2053. if (DoesKMove)
  2054. K->setMetadata(Kind, JMD);
  2055. break;
  2056. case LLVMContext::MD_invariant_group:
  2057. // Preserve !invariant.group in K.
  2058. break;
  2059. case LLVMContext::MD_align:
  2060. K->setMetadata(Kind,
  2061. MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
  2062. break;
  2063. case LLVMContext::MD_dereferenceable:
  2064. case LLVMContext::MD_dereferenceable_or_null:
  2065. K->setMetadata(Kind,
  2066. MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
  2067. break;
  2068. }
  2069. }
  2070. // Set !invariant.group from J if J has it. If both instructions have it
  2071. // then we will just pick it from J - even when they are different.
  2072. // Also make sure that K is load or store - f.e. combining bitcast with load
  2073. // could produce bitcast with invariant.group metadata, which is invalid.
  2074. // FIXME: we should try to preserve both invariant.group md if they are
  2075. // different, but right now instruction can only have one invariant.group.
  2076. if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
  2077. if (isa<LoadInst>(K) || isa<StoreInst>(K))
  2078. K->setMetadata(LLVMContext::MD_invariant_group, JMD);
  2079. }
  2080. void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
  2081. bool KDominatesJ) {
  2082. unsigned KnownIDs[] = {
  2083. LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  2084. LLVMContext::MD_noalias, LLVMContext::MD_range,
  2085. LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
  2086. LLVMContext::MD_invariant_group, LLVMContext::MD_align,
  2087. LLVMContext::MD_dereferenceable,
  2088. LLVMContext::MD_dereferenceable_or_null,
  2089. LLVMContext::MD_access_group};
  2090. combineMetadata(K, J, KnownIDs, KDominatesJ);
  2091. }
  2092. void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
  2093. auto *ReplInst = dyn_cast<Instruction>(Repl);
  2094. if (!ReplInst)
  2095. return;
  2096. // Patch the replacement so that it is not more restrictive than the value
  2097. // being replaced.
  2098. // Note that if 'I' is a load being replaced by some operation,
  2099. // for example, by an arithmetic operation, then andIRFlags()
  2100. // would just erase all math flags from the original arithmetic
  2101. // operation, which is clearly not wanted and not needed.
  2102. if (!isa<LoadInst>(I))
  2103. ReplInst->andIRFlags(I);
  2104. // FIXME: If both the original and replacement value are part of the
  2105. // same control-flow region (meaning that the execution of one
  2106. // guarantees the execution of the other), then we can combine the
  2107. // noalias scopes here and do better than the general conservative
  2108. // answer used in combineMetadata().
  2109. // In general, GVN unifies expressions over different control-flow
  2110. // regions, and so we need a conservative combination of the noalias
  2111. // scopes.
  2112. static const unsigned KnownIDs[] = {
  2113. LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  2114. LLVMContext::MD_noalias, LLVMContext::MD_range,
  2115. LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
  2116. LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
  2117. LLVMContext::MD_access_group};
  2118. combineMetadata(ReplInst, I, KnownIDs, false);
  2119. }
  2120. template <typename RootType, typename DominatesFn>
  2121. static unsigned replaceDominatedUsesWith(Value *From, Value *To,
  2122. const RootType &Root,
  2123. const DominatesFn &Dominates) {
  2124. assert(From->getType() == To->getType());
  2125. unsigned Count = 0;
  2126. for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
  2127. UI != UE;) {
  2128. Use &U = *UI++;
  2129. if (!Dominates(Root, U))
  2130. continue;
  2131. U.set(To);
  2132. LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
  2133. << "' as " << *To << " in " << *U << "\n");
  2134. ++Count;
  2135. }
  2136. return Count;
  2137. }
  2138. unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
  2139. assert(From->getType() == To->getType());
  2140. auto *BB = From->getParent();
  2141. unsigned Count = 0;
  2142. for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
  2143. UI != UE;) {
  2144. Use &U = *UI++;
  2145. auto *I = cast<Instruction>(U.getUser());
  2146. if (I->getParent() == BB)
  2147. continue;
  2148. U.set(To);
  2149. ++Count;
  2150. }
  2151. return Count;
  2152. }
  2153. unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
  2154. DominatorTree &DT,
  2155. const BasicBlockEdge &Root) {
  2156. auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
  2157. return DT.dominates(Root, U);
  2158. };
  2159. return ::replaceDominatedUsesWith(From, To, Root, Dominates);
  2160. }
  2161. unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
  2162. DominatorTree &DT,
  2163. const BasicBlock *BB) {
  2164. auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
  2165. auto *I = cast<Instruction>(U.getUser())->getParent();
  2166. return DT.properlyDominates(BB, I);
  2167. };
  2168. return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
  2169. }
  2170. bool llvm::callsGCLeafFunction(ImmutableCallSite CS,
  2171. const TargetLibraryInfo &TLI) {
  2172. // Check if the function is specifically marked as a gc leaf function.
  2173. if (CS.hasFnAttr("gc-leaf-function"))
  2174. return true;
  2175. if (const Function *F = CS.getCalledFunction()) {
  2176. if (F->hasFnAttribute("gc-leaf-function"))
  2177. return true;
  2178. if (auto IID = F->getIntrinsicID())
  2179. // Most LLVM intrinsics do not take safepoints.
  2180. return IID != Intrinsic::experimental_gc_statepoint &&
  2181. IID != Intrinsic::experimental_deoptimize;
  2182. }
  2183. // Lib calls can be materialized by some passes, and won't be
  2184. // marked as 'gc-leaf-function.' All available Libcalls are
  2185. // GC-leaf.
  2186. LibFunc LF;
  2187. if (TLI.getLibFunc(CS, LF)) {
  2188. return TLI.has(LF);
  2189. }
  2190. return false;
  2191. }
  2192. void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
  2193. LoadInst &NewLI) {
  2194. auto *NewTy = NewLI.getType();
  2195. // This only directly applies if the new type is also a pointer.
  2196. if (NewTy->isPointerTy()) {
  2197. NewLI.setMetadata(LLVMContext::MD_nonnull, N);
  2198. return;
  2199. }
  2200. // The only other translation we can do is to integral loads with !range
  2201. // metadata.
  2202. if (!NewTy->isIntegerTy())
  2203. return;
  2204. MDBuilder MDB(NewLI.getContext());
  2205. const Value *Ptr = OldLI.getPointerOperand();
  2206. auto *ITy = cast<IntegerType>(NewTy);
  2207. auto *NullInt = ConstantExpr::getPtrToInt(
  2208. ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
  2209. auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
  2210. NewLI.setMetadata(LLVMContext::MD_range,
  2211. MDB.createRange(NonNullInt, NullInt));
  2212. }
  2213. void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
  2214. MDNode *N, LoadInst &NewLI) {
  2215. auto *NewTy = NewLI.getType();
  2216. // Give up unless it is converted to a pointer where there is a single very
  2217. // valuable mapping we can do reliably.
  2218. // FIXME: It would be nice to propagate this in more ways, but the type
  2219. // conversions make it hard.
  2220. if (!NewTy->isPointerTy())
  2221. return;
  2222. unsigned BitWidth = DL.getIndexTypeSizeInBits(NewTy);
  2223. if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
  2224. MDNode *NN = MDNode::get(OldLI.getContext(), None);
  2225. NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
  2226. }
  2227. }
  2228. void llvm::dropDebugUsers(Instruction &I) {
  2229. SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
  2230. findDbgUsers(DbgUsers, &I);
  2231. for (auto *DII : DbgUsers)
  2232. DII->eraseFromParent();
  2233. }
  2234. void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
  2235. BasicBlock *BB) {
  2236. // Since we are moving the instructions out of its basic block, we do not
  2237. // retain their original debug locations (DILocations) and debug intrinsic
  2238. // instructions (dbg.values).
  2239. //
  2240. // Doing so would degrade the debugging experience and adversely affect the
  2241. // accuracy of profiling information.
  2242. //
  2243. // Currently, when hoisting the instructions, we take the following actions:
  2244. // - Remove their dbg.values.
  2245. // - Set their debug locations to the values from the insertion point.
  2246. //
  2247. // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
  2248. // need to be deleted, is because there will not be any instructions with a
  2249. // DILocation in either branch left after performing the transformation. We
  2250. // can only insert a dbg.value after the two branches are joined again.
  2251. //
  2252. // See PR38762, PR39243 for more details.
  2253. //
  2254. // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
  2255. // encode predicated DIExpressions that yield different results on different
  2256. // code paths.
  2257. for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
  2258. Instruction *I = &*II;
  2259. I->dropUnknownNonDebugMetadata();
  2260. if (I->isUsedByMetadata())
  2261. dropDebugUsers(*I);
  2262. if (isa<DbgVariableIntrinsic>(I)) {
  2263. // Remove DbgInfo Intrinsics.
  2264. II = I->eraseFromParent();
  2265. continue;
  2266. }
  2267. I->setDebugLoc(InsertPt->getDebugLoc());
  2268. ++II;
  2269. }
  2270. DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
  2271. BB->begin(),
  2272. BB->getTerminator()->getIterator());
  2273. }
  2274. namespace {
  2275. /// A potential constituent of a bitreverse or bswap expression. See
  2276. /// collectBitParts for a fuller explanation.
  2277. struct BitPart {
  2278. BitPart(Value *P, unsigned BW) : Provider(P) {
  2279. Provenance.resize(BW);
  2280. }
  2281. /// The Value that this is a bitreverse/bswap of.
  2282. Value *Provider;
  2283. /// The "provenance" of each bit. Provenance[A] = B means that bit A
  2284. /// in Provider becomes bit B in the result of this expression.
  2285. SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
  2286. enum { Unset = -1 };
  2287. };
  2288. } // end anonymous namespace
  2289. /// Analyze the specified subexpression and see if it is capable of providing
  2290. /// pieces of a bswap or bitreverse. The subexpression provides a potential
  2291. /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
  2292. /// the output of the expression came from a corresponding bit in some other
  2293. /// value. This function is recursive, and the end result is a mapping of
  2294. /// bitnumber to bitnumber. It is the caller's responsibility to validate that
  2295. /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
  2296. ///
  2297. /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
  2298. /// that the expression deposits the low byte of %X into the high byte of the
  2299. /// result and that all other bits are zero. This expression is accepted and a
  2300. /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
  2301. /// [0-7].
  2302. ///
  2303. /// To avoid revisiting values, the BitPart results are memoized into the
  2304. /// provided map. To avoid unnecessary copying of BitParts, BitParts are
  2305. /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
  2306. /// store BitParts objects, not pointers. As we need the concept of a nullptr
  2307. /// BitParts (Value has been analyzed and the analysis failed), we an Optional
  2308. /// type instead to provide the same functionality.
  2309. ///
  2310. /// Because we pass around references into \c BPS, we must use a container that
  2311. /// does not invalidate internal references (std::map instead of DenseMap).
  2312. static const Optional<BitPart> &
  2313. collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
  2314. std::map<Value *, Optional<BitPart>> &BPS) {
  2315. auto I = BPS.find(V);
  2316. if (I != BPS.end())
  2317. return I->second;
  2318. auto &Result = BPS[V] = None;
  2319. auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
  2320. if (Instruction *I = dyn_cast<Instruction>(V)) {
  2321. // If this is an or instruction, it may be an inner node of the bswap.
  2322. if (I->getOpcode() == Instruction::Or) {
  2323. auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
  2324. MatchBitReversals, BPS);
  2325. auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
  2326. MatchBitReversals, BPS);
  2327. if (!A || !B)
  2328. return Result;
  2329. // Try and merge the two together.
  2330. if (!A->Provider || A->Provider != B->Provider)
  2331. return Result;
  2332. Result = BitPart(A->Provider, BitWidth);
  2333. for (unsigned i = 0; i < A->Provenance.size(); ++i) {
  2334. if (A->Provenance[i] != BitPart::Unset &&
  2335. B->Provenance[i] != BitPart::Unset &&
  2336. A->Provenance[i] != B->Provenance[i])
  2337. return Result = None;
  2338. if (A->Provenance[i] == BitPart::Unset)
  2339. Result->Provenance[i] = B->Provenance[i];
  2340. else
  2341. Result->Provenance[i] = A->Provenance[i];
  2342. }
  2343. return Result;
  2344. }
  2345. // If this is a logical shift by a constant, recurse then shift the result.
  2346. if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
  2347. unsigned BitShift =
  2348. cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
  2349. // Ensure the shift amount is defined.
  2350. if (BitShift > BitWidth)
  2351. return Result;
  2352. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  2353. MatchBitReversals, BPS);
  2354. if (!Res)
  2355. return Result;
  2356. Result = Res;
  2357. // Perform the "shift" on BitProvenance.
  2358. auto &P = Result->Provenance;
  2359. if (I->getOpcode() == Instruction::Shl) {
  2360. P.erase(std::prev(P.end(), BitShift), P.end());
  2361. P.insert(P.begin(), BitShift, BitPart::Unset);
  2362. } else {
  2363. P.erase(P.begin(), std::next(P.begin(), BitShift));
  2364. P.insert(P.end(), BitShift, BitPart::Unset);
  2365. }
  2366. return Result;
  2367. }
  2368. // If this is a logical 'and' with a mask that clears bits, recurse then
  2369. // unset the appropriate bits.
  2370. if (I->getOpcode() == Instruction::And &&
  2371. isa<ConstantInt>(I->getOperand(1))) {
  2372. APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
  2373. const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
  2374. // Check that the mask allows a multiple of 8 bits for a bswap, for an
  2375. // early exit.
  2376. unsigned NumMaskedBits = AndMask.countPopulation();
  2377. if (!MatchBitReversals && NumMaskedBits % 8 != 0)
  2378. return Result;
  2379. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  2380. MatchBitReversals, BPS);
  2381. if (!Res)
  2382. return Result;
  2383. Result = Res;
  2384. for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
  2385. // If the AndMask is zero for this bit, clear the bit.
  2386. if ((AndMask & Bit) == 0)
  2387. Result->Provenance[i] = BitPart::Unset;
  2388. return Result;
  2389. }
  2390. // If this is a zext instruction zero extend the result.
  2391. if (I->getOpcode() == Instruction::ZExt) {
  2392. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  2393. MatchBitReversals, BPS);
  2394. if (!Res)
  2395. return Result;
  2396. Result = BitPart(Res->Provider, BitWidth);
  2397. auto NarrowBitWidth =
  2398. cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
  2399. for (unsigned i = 0; i < NarrowBitWidth; ++i)
  2400. Result->Provenance[i] = Res->Provenance[i];
  2401. for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
  2402. Result->Provenance[i] = BitPart::Unset;
  2403. return Result;
  2404. }
  2405. }
  2406. // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
  2407. // the input value to the bswap/bitreverse.
  2408. Result = BitPart(V, BitWidth);
  2409. for (unsigned i = 0; i < BitWidth; ++i)
  2410. Result->Provenance[i] = i;
  2411. return Result;
  2412. }
  2413. static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
  2414. unsigned BitWidth) {
  2415. if (From % 8 != To % 8)
  2416. return false;
  2417. // Convert from bit indices to byte indices and check for a byte reversal.
  2418. From >>= 3;
  2419. To >>= 3;
  2420. BitWidth >>= 3;
  2421. return From == BitWidth - To - 1;
  2422. }
  2423. static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
  2424. unsigned BitWidth) {
  2425. return From == BitWidth - To - 1;
  2426. }
  2427. bool llvm::recognizeBSwapOrBitReverseIdiom(
  2428. Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
  2429. SmallVectorImpl<Instruction *> &InsertedInsts) {
  2430. if (Operator::getOpcode(I) != Instruction::Or)
  2431. return false;
  2432. if (!MatchBSwaps && !MatchBitReversals)
  2433. return false;
  2434. IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
  2435. if (!ITy || ITy->getBitWidth() > 128)
  2436. return false; // Can't do vectors or integers > 128 bits.
  2437. unsigned BW = ITy->getBitWidth();
  2438. unsigned DemandedBW = BW;
  2439. IntegerType *DemandedTy = ITy;
  2440. if (I->hasOneUse()) {
  2441. if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
  2442. DemandedTy = cast<IntegerType>(Trunc->getType());
  2443. DemandedBW = DemandedTy->getBitWidth();
  2444. }
  2445. }
  2446. // Try to find all the pieces corresponding to the bswap.
  2447. std::map<Value *, Optional<BitPart>> BPS;
  2448. auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
  2449. if (!Res)
  2450. return false;
  2451. auto &BitProvenance = Res->Provenance;
  2452. // Now, is the bit permutation correct for a bswap or a bitreverse? We can
  2453. // only byteswap values with an even number of bytes.
  2454. bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
  2455. for (unsigned i = 0; i < DemandedBW; ++i) {
  2456. OKForBSwap &=
  2457. bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
  2458. OKForBitReverse &=
  2459. bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
  2460. }
  2461. Intrinsic::ID Intrin;
  2462. if (OKForBSwap && MatchBSwaps)
  2463. Intrin = Intrinsic::bswap;
  2464. else if (OKForBitReverse && MatchBitReversals)
  2465. Intrin = Intrinsic::bitreverse;
  2466. else
  2467. return false;
  2468. if (ITy != DemandedTy) {
  2469. Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
  2470. Value *Provider = Res->Provider;
  2471. IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
  2472. // We may need to truncate the provider.
  2473. if (DemandedTy != ProviderTy) {
  2474. auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
  2475. "trunc", I);
  2476. InsertedInsts.push_back(Trunc);
  2477. Provider = Trunc;
  2478. }
  2479. auto *CI = CallInst::Create(F, Provider, "rev", I);
  2480. InsertedInsts.push_back(CI);
  2481. auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
  2482. InsertedInsts.push_back(ExtInst);
  2483. return true;
  2484. }
  2485. Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
  2486. InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
  2487. return true;
  2488. }
  2489. // CodeGen has special handling for some string functions that may replace
  2490. // them with target-specific intrinsics. Since that'd skip our interceptors
  2491. // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
  2492. // we mark affected calls as NoBuiltin, which will disable optimization
  2493. // in CodeGen.
  2494. void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
  2495. CallInst *CI, const TargetLibraryInfo *TLI) {
  2496. Function *F = CI->getCalledFunction();
  2497. LibFunc Func;
  2498. if (F && !F->hasLocalLinkage() && F->hasName() &&
  2499. TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
  2500. !F->doesNotAccessMemory())
  2501. CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
  2502. }
  2503. bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
  2504. // We can't have a PHI with a metadata type.
  2505. if (I->getOperand(OpIdx)->getType()->isMetadataTy())
  2506. return false;
  2507. // Early exit.
  2508. if (!isa<Constant>(I->getOperand(OpIdx)))
  2509. return true;
  2510. switch (I->getOpcode()) {
  2511. default:
  2512. return true;
  2513. case Instruction::Call:
  2514. case Instruction::Invoke:
  2515. // Can't handle inline asm. Skip it.
  2516. if (isa<InlineAsm>(ImmutableCallSite(I).getCalledValue()))
  2517. return false;
  2518. // Many arithmetic intrinsics have no issue taking a
  2519. // variable, however it's hard to distingish these from
  2520. // specials such as @llvm.frameaddress that require a constant.
  2521. if (isa<IntrinsicInst>(I))
  2522. return false;
  2523. // Constant bundle operands may need to retain their constant-ness for
  2524. // correctness.
  2525. if (ImmutableCallSite(I).isBundleOperand(OpIdx))
  2526. return false;
  2527. return true;
  2528. case Instruction::ShuffleVector:
  2529. // Shufflevector masks are constant.
  2530. return OpIdx != 2;
  2531. case Instruction::Switch:
  2532. case Instruction::ExtractValue:
  2533. // All operands apart from the first are constant.
  2534. return OpIdx == 0;
  2535. case Instruction::InsertValue:
  2536. // All operands apart from the first and the second are constant.
  2537. return OpIdx < 2;
  2538. case Instruction::Alloca:
  2539. // Static allocas (constant size in the entry block) are handled by
  2540. // prologue/epilogue insertion so they're free anyway. We definitely don't
  2541. // want to make them non-constant.
  2542. return !cast<AllocaInst>(I)->isStaticAlloca();
  2543. case Instruction::GetElementPtr:
  2544. if (OpIdx == 0)
  2545. return true;
  2546. gep_type_iterator It = gep_type_begin(I);
  2547. for (auto E = std::next(It, OpIdx); It != E; ++It)
  2548. if (It.isStruct())
  2549. return false;
  2550. return true;
  2551. }
  2552. }