Local.cpp 93 KB

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