Local.cpp 111 KB

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