Local.cpp 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284
  1. //===- Local.cpp - Functions to perform local transformations -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This family of functions perform various local transformations to the
  11. // program.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/Local.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/DenseMapInfo.h"
  18. #include "llvm/ADT/DenseSet.h"
  19. #include "llvm/ADT/Hashing.h"
  20. #include "llvm/ADT/None.h"
  21. #include "llvm/ADT/Optional.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/ADT/TinyPtrVector.h"
  28. #include "llvm/Analysis/ConstantFolding.h"
  29. #include "llvm/Analysis/EHPersonalities.h"
  30. #include "llvm/Analysis/InstructionSimplify.h"
  31. #include "llvm/Analysis/LazyValueInfo.h"
  32. #include "llvm/Analysis/MemoryBuiltins.h"
  33. #include "llvm/Analysis/TargetLibraryInfo.h"
  34. #include "llvm/Analysis/ValueTracking.h"
  35. #include "llvm/BinaryFormat/Dwarf.h"
  36. #include "llvm/IR/Argument.h"
  37. #include "llvm/IR/Attributes.h"
  38. #include "llvm/IR/BasicBlock.h"
  39. #include "llvm/IR/CFG.h"
  40. #include "llvm/IR/CallSite.h"
  41. #include "llvm/IR/Constant.h"
  42. #include "llvm/IR/ConstantRange.h"
  43. #include "llvm/IR/Constants.h"
  44. #include "llvm/IR/DIBuilder.h"
  45. #include "llvm/IR/DataLayout.h"
  46. #include "llvm/IR/DebugInfoMetadata.h"
  47. #include "llvm/IR/DebugLoc.h"
  48. #include "llvm/IR/DerivedTypes.h"
  49. #include "llvm/IR/Dominators.h"
  50. #include "llvm/IR/Function.h"
  51. #include "llvm/IR/GetElementPtrTypeIterator.h"
  52. #include "llvm/IR/GlobalObject.h"
  53. #include "llvm/IR/IRBuilder.h"
  54. #include "llvm/IR/InstrTypes.h"
  55. #include "llvm/IR/Instruction.h"
  56. #include "llvm/IR/Instructions.h"
  57. #include "llvm/IR/IntrinsicInst.h"
  58. #include "llvm/IR/Intrinsics.h"
  59. #include "llvm/IR/LLVMContext.h"
  60. #include "llvm/IR/MDBuilder.h"
  61. #include "llvm/IR/Metadata.h"
  62. #include "llvm/IR/Module.h"
  63. #include "llvm/IR/Operator.h"
  64. #include "llvm/IR/PatternMatch.h"
  65. #include "llvm/IR/Type.h"
  66. #include "llvm/IR/Use.h"
  67. #include "llvm/IR/User.h"
  68. #include "llvm/IR/Value.h"
  69. #include "llvm/IR/ValueHandle.h"
  70. #include "llvm/Support/Casting.h"
  71. #include "llvm/Support/Debug.h"
  72. #include "llvm/Support/ErrorHandling.h"
  73. #include "llvm/Support/KnownBits.h"
  74. #include "llvm/Support/raw_ostream.h"
  75. #include <algorithm>
  76. #include <cassert>
  77. #include <climits>
  78. #include <cstdint>
  79. #include <iterator>
  80. #include <map>
  81. #include <utility>
  82. using namespace llvm;
  83. using namespace llvm::PatternMatch;
  84. #define DEBUG_TYPE "local"
  85. STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
  86. //===----------------------------------------------------------------------===//
  87. // Local constant propagation.
  88. //
  89. /// ConstantFoldTerminator - If a terminator instruction is predicated on a
  90. /// constant value, convert it into an unconditional branch to the constant
  91. /// destination. This is a nontrivial operation because the successors of this
  92. /// basic block must have their PHI nodes updated.
  93. /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
  94. /// conditions and indirectbr addresses this might make dead if
  95. /// DeleteDeadConditions is true.
  96. bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
  97. const TargetLibraryInfo *TLI) {
  98. TerminatorInst *T = BB->getTerminator();
  99. IRBuilder<> Builder(T);
  100. // Branch - See if we are conditional jumping on constant
  101. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  102. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  103. BasicBlock *Dest1 = BI->getSuccessor(0);
  104. BasicBlock *Dest2 = BI->getSuccessor(1);
  105. if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  106. // Are we branching on constant?
  107. // YES. Change to unconditional branch...
  108. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  109. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  110. //cerr << "Function: " << T->getParent()->getParent()
  111. // << "\nRemoving branch from " << T->getParent()
  112. // << "\n\nTo: " << OldDest << endl;
  113. // Let the basic block know that we are letting go of it. Based on this,
  114. // it will adjust it's PHI nodes.
  115. OldDest->removePredecessor(BB);
  116. // Replace the conditional branch with an unconditional one.
  117. Builder.CreateBr(Destination);
  118. BI->eraseFromParent();
  119. return true;
  120. }
  121. if (Dest2 == Dest1) { // Conditional branch to same location?
  122. // This branch matches something like this:
  123. // br bool %cond, label %Dest, label %Dest
  124. // and changes it into: br label %Dest
  125. // Let the basic block know that we are letting go of one copy of it.
  126. assert(BI->getParent() && "Terminator not inserted in block!");
  127. Dest1->removePredecessor(BI->getParent());
  128. // Replace the conditional branch with an unconditional one.
  129. Builder.CreateBr(Dest1);
  130. Value *Cond = BI->getCondition();
  131. BI->eraseFromParent();
  132. if (DeleteDeadConditions)
  133. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  134. return true;
  135. }
  136. return false;
  137. }
  138. if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
  139. // If we are switching on a constant, we can convert the switch to an
  140. // unconditional branch.
  141. ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
  142. BasicBlock *DefaultDest = SI->getDefaultDest();
  143. BasicBlock *TheOnlyDest = DefaultDest;
  144. // If the default is unreachable, ignore it when searching for TheOnlyDest.
  145. if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
  146. SI->getNumCases() > 0) {
  147. TheOnlyDest = SI->case_begin()->getCaseSuccessor();
  148. }
  149. // Figure out which case it goes to.
  150. for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
  151. // Found case matching a constant operand?
  152. if (i->getCaseValue() == CI) {
  153. TheOnlyDest = i->getCaseSuccessor();
  154. break;
  155. }
  156. // Check to see if this branch is going to the same place as the default
  157. // dest. If so, eliminate it as an explicit compare.
  158. if (i->getCaseSuccessor() == DefaultDest) {
  159. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  160. unsigned NCases = SI->getNumCases();
  161. // Fold the case metadata into the default if there will be any branches
  162. // left, unless the metadata doesn't match the switch.
  163. if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
  164. // Collect branch weights into a vector.
  165. SmallVector<uint32_t, 8> Weights;
  166. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  167. ++MD_i) {
  168. auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
  169. Weights.push_back(CI->getValue().getZExtValue());
  170. }
  171. // Merge weight of this case to the default weight.
  172. unsigned idx = i->getCaseIndex();
  173. Weights[0] += Weights[idx+1];
  174. // Remove weight for this case.
  175. std::swap(Weights[idx+1], Weights.back());
  176. Weights.pop_back();
  177. SI->setMetadata(LLVMContext::MD_prof,
  178. MDBuilder(BB->getContext()).
  179. createBranchWeights(Weights));
  180. }
  181. // Remove this entry.
  182. DefaultDest->removePredecessor(SI->getParent());
  183. i = SI->removeCase(i);
  184. e = SI->case_end();
  185. continue;
  186. }
  187. // Otherwise, check to see if the switch only branches to one destination.
  188. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  189. // destinations.
  190. if (i->getCaseSuccessor() != TheOnlyDest)
  191. TheOnlyDest = nullptr;
  192. // Increment this iterator as we haven't removed the case.
  193. ++i;
  194. }
  195. if (CI && !TheOnlyDest) {
  196. // Branching on a constant, but not any of the cases, go to the default
  197. // successor.
  198. TheOnlyDest = SI->getDefaultDest();
  199. }
  200. // If we found a single destination that we can fold the switch into, do so
  201. // now.
  202. if (TheOnlyDest) {
  203. // Insert the new branch.
  204. Builder.CreateBr(TheOnlyDest);
  205. BasicBlock *BB = SI->getParent();
  206. // Remove entries from PHI nodes which we no longer branch to...
  207. for (BasicBlock *Succ : SI->successors()) {
  208. // Found case matching a constant operand?
  209. if (Succ == TheOnlyDest)
  210. TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
  211. else
  212. Succ->removePredecessor(BB);
  213. }
  214. // Delete the old switch.
  215. Value *Cond = SI->getCondition();
  216. SI->eraseFromParent();
  217. if (DeleteDeadConditions)
  218. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  219. return true;
  220. }
  221. if (SI->getNumCases() == 1) {
  222. // Otherwise, we can fold this switch into a conditional branch
  223. // instruction if it has only one non-default destination.
  224. auto FirstCase = *SI->case_begin();
  225. Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
  226. FirstCase.getCaseValue(), "cond");
  227. // Insert the new branch.
  228. BranchInst *NewBr = Builder.CreateCondBr(Cond,
  229. FirstCase.getCaseSuccessor(),
  230. SI->getDefaultDest());
  231. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  232. if (MD && MD->getNumOperands() == 3) {
  233. ConstantInt *SICase =
  234. mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
  235. ConstantInt *SIDef =
  236. mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
  237. assert(SICase && SIDef);
  238. // The TrueWeight should be the weight for the single case of SI.
  239. NewBr->setMetadata(LLVMContext::MD_prof,
  240. MDBuilder(BB->getContext()).
  241. createBranchWeights(SICase->getValue().getZExtValue(),
  242. SIDef->getValue().getZExtValue()));
  243. }
  244. // Update make.implicit metadata to the newly-created conditional branch.
  245. MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
  246. if (MakeImplicitMD)
  247. NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
  248. // Delete the old switch.
  249. SI->eraseFromParent();
  250. return true;
  251. }
  252. return false;
  253. }
  254. if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
  255. // indirectbr blockaddress(@F, @BB) -> br label @BB
  256. if (BlockAddress *BA =
  257. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  258. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  259. // Insert the new branch.
  260. Builder.CreateBr(TheOnlyDest);
  261. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  262. if (IBI->getDestination(i) == TheOnlyDest)
  263. TheOnlyDest = nullptr;
  264. else
  265. IBI->getDestination(i)->removePredecessor(IBI->getParent());
  266. }
  267. Value *Address = IBI->getAddress();
  268. IBI->eraseFromParent();
  269. if (DeleteDeadConditions)
  270. RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
  271. // If we didn't find our destination in the IBI successor list, then we
  272. // have undefined behavior. Replace the unconditional branch with an
  273. // 'unreachable' instruction.
  274. if (TheOnlyDest) {
  275. BB->getTerminator()->eraseFromParent();
  276. new UnreachableInst(BB->getContext(), BB);
  277. }
  278. return true;
  279. }
  280. }
  281. return false;
  282. }
  283. //===----------------------------------------------------------------------===//
  284. // Local dead code elimination.
  285. //
  286. /// isInstructionTriviallyDead - Return true if the result produced by the
  287. /// instruction is not used, and the instruction has no side effects.
  288. ///
  289. bool llvm::isInstructionTriviallyDead(Instruction *I,
  290. const TargetLibraryInfo *TLI) {
  291. if (!I->use_empty())
  292. return false;
  293. return wouldInstructionBeTriviallyDead(I, TLI);
  294. }
  295. bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
  296. const TargetLibraryInfo *TLI) {
  297. if (isa<TerminatorInst>(I))
  298. return false;
  299. // We don't want the landingpad-like instructions removed by anything this
  300. // general.
  301. if (I->isEHPad())
  302. return false;
  303. // We don't want debug info removed by anything this general, unless
  304. // debug info is empty.
  305. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  306. if (DDI->getAddress())
  307. return false;
  308. return true;
  309. }
  310. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  311. if (DVI->getValue())
  312. return false;
  313. return true;
  314. }
  315. if (!I->mayHaveSideEffects())
  316. return true;
  317. // Special case intrinsics that "may have side effects" but can be deleted
  318. // when dead.
  319. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  320. // Safe to delete llvm.stacksave if dead.
  321. if (II->getIntrinsicID() == Intrinsic::stacksave)
  322. return true;
  323. // Lifetime intrinsics are dead when their right-hand is undef.
  324. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  325. II->getIntrinsicID() == Intrinsic::lifetime_end)
  326. return isa<UndefValue>(II->getArgOperand(1));
  327. // Assumptions are dead if their condition is trivially true. Guards on
  328. // true are operationally no-ops. In the future we can consider more
  329. // sophisticated tradeoffs for guards considering potential for check
  330. // widening, but for now we keep things simple.
  331. if (II->getIntrinsicID() == Intrinsic::assume ||
  332. II->getIntrinsicID() == Intrinsic::experimental_guard) {
  333. if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
  334. return !Cond->isZero();
  335. return false;
  336. }
  337. }
  338. if (isAllocLikeFn(I, TLI))
  339. return true;
  340. if (CallInst *CI = isFreeCall(I, TLI))
  341. if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
  342. return C->isNullValue() || isa<UndefValue>(C);
  343. if (CallSite CS = CallSite(I))
  344. if (isMathLibCallNoop(CS, TLI))
  345. return true;
  346. return false;
  347. }
  348. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  349. /// trivially dead instruction, delete it. If that makes any of its operands
  350. /// trivially dead, delete them too, recursively. Return true if any
  351. /// instructions were deleted.
  352. bool
  353. llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
  354. const TargetLibraryInfo *TLI) {
  355. Instruction *I = dyn_cast<Instruction>(V);
  356. if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
  357. return false;
  358. SmallVector<Instruction*, 16> DeadInsts;
  359. DeadInsts.push_back(I);
  360. do {
  361. I = DeadInsts.pop_back_val();
  362. // Null out all of the instruction's operands to see if any operand becomes
  363. // dead as we go.
  364. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  365. Value *OpV = I->getOperand(i);
  366. I->setOperand(i, nullptr);
  367. if (!OpV->use_empty()) continue;
  368. // If the operand is an instruction that became dead as we nulled out the
  369. // operand, and if it is 'trivially' dead, delete it in a future loop
  370. // iteration.
  371. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  372. if (isInstructionTriviallyDead(OpI, TLI))
  373. DeadInsts.push_back(OpI);
  374. }
  375. I->eraseFromParent();
  376. } while (!DeadInsts.empty());
  377. return true;
  378. }
  379. /// areAllUsesEqual - Check whether the uses of a value are all the same.
  380. /// This is similar to Instruction::hasOneUse() except this will also return
  381. /// true when there are no uses or multiple uses that all refer to the same
  382. /// value.
  383. static bool areAllUsesEqual(Instruction *I) {
  384. Value::user_iterator UI = I->user_begin();
  385. Value::user_iterator UE = I->user_end();
  386. if (UI == UE)
  387. return true;
  388. User *TheUse = *UI;
  389. for (++UI; UI != UE; ++UI) {
  390. if (*UI != TheUse)
  391. return false;
  392. }
  393. return true;
  394. }
  395. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  396. /// dead PHI node, due to being a def-use chain of single-use nodes that
  397. /// either forms a cycle or is terminated by a trivially dead instruction,
  398. /// delete it. If that makes any of its operands trivially dead, delete them
  399. /// too, recursively. Return true if a change was made.
  400. bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
  401. const TargetLibraryInfo *TLI) {
  402. SmallPtrSet<Instruction*, 4> Visited;
  403. for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
  404. I = cast<Instruction>(*I->user_begin())) {
  405. if (I->use_empty())
  406. return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  407. // If we find an instruction more than once, we're on a cycle that
  408. // won't prove fruitful.
  409. if (!Visited.insert(I).second) {
  410. // Break the cycle and delete the instruction and its operands.
  411. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  412. (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  413. return true;
  414. }
  415. }
  416. return false;
  417. }
  418. static bool
  419. simplifyAndDCEInstruction(Instruction *I,
  420. SmallSetVector<Instruction *, 16> &WorkList,
  421. const DataLayout &DL,
  422. const TargetLibraryInfo *TLI) {
  423. if (isInstructionTriviallyDead(I, TLI)) {
  424. // Null out all of the instruction's operands to see if any operand becomes
  425. // dead as we go.
  426. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  427. Value *OpV = I->getOperand(i);
  428. I->setOperand(i, nullptr);
  429. if (!OpV->use_empty() || I == OpV)
  430. continue;
  431. // If the operand is an instruction that became dead as we nulled out the
  432. // operand, and if it is 'trivially' dead, delete it in a future loop
  433. // iteration.
  434. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  435. if (isInstructionTriviallyDead(OpI, TLI))
  436. WorkList.insert(OpI);
  437. }
  438. I->eraseFromParent();
  439. return true;
  440. }
  441. if (Value *SimpleV = SimplifyInstruction(I, DL)) {
  442. // Add the users to the worklist. CAREFUL: an instruction can use itself,
  443. // in the case of a phi node.
  444. for (User *U : I->users()) {
  445. if (U != I) {
  446. WorkList.insert(cast<Instruction>(U));
  447. }
  448. }
  449. // Replace the instruction with its simplified value.
  450. bool Changed = false;
  451. if (!I->use_empty()) {
  452. I->replaceAllUsesWith(SimpleV);
  453. Changed = true;
  454. }
  455. if (isInstructionTriviallyDead(I, TLI)) {
  456. I->eraseFromParent();
  457. Changed = true;
  458. }
  459. return Changed;
  460. }
  461. return false;
  462. }
  463. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  464. /// simplify any instructions in it and recursively delete dead instructions.
  465. ///
  466. /// This returns true if it changed the code, note that it can delete
  467. /// instructions in other blocks as well in this block.
  468. bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
  469. const TargetLibraryInfo *TLI) {
  470. bool MadeChange = false;
  471. const DataLayout &DL = BB->getModule()->getDataLayout();
  472. #ifndef NDEBUG
  473. // In debug builds, ensure that the terminator of the block is never replaced
  474. // or deleted by these simplifications. The idea of simplification is that it
  475. // cannot introduce new instructions, and there is no way to replace the
  476. // terminator of a block without introducing a new instruction.
  477. AssertingVH<Instruction> TerminatorVH(&BB->back());
  478. #endif
  479. SmallSetVector<Instruction *, 16> WorkList;
  480. // Iterate over the original function, only adding insts to the worklist
  481. // if they actually need to be revisited. This avoids having to pre-init
  482. // the worklist with the entire function's worth of instructions.
  483. for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
  484. BI != E;) {
  485. assert(!BI->isTerminator());
  486. Instruction *I = &*BI;
  487. ++BI;
  488. // We're visiting this instruction now, so make sure it's not in the
  489. // worklist from an earlier visit.
  490. if (!WorkList.count(I))
  491. MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
  492. }
  493. while (!WorkList.empty()) {
  494. Instruction *I = WorkList.pop_back_val();
  495. MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
  496. }
  497. return MadeChange;
  498. }
  499. //===----------------------------------------------------------------------===//
  500. // Control Flow Graph Restructuring.
  501. //
  502. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  503. /// method is called when we're about to delete Pred as a predecessor of BB. If
  504. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  505. ///
  506. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  507. /// nodes that collapse into identity values. For example, if we have:
  508. /// x = phi(1, 0, 0, 0)
  509. /// y = and x, z
  510. ///
  511. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  512. /// recursively fold the and to 0.
  513. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) {
  514. // This only adjusts blocks with PHI nodes.
  515. if (!isa<PHINode>(BB->begin()))
  516. return;
  517. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  518. // them down. This will leave us with single entry phi nodes and other phis
  519. // that can be removed.
  520. BB->removePredecessor(Pred, true);
  521. WeakTrackingVH PhiIt = &BB->front();
  522. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  523. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  524. Value *OldPhiIt = PhiIt;
  525. if (!recursivelySimplifyInstruction(PN))
  526. continue;
  527. // If recursive simplification ended up deleting the next PHI node we would
  528. // iterate to, then our iterator is invalid, restart scanning from the top
  529. // of the block.
  530. if (PhiIt != OldPhiIt) PhiIt = &BB->front();
  531. }
  532. }
  533. /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
  534. /// predecessor is known to have one successor (DestBB!). Eliminate the edge
  535. /// between them, moving the instructions in the predecessor into DestBB and
  536. /// deleting the predecessor block.
  537. void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
  538. // If BB has single-entry PHI nodes, fold them.
  539. while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  540. Value *NewVal = PN->getIncomingValue(0);
  541. // Replace self referencing PHI with undef, it must be dead.
  542. if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
  543. PN->replaceAllUsesWith(NewVal);
  544. PN->eraseFromParent();
  545. }
  546. BasicBlock *PredBB = DestBB->getSinglePredecessor();
  547. assert(PredBB && "Block doesn't have a single predecessor!");
  548. // Zap anything that took the address of DestBB. Not doing this will give the
  549. // address an invalid value.
  550. if (DestBB->hasAddressTaken()) {
  551. BlockAddress *BA = BlockAddress::get(DestBB);
  552. Constant *Replacement =
  553. ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
  554. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  555. BA->getType()));
  556. BA->destroyConstant();
  557. }
  558. // Anything that branched to PredBB now branches to DestBB.
  559. PredBB->replaceAllUsesWith(DestBB);
  560. // Splice all the instructions from PredBB to DestBB.
  561. PredBB->getTerminator()->eraseFromParent();
  562. DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
  563. // If the PredBB is the entry block of the function, move DestBB up to
  564. // become the entry block after we erase PredBB.
  565. if (PredBB == &DestBB->getParent()->getEntryBlock())
  566. DestBB->moveAfter(PredBB);
  567. if (DT) {
  568. // For some irreducible CFG we end up having forward-unreachable blocks
  569. // so check if getNode returns a valid node before updating the domtree.
  570. if (DomTreeNode *DTN = DT->getNode(PredBB)) {
  571. BasicBlock *PredBBIDom = DTN->getIDom()->getBlock();
  572. DT->changeImmediateDominator(DestBB, PredBBIDom);
  573. DT->eraseNode(PredBB);
  574. }
  575. }
  576. // Nuke BB.
  577. PredBB->eraseFromParent();
  578. }
  579. /// CanMergeValues - Return true if we can choose one of these values to use
  580. /// in place of the other. Note that we will always choose the non-undef
  581. /// value to keep.
  582. static bool CanMergeValues(Value *First, Value *Second) {
  583. return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
  584. }
  585. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  586. /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
  587. ///
  588. /// Assumption: Succ is the single successor for BB.
  589. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  590. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  591. DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
  592. << Succ->getName() << "\n");
  593. // Shortcut, if there is only a single predecessor it must be BB and merging
  594. // is always safe
  595. if (Succ->getSinglePredecessor()) return true;
  596. // Make a list of the predecessors of BB
  597. SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  598. // Look at all the phi nodes in Succ, to see if they present a conflict when
  599. // merging these blocks
  600. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  601. PHINode *PN = cast<PHINode>(I);
  602. // If the incoming value from BB is again a PHINode in
  603. // BB which has the same incoming value for *PI as PN does, we can
  604. // merge the phi nodes and then the blocks can still be merged
  605. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  606. if (BBPN && BBPN->getParent() == BB) {
  607. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  608. BasicBlock *IBB = PN->getIncomingBlock(PI);
  609. if (BBPreds.count(IBB) &&
  610. !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
  611. PN->getIncomingValue(PI))) {
  612. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  613. << Succ->getName() << " is conflicting with "
  614. << BBPN->getName() << " with regard to common predecessor "
  615. << IBB->getName() << "\n");
  616. return false;
  617. }
  618. }
  619. } else {
  620. Value* Val = PN->getIncomingValueForBlock(BB);
  621. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  622. // See if the incoming value for the common predecessor is equal to the
  623. // one for BB, in which case this phi node will not prevent the merging
  624. // of the block.
  625. BasicBlock *IBB = PN->getIncomingBlock(PI);
  626. if (BBPreds.count(IBB) &&
  627. !CanMergeValues(Val, PN->getIncomingValue(PI))) {
  628. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  629. << Succ->getName() << " is conflicting with regard to common "
  630. << "predecessor " << IBB->getName() << "\n");
  631. return false;
  632. }
  633. }
  634. }
  635. }
  636. return true;
  637. }
  638. using PredBlockVector = SmallVector<BasicBlock *, 16>;
  639. using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
  640. /// \brief Determines the value to use as the phi node input for a block.
  641. ///
  642. /// Select between \p OldVal any value that we know flows from \p BB
  643. /// to a particular phi on the basis of which one (if either) is not
  644. /// undef. Update IncomingValues based on the selected value.
  645. ///
  646. /// \param OldVal The value we are considering selecting.
  647. /// \param BB The block that the value flows in from.
  648. /// \param IncomingValues A map from block-to-value for other phi inputs
  649. /// that we have examined.
  650. ///
  651. /// \returns the selected value.
  652. static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
  653. IncomingValueMap &IncomingValues) {
  654. if (!isa<UndefValue>(OldVal)) {
  655. assert((!IncomingValues.count(BB) ||
  656. IncomingValues.find(BB)->second == OldVal) &&
  657. "Expected OldVal to match incoming value from BB!");
  658. IncomingValues.insert(std::make_pair(BB, OldVal));
  659. return OldVal;
  660. }
  661. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  662. if (It != IncomingValues.end()) return It->second;
  663. return OldVal;
  664. }
  665. /// \brief Create a map from block to value for the operands of a
  666. /// given phi.
  667. ///
  668. /// Create a map from block to value for each non-undef value flowing
  669. /// into \p PN.
  670. ///
  671. /// \param PN The phi we are collecting the map for.
  672. /// \param IncomingValues [out] The map from block to value for this phi.
  673. static void gatherIncomingValuesToPhi(PHINode *PN,
  674. IncomingValueMap &IncomingValues) {
  675. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  676. BasicBlock *BB = PN->getIncomingBlock(i);
  677. Value *V = PN->getIncomingValue(i);
  678. if (!isa<UndefValue>(V))
  679. IncomingValues.insert(std::make_pair(BB, V));
  680. }
  681. }
  682. /// \brief Replace the incoming undef values to a phi with the values
  683. /// from a block-to-value map.
  684. ///
  685. /// \param PN The phi we are replacing the undefs in.
  686. /// \param IncomingValues A map from block to value.
  687. static void replaceUndefValuesInPhi(PHINode *PN,
  688. const IncomingValueMap &IncomingValues) {
  689. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  690. Value *V = PN->getIncomingValue(i);
  691. if (!isa<UndefValue>(V)) continue;
  692. BasicBlock *BB = PN->getIncomingBlock(i);
  693. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  694. if (It == IncomingValues.end()) continue;
  695. PN->setIncomingValue(i, It->second);
  696. }
  697. }
  698. /// \brief Replace a value flowing from a block to a phi with
  699. /// potentially multiple instances of that value flowing from the
  700. /// block's predecessors to the phi.
  701. ///
  702. /// \param BB The block with the value flowing into the phi.
  703. /// \param BBPreds The predecessors of BB.
  704. /// \param PN The phi that we are updating.
  705. static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
  706. const PredBlockVector &BBPreds,
  707. PHINode *PN) {
  708. Value *OldVal = PN->removeIncomingValue(BB, false);
  709. assert(OldVal && "No entry in PHI for Pred BB!");
  710. IncomingValueMap IncomingValues;
  711. // We are merging two blocks - BB, and the block containing PN - and
  712. // as a result we need to redirect edges from the predecessors of BB
  713. // to go to the block containing PN, and update PN
  714. // accordingly. Since we allow merging blocks in the case where the
  715. // predecessor and successor blocks both share some predecessors,
  716. // and where some of those common predecessors might have undef
  717. // values flowing into PN, we want to rewrite those values to be
  718. // consistent with the non-undef values.
  719. gatherIncomingValuesToPhi(PN, IncomingValues);
  720. // If this incoming value is one of the PHI nodes in BB, the new entries
  721. // in the PHI node are the entries from the old PHI.
  722. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  723. PHINode *OldValPN = cast<PHINode>(OldVal);
  724. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
  725. // Note that, since we are merging phi nodes and BB and Succ might
  726. // have common predecessors, we could end up with a phi node with
  727. // identical incoming branches. This will be cleaned up later (and
  728. // will trigger asserts if we try to clean it up now, without also
  729. // simplifying the corresponding conditional branch).
  730. BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
  731. Value *PredVal = OldValPN->getIncomingValue(i);
  732. Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
  733. IncomingValues);
  734. // And add a new incoming value for this predecessor for the
  735. // newly retargeted branch.
  736. PN->addIncoming(Selected, PredBB);
  737. }
  738. } else {
  739. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
  740. // Update existing incoming values in PN for this
  741. // predecessor of BB.
  742. BasicBlock *PredBB = BBPreds[i];
  743. Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
  744. IncomingValues);
  745. // And add a new incoming value for this predecessor for the
  746. // newly retargeted branch.
  747. PN->addIncoming(Selected, PredBB);
  748. }
  749. }
  750. replaceUndefValuesInPhi(PN, IncomingValues);
  751. }
  752. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  753. /// unconditional branch, and contains no instructions other than PHI nodes,
  754. /// potential side-effect free intrinsics and the branch. If possible,
  755. /// eliminate BB by rewriting all the predecessors to branch to the successor
  756. /// block and return true. If we can't transform, return false.
  757. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
  758. assert(BB != &BB->getParent()->getEntryBlock() &&
  759. "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
  760. // We can't eliminate infinite loops.
  761. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  762. if (BB == Succ) return false;
  763. // Check to see if merging these blocks would cause conflicts for any of the
  764. // phi nodes in BB or Succ. If not, we can safely merge.
  765. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  766. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  767. // has uses which will not disappear when the PHI nodes are merged. It is
  768. // possible to handle such cases, but difficult: it requires checking whether
  769. // BB dominates Succ, which is non-trivial to calculate in the case where
  770. // Succ has multiple predecessors. Also, it requires checking whether
  771. // constructing the necessary self-referential PHI node doesn't introduce any
  772. // conflicts; this isn't too difficult, but the previous code for doing this
  773. // was incorrect.
  774. //
  775. // Note that if this check finds a live use, BB dominates Succ, so BB is
  776. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  777. // folding the branch isn't profitable in that case anyway.
  778. if (!Succ->getSinglePredecessor()) {
  779. BasicBlock::iterator BBI = BB->begin();
  780. while (isa<PHINode>(*BBI)) {
  781. for (Use &U : BBI->uses()) {
  782. if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
  783. if (PN->getIncomingBlock(U) != BB)
  784. return false;
  785. } else {
  786. return false;
  787. }
  788. }
  789. ++BBI;
  790. }
  791. }
  792. DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
  793. if (isa<PHINode>(Succ->begin())) {
  794. // If there is more than one pred of succ, and there are PHI nodes in
  795. // the successor, then we need to add incoming edges for the PHI nodes
  796. //
  797. const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
  798. // Loop over all of the PHI nodes in the successor of BB.
  799. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  800. PHINode *PN = cast<PHINode>(I);
  801. redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
  802. }
  803. }
  804. if (Succ->getSinglePredecessor()) {
  805. // BB is the only predecessor of Succ, so Succ will end up with exactly
  806. // the same predecessors BB had.
  807. // Copy over any phi, debug or lifetime instruction.
  808. BB->getTerminator()->eraseFromParent();
  809. Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
  810. BB->getInstList());
  811. } else {
  812. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  813. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  814. assert(PN->use_empty() && "There shouldn't be any uses here!");
  815. PN->eraseFromParent();
  816. }
  817. }
  818. // If the unconditional branch we replaced contains llvm.loop metadata, we
  819. // add the metadata to the branch instructions in the predecessors.
  820. unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
  821. Instruction *TI = BB->getTerminator();
  822. if (TI)
  823. if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
  824. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  825. BasicBlock *Pred = *PI;
  826. Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
  827. }
  828. // Everything that jumped to BB now goes to Succ.
  829. BB->replaceAllUsesWith(Succ);
  830. if (!Succ->hasName()) Succ->takeName(BB);
  831. BB->eraseFromParent(); // Delete the old basic block.
  832. return true;
  833. }
  834. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  835. /// nodes in this block. This doesn't try to be clever about PHI nodes
  836. /// which differ only in the order of the incoming values, but instcombine
  837. /// orders them so it usually won't matter.
  838. bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
  839. // This implementation doesn't currently consider undef operands
  840. // specially. Theoretically, two phis which are identical except for
  841. // one having an undef where the other doesn't could be collapsed.
  842. struct PHIDenseMapInfo {
  843. static PHINode *getEmptyKey() {
  844. return DenseMapInfo<PHINode *>::getEmptyKey();
  845. }
  846. static PHINode *getTombstoneKey() {
  847. return DenseMapInfo<PHINode *>::getTombstoneKey();
  848. }
  849. static unsigned getHashValue(PHINode *PN) {
  850. // Compute a hash value on the operands. Instcombine will likely have
  851. // sorted them, which helps expose duplicates, but we have to check all
  852. // the operands to be safe in case instcombine hasn't run.
  853. return static_cast<unsigned>(hash_combine(
  854. hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
  855. hash_combine_range(PN->block_begin(), PN->block_end())));
  856. }
  857. static bool isEqual(PHINode *LHS, PHINode *RHS) {
  858. if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
  859. RHS == getEmptyKey() || RHS == getTombstoneKey())
  860. return LHS == RHS;
  861. return LHS->isIdenticalTo(RHS);
  862. }
  863. };
  864. // Set of unique PHINodes.
  865. DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
  866. // Examine each PHI.
  867. bool Changed = false;
  868. for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
  869. auto Inserted = PHISet.insert(PN);
  870. if (!Inserted.second) {
  871. // A duplicate. Replace this PHI with its duplicate.
  872. PN->replaceAllUsesWith(*Inserted.first);
  873. PN->eraseFromParent();
  874. Changed = true;
  875. // The RAUW can change PHIs that we already visited. Start over from the
  876. // beginning.
  877. PHISet.clear();
  878. I = BB->begin();
  879. }
  880. }
  881. return Changed;
  882. }
  883. /// enforceKnownAlignment - If the specified pointer points to an object that
  884. /// we control, modify the object's alignment to PrefAlign. This isn't
  885. /// often possible though. If alignment is important, a more reliable approach
  886. /// is to simply align all global variables and allocation instructions to
  887. /// their preferred alignment from the beginning.
  888. static unsigned enforceKnownAlignment(Value *V, unsigned Align,
  889. unsigned PrefAlign,
  890. const DataLayout &DL) {
  891. assert(PrefAlign > Align);
  892. V = V->stripPointerCasts();
  893. if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  894. // TODO: ideally, computeKnownBits ought to have used
  895. // AllocaInst::getAlignment() in its computation already, making
  896. // the below max redundant. But, as it turns out,
  897. // stripPointerCasts recurses through infinite layers of bitcasts,
  898. // while computeKnownBits is not allowed to traverse more than 6
  899. // levels.
  900. Align = std::max(AI->getAlignment(), Align);
  901. if (PrefAlign <= Align)
  902. return Align;
  903. // If the preferred alignment is greater than the natural stack alignment
  904. // then don't round up. This avoids dynamic stack realignment.
  905. if (DL.exceedsNaturalStackAlignment(PrefAlign))
  906. return Align;
  907. AI->setAlignment(PrefAlign);
  908. return PrefAlign;
  909. }
  910. if (auto *GO = dyn_cast<GlobalObject>(V)) {
  911. // TODO: as above, this shouldn't be necessary.
  912. Align = std::max(GO->getAlignment(), Align);
  913. if (PrefAlign <= Align)
  914. return Align;
  915. // If there is a large requested alignment and we can, bump up the alignment
  916. // of the global. If the memory we set aside for the global may not be the
  917. // memory used by the final program then it is impossible for us to reliably
  918. // enforce the preferred alignment.
  919. if (!GO->canIncreaseAlignment())
  920. return Align;
  921. GO->setAlignment(PrefAlign);
  922. return PrefAlign;
  923. }
  924. return Align;
  925. }
  926. unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
  927. const DataLayout &DL,
  928. const Instruction *CxtI,
  929. AssumptionCache *AC,
  930. const DominatorTree *DT) {
  931. assert(V->getType()->isPointerTy() &&
  932. "getOrEnforceKnownAlignment expects a pointer!");
  933. KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
  934. unsigned TrailZ = Known.countMinTrailingZeros();
  935. // Avoid trouble with ridiculously large TrailZ values, such as
  936. // those computed from a null pointer.
  937. TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
  938. unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
  939. // LLVM doesn't support alignments larger than this currently.
  940. Align = std::min(Align, +Value::MaximumAlignment);
  941. if (PrefAlign > Align)
  942. Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
  943. // We don't need to make any adjustment.
  944. return Align;
  945. }
  946. ///===---------------------------------------------------------------------===//
  947. /// Dbg Intrinsic utilities
  948. ///
  949. /// See if there is a dbg.value intrinsic for DIVar before I.
  950. static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
  951. Instruction *I) {
  952. // Since we can't guarantee that the original dbg.declare instrinsic
  953. // is removed by LowerDbgDeclare(), we need to make sure that we are
  954. // not inserting the same dbg.value intrinsic over and over.
  955. BasicBlock::InstListType::iterator PrevI(I);
  956. if (PrevI != I->getParent()->getInstList().begin()) {
  957. --PrevI;
  958. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
  959. if (DVI->getValue() == I->getOperand(0) &&
  960. DVI->getVariable() == DIVar &&
  961. DVI->getExpression() == DIExpr)
  962. return true;
  963. }
  964. return false;
  965. }
  966. /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
  967. static bool PhiHasDebugValue(DILocalVariable *DIVar,
  968. DIExpression *DIExpr,
  969. PHINode *APN) {
  970. // Since we can't guarantee that the original dbg.declare instrinsic
  971. // is removed by LowerDbgDeclare(), we need to make sure that we are
  972. // not inserting the same dbg.value intrinsic over and over.
  973. SmallVector<DbgValueInst *, 1> DbgValues;
  974. findDbgValues(DbgValues, APN);
  975. for (auto *DVI : DbgValues) {
  976. assert(DVI->getValue() == APN);
  977. if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
  978. return true;
  979. }
  980. return false;
  981. }
  982. /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
  983. /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
  984. void llvm::ConvertDebugDeclareToDebugValue(DbgInfoIntrinsic *DII,
  985. StoreInst *SI, DIBuilder &Builder) {
  986. assert(DII->isAddressOfVariable());
  987. auto *DIVar = DII->getVariable();
  988. assert(DIVar && "Missing variable");
  989. auto *DIExpr = DII->getExpression();
  990. Value *DV = SI->getOperand(0);
  991. // If an argument is zero extended then use argument directly. The ZExt
  992. // may be zapped by an optimization pass in future.
  993. Argument *ExtendedArg = nullptr;
  994. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  995. ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
  996. if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  997. ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
  998. if (ExtendedArg) {
  999. // If this DII was already describing only a fragment of a variable, ensure
  1000. // that fragment is appropriately narrowed here.
  1001. // But if a fragment wasn't used, describe the value as the original
  1002. // argument (rather than the zext or sext) so that it remains described even
  1003. // if the sext/zext is optimized away. This widens the variable description,
  1004. // leaving it up to the consumer to know how the smaller value may be
  1005. // represented in a larger register.
  1006. if (auto Fragment = DIExpr->getFragmentInfo()) {
  1007. unsigned FragmentOffset = Fragment->OffsetInBits;
  1008. SmallVector<uint64_t, 3> Ops(DIExpr->elements_begin(),
  1009. DIExpr->elements_end() - 3);
  1010. Ops.push_back(dwarf::DW_OP_LLVM_fragment);
  1011. Ops.push_back(FragmentOffset);
  1012. const DataLayout &DL = DII->getModule()->getDataLayout();
  1013. Ops.push_back(DL.getTypeSizeInBits(ExtendedArg->getType()));
  1014. DIExpr = Builder.createExpression(Ops);
  1015. }
  1016. DV = ExtendedArg;
  1017. }
  1018. if (!LdStHasDebugValue(DIVar, DIExpr, SI))
  1019. Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
  1020. SI);
  1021. }
  1022. /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
  1023. /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
  1024. void llvm::ConvertDebugDeclareToDebugValue(DbgInfoIntrinsic *DII,
  1025. LoadInst *LI, DIBuilder &Builder) {
  1026. auto *DIVar = DII->getVariable();
  1027. auto *DIExpr = DII->getExpression();
  1028. assert(DIVar && "Missing variable");
  1029. if (LdStHasDebugValue(DIVar, DIExpr, LI))
  1030. return;
  1031. // We are now tracking the loaded value instead of the address. In the
  1032. // future if multi-location support is added to the IR, it might be
  1033. // preferable to keep tracking both the loaded value and the original
  1034. // address in case the alloca can not be elided.
  1035. Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
  1036. LI, DIVar, DIExpr, DII->getDebugLoc(), (Instruction *)nullptr);
  1037. DbgValue->insertAfter(LI);
  1038. }
  1039. /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
  1040. /// llvm.dbg.declare or llvm.dbg.addr intrinsic.
  1041. void llvm::ConvertDebugDeclareToDebugValue(DbgInfoIntrinsic *DII,
  1042. PHINode *APN, DIBuilder &Builder) {
  1043. auto *DIVar = DII->getVariable();
  1044. auto *DIExpr = DII->getExpression();
  1045. assert(DIVar && "Missing variable");
  1046. if (PhiHasDebugValue(DIVar, DIExpr, APN))
  1047. return;
  1048. BasicBlock *BB = APN->getParent();
  1049. auto InsertionPt = BB->getFirstInsertionPt();
  1050. // The block may be a catchswitch block, which does not have a valid
  1051. // insertion point.
  1052. // FIXME: Insert dbg.value markers in the successors when appropriate.
  1053. if (InsertionPt != BB->end())
  1054. Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, DII->getDebugLoc(),
  1055. &*InsertionPt);
  1056. }
  1057. /// Determine whether this alloca is either a VLA or an array.
  1058. static bool isArray(AllocaInst *AI) {
  1059. return AI->isArrayAllocation() ||
  1060. AI->getType()->getElementType()->isArrayTy();
  1061. }
  1062. /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
  1063. /// of llvm.dbg.value intrinsics.
  1064. bool llvm::LowerDbgDeclare(Function &F) {
  1065. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  1066. SmallVector<DbgDeclareInst *, 4> Dbgs;
  1067. for (auto &FI : F)
  1068. for (Instruction &BI : FI)
  1069. if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
  1070. Dbgs.push_back(DDI);
  1071. if (Dbgs.empty())
  1072. return false;
  1073. for (auto &I : Dbgs) {
  1074. DbgDeclareInst *DDI = I;
  1075. AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
  1076. // If this is an alloca for a scalar variable, insert a dbg.value
  1077. // at each load and store to the alloca and erase the dbg.declare.
  1078. // The dbg.values allow tracking a variable even if it is not
  1079. // stored on the stack, while the dbg.declare can only describe
  1080. // the stack slot (and at a lexical-scope granularity). Later
  1081. // passes will attempt to elide the stack slot.
  1082. if (AI && !isArray(AI)) {
  1083. for (auto &AIUse : AI->uses()) {
  1084. User *U = AIUse.getUser();
  1085. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  1086. if (AIUse.getOperandNo() == 1)
  1087. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  1088. } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1089. ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
  1090. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  1091. // This is a call by-value or some other instruction that
  1092. // takes a pointer to the variable. Insert a *value*
  1093. // intrinsic that describes the alloca.
  1094. DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(),
  1095. DDI->getExpression(), DDI->getDebugLoc(),
  1096. CI);
  1097. }
  1098. }
  1099. DDI->eraseFromParent();
  1100. }
  1101. }
  1102. return true;
  1103. }
  1104. /// Finds all intrinsics declaring local variables as living in the memory that
  1105. /// 'V' points to. This may include a mix of dbg.declare and
  1106. /// dbg.addr intrinsics.
  1107. TinyPtrVector<DbgInfoIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
  1108. auto *L = LocalAsMetadata::getIfExists(V);
  1109. if (!L)
  1110. return {};
  1111. auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
  1112. if (!MDV)
  1113. return {};
  1114. TinyPtrVector<DbgInfoIntrinsic *> Declares;
  1115. for (User *U : MDV->users()) {
  1116. if (auto *DII = dyn_cast<DbgInfoIntrinsic>(U))
  1117. if (DII->isAddressOfVariable())
  1118. Declares.push_back(DII);
  1119. }
  1120. return Declares;
  1121. }
  1122. void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
  1123. if (auto *L = LocalAsMetadata::getIfExists(V))
  1124. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
  1125. for (User *U : MDV->users())
  1126. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  1127. DbgValues.push_back(DVI);
  1128. }
  1129. static void findDbgUsers(SmallVectorImpl<DbgInfoIntrinsic *> &DbgUsers,
  1130. Value *V) {
  1131. if (auto *L = LocalAsMetadata::getIfExists(V))
  1132. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
  1133. for (User *U : MDV->users())
  1134. if (DbgInfoIntrinsic *DII = dyn_cast<DbgInfoIntrinsic>(U))
  1135. DbgUsers.push_back(DII);
  1136. }
  1137. bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
  1138. Instruction *InsertBefore, DIBuilder &Builder,
  1139. bool DerefBefore, int Offset, bool DerefAfter) {
  1140. auto DbgAddrs = FindDbgAddrUses(Address);
  1141. for (DbgInfoIntrinsic *DII : DbgAddrs) {
  1142. DebugLoc Loc = DII->getDebugLoc();
  1143. auto *DIVar = DII->getVariable();
  1144. auto *DIExpr = DII->getExpression();
  1145. assert(DIVar && "Missing variable");
  1146. DIExpr = DIExpression::prepend(DIExpr, DerefBefore, Offset, DerefAfter);
  1147. // Insert llvm.dbg.declare immediately after InsertBefore, and remove old
  1148. // llvm.dbg.declare.
  1149. Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
  1150. if (DII == InsertBefore)
  1151. InsertBefore = &*std::next(InsertBefore->getIterator());
  1152. DII->eraseFromParent();
  1153. }
  1154. return !DbgAddrs.empty();
  1155. }
  1156. bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  1157. DIBuilder &Builder, bool DerefBefore,
  1158. int Offset, bool DerefAfter) {
  1159. return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
  1160. DerefBefore, Offset, DerefAfter);
  1161. }
  1162. static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
  1163. DIBuilder &Builder, int Offset) {
  1164. DebugLoc Loc = DVI->getDebugLoc();
  1165. auto *DIVar = DVI->getVariable();
  1166. auto *DIExpr = DVI->getExpression();
  1167. assert(DIVar && "Missing variable");
  1168. // This is an alloca-based llvm.dbg.value. The first thing it should do with
  1169. // the alloca pointer is dereference it. Otherwise we don't know how to handle
  1170. // it and give up.
  1171. if (!DIExpr || DIExpr->getNumElements() < 1 ||
  1172. DIExpr->getElement(0) != dwarf::DW_OP_deref)
  1173. return;
  1174. // Insert the offset immediately after the first deref.
  1175. // We could just change the offset argument of dbg.value, but it's unsigned...
  1176. if (Offset) {
  1177. SmallVector<uint64_t, 4> Ops;
  1178. Ops.push_back(dwarf::DW_OP_deref);
  1179. DIExpression::appendOffset(Ops, Offset);
  1180. Ops.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
  1181. DIExpr = Builder.createExpression(Ops);
  1182. }
  1183. Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
  1184. DVI->eraseFromParent();
  1185. }
  1186. void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  1187. DIBuilder &Builder, int Offset) {
  1188. if (auto *L = LocalAsMetadata::getIfExists(AI))
  1189. if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
  1190. for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
  1191. Use &U = *UI++;
  1192. if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
  1193. replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
  1194. }
  1195. }
  1196. void llvm::salvageDebugInfo(Instruction &I) {
  1197. SmallVector<DbgValueInst *, 1> DbgValues;
  1198. auto &M = *I.getModule();
  1199. auto wrapMD = [&](Value *V) {
  1200. return MetadataAsValue::get(I.getContext(), ValueAsMetadata::get(V));
  1201. };
  1202. auto applyOffset = [&](DbgValueInst *DVI, uint64_t Offset) {
  1203. auto *DIExpr = DVI->getExpression();
  1204. DIExpr = DIExpression::prepend(DIExpr, DIExpression::NoDeref, Offset,
  1205. DIExpression::NoDeref,
  1206. DIExpression::WithStackValue);
  1207. DVI->setOperand(0, wrapMD(I.getOperand(0)));
  1208. DVI->setOperand(2, MetadataAsValue::get(I.getContext(), DIExpr));
  1209. DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n');
  1210. };
  1211. if (isa<BitCastInst>(&I) || isa<IntToPtrInst>(&I)) {
  1212. // Bitcasts are entirely irrelevant for debug info. Rewrite dbg.value,
  1213. // dbg.addr, and dbg.declare to use the cast's source.
  1214. SmallVector<DbgInfoIntrinsic *, 1> DbgUsers;
  1215. findDbgUsers(DbgUsers, &I);
  1216. for (auto *DII : DbgUsers) {
  1217. DII->setOperand(0, wrapMD(I.getOperand(0)));
  1218. DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
  1219. }
  1220. } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  1221. findDbgValues(DbgValues, &I);
  1222. for (auto *DVI : DbgValues) {
  1223. unsigned BitWidth =
  1224. M.getDataLayout().getPointerSizeInBits(GEP->getPointerAddressSpace());
  1225. APInt Offset(BitWidth, 0);
  1226. // Rewrite a constant GEP into a DIExpression. Since we are performing
  1227. // arithmetic to compute the variable's *value* in the DIExpression, we
  1228. // need to mark the expression with a DW_OP_stack_value.
  1229. if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset))
  1230. // GEP offsets are i32 and thus always fit into an int64_t.
  1231. applyOffset(DVI, Offset.getSExtValue());
  1232. }
  1233. } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
  1234. if (BI->getOpcode() == Instruction::Add)
  1235. if (auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1)))
  1236. if (ConstInt->getBitWidth() <= 64) {
  1237. APInt Offset = ConstInt->getValue();
  1238. findDbgValues(DbgValues, &I);
  1239. for (auto *DVI : DbgValues)
  1240. applyOffset(DVI, Offset.getSExtValue());
  1241. }
  1242. } else if (isa<LoadInst>(&I)) {
  1243. findDbgValues(DbgValues, &I);
  1244. for (auto *DVI : DbgValues) {
  1245. // Rewrite the load into DW_OP_deref.
  1246. auto *DIExpr = DVI->getExpression();
  1247. DIExpr = DIExpression::prepend(DIExpr, DIExpression::WithDeref);
  1248. DVI->setOperand(0, wrapMD(I.getOperand(0)));
  1249. DVI->setOperand(2, MetadataAsValue::get(I.getContext(), DIExpr));
  1250. DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n');
  1251. }
  1252. }
  1253. }
  1254. unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
  1255. unsigned NumDeadInst = 0;
  1256. // Delete the instructions backwards, as it has a reduced likelihood of
  1257. // having to update as many def-use and use-def chains.
  1258. Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
  1259. while (EndInst != &BB->front()) {
  1260. // Delete the next to last instruction.
  1261. Instruction *Inst = &*--EndInst->getIterator();
  1262. if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
  1263. Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
  1264. if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
  1265. EndInst = Inst;
  1266. continue;
  1267. }
  1268. if (!isa<DbgInfoIntrinsic>(Inst))
  1269. ++NumDeadInst;
  1270. Inst->eraseFromParent();
  1271. }
  1272. return NumDeadInst;
  1273. }
  1274. unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
  1275. bool PreserveLCSSA) {
  1276. BasicBlock *BB = I->getParent();
  1277. // Loop over all of the successors, removing BB's entry from any PHI
  1278. // nodes.
  1279. for (BasicBlock *Successor : successors(BB))
  1280. Successor->removePredecessor(BB, PreserveLCSSA);
  1281. // Insert a call to llvm.trap right before this. This turns the undefined
  1282. // behavior into a hard fail instead of falling through into random code.
  1283. if (UseLLVMTrap) {
  1284. Function *TrapFn =
  1285. Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
  1286. CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
  1287. CallTrap->setDebugLoc(I->getDebugLoc());
  1288. }
  1289. new UnreachableInst(I->getContext(), I);
  1290. // All instructions after this are dead.
  1291. unsigned NumInstrsRemoved = 0;
  1292. BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
  1293. while (BBI != BBE) {
  1294. if (!BBI->use_empty())
  1295. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  1296. BB->getInstList().erase(BBI++);
  1297. ++NumInstrsRemoved;
  1298. }
  1299. return NumInstrsRemoved;
  1300. }
  1301. /// changeToCall - Convert the specified invoke into a normal call.
  1302. static void changeToCall(InvokeInst *II) {
  1303. SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
  1304. SmallVector<OperandBundleDef, 1> OpBundles;
  1305. II->getOperandBundlesAsDefs(OpBundles);
  1306. CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
  1307. "", II);
  1308. NewCall->takeName(II);
  1309. NewCall->setCallingConv(II->getCallingConv());
  1310. NewCall->setAttributes(II->getAttributes());
  1311. NewCall->setDebugLoc(II->getDebugLoc());
  1312. II->replaceAllUsesWith(NewCall);
  1313. // Follow the call by a branch to the normal destination.
  1314. BranchInst::Create(II->getNormalDest(), II);
  1315. // Update PHI nodes in the unwind destination
  1316. II->getUnwindDest()->removePredecessor(II->getParent());
  1317. II->eraseFromParent();
  1318. }
  1319. BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
  1320. BasicBlock *UnwindEdge) {
  1321. BasicBlock *BB = CI->getParent();
  1322. // Convert this function call into an invoke instruction. First, split the
  1323. // basic block.
  1324. BasicBlock *Split =
  1325. BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
  1326. // Delete the unconditional branch inserted by splitBasicBlock
  1327. BB->getInstList().pop_back();
  1328. // Create the new invoke instruction.
  1329. SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
  1330. SmallVector<OperandBundleDef, 1> OpBundles;
  1331. CI->getOperandBundlesAsDefs(OpBundles);
  1332. // Note: we're round tripping operand bundles through memory here, and that
  1333. // can potentially be avoided with a cleverer API design that we do not have
  1334. // as of this time.
  1335. InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge,
  1336. InvokeArgs, OpBundles, CI->getName(), BB);
  1337. II->setDebugLoc(CI->getDebugLoc());
  1338. II->setCallingConv(CI->getCallingConv());
  1339. II->setAttributes(CI->getAttributes());
  1340. // Make sure that anything using the call now uses the invoke! This also
  1341. // updates the CallGraph if present, because it uses a WeakTrackingVH.
  1342. CI->replaceAllUsesWith(II);
  1343. // Delete the original call
  1344. Split->getInstList().pop_front();
  1345. return Split;
  1346. }
  1347. static bool markAliveBlocks(Function &F,
  1348. SmallPtrSetImpl<BasicBlock*> &Reachable) {
  1349. SmallVector<BasicBlock*, 128> Worklist;
  1350. BasicBlock *BB = &F.front();
  1351. Worklist.push_back(BB);
  1352. Reachable.insert(BB);
  1353. bool Changed = false;
  1354. do {
  1355. BB = Worklist.pop_back_val();
  1356. // Do a quick scan of the basic block, turning any obviously unreachable
  1357. // instructions into LLVM unreachable insts. The instruction combining pass
  1358. // canonicalizes unreachable insts into stores to null or undef.
  1359. for (Instruction &I : *BB) {
  1360. // Assumptions that are known to be false are equivalent to unreachable.
  1361. // Also, if the condition is undefined, then we make the choice most
  1362. // beneficial to the optimizer, and choose that to also be unreachable.
  1363. if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
  1364. if (II->getIntrinsicID() == Intrinsic::assume) {
  1365. if (match(II->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
  1366. // Don't insert a call to llvm.trap right before the unreachable.
  1367. changeToUnreachable(II, false);
  1368. Changed = true;
  1369. break;
  1370. }
  1371. }
  1372. if (II->getIntrinsicID() == Intrinsic::experimental_guard) {
  1373. // A call to the guard intrinsic bails out of the current compilation
  1374. // unit if the predicate passed to it is false. If the predicate is a
  1375. // constant false, then we know the guard will bail out of the current
  1376. // compile unconditionally, so all code following it is dead.
  1377. //
  1378. // Note: unlike in llvm.assume, it is not "obviously profitable" for
  1379. // guards to treat `undef` as `false` since a guard on `undef` can
  1380. // still be useful for widening.
  1381. if (match(II->getArgOperand(0), m_Zero()))
  1382. if (!isa<UnreachableInst>(II->getNextNode())) {
  1383. changeToUnreachable(II->getNextNode(), /*UseLLVMTrap=*/ false);
  1384. Changed = true;
  1385. break;
  1386. }
  1387. }
  1388. }
  1389. if (auto *CI = dyn_cast<CallInst>(&I)) {
  1390. Value *Callee = CI->getCalledValue();
  1391. if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
  1392. changeToUnreachable(CI, /*UseLLVMTrap=*/false);
  1393. Changed = true;
  1394. break;
  1395. }
  1396. if (CI->doesNotReturn()) {
  1397. // If we found a call to a no-return function, insert an unreachable
  1398. // instruction after it. Make sure there isn't *already* one there
  1399. // though.
  1400. if (!isa<UnreachableInst>(CI->getNextNode())) {
  1401. // Don't insert a call to llvm.trap right before the unreachable.
  1402. changeToUnreachable(CI->getNextNode(), false);
  1403. Changed = true;
  1404. }
  1405. break;
  1406. }
  1407. }
  1408. // Store to undef and store to null are undefined and used to signal that
  1409. // they should be changed to unreachable by passes that can't modify the
  1410. // CFG.
  1411. if (auto *SI = dyn_cast<StoreInst>(&I)) {
  1412. // Don't touch volatile stores.
  1413. if (SI->isVolatile()) continue;
  1414. Value *Ptr = SI->getOperand(1);
  1415. if (isa<UndefValue>(Ptr) ||
  1416. (isa<ConstantPointerNull>(Ptr) &&
  1417. SI->getPointerAddressSpace() == 0)) {
  1418. changeToUnreachable(SI, true);
  1419. Changed = true;
  1420. break;
  1421. }
  1422. }
  1423. }
  1424. TerminatorInst *Terminator = BB->getTerminator();
  1425. if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
  1426. // Turn invokes that call 'nounwind' functions into ordinary calls.
  1427. Value *Callee = II->getCalledValue();
  1428. if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
  1429. changeToUnreachable(II, true);
  1430. Changed = true;
  1431. } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
  1432. if (II->use_empty() && II->onlyReadsMemory()) {
  1433. // jump to the normal destination branch.
  1434. BranchInst::Create(II->getNormalDest(), II);
  1435. II->getUnwindDest()->removePredecessor(II->getParent());
  1436. II->eraseFromParent();
  1437. } else
  1438. changeToCall(II);
  1439. Changed = true;
  1440. }
  1441. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
  1442. // Remove catchpads which cannot be reached.
  1443. struct CatchPadDenseMapInfo {
  1444. static CatchPadInst *getEmptyKey() {
  1445. return DenseMapInfo<CatchPadInst *>::getEmptyKey();
  1446. }
  1447. static CatchPadInst *getTombstoneKey() {
  1448. return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
  1449. }
  1450. static unsigned getHashValue(CatchPadInst *CatchPad) {
  1451. return static_cast<unsigned>(hash_combine_range(
  1452. CatchPad->value_op_begin(), CatchPad->value_op_end()));
  1453. }
  1454. static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
  1455. if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
  1456. RHS == getEmptyKey() || RHS == getTombstoneKey())
  1457. return LHS == RHS;
  1458. return LHS->isIdenticalTo(RHS);
  1459. }
  1460. };
  1461. // Set of unique CatchPads.
  1462. SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
  1463. CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
  1464. HandlerSet;
  1465. detail::DenseSetEmpty Empty;
  1466. for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
  1467. E = CatchSwitch->handler_end();
  1468. I != E; ++I) {
  1469. BasicBlock *HandlerBB = *I;
  1470. auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
  1471. if (!HandlerSet.insert({CatchPad, Empty}).second) {
  1472. CatchSwitch->removeHandler(I);
  1473. --I;
  1474. --E;
  1475. Changed = true;
  1476. }
  1477. }
  1478. }
  1479. Changed |= ConstantFoldTerminator(BB, true);
  1480. for (BasicBlock *Successor : successors(BB))
  1481. if (Reachable.insert(Successor).second)
  1482. Worklist.push_back(Successor);
  1483. } while (!Worklist.empty());
  1484. return Changed;
  1485. }
  1486. void llvm::removeUnwindEdge(BasicBlock *BB) {
  1487. TerminatorInst *TI = BB->getTerminator();
  1488. if (auto *II = dyn_cast<InvokeInst>(TI)) {
  1489. changeToCall(II);
  1490. return;
  1491. }
  1492. TerminatorInst *NewTI;
  1493. BasicBlock *UnwindDest;
  1494. if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
  1495. NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
  1496. UnwindDest = CRI->getUnwindDest();
  1497. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
  1498. auto *NewCatchSwitch = CatchSwitchInst::Create(
  1499. CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
  1500. CatchSwitch->getName(), CatchSwitch);
  1501. for (BasicBlock *PadBB : CatchSwitch->handlers())
  1502. NewCatchSwitch->addHandler(PadBB);
  1503. NewTI = NewCatchSwitch;
  1504. UnwindDest = CatchSwitch->getUnwindDest();
  1505. } else {
  1506. llvm_unreachable("Could not find unwind successor");
  1507. }
  1508. NewTI->takeName(TI);
  1509. NewTI->setDebugLoc(TI->getDebugLoc());
  1510. UnwindDest->removePredecessor(BB);
  1511. TI->replaceAllUsesWith(NewTI);
  1512. TI->eraseFromParent();
  1513. }
  1514. /// removeUnreachableBlocks - Remove blocks that are not reachable, even
  1515. /// if they are in a dead cycle. Return true if a change was made, false
  1516. /// otherwise. If `LVI` is passed, this function preserves LazyValueInfo
  1517. /// after modifying the CFG.
  1518. bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI) {
  1519. SmallPtrSet<BasicBlock*, 16> Reachable;
  1520. bool Changed = markAliveBlocks(F, Reachable);
  1521. // If there are unreachable blocks in the CFG...
  1522. if (Reachable.size() == F.size())
  1523. return Changed;
  1524. assert(Reachable.size() < F.size());
  1525. NumRemoved += F.size()-Reachable.size();
  1526. // Loop over all of the basic blocks that are not reachable, dropping all of
  1527. // their internal references...
  1528. for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
  1529. if (Reachable.count(&*BB))
  1530. continue;
  1531. for (BasicBlock *Successor : successors(&*BB))
  1532. if (Reachable.count(Successor))
  1533. Successor->removePredecessor(&*BB);
  1534. if (LVI)
  1535. LVI->eraseBlock(&*BB);
  1536. BB->dropAllReferences();
  1537. }
  1538. for (Function::iterator I = ++F.begin(); I != F.end();)
  1539. if (!Reachable.count(&*I))
  1540. I = F.getBasicBlockList().erase(I);
  1541. else
  1542. ++I;
  1543. return true;
  1544. }
  1545. void llvm::combineMetadata(Instruction *K, const Instruction *J,
  1546. ArrayRef<unsigned> KnownIDs) {
  1547. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  1548. K->dropUnknownNonDebugMetadata(KnownIDs);
  1549. K->getAllMetadataOtherThanDebugLoc(Metadata);
  1550. for (const auto &MD : Metadata) {
  1551. unsigned Kind = MD.first;
  1552. MDNode *JMD = J->getMetadata(Kind);
  1553. MDNode *KMD = MD.second;
  1554. switch (Kind) {
  1555. default:
  1556. K->setMetadata(Kind, nullptr); // Remove unknown metadata
  1557. break;
  1558. case LLVMContext::MD_dbg:
  1559. llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
  1560. case LLVMContext::MD_tbaa:
  1561. K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
  1562. break;
  1563. case LLVMContext::MD_alias_scope:
  1564. K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
  1565. break;
  1566. case LLVMContext::MD_noalias:
  1567. case LLVMContext::MD_mem_parallel_loop_access:
  1568. K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
  1569. break;
  1570. case LLVMContext::MD_range:
  1571. K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
  1572. break;
  1573. case LLVMContext::MD_fpmath:
  1574. K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
  1575. break;
  1576. case LLVMContext::MD_invariant_load:
  1577. // Only set the !invariant.load if it is present in both instructions.
  1578. K->setMetadata(Kind, JMD);
  1579. break;
  1580. case LLVMContext::MD_nonnull:
  1581. // Only set the !nonnull if it is present in both instructions.
  1582. K->setMetadata(Kind, JMD);
  1583. break;
  1584. case LLVMContext::MD_invariant_group:
  1585. // Preserve !invariant.group in K.
  1586. break;
  1587. case LLVMContext::MD_align:
  1588. K->setMetadata(Kind,
  1589. MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
  1590. break;
  1591. case LLVMContext::MD_dereferenceable:
  1592. case LLVMContext::MD_dereferenceable_or_null:
  1593. K->setMetadata(Kind,
  1594. MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
  1595. break;
  1596. }
  1597. }
  1598. // Set !invariant.group from J if J has it. If both instructions have it
  1599. // then we will just pick it from J - even when they are different.
  1600. // Also make sure that K is load or store - f.e. combining bitcast with load
  1601. // could produce bitcast with invariant.group metadata, which is invalid.
  1602. // FIXME: we should try to preserve both invariant.group md if they are
  1603. // different, but right now instruction can only have one invariant.group.
  1604. if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
  1605. if (isa<LoadInst>(K) || isa<StoreInst>(K))
  1606. K->setMetadata(LLVMContext::MD_invariant_group, JMD);
  1607. }
  1608. void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J) {
  1609. unsigned KnownIDs[] = {
  1610. LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  1611. LLVMContext::MD_noalias, LLVMContext::MD_range,
  1612. LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
  1613. LLVMContext::MD_invariant_group, LLVMContext::MD_align,
  1614. LLVMContext::MD_dereferenceable,
  1615. LLVMContext::MD_dereferenceable_or_null};
  1616. combineMetadata(K, J, KnownIDs);
  1617. }
  1618. template <typename RootType, typename DominatesFn>
  1619. static unsigned replaceDominatedUsesWith(Value *From, Value *To,
  1620. const RootType &Root,
  1621. const DominatesFn &Dominates) {
  1622. assert(From->getType() == To->getType());
  1623. unsigned Count = 0;
  1624. for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
  1625. UI != UE;) {
  1626. Use &U = *UI++;
  1627. if (!Dominates(Root, U))
  1628. continue;
  1629. U.set(To);
  1630. DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as "
  1631. << *To << " in " << *U << "\n");
  1632. ++Count;
  1633. }
  1634. return Count;
  1635. }
  1636. unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
  1637. assert(From->getType() == To->getType());
  1638. auto *BB = From->getParent();
  1639. unsigned Count = 0;
  1640. for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
  1641. UI != UE;) {
  1642. Use &U = *UI++;
  1643. auto *I = cast<Instruction>(U.getUser());
  1644. if (I->getParent() == BB)
  1645. continue;
  1646. U.set(To);
  1647. ++Count;
  1648. }
  1649. return Count;
  1650. }
  1651. unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
  1652. DominatorTree &DT,
  1653. const BasicBlockEdge &Root) {
  1654. auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
  1655. return DT.dominates(Root, U);
  1656. };
  1657. return ::replaceDominatedUsesWith(From, To, Root, Dominates);
  1658. }
  1659. unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
  1660. DominatorTree &DT,
  1661. const BasicBlock *BB) {
  1662. auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
  1663. auto *I = cast<Instruction>(U.getUser())->getParent();
  1664. return DT.properlyDominates(BB, I);
  1665. };
  1666. return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
  1667. }
  1668. bool llvm::callsGCLeafFunction(ImmutableCallSite CS,
  1669. const TargetLibraryInfo &TLI) {
  1670. // Check if the function is specifically marked as a gc leaf function.
  1671. if (CS.hasFnAttr("gc-leaf-function"))
  1672. return true;
  1673. if (const Function *F = CS.getCalledFunction()) {
  1674. if (F->hasFnAttribute("gc-leaf-function"))
  1675. return true;
  1676. if (auto IID = F->getIntrinsicID())
  1677. // Most LLVM intrinsics do not take safepoints.
  1678. return IID != Intrinsic::experimental_gc_statepoint &&
  1679. IID != Intrinsic::experimental_deoptimize;
  1680. }
  1681. // Lib calls can be materialized by some passes, and won't be
  1682. // marked as 'gc-leaf-function.' All available Libcalls are
  1683. // GC-leaf.
  1684. LibFunc LF;
  1685. if (TLI.getLibFunc(CS, LF)) {
  1686. return TLI.has(LF);
  1687. }
  1688. return false;
  1689. }
  1690. void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
  1691. LoadInst &NewLI) {
  1692. auto *NewTy = NewLI.getType();
  1693. // This only directly applies if the new type is also a pointer.
  1694. if (NewTy->isPointerTy()) {
  1695. NewLI.setMetadata(LLVMContext::MD_nonnull, N);
  1696. return;
  1697. }
  1698. // The only other translation we can do is to integral loads with !range
  1699. // metadata.
  1700. if (!NewTy->isIntegerTy())
  1701. return;
  1702. MDBuilder MDB(NewLI.getContext());
  1703. const Value *Ptr = OldLI.getPointerOperand();
  1704. auto *ITy = cast<IntegerType>(NewTy);
  1705. auto *NullInt = ConstantExpr::getPtrToInt(
  1706. ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
  1707. auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
  1708. NewLI.setMetadata(LLVMContext::MD_range,
  1709. MDB.createRange(NonNullInt, NullInt));
  1710. }
  1711. void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
  1712. MDNode *N, LoadInst &NewLI) {
  1713. auto *NewTy = NewLI.getType();
  1714. // Give up unless it is converted to a pointer where there is a single very
  1715. // valuable mapping we can do reliably.
  1716. // FIXME: It would be nice to propagate this in more ways, but the type
  1717. // conversions make it hard.
  1718. if (!NewTy->isPointerTy())
  1719. return;
  1720. unsigned BitWidth = DL.getTypeSizeInBits(NewTy);
  1721. if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
  1722. MDNode *NN = MDNode::get(OldLI.getContext(), None);
  1723. NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
  1724. }
  1725. }
  1726. namespace {
  1727. /// A potential constituent of a bitreverse or bswap expression. See
  1728. /// collectBitParts for a fuller explanation.
  1729. struct BitPart {
  1730. BitPart(Value *P, unsigned BW) : Provider(P) {
  1731. Provenance.resize(BW);
  1732. }
  1733. /// The Value that this is a bitreverse/bswap of.
  1734. Value *Provider;
  1735. /// The "provenance" of each bit. Provenance[A] = B means that bit A
  1736. /// in Provider becomes bit B in the result of this expression.
  1737. SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
  1738. enum { Unset = -1 };
  1739. };
  1740. } // end anonymous namespace
  1741. /// Analyze the specified subexpression and see if it is capable of providing
  1742. /// pieces of a bswap or bitreverse. The subexpression provides a potential
  1743. /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
  1744. /// the output of the expression came from a corresponding bit in some other
  1745. /// value. This function is recursive, and the end result is a mapping of
  1746. /// bitnumber to bitnumber. It is the caller's responsibility to validate that
  1747. /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
  1748. ///
  1749. /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
  1750. /// that the expression deposits the low byte of %X into the high byte of the
  1751. /// result and that all other bits are zero. This expression is accepted and a
  1752. /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
  1753. /// [0-7].
  1754. ///
  1755. /// To avoid revisiting values, the BitPart results are memoized into the
  1756. /// provided map. To avoid unnecessary copying of BitParts, BitParts are
  1757. /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
  1758. /// store BitParts objects, not pointers. As we need the concept of a nullptr
  1759. /// BitParts (Value has been analyzed and the analysis failed), we an Optional
  1760. /// type instead to provide the same functionality.
  1761. ///
  1762. /// Because we pass around references into \c BPS, we must use a container that
  1763. /// does not invalidate internal references (std::map instead of DenseMap).
  1764. static const Optional<BitPart> &
  1765. collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
  1766. std::map<Value *, Optional<BitPart>> &BPS) {
  1767. auto I = BPS.find(V);
  1768. if (I != BPS.end())
  1769. return I->second;
  1770. auto &Result = BPS[V] = None;
  1771. auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
  1772. if (Instruction *I = dyn_cast<Instruction>(V)) {
  1773. // If this is an or instruction, it may be an inner node of the bswap.
  1774. if (I->getOpcode() == Instruction::Or) {
  1775. auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
  1776. MatchBitReversals, BPS);
  1777. auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
  1778. MatchBitReversals, BPS);
  1779. if (!A || !B)
  1780. return Result;
  1781. // Try and merge the two together.
  1782. if (!A->Provider || A->Provider != B->Provider)
  1783. return Result;
  1784. Result = BitPart(A->Provider, BitWidth);
  1785. for (unsigned i = 0; i < A->Provenance.size(); ++i) {
  1786. if (A->Provenance[i] != BitPart::Unset &&
  1787. B->Provenance[i] != BitPart::Unset &&
  1788. A->Provenance[i] != B->Provenance[i])
  1789. return Result = None;
  1790. if (A->Provenance[i] == BitPart::Unset)
  1791. Result->Provenance[i] = B->Provenance[i];
  1792. else
  1793. Result->Provenance[i] = A->Provenance[i];
  1794. }
  1795. return Result;
  1796. }
  1797. // If this is a logical shift by a constant, recurse then shift the result.
  1798. if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
  1799. unsigned BitShift =
  1800. cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
  1801. // Ensure the shift amount is defined.
  1802. if (BitShift > BitWidth)
  1803. return Result;
  1804. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  1805. MatchBitReversals, BPS);
  1806. if (!Res)
  1807. return Result;
  1808. Result = Res;
  1809. // Perform the "shift" on BitProvenance.
  1810. auto &P = Result->Provenance;
  1811. if (I->getOpcode() == Instruction::Shl) {
  1812. P.erase(std::prev(P.end(), BitShift), P.end());
  1813. P.insert(P.begin(), BitShift, BitPart::Unset);
  1814. } else {
  1815. P.erase(P.begin(), std::next(P.begin(), BitShift));
  1816. P.insert(P.end(), BitShift, BitPart::Unset);
  1817. }
  1818. return Result;
  1819. }
  1820. // If this is a logical 'and' with a mask that clears bits, recurse then
  1821. // unset the appropriate bits.
  1822. if (I->getOpcode() == Instruction::And &&
  1823. isa<ConstantInt>(I->getOperand(1))) {
  1824. APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
  1825. const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
  1826. // Check that the mask allows a multiple of 8 bits for a bswap, for an
  1827. // early exit.
  1828. unsigned NumMaskedBits = AndMask.countPopulation();
  1829. if (!MatchBitReversals && NumMaskedBits % 8 != 0)
  1830. return Result;
  1831. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  1832. MatchBitReversals, BPS);
  1833. if (!Res)
  1834. return Result;
  1835. Result = Res;
  1836. for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
  1837. // If the AndMask is zero for this bit, clear the bit.
  1838. if ((AndMask & Bit) == 0)
  1839. Result->Provenance[i] = BitPart::Unset;
  1840. return Result;
  1841. }
  1842. // If this is a zext instruction zero extend the result.
  1843. if (I->getOpcode() == Instruction::ZExt) {
  1844. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  1845. MatchBitReversals, BPS);
  1846. if (!Res)
  1847. return Result;
  1848. Result = BitPart(Res->Provider, BitWidth);
  1849. auto NarrowBitWidth =
  1850. cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
  1851. for (unsigned i = 0; i < NarrowBitWidth; ++i)
  1852. Result->Provenance[i] = Res->Provenance[i];
  1853. for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
  1854. Result->Provenance[i] = BitPart::Unset;
  1855. return Result;
  1856. }
  1857. }
  1858. // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
  1859. // the input value to the bswap/bitreverse.
  1860. Result = BitPart(V, BitWidth);
  1861. for (unsigned i = 0; i < BitWidth; ++i)
  1862. Result->Provenance[i] = i;
  1863. return Result;
  1864. }
  1865. static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
  1866. unsigned BitWidth) {
  1867. if (From % 8 != To % 8)
  1868. return false;
  1869. // Convert from bit indices to byte indices and check for a byte reversal.
  1870. From >>= 3;
  1871. To >>= 3;
  1872. BitWidth >>= 3;
  1873. return From == BitWidth - To - 1;
  1874. }
  1875. static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
  1876. unsigned BitWidth) {
  1877. return From == BitWidth - To - 1;
  1878. }
  1879. /// Given an OR instruction, check to see if this is a bitreverse
  1880. /// idiom. If so, insert the new intrinsic and return true.
  1881. bool llvm::recognizeBSwapOrBitReverseIdiom(
  1882. Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
  1883. SmallVectorImpl<Instruction *> &InsertedInsts) {
  1884. if (Operator::getOpcode(I) != Instruction::Or)
  1885. return false;
  1886. if (!MatchBSwaps && !MatchBitReversals)
  1887. return false;
  1888. IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
  1889. if (!ITy || ITy->getBitWidth() > 128)
  1890. return false; // Can't do vectors or integers > 128 bits.
  1891. unsigned BW = ITy->getBitWidth();
  1892. unsigned DemandedBW = BW;
  1893. IntegerType *DemandedTy = ITy;
  1894. if (I->hasOneUse()) {
  1895. if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
  1896. DemandedTy = cast<IntegerType>(Trunc->getType());
  1897. DemandedBW = DemandedTy->getBitWidth();
  1898. }
  1899. }
  1900. // Try to find all the pieces corresponding to the bswap.
  1901. std::map<Value *, Optional<BitPart>> BPS;
  1902. auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
  1903. if (!Res)
  1904. return false;
  1905. auto &BitProvenance = Res->Provenance;
  1906. // Now, is the bit permutation correct for a bswap or a bitreverse? We can
  1907. // only byteswap values with an even number of bytes.
  1908. bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
  1909. for (unsigned i = 0; i < DemandedBW; ++i) {
  1910. OKForBSwap &=
  1911. bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
  1912. OKForBitReverse &=
  1913. bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
  1914. }
  1915. Intrinsic::ID Intrin;
  1916. if (OKForBSwap && MatchBSwaps)
  1917. Intrin = Intrinsic::bswap;
  1918. else if (OKForBitReverse && MatchBitReversals)
  1919. Intrin = Intrinsic::bitreverse;
  1920. else
  1921. return false;
  1922. if (ITy != DemandedTy) {
  1923. Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
  1924. Value *Provider = Res->Provider;
  1925. IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
  1926. // We may need to truncate the provider.
  1927. if (DemandedTy != ProviderTy) {
  1928. auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
  1929. "trunc", I);
  1930. InsertedInsts.push_back(Trunc);
  1931. Provider = Trunc;
  1932. }
  1933. auto *CI = CallInst::Create(F, Provider, "rev", I);
  1934. InsertedInsts.push_back(CI);
  1935. auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
  1936. InsertedInsts.push_back(ExtInst);
  1937. return true;
  1938. }
  1939. Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
  1940. InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
  1941. return true;
  1942. }
  1943. // CodeGen has special handling for some string functions that may replace
  1944. // them with target-specific intrinsics. Since that'd skip our interceptors
  1945. // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
  1946. // we mark affected calls as NoBuiltin, which will disable optimization
  1947. // in CodeGen.
  1948. void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
  1949. CallInst *CI, const TargetLibraryInfo *TLI) {
  1950. Function *F = CI->getCalledFunction();
  1951. LibFunc Func;
  1952. if (F && !F->hasLocalLinkage() && F->hasName() &&
  1953. TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
  1954. !F->doesNotAccessMemory())
  1955. CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
  1956. }
  1957. bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
  1958. // We can't have a PHI with a metadata type.
  1959. if (I->getOperand(OpIdx)->getType()->isMetadataTy())
  1960. return false;
  1961. // Early exit.
  1962. if (!isa<Constant>(I->getOperand(OpIdx)))
  1963. return true;
  1964. switch (I->getOpcode()) {
  1965. default:
  1966. return true;
  1967. case Instruction::Call:
  1968. case Instruction::Invoke:
  1969. // Can't handle inline asm. Skip it.
  1970. if (isa<InlineAsm>(ImmutableCallSite(I).getCalledValue()))
  1971. return false;
  1972. // Many arithmetic intrinsics have no issue taking a
  1973. // variable, however it's hard to distingish these from
  1974. // specials such as @llvm.frameaddress that require a constant.
  1975. if (isa<IntrinsicInst>(I))
  1976. return false;
  1977. // Constant bundle operands may need to retain their constant-ness for
  1978. // correctness.
  1979. if (ImmutableCallSite(I).isBundleOperand(OpIdx))
  1980. return false;
  1981. return true;
  1982. case Instruction::ShuffleVector:
  1983. // Shufflevector masks are constant.
  1984. return OpIdx != 2;
  1985. case Instruction::Switch:
  1986. case Instruction::ExtractValue:
  1987. // All operands apart from the first are constant.
  1988. return OpIdx == 0;
  1989. case Instruction::InsertValue:
  1990. // All operands apart from the first and the second are constant.
  1991. return OpIdx < 2;
  1992. case Instruction::Alloca:
  1993. // Static allocas (constant size in the entry block) are handled by
  1994. // prologue/epilogue insertion so they're free anyway. We definitely don't
  1995. // want to make them non-constant.
  1996. return !dyn_cast<AllocaInst>(I)->isStaticAlloca();
  1997. case Instruction::GetElementPtr:
  1998. if (OpIdx == 0)
  1999. return true;
  2000. gep_type_iterator It = gep_type_begin(I);
  2001. for (auto E = std::next(It, OpIdx); It != E; ++It)
  2002. if (It.isStruct())
  2003. return false;
  2004. return true;
  2005. }
  2006. }