Local.cpp 80 KB

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