InstructionCombining.cpp 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094
  1. //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
  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. // InstructionCombining - Combine instructions to form fewer, simple
  11. // instructions. This pass does not modify the CFG. This pass is where
  12. // algebraic simplification happens.
  13. //
  14. // This pass combines things like:
  15. // %Y = add i32 %X, 1
  16. // %Z = add i32 %Y, 1
  17. // into:
  18. // %Z = add i32 %X, 2
  19. //
  20. // This is a simple worklist driven algorithm.
  21. //
  22. // This pass guarantees that the following canonicalizations are performed on
  23. // the program:
  24. // 1. If a binary operator has a constant operand, it is moved to the RHS
  25. // 2. Bitwise operators with constant operands are always grouped so that
  26. // shifts are performed first, then or's, then and's, then xor's.
  27. // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
  28. // 4. All cmp instructions on boolean values are replaced with logical ops
  29. // 5. add X, X is represented as (X*2) => (X << 1)
  30. // 6. Multiplies with a power-of-two constant argument are transformed into
  31. // shifts.
  32. // ... etc.
  33. //
  34. //===----------------------------------------------------------------------===//
  35. #include "llvm/Transforms/InstCombine/InstCombine.h"
  36. #include "InstCombineInternal.h"
  37. #include "llvm-c/Initialization.h"
  38. #include "llvm/ADT/SmallPtrSet.h"
  39. #include "llvm/ADT/Statistic.h"
  40. #include "llvm/ADT/StringSwitch.h"
  41. #include "llvm/Analysis/AssumptionCache.h"
  42. #include "llvm/Analysis/CFG.h"
  43. #include "llvm/Analysis/ConstantFolding.h"
  44. #include "llvm/Analysis/InstructionSimplify.h"
  45. #include "llvm/Analysis/LibCallSemantics.h"
  46. #include "llvm/Analysis/LoopInfo.h"
  47. #include "llvm/Analysis/MemoryBuiltins.h"
  48. #include "llvm/Analysis/TargetLibraryInfo.h"
  49. #include "llvm/Analysis/ValueTracking.h"
  50. #include "llvm/IR/CFG.h"
  51. #include "llvm/IR/DataLayout.h"
  52. #include "llvm/IR/Dominators.h"
  53. #include "llvm/IR/GetElementPtrTypeIterator.h"
  54. #include "llvm/IR/IntrinsicInst.h"
  55. #include "llvm/IR/PatternMatch.h"
  56. #include "llvm/IR/ValueHandle.h"
  57. #include "llvm/Support/CommandLine.h"
  58. #include "llvm/Support/Debug.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include "llvm/Transforms/Scalar.h"
  61. #include "llvm/Transforms/Utils/Local.h"
  62. #include <algorithm>
  63. #include <climits>
  64. using namespace llvm;
  65. using namespace llvm::PatternMatch;
  66. #define DEBUG_TYPE "instcombine"
  67. STATISTIC(NumCombined , "Number of insts combined");
  68. STATISTIC(NumConstProp, "Number of constant folds");
  69. STATISTIC(NumDeadInst , "Number of dead inst eliminated");
  70. STATISTIC(NumSunkInst , "Number of instructions sunk");
  71. STATISTIC(NumExpand, "Number of expansions");
  72. STATISTIC(NumFactor , "Number of factorizations");
  73. STATISTIC(NumReassoc , "Number of reassociations");
  74. Value *InstCombiner::EmitGEPOffset(User *GEP) {
  75. return llvm::EmitGEPOffset(Builder, DL, GEP);
  76. }
  77. /// ShouldChangeType - Return true if it is desirable to convert a computation
  78. /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
  79. /// type for example, or from a smaller to a larger illegal type.
  80. bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
  81. assert(From->isIntegerTy() && To->isIntegerTy());
  82. unsigned FromWidth = From->getPrimitiveSizeInBits();
  83. unsigned ToWidth = To->getPrimitiveSizeInBits();
  84. bool FromLegal = DL.isLegalInteger(FromWidth);
  85. bool ToLegal = DL.isLegalInteger(ToWidth);
  86. // If this is a legal integer from type, and the result would be an illegal
  87. // type, don't do the transformation.
  88. if (FromLegal && !ToLegal)
  89. return false;
  90. // Otherwise, if both are illegal, do not increase the size of the result. We
  91. // do allow things like i160 -> i64, but not i64 -> i160.
  92. if (!FromLegal && !ToLegal && ToWidth > FromWidth)
  93. return false;
  94. return true;
  95. }
  96. // Return true, if No Signed Wrap should be maintained for I.
  97. // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
  98. // where both B and C should be ConstantInts, results in a constant that does
  99. // not overflow. This function only handles the Add and Sub opcodes. For
  100. // all other opcodes, the function conservatively returns false.
  101. static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
  102. OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
  103. if (!OBO || !OBO->hasNoSignedWrap()) {
  104. return false;
  105. }
  106. // We reason about Add and Sub Only.
  107. Instruction::BinaryOps Opcode = I.getOpcode();
  108. if (Opcode != Instruction::Add &&
  109. Opcode != Instruction::Sub) {
  110. return false;
  111. }
  112. ConstantInt *CB = dyn_cast<ConstantInt>(B);
  113. ConstantInt *CC = dyn_cast<ConstantInt>(C);
  114. if (!CB || !CC) {
  115. return false;
  116. }
  117. const APInt &BVal = CB->getValue();
  118. const APInt &CVal = CC->getValue();
  119. bool Overflow = false;
  120. if (Opcode == Instruction::Add) {
  121. BVal.sadd_ov(CVal, Overflow);
  122. } else {
  123. BVal.ssub_ov(CVal, Overflow);
  124. }
  125. return !Overflow;
  126. }
  127. /// Conservatively clears subclassOptionalData after a reassociation or
  128. /// commutation. We preserve fast-math flags when applicable as they can be
  129. /// preserved.
  130. static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
  131. FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
  132. if (!FPMO) {
  133. I.clearSubclassOptionalData();
  134. return;
  135. }
  136. FastMathFlags FMF = I.getFastMathFlags();
  137. I.clearSubclassOptionalData();
  138. I.setFastMathFlags(FMF);
  139. }
  140. /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
  141. /// operators which are associative or commutative:
  142. //
  143. // Commutative operators:
  144. //
  145. // 1. Order operands such that they are listed from right (least complex) to
  146. // left (most complex). This puts constants before unary operators before
  147. // binary operators.
  148. //
  149. // Associative operators:
  150. //
  151. // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
  152. // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
  153. //
  154. // Associative and commutative operators:
  155. //
  156. // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
  157. // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
  158. // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
  159. // if C1 and C2 are constants.
  160. //
  161. bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
  162. Instruction::BinaryOps Opcode = I.getOpcode();
  163. bool Changed = false;
  164. do {
  165. // Order operands such that they are listed from right (least complex) to
  166. // left (most complex). This puts constants before unary operators before
  167. // binary operators.
  168. if (I.isCommutative() && getComplexity(I.getOperand(0)) <
  169. getComplexity(I.getOperand(1)))
  170. Changed = !I.swapOperands();
  171. BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
  172. BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
  173. if (I.isAssociative()) {
  174. // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
  175. if (Op0 && Op0->getOpcode() == Opcode) {
  176. Value *A = Op0->getOperand(0);
  177. Value *B = Op0->getOperand(1);
  178. Value *C = I.getOperand(1);
  179. // Does "B op C" simplify?
  180. if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
  181. // It simplifies to V. Form "A op V".
  182. I.setOperand(0, A);
  183. I.setOperand(1, V);
  184. // Conservatively clear the optional flags, since they may not be
  185. // preserved by the reassociation.
  186. if (MaintainNoSignedWrap(I, B, C) &&
  187. (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
  188. // Note: this is only valid because SimplifyBinOp doesn't look at
  189. // the operands to Op0.
  190. I.clearSubclassOptionalData();
  191. I.setHasNoSignedWrap(true);
  192. } else {
  193. ClearSubclassDataAfterReassociation(I);
  194. }
  195. Changed = true;
  196. ++NumReassoc;
  197. continue;
  198. }
  199. }
  200. // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
  201. if (Op1 && Op1->getOpcode() == Opcode) {
  202. Value *A = I.getOperand(0);
  203. Value *B = Op1->getOperand(0);
  204. Value *C = Op1->getOperand(1);
  205. // Does "A op B" simplify?
  206. if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
  207. // It simplifies to V. Form "V op C".
  208. I.setOperand(0, V);
  209. I.setOperand(1, C);
  210. // Conservatively clear the optional flags, since they may not be
  211. // preserved by the reassociation.
  212. ClearSubclassDataAfterReassociation(I);
  213. Changed = true;
  214. ++NumReassoc;
  215. continue;
  216. }
  217. }
  218. }
  219. if (I.isAssociative() && I.isCommutative()) {
  220. // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
  221. if (Op0 && Op0->getOpcode() == Opcode) {
  222. Value *A = Op0->getOperand(0);
  223. Value *B = Op0->getOperand(1);
  224. Value *C = I.getOperand(1);
  225. // Does "C op A" simplify?
  226. if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
  227. // It simplifies to V. Form "V op B".
  228. I.setOperand(0, V);
  229. I.setOperand(1, B);
  230. // Conservatively clear the optional flags, since they may not be
  231. // preserved by the reassociation.
  232. ClearSubclassDataAfterReassociation(I);
  233. Changed = true;
  234. ++NumReassoc;
  235. continue;
  236. }
  237. }
  238. // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
  239. if (Op1 && Op1->getOpcode() == Opcode) {
  240. Value *A = I.getOperand(0);
  241. Value *B = Op1->getOperand(0);
  242. Value *C = Op1->getOperand(1);
  243. // Does "C op A" simplify?
  244. if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
  245. // It simplifies to V. Form "B op V".
  246. I.setOperand(0, B);
  247. I.setOperand(1, V);
  248. // Conservatively clear the optional flags, since they may not be
  249. // preserved by the reassociation.
  250. ClearSubclassDataAfterReassociation(I);
  251. Changed = true;
  252. ++NumReassoc;
  253. continue;
  254. }
  255. }
  256. // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
  257. // if C1 and C2 are constants.
  258. if (Op0 && Op1 &&
  259. Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
  260. isa<Constant>(Op0->getOperand(1)) &&
  261. isa<Constant>(Op1->getOperand(1)) &&
  262. Op0->hasOneUse() && Op1->hasOneUse()) {
  263. Value *A = Op0->getOperand(0);
  264. Constant *C1 = cast<Constant>(Op0->getOperand(1));
  265. Value *B = Op1->getOperand(0);
  266. Constant *C2 = cast<Constant>(Op1->getOperand(1));
  267. Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
  268. BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
  269. if (isa<FPMathOperator>(New)) {
  270. FastMathFlags Flags = I.getFastMathFlags();
  271. Flags &= Op0->getFastMathFlags();
  272. Flags &= Op1->getFastMathFlags();
  273. New->setFastMathFlags(Flags);
  274. }
  275. InsertNewInstWith(New, I);
  276. New->takeName(Op1);
  277. I.setOperand(0, New);
  278. I.setOperand(1, Folded);
  279. // Conservatively clear the optional flags, since they may not be
  280. // preserved by the reassociation.
  281. ClearSubclassDataAfterReassociation(I);
  282. Changed = true;
  283. continue;
  284. }
  285. }
  286. // No further simplifications.
  287. return Changed;
  288. } while (1);
  289. }
  290. /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
  291. /// "(X LOp Y) ROp (X LOp Z)".
  292. static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
  293. Instruction::BinaryOps ROp) {
  294. switch (LOp) {
  295. default:
  296. return false;
  297. case Instruction::And:
  298. // And distributes over Or and Xor.
  299. switch (ROp) {
  300. default:
  301. return false;
  302. case Instruction::Or:
  303. case Instruction::Xor:
  304. return true;
  305. }
  306. case Instruction::Mul:
  307. // Multiplication distributes over addition and subtraction.
  308. switch (ROp) {
  309. default:
  310. return false;
  311. case Instruction::Add:
  312. case Instruction::Sub:
  313. return true;
  314. }
  315. case Instruction::Or:
  316. // Or distributes over And.
  317. switch (ROp) {
  318. default:
  319. return false;
  320. case Instruction::And:
  321. return true;
  322. }
  323. }
  324. }
  325. /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
  326. /// "(X ROp Z) LOp (Y ROp Z)".
  327. static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
  328. Instruction::BinaryOps ROp) {
  329. if (Instruction::isCommutative(ROp))
  330. return LeftDistributesOverRight(ROp, LOp);
  331. switch (LOp) {
  332. default:
  333. return false;
  334. // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
  335. // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
  336. // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
  337. case Instruction::And:
  338. case Instruction::Or:
  339. case Instruction::Xor:
  340. switch (ROp) {
  341. default:
  342. return false;
  343. case Instruction::Shl:
  344. case Instruction::LShr:
  345. case Instruction::AShr:
  346. return true;
  347. }
  348. }
  349. // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
  350. // but this requires knowing that the addition does not overflow and other
  351. // such subtleties.
  352. return false;
  353. }
  354. /// This function returns identity value for given opcode, which can be used to
  355. /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
  356. static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
  357. if (isa<Constant>(V))
  358. return nullptr;
  359. if (OpCode == Instruction::Mul)
  360. return ConstantInt::get(V->getType(), 1);
  361. // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
  362. return nullptr;
  363. }
  364. /// This function factors binary ops which can be combined using distributive
  365. /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
  366. /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
  367. /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
  368. /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
  369. /// RHS to 4.
  370. static Instruction::BinaryOps
  371. getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
  372. BinaryOperator *Op, Value *&LHS, Value *&RHS) {
  373. if (!Op)
  374. return Instruction::BinaryOpsEnd;
  375. LHS = Op->getOperand(0);
  376. RHS = Op->getOperand(1);
  377. switch (TopLevelOpcode) {
  378. default:
  379. return Op->getOpcode();
  380. case Instruction::Add:
  381. case Instruction::Sub:
  382. if (Op->getOpcode() == Instruction::Shl) {
  383. if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
  384. // The multiplier is really 1 << CST.
  385. RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
  386. return Instruction::Mul;
  387. }
  388. }
  389. return Op->getOpcode();
  390. }
  391. // TODO: We can add other conversions e.g. shr => div etc.
  392. }
  393. /// This tries to simplify binary operations by factorizing out common terms
  394. /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
  395. static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
  396. const DataLayout &DL, BinaryOperator &I,
  397. Instruction::BinaryOps InnerOpcode, Value *A,
  398. Value *B, Value *C, Value *D) {
  399. // If any of A, B, C, D are null, we can not factor I, return early.
  400. // Checking A and C should be enough.
  401. if (!A || !C || !B || !D)
  402. return nullptr;
  403. Value *V = nullptr;
  404. Value *SimplifiedInst = nullptr;
  405. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  406. Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
  407. // Does "X op' Y" always equal "Y op' X"?
  408. bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
  409. // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
  410. if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
  411. // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
  412. // commutative case, "(A op' B) op (C op' A)"?
  413. if (A == C || (InnerCommutative && A == D)) {
  414. if (A != C)
  415. std::swap(C, D);
  416. // Consider forming "A op' (B op D)".
  417. // If "B op D" simplifies then it can be formed with no cost.
  418. V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
  419. // If "B op D" doesn't simplify then only go on if both of the existing
  420. // operations "A op' B" and "C op' D" will be zapped as no longer used.
  421. if (!V && LHS->hasOneUse() && RHS->hasOneUse())
  422. V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
  423. if (V) {
  424. SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
  425. }
  426. }
  427. // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
  428. if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
  429. // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
  430. // commutative case, "(A op' B) op (B op' D)"?
  431. if (B == D || (InnerCommutative && B == C)) {
  432. if (B != D)
  433. std::swap(C, D);
  434. // Consider forming "(A op C) op' B".
  435. // If "A op C" simplifies then it can be formed with no cost.
  436. V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
  437. // If "A op C" doesn't simplify then only go on if both of the existing
  438. // operations "A op' B" and "C op' D" will be zapped as no longer used.
  439. if (!V && LHS->hasOneUse() && RHS->hasOneUse())
  440. V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
  441. if (V) {
  442. SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
  443. }
  444. }
  445. if (SimplifiedInst) {
  446. ++NumFactor;
  447. SimplifiedInst->takeName(&I);
  448. // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
  449. // TODO: Check for NUW.
  450. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
  451. if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
  452. bool HasNSW = false;
  453. if (isa<OverflowingBinaryOperator>(&I))
  454. HasNSW = I.hasNoSignedWrap();
  455. if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
  456. if (isa<OverflowingBinaryOperator>(Op0))
  457. HasNSW &= Op0->hasNoSignedWrap();
  458. if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
  459. if (isa<OverflowingBinaryOperator>(Op1))
  460. HasNSW &= Op1->hasNoSignedWrap();
  461. // We can propogate 'nsw' if we know that
  462. // %Y = mul nsw i16 %X, C
  463. // %Z = add nsw i16 %Y, %X
  464. // =>
  465. // %Z = mul nsw i16 %X, C+1
  466. //
  467. // iff C+1 isn't INT_MIN
  468. const APInt *CInt;
  469. if (TopLevelOpcode == Instruction::Add &&
  470. InnerOpcode == Instruction::Mul)
  471. if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
  472. BO->setHasNoSignedWrap(HasNSW);
  473. }
  474. }
  475. }
  476. return SimplifiedInst;
  477. }
  478. /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
  479. /// which some other binary operation distributes over either by factorizing
  480. /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
  481. /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
  482. /// a win). Returns the simplified value, or null if it didn't simplify.
  483. Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
  484. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  485. BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
  486. BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
  487. // Factorization.
  488. Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
  489. auto TopLevelOpcode = I.getOpcode();
  490. auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
  491. auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
  492. // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
  493. // a common term.
  494. if (LHSOpcode == RHSOpcode) {
  495. if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
  496. return V;
  497. }
  498. // The instruction has the form "(A op' B) op (C)". Try to factorize common
  499. // term.
  500. if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
  501. getIdentityValue(LHSOpcode, RHS)))
  502. return V;
  503. // The instruction has the form "(B) op (C op' D)". Try to factorize common
  504. // term.
  505. if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
  506. getIdentityValue(RHSOpcode, LHS), C, D))
  507. return V;
  508. // Expansion.
  509. if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
  510. // The instruction has the form "(A op' B) op C". See if expanding it out
  511. // to "(A op C) op' (B op C)" results in simplifications.
  512. Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
  513. Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
  514. // Do "A op C" and "B op C" both simplify?
  515. if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
  516. if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
  517. // They do! Return "L op' R".
  518. ++NumExpand;
  519. // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
  520. if ((L == A && R == B) ||
  521. (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
  522. return Op0;
  523. // Otherwise return "L op' R" if it simplifies.
  524. if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
  525. return V;
  526. // Otherwise, create a new instruction.
  527. C = Builder->CreateBinOp(InnerOpcode, L, R);
  528. C->takeName(&I);
  529. return C;
  530. }
  531. }
  532. if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
  533. // The instruction has the form "A op (B op' C)". See if expanding it out
  534. // to "(A op B) op' (A op C)" results in simplifications.
  535. Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
  536. Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
  537. // Do "A op B" and "A op C" both simplify?
  538. if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
  539. if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
  540. // They do! Return "L op' R".
  541. ++NumExpand;
  542. // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
  543. if ((L == B && R == C) ||
  544. (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
  545. return Op1;
  546. // Otherwise return "L op' R" if it simplifies.
  547. if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
  548. return V;
  549. // Otherwise, create a new instruction.
  550. A = Builder->CreateBinOp(InnerOpcode, L, R);
  551. A->takeName(&I);
  552. return A;
  553. }
  554. }
  555. return nullptr;
  556. }
  557. // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
  558. // if the LHS is a constant zero (which is the 'negate' form).
  559. //
  560. Value *InstCombiner::dyn_castNegVal(Value *V) const {
  561. if (BinaryOperator::isNeg(V))
  562. return BinaryOperator::getNegArgument(V);
  563. // Constants can be considered to be negated values if they can be folded.
  564. if (ConstantInt *C = dyn_cast<ConstantInt>(V))
  565. return ConstantExpr::getNeg(C);
  566. if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
  567. if (C->getType()->getElementType()->isIntegerTy())
  568. return ConstantExpr::getNeg(C);
  569. return nullptr;
  570. }
  571. // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
  572. // instruction if the LHS is a constant negative zero (which is the 'negate'
  573. // form).
  574. //
  575. Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
  576. if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
  577. return BinaryOperator::getFNegArgument(V);
  578. // Constants can be considered to be negated values if they can be folded.
  579. if (ConstantFP *C = dyn_cast<ConstantFP>(V))
  580. return ConstantExpr::getFNeg(C);
  581. if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
  582. if (C->getType()->getElementType()->isFloatingPointTy())
  583. return ConstantExpr::getFNeg(C);
  584. return nullptr;
  585. }
  586. static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
  587. InstCombiner *IC) {
  588. if (CastInst *CI = dyn_cast<CastInst>(&I)) {
  589. return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
  590. }
  591. // Figure out if the constant is the left or the right argument.
  592. bool ConstIsRHS = isa<Constant>(I.getOperand(1));
  593. Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
  594. if (Constant *SOC = dyn_cast<Constant>(SO)) {
  595. if (ConstIsRHS)
  596. return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
  597. return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
  598. }
  599. Value *Op0 = SO, *Op1 = ConstOperand;
  600. if (!ConstIsRHS)
  601. std::swap(Op0, Op1);
  602. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
  603. Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
  604. SO->getName()+".op");
  605. Instruction *FPInst = dyn_cast<Instruction>(RI);
  606. if (FPInst && isa<FPMathOperator>(FPInst))
  607. FPInst->copyFastMathFlags(BO);
  608. return RI;
  609. }
  610. if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
  611. return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
  612. SO->getName()+".cmp");
  613. if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
  614. return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
  615. SO->getName()+".cmp");
  616. llvm_unreachable("Unknown binary instruction type!");
  617. }
  618. // FoldOpIntoSelect - Given an instruction with a select as one operand and a
  619. // constant as the other operand, try to fold the binary operator into the
  620. // select arguments. This also works for Cast instructions, which obviously do
  621. // not have a second operand.
  622. Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
  623. // Don't modify shared select instructions
  624. if (!SI->hasOneUse()) return nullptr;
  625. Value *TV = SI->getOperand(1);
  626. Value *FV = SI->getOperand(2);
  627. if (isa<Constant>(TV) || isa<Constant>(FV)) {
  628. // Bool selects with constant operands can be folded to logical ops.
  629. if (SI->getType()->isIntegerTy(1)) return nullptr;
  630. // If it's a bitcast involving vectors, make sure it has the same number of
  631. // elements on both sides.
  632. if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
  633. VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
  634. VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
  635. // Verify that either both or neither are vectors.
  636. if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
  637. // If vectors, verify that they have the same number of elements.
  638. if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
  639. return nullptr;
  640. }
  641. // Test if a CmpInst instruction is used exclusively by a select as
  642. // part of a minimum or maximum operation. If so, refrain from doing
  643. // any other folding. This helps out other analyses which understand
  644. // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
  645. // and CodeGen. And in this case, at least one of the comparison
  646. // operands has at least one user besides the compare (the select),
  647. // which would often largely negate the benefit of folding anyway.
  648. if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
  649. if (CI->hasOneUse()) {
  650. Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
  651. if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
  652. (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
  653. return nullptr;
  654. }
  655. }
  656. Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
  657. Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
  658. return SelectInst::Create(SI->getCondition(),
  659. SelectTrueVal, SelectFalseVal);
  660. }
  661. return nullptr;
  662. }
  663. /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
  664. /// has a PHI node as operand #0, see if we can fold the instruction into the
  665. /// PHI (which is only possible if all operands to the PHI are constants).
  666. ///
  667. Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
  668. PHINode *PN = cast<PHINode>(I.getOperand(0));
  669. unsigned NumPHIValues = PN->getNumIncomingValues();
  670. if (NumPHIValues == 0)
  671. return nullptr;
  672. // We normally only transform phis with a single use. However, if a PHI has
  673. // multiple uses and they are all the same operation, we can fold *all* of the
  674. // uses into the PHI.
  675. if (!PN->hasOneUse()) {
  676. // Walk the use list for the instruction, comparing them to I.
  677. for (User *U : PN->users()) {
  678. Instruction *UI = cast<Instruction>(U);
  679. if (UI != &I && !I.isIdenticalTo(UI))
  680. return nullptr;
  681. }
  682. // Otherwise, we can replace *all* users with the new PHI we form.
  683. }
  684. // Check to see if all of the operands of the PHI are simple constants
  685. // (constantint/constantfp/undef). If there is one non-constant value,
  686. // remember the BB it is in. If there is more than one or if *it* is a PHI,
  687. // bail out. We don't do arbitrary constant expressions here because moving
  688. // their computation can be expensive without a cost model.
  689. BasicBlock *NonConstBB = nullptr;
  690. for (unsigned i = 0; i != NumPHIValues; ++i) {
  691. Value *InVal = PN->getIncomingValue(i);
  692. if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
  693. continue;
  694. if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
  695. if (NonConstBB) return nullptr; // More than one non-const value.
  696. NonConstBB = PN->getIncomingBlock(i);
  697. // If the InVal is an invoke at the end of the pred block, then we can't
  698. // insert a computation after it without breaking the edge.
  699. if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
  700. if (II->getParent() == NonConstBB)
  701. return nullptr;
  702. // If the incoming non-constant value is in I's block, we will remove one
  703. // instruction, but insert another equivalent one, leading to infinite
  704. // instcombine.
  705. if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
  706. return nullptr;
  707. }
  708. // If there is exactly one non-constant value, we can insert a copy of the
  709. // operation in that block. However, if this is a critical edge, we would be
  710. // inserting the computation on some other paths (e.g. inside a loop). Only
  711. // do this if the pred block is unconditionally branching into the phi block.
  712. if (NonConstBB != nullptr) {
  713. BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
  714. if (!BI || !BI->isUnconditional()) return nullptr;
  715. }
  716. // Okay, we can do the transformation: create the new PHI node.
  717. PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
  718. InsertNewInstBefore(NewPN, *PN);
  719. NewPN->takeName(PN);
  720. // If we are going to have to insert a new computation, do so right before the
  721. // predecessors terminator.
  722. if (NonConstBB)
  723. Builder->SetInsertPoint(NonConstBB->getTerminator());
  724. // Next, add all of the operands to the PHI.
  725. if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
  726. // We only currently try to fold the condition of a select when it is a phi,
  727. // not the true/false values.
  728. Value *TrueV = SI->getTrueValue();
  729. Value *FalseV = SI->getFalseValue();
  730. BasicBlock *PhiTransBB = PN->getParent();
  731. for (unsigned i = 0; i != NumPHIValues; ++i) {
  732. BasicBlock *ThisBB = PN->getIncomingBlock(i);
  733. Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
  734. Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
  735. Value *InV = nullptr;
  736. // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
  737. // even if currently isNullValue gives false.
  738. Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
  739. if (InC && !isa<ConstantExpr>(InC))
  740. InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
  741. else
  742. InV = Builder->CreateSelect(PN->getIncomingValue(i),
  743. TrueVInPred, FalseVInPred, "phitmp");
  744. NewPN->addIncoming(InV, ThisBB);
  745. }
  746. } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
  747. Constant *C = cast<Constant>(I.getOperand(1));
  748. for (unsigned i = 0; i != NumPHIValues; ++i) {
  749. Value *InV = nullptr;
  750. if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
  751. InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
  752. else if (isa<ICmpInst>(CI))
  753. InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
  754. C, "phitmp");
  755. else
  756. InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
  757. C, "phitmp");
  758. NewPN->addIncoming(InV, PN->getIncomingBlock(i));
  759. }
  760. } else if (I.getNumOperands() == 2) {
  761. Constant *C = cast<Constant>(I.getOperand(1));
  762. for (unsigned i = 0; i != NumPHIValues; ++i) {
  763. Value *InV = nullptr;
  764. if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
  765. InV = ConstantExpr::get(I.getOpcode(), InC, C);
  766. else
  767. InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
  768. PN->getIncomingValue(i), C, "phitmp");
  769. NewPN->addIncoming(InV, PN->getIncomingBlock(i));
  770. }
  771. } else {
  772. CastInst *CI = cast<CastInst>(&I);
  773. Type *RetTy = CI->getType();
  774. for (unsigned i = 0; i != NumPHIValues; ++i) {
  775. Value *InV;
  776. if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
  777. InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
  778. else
  779. InV = Builder->CreateCast(CI->getOpcode(),
  780. PN->getIncomingValue(i), I.getType(), "phitmp");
  781. NewPN->addIncoming(InV, PN->getIncomingBlock(i));
  782. }
  783. }
  784. for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
  785. Instruction *User = cast<Instruction>(*UI++);
  786. if (User == &I) continue;
  787. ReplaceInstUsesWith(*User, NewPN);
  788. EraseInstFromFunction(*User);
  789. }
  790. return ReplaceInstUsesWith(I, NewPN);
  791. }
  792. /// FindElementAtOffset - Given a pointer type and a constant offset, determine
  793. /// whether or not there is a sequence of GEP indices into the pointed type that
  794. /// will land us at the specified offset. If so, fill them into NewIndices and
  795. /// return the resultant element type, otherwise return null.
  796. Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
  797. SmallVectorImpl<Value *> &NewIndices) {
  798. Type *Ty = PtrTy->getElementType();
  799. if (!Ty->isSized())
  800. return nullptr;
  801. // Start with the index over the outer type. Note that the type size
  802. // might be zero (even if the offset isn't zero) if the indexed type
  803. // is something like [0 x {int, int}]
  804. Type *IntPtrTy = DL.getIntPtrType(PtrTy);
  805. int64_t FirstIdx = 0;
  806. if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
  807. FirstIdx = Offset/TySize;
  808. Offset -= FirstIdx*TySize;
  809. // Handle hosts where % returns negative instead of values [0..TySize).
  810. if (Offset < 0) {
  811. --FirstIdx;
  812. Offset += TySize;
  813. assert(Offset >= 0);
  814. }
  815. assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
  816. }
  817. NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
  818. // Index into the types. If we fail, set OrigBase to null.
  819. while (Offset) {
  820. // Indexing into tail padding between struct/array elements.
  821. if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
  822. return nullptr;
  823. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  824. const StructLayout *SL = DL.getStructLayout(STy);
  825. assert(Offset < (int64_t)SL->getSizeInBytes() &&
  826. "Offset must stay within the indexed type");
  827. unsigned Elt = SL->getElementContainingOffset(Offset);
  828. NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
  829. Elt));
  830. Offset -= SL->getElementOffset(Elt);
  831. Ty = STy->getElementType(Elt);
  832. } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  833. uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
  834. assert(EltSize && "Cannot index into a zero-sized array");
  835. NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
  836. Offset %= EltSize;
  837. Ty = AT->getElementType();
  838. } else {
  839. // Otherwise, we can't index into the middle of this atomic type, bail.
  840. return nullptr;
  841. }
  842. }
  843. return Ty;
  844. }
  845. static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
  846. // If this GEP has only 0 indices, it is the same pointer as
  847. // Src. If Src is not a trivial GEP too, don't combine
  848. // the indices.
  849. if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
  850. !Src.hasOneUse())
  851. return false;
  852. return true;
  853. }
  854. /// Descale - Return a value X such that Val = X * Scale, or null if none. If
  855. /// the multiplication is known not to overflow then NoSignedWrap is set.
  856. Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
  857. assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
  858. assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
  859. Scale.getBitWidth() && "Scale not compatible with value!");
  860. // If Val is zero or Scale is one then Val = Val * Scale.
  861. if (match(Val, m_Zero()) || Scale == 1) {
  862. NoSignedWrap = true;
  863. return Val;
  864. }
  865. // If Scale is zero then it does not divide Val.
  866. if (Scale.isMinValue())
  867. return nullptr;
  868. // Look through chains of multiplications, searching for a constant that is
  869. // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
  870. // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
  871. // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
  872. // down from Val:
  873. //
  874. // Val = M1 * X || Analysis starts here and works down
  875. // M1 = M2 * Y || Doesn't descend into terms with more
  876. // M2 = Z * 4 \/ than one use
  877. //
  878. // Then to modify a term at the bottom:
  879. //
  880. // Val = M1 * X
  881. // M1 = Z * Y || Replaced M2 with Z
  882. //
  883. // Then to work back up correcting nsw flags.
  884. // Op - the term we are currently analyzing. Starts at Val then drills down.
  885. // Replaced with its descaled value before exiting from the drill down loop.
  886. Value *Op = Val;
  887. // Parent - initially null, but after drilling down notes where Op came from.
  888. // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
  889. // 0'th operand of Val.
  890. std::pair<Instruction*, unsigned> Parent;
  891. // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
  892. // levels that doesn't overflow.
  893. bool RequireNoSignedWrap = false;
  894. // logScale - log base 2 of the scale. Negative if not a power of 2.
  895. int32_t logScale = Scale.exactLogBase2();
  896. for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
  897. if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
  898. // If Op is a constant divisible by Scale then descale to the quotient.
  899. APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
  900. APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
  901. if (!Remainder.isMinValue())
  902. // Not divisible by Scale.
  903. return nullptr;
  904. // Replace with the quotient in the parent.
  905. Op = ConstantInt::get(CI->getType(), Quotient);
  906. NoSignedWrap = true;
  907. break;
  908. }
  909. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
  910. if (BO->getOpcode() == Instruction::Mul) {
  911. // Multiplication.
  912. NoSignedWrap = BO->hasNoSignedWrap();
  913. if (RequireNoSignedWrap && !NoSignedWrap)
  914. return nullptr;
  915. // There are three cases for multiplication: multiplication by exactly
  916. // the scale, multiplication by a constant different to the scale, and
  917. // multiplication by something else.
  918. Value *LHS = BO->getOperand(0);
  919. Value *RHS = BO->getOperand(1);
  920. if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
  921. // Multiplication by a constant.
  922. if (CI->getValue() == Scale) {
  923. // Multiplication by exactly the scale, replace the multiplication
  924. // by its left-hand side in the parent.
  925. Op = LHS;
  926. break;
  927. }
  928. // Otherwise drill down into the constant.
  929. if (!Op->hasOneUse())
  930. return nullptr;
  931. Parent = std::make_pair(BO, 1);
  932. continue;
  933. }
  934. // Multiplication by something else. Drill down into the left-hand side
  935. // since that's where the reassociate pass puts the good stuff.
  936. if (!Op->hasOneUse())
  937. return nullptr;
  938. Parent = std::make_pair(BO, 0);
  939. continue;
  940. }
  941. if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
  942. isa<ConstantInt>(BO->getOperand(1))) {
  943. // Multiplication by a power of 2.
  944. NoSignedWrap = BO->hasNoSignedWrap();
  945. if (RequireNoSignedWrap && !NoSignedWrap)
  946. return nullptr;
  947. Value *LHS = BO->getOperand(0);
  948. int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
  949. getLimitedValue(Scale.getBitWidth());
  950. // Op = LHS << Amt.
  951. if (Amt == logScale) {
  952. // Multiplication by exactly the scale, replace the multiplication
  953. // by its left-hand side in the parent.
  954. Op = LHS;
  955. break;
  956. }
  957. if (Amt < logScale || !Op->hasOneUse())
  958. return nullptr;
  959. // Multiplication by more than the scale. Reduce the multiplying amount
  960. // by the scale in the parent.
  961. Parent = std::make_pair(BO, 1);
  962. Op = ConstantInt::get(BO->getType(), Amt - logScale);
  963. break;
  964. }
  965. }
  966. if (!Op->hasOneUse())
  967. return nullptr;
  968. if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
  969. if (Cast->getOpcode() == Instruction::SExt) {
  970. // Op is sign-extended from a smaller type, descale in the smaller type.
  971. unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
  972. APInt SmallScale = Scale.trunc(SmallSize);
  973. // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
  974. // descale Op as (sext Y) * Scale. In order to have
  975. // sext (Y * SmallScale) = (sext Y) * Scale
  976. // some conditions need to hold however: SmallScale must sign-extend to
  977. // Scale and the multiplication Y * SmallScale should not overflow.
  978. if (SmallScale.sext(Scale.getBitWidth()) != Scale)
  979. // SmallScale does not sign-extend to Scale.
  980. return nullptr;
  981. assert(SmallScale.exactLogBase2() == logScale);
  982. // Require that Y * SmallScale must not overflow.
  983. RequireNoSignedWrap = true;
  984. // Drill down through the cast.
  985. Parent = std::make_pair(Cast, 0);
  986. Scale = SmallScale;
  987. continue;
  988. }
  989. if (Cast->getOpcode() == Instruction::Trunc) {
  990. // Op is truncated from a larger type, descale in the larger type.
  991. // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
  992. // trunc (Y * sext Scale) = (trunc Y) * Scale
  993. // always holds. However (trunc Y) * Scale may overflow even if
  994. // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
  995. // from this point up in the expression (see later).
  996. if (RequireNoSignedWrap)
  997. return nullptr;
  998. // Drill down through the cast.
  999. unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
  1000. Parent = std::make_pair(Cast, 0);
  1001. Scale = Scale.sext(LargeSize);
  1002. if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
  1003. logScale = -1;
  1004. assert(Scale.exactLogBase2() == logScale);
  1005. continue;
  1006. }
  1007. }
  1008. // Unsupported expression, bail out.
  1009. return nullptr;
  1010. }
  1011. // If Op is zero then Val = Op * Scale.
  1012. if (match(Op, m_Zero())) {
  1013. NoSignedWrap = true;
  1014. return Op;
  1015. }
  1016. // We know that we can successfully descale, so from here on we can safely
  1017. // modify the IR. Op holds the descaled version of the deepest term in the
  1018. // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
  1019. // not to overflow.
  1020. if (!Parent.first)
  1021. // The expression only had one term.
  1022. return Op;
  1023. // Rewrite the parent using the descaled version of its operand.
  1024. assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
  1025. assert(Op != Parent.first->getOperand(Parent.second) &&
  1026. "Descaling was a no-op?");
  1027. Parent.first->setOperand(Parent.second, Op);
  1028. Worklist.Add(Parent.first);
  1029. // Now work back up the expression correcting nsw flags. The logic is based
  1030. // on the following observation: if X * Y is known not to overflow as a signed
  1031. // multiplication, and Y is replaced by a value Z with smaller absolute value,
  1032. // then X * Z will not overflow as a signed multiplication either. As we work
  1033. // our way up, having NoSignedWrap 'true' means that the descaled value at the
  1034. // current level has strictly smaller absolute value than the original.
  1035. Instruction *Ancestor = Parent.first;
  1036. do {
  1037. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
  1038. // If the multiplication wasn't nsw then we can't say anything about the
  1039. // value of the descaled multiplication, and we have to clear nsw flags
  1040. // from this point on up.
  1041. bool OpNoSignedWrap = BO->hasNoSignedWrap();
  1042. NoSignedWrap &= OpNoSignedWrap;
  1043. if (NoSignedWrap != OpNoSignedWrap) {
  1044. BO->setHasNoSignedWrap(NoSignedWrap);
  1045. Worklist.Add(Ancestor);
  1046. }
  1047. } else if (Ancestor->getOpcode() == Instruction::Trunc) {
  1048. // The fact that the descaled input to the trunc has smaller absolute
  1049. // value than the original input doesn't tell us anything useful about
  1050. // the absolute values of the truncations.
  1051. NoSignedWrap = false;
  1052. }
  1053. assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
  1054. "Failed to keep proper track of nsw flags while drilling down?");
  1055. if (Ancestor == Val)
  1056. // Got to the top, all done!
  1057. return Val;
  1058. // Move up one level in the expression.
  1059. assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
  1060. Ancestor = Ancestor->user_back();
  1061. } while (1);
  1062. }
  1063. /// \brief Creates node of binary operation with the same attributes as the
  1064. /// specified one but with other operands.
  1065. static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
  1066. InstCombiner::BuilderTy *B) {
  1067. Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
  1068. if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
  1069. if (isa<OverflowingBinaryOperator>(NewBO)) {
  1070. NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
  1071. NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
  1072. }
  1073. if (isa<PossiblyExactOperator>(NewBO))
  1074. NewBO->setIsExact(Inst.isExact());
  1075. }
  1076. return BORes;
  1077. }
  1078. /// \brief Makes transformation of binary operation specific for vector types.
  1079. /// \param Inst Binary operator to transform.
  1080. /// \return Pointer to node that must replace the original binary operator, or
  1081. /// null pointer if no transformation was made.
  1082. Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
  1083. if (!Inst.getType()->isVectorTy()) return nullptr;
  1084. // It may not be safe to reorder shuffles and things like div, urem, etc.
  1085. // because we may trap when executing those ops on unknown vector elements.
  1086. // See PR20059.
  1087. if (!isSafeToSpeculativelyExecute(&Inst))
  1088. return nullptr;
  1089. unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
  1090. Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
  1091. assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
  1092. assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
  1093. // If both arguments of binary operation are shuffles, which use the same
  1094. // mask and shuffle within a single vector, it is worthwhile to move the
  1095. // shuffle after binary operation:
  1096. // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
  1097. if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
  1098. ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
  1099. ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
  1100. if (isa<UndefValue>(LShuf->getOperand(1)) &&
  1101. isa<UndefValue>(RShuf->getOperand(1)) &&
  1102. LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
  1103. LShuf->getMask() == RShuf->getMask()) {
  1104. Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
  1105. RShuf->getOperand(0), Builder);
  1106. Value *Res = Builder->CreateShuffleVector(NewBO,
  1107. UndefValue::get(NewBO->getType()), LShuf->getMask());
  1108. return Res;
  1109. }
  1110. }
  1111. // If one argument is a shuffle within one vector, the other is a constant,
  1112. // try moving the shuffle after the binary operation.
  1113. ShuffleVectorInst *Shuffle = nullptr;
  1114. Constant *C1 = nullptr;
  1115. if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
  1116. if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
  1117. if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
  1118. if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
  1119. if (Shuffle && C1 &&
  1120. (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
  1121. isa<UndefValue>(Shuffle->getOperand(1)) &&
  1122. Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
  1123. SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
  1124. // Find constant C2 that has property:
  1125. // shuffle(C2, ShMask) = C1
  1126. // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
  1127. // reorder is not possible.
  1128. SmallVector<Constant*, 16> C2M(VWidth,
  1129. UndefValue::get(C1->getType()->getScalarType()));
  1130. bool MayChange = true;
  1131. for (unsigned I = 0; I < VWidth; ++I) {
  1132. if (ShMask[I] >= 0) {
  1133. assert(ShMask[I] < (int)VWidth);
  1134. if (!isa<UndefValue>(C2M[ShMask[I]])) {
  1135. MayChange = false;
  1136. break;
  1137. }
  1138. C2M[ShMask[I]] = C1->getAggregateElement(I);
  1139. }
  1140. }
  1141. if (MayChange) {
  1142. Constant *C2 = ConstantVector::get(C2M);
  1143. Value *NewLHS, *NewRHS;
  1144. if (isa<Constant>(LHS)) {
  1145. NewLHS = C2;
  1146. NewRHS = Shuffle->getOperand(0);
  1147. } else {
  1148. NewLHS = Shuffle->getOperand(0);
  1149. NewRHS = C2;
  1150. }
  1151. Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
  1152. Value *Res = Builder->CreateShuffleVector(NewBO,
  1153. UndefValue::get(Inst.getType()), Shuffle->getMask());
  1154. return Res;
  1155. }
  1156. }
  1157. return nullptr;
  1158. }
  1159. Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
  1160. SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
  1161. if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
  1162. return ReplaceInstUsesWith(GEP, V);
  1163. Value *PtrOp = GEP.getOperand(0);
  1164. // Eliminate unneeded casts for indices, and replace indices which displace
  1165. // by multiples of a zero size type with zero.
  1166. bool MadeChange = false;
  1167. Type *IntPtrTy = DL.getIntPtrType(GEP.getPointerOperandType());
  1168. gep_type_iterator GTI = gep_type_begin(GEP);
  1169. for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
  1170. ++I, ++GTI) {
  1171. // Skip indices into struct types.
  1172. SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
  1173. if (!SeqTy)
  1174. continue;
  1175. // If the element type has zero size then any index over it is equivalent
  1176. // to an index of zero, so replace it with zero if it is not zero already.
  1177. if (SeqTy->getElementType()->isSized() &&
  1178. DL.getTypeAllocSize(SeqTy->getElementType()) == 0)
  1179. if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
  1180. *I = Constant::getNullValue(IntPtrTy);
  1181. MadeChange = true;
  1182. }
  1183. Type *IndexTy = (*I)->getType();
  1184. if (IndexTy != IntPtrTy) {
  1185. // If we are using a wider index than needed for this platform, shrink
  1186. // it to what we need. If narrower, sign-extend it to what we need.
  1187. // This explicit cast can make subsequent optimizations more obvious.
  1188. *I = Builder->CreateIntCast(*I, IntPtrTy, true);
  1189. MadeChange = true;
  1190. }
  1191. }
  1192. if (MadeChange)
  1193. return &GEP;
  1194. // Check to see if the inputs to the PHI node are getelementptr instructions.
  1195. if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
  1196. GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
  1197. if (!Op1)
  1198. return nullptr;
  1199. // Don't fold a GEP into itself through a PHI node. This can only happen
  1200. // through the back-edge of a loop. Folding a GEP into itself means that
  1201. // the value of the previous iteration needs to be stored in the meantime,
  1202. // thus requiring an additional register variable to be live, but not
  1203. // actually achieving anything (the GEP still needs to be executed once per
  1204. // loop iteration).
  1205. if (Op1 == &GEP)
  1206. return nullptr;
  1207. signed DI = -1;
  1208. for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
  1209. GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
  1210. if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
  1211. return nullptr;
  1212. // As for Op1 above, don't try to fold a GEP into itself.
  1213. if (Op2 == &GEP)
  1214. return nullptr;
  1215. // Keep track of the type as we walk the GEP.
  1216. Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
  1217. for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
  1218. if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
  1219. return nullptr;
  1220. if (Op1->getOperand(J) != Op2->getOperand(J)) {
  1221. if (DI == -1) {
  1222. // We have not seen any differences yet in the GEPs feeding the
  1223. // PHI yet, so we record this one if it is allowed to be a
  1224. // variable.
  1225. // The first two arguments can vary for any GEP, the rest have to be
  1226. // static for struct slots
  1227. if (J > 1 && CurTy->isStructTy())
  1228. return nullptr;
  1229. DI = J;
  1230. } else {
  1231. // The GEP is different by more than one input. While this could be
  1232. // extended to support GEPs that vary by more than one variable it
  1233. // doesn't make sense since it greatly increases the complexity and
  1234. // would result in an R+R+R addressing mode which no backend
  1235. // directly supports and would need to be broken into several
  1236. // simpler instructions anyway.
  1237. return nullptr;
  1238. }
  1239. }
  1240. // Sink down a layer of the type for the next iteration.
  1241. if (J > 0) {
  1242. if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
  1243. CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
  1244. } else {
  1245. CurTy = nullptr;
  1246. }
  1247. }
  1248. }
  1249. }
  1250. GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
  1251. if (DI == -1) {
  1252. // All the GEPs feeding the PHI are identical. Clone one down into our
  1253. // BB so that it can be merged with the current GEP.
  1254. GEP.getParent()->getInstList().insert(
  1255. GEP.getParent()->getFirstInsertionPt(), NewGEP);
  1256. } else {
  1257. // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
  1258. // into the current block so it can be merged, and create a new PHI to
  1259. // set that index.
  1260. Instruction *InsertPt = Builder->GetInsertPoint();
  1261. Builder->SetInsertPoint(PN);
  1262. PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
  1263. PN->getNumOperands());
  1264. Builder->SetInsertPoint(InsertPt);
  1265. for (auto &I : PN->operands())
  1266. NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
  1267. PN->getIncomingBlock(I));
  1268. NewGEP->setOperand(DI, NewPN);
  1269. GEP.getParent()->getInstList().insert(
  1270. GEP.getParent()->getFirstInsertionPt(), NewGEP);
  1271. NewGEP->setOperand(DI, NewPN);
  1272. }
  1273. GEP.setOperand(0, NewGEP);
  1274. PtrOp = NewGEP;
  1275. }
  1276. // Combine Indices - If the source pointer to this getelementptr instruction
  1277. // is a getelementptr instruction, combine the indices of the two
  1278. // getelementptr instructions into a single instruction.
  1279. //
  1280. if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
  1281. if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
  1282. return nullptr;
  1283. // Note that if our source is a gep chain itself then we wait for that
  1284. // chain to be resolved before we perform this transformation. This
  1285. // avoids us creating a TON of code in some cases.
  1286. if (GEPOperator *SrcGEP =
  1287. dyn_cast<GEPOperator>(Src->getOperand(0)))
  1288. if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
  1289. return nullptr; // Wait until our source is folded to completion.
  1290. SmallVector<Value*, 8> Indices;
  1291. // Find out whether the last index in the source GEP is a sequential idx.
  1292. bool EndsWithSequential = false;
  1293. for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
  1294. I != E; ++I)
  1295. EndsWithSequential = !(*I)->isStructTy();
  1296. // Can we combine the two pointer arithmetics offsets?
  1297. if (EndsWithSequential) {
  1298. // Replace: gep (gep %P, long B), long A, ...
  1299. // With: T = long A+B; gep %P, T, ...
  1300. //
  1301. Value *Sum;
  1302. Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
  1303. Value *GO1 = GEP.getOperand(1);
  1304. if (SO1 == Constant::getNullValue(SO1->getType())) {
  1305. Sum = GO1;
  1306. } else if (GO1 == Constant::getNullValue(GO1->getType())) {
  1307. Sum = SO1;
  1308. } else {
  1309. // If they aren't the same type, then the input hasn't been processed
  1310. // by the loop above yet (which canonicalizes sequential index types to
  1311. // intptr_t). Just avoid transforming this until the input has been
  1312. // normalized.
  1313. if (SO1->getType() != GO1->getType())
  1314. return nullptr;
  1315. // Only do the combine when GO1 and SO1 are both constants. Only in
  1316. // this case, we are sure the cost after the merge is never more than
  1317. // that before the merge.
  1318. if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
  1319. return nullptr;
  1320. Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
  1321. }
  1322. // Update the GEP in place if possible.
  1323. if (Src->getNumOperands() == 2) {
  1324. GEP.setOperand(0, Src->getOperand(0));
  1325. GEP.setOperand(1, Sum);
  1326. return &GEP;
  1327. }
  1328. Indices.append(Src->op_begin()+1, Src->op_end()-1);
  1329. Indices.push_back(Sum);
  1330. Indices.append(GEP.op_begin()+2, GEP.op_end());
  1331. } else if (isa<Constant>(*GEP.idx_begin()) &&
  1332. cast<Constant>(*GEP.idx_begin())->isNullValue() &&
  1333. Src->getNumOperands() != 1) {
  1334. // Otherwise we can do the fold if the first index of the GEP is a zero
  1335. Indices.append(Src->op_begin()+1, Src->op_end());
  1336. Indices.append(GEP.idx_begin()+1, GEP.idx_end());
  1337. }
  1338. if (!Indices.empty())
  1339. return GEP.isInBounds() && Src->isInBounds()
  1340. ? GetElementPtrInst::CreateInBounds(
  1341. Src->getSourceElementType(), Src->getOperand(0), Indices,
  1342. GEP.getName())
  1343. : GetElementPtrInst::Create(Src->getSourceElementType(),
  1344. Src->getOperand(0), Indices,
  1345. GEP.getName());
  1346. }
  1347. if (GEP.getNumIndices() == 1) {
  1348. unsigned AS = GEP.getPointerAddressSpace();
  1349. if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
  1350. DL.getPointerSizeInBits(AS)) {
  1351. Type *PtrTy = GEP.getPointerOperandType();
  1352. Type *Ty = PtrTy->getPointerElementType();
  1353. uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
  1354. bool Matched = false;
  1355. uint64_t C;
  1356. Value *V = nullptr;
  1357. if (TyAllocSize == 1) {
  1358. V = GEP.getOperand(1);
  1359. Matched = true;
  1360. } else if (match(GEP.getOperand(1),
  1361. m_AShr(m_Value(V), m_ConstantInt(C)))) {
  1362. if (TyAllocSize == 1ULL << C)
  1363. Matched = true;
  1364. } else if (match(GEP.getOperand(1),
  1365. m_SDiv(m_Value(V), m_ConstantInt(C)))) {
  1366. if (TyAllocSize == C)
  1367. Matched = true;
  1368. }
  1369. if (Matched) {
  1370. // Canonicalize (gep i8* X, -(ptrtoint Y))
  1371. // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
  1372. // The GEP pattern is emitted by the SCEV expander for certain kinds of
  1373. // pointer arithmetic.
  1374. if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
  1375. Operator *Index = cast<Operator>(V);
  1376. Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
  1377. Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
  1378. return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
  1379. }
  1380. // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
  1381. // to (bitcast Y)
  1382. Value *Y;
  1383. if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
  1384. m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
  1385. return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
  1386. GEP.getType());
  1387. }
  1388. }
  1389. }
  1390. }
  1391. // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
  1392. Value *StrippedPtr = PtrOp->stripPointerCasts();
  1393. PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
  1394. // We do not handle pointer-vector geps here.
  1395. if (!StrippedPtrTy)
  1396. return nullptr;
  1397. if (StrippedPtr != PtrOp) {
  1398. bool HasZeroPointerIndex = false;
  1399. if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
  1400. HasZeroPointerIndex = C->isZero();
  1401. // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
  1402. // into : GEP [10 x i8]* X, i32 0, ...
  1403. //
  1404. // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
  1405. // into : GEP i8* X, ...
  1406. //
  1407. // This occurs when the program declares an array extern like "int X[];"
  1408. if (HasZeroPointerIndex) {
  1409. PointerType *CPTy = cast<PointerType>(PtrOp->getType());
  1410. if (ArrayType *CATy =
  1411. dyn_cast<ArrayType>(CPTy->getElementType())) {
  1412. // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
  1413. if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
  1414. // -> GEP i8* X, ...
  1415. SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
  1416. GetElementPtrInst *Res = GetElementPtrInst::Create(
  1417. StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
  1418. Res->setIsInBounds(GEP.isInBounds());
  1419. if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
  1420. return Res;
  1421. // Insert Res, and create an addrspacecast.
  1422. // e.g.,
  1423. // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
  1424. // ->
  1425. // %0 = GEP i8 addrspace(1)* X, ...
  1426. // addrspacecast i8 addrspace(1)* %0 to i8*
  1427. return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
  1428. }
  1429. if (ArrayType *XATy =
  1430. dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
  1431. // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
  1432. if (CATy->getElementType() == XATy->getElementType()) {
  1433. // -> GEP [10 x i8]* X, i32 0, ...
  1434. // At this point, we know that the cast source type is a pointer
  1435. // to an array of the same type as the destination pointer
  1436. // array. Because the array type is never stepped over (there
  1437. // is a leading zero) we can fold the cast into this GEP.
  1438. if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
  1439. GEP.setOperand(0, StrippedPtr);
  1440. GEP.setSourceElementType(XATy);
  1441. return &GEP;
  1442. }
  1443. // Cannot replace the base pointer directly because StrippedPtr's
  1444. // address space is different. Instead, create a new GEP followed by
  1445. // an addrspacecast.
  1446. // e.g.,
  1447. // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
  1448. // i32 0, ...
  1449. // ->
  1450. // %0 = GEP [10 x i8] addrspace(1)* X, ...
  1451. // addrspacecast i8 addrspace(1)* %0 to i8*
  1452. SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
  1453. Value *NewGEP = GEP.isInBounds()
  1454. ? Builder->CreateInBoundsGEP(
  1455. nullptr, StrippedPtr, Idx, GEP.getName())
  1456. : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
  1457. GEP.getName());
  1458. return new AddrSpaceCastInst(NewGEP, GEP.getType());
  1459. }
  1460. }
  1461. }
  1462. } else if (GEP.getNumOperands() == 2) {
  1463. // Transform things like:
  1464. // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
  1465. // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
  1466. Type *SrcElTy = StrippedPtrTy->getElementType();
  1467. Type *ResElTy = PtrOp->getType()->getPointerElementType();
  1468. if (SrcElTy->isArrayTy() &&
  1469. DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
  1470. DL.getTypeAllocSize(ResElTy)) {
  1471. Type *IdxType = DL.getIntPtrType(GEP.getType());
  1472. Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
  1473. Value *NewGEP =
  1474. GEP.isInBounds()
  1475. ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
  1476. GEP.getName())
  1477. : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
  1478. // V and GEP are both pointer types --> BitCast
  1479. return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
  1480. GEP.getType());
  1481. }
  1482. // Transform things like:
  1483. // %V = mul i64 %N, 4
  1484. // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
  1485. // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
  1486. if (ResElTy->isSized() && SrcElTy->isSized()) {
  1487. // Check that changing the type amounts to dividing the index by a scale
  1488. // factor.
  1489. uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
  1490. uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
  1491. if (ResSize && SrcSize % ResSize == 0) {
  1492. Value *Idx = GEP.getOperand(1);
  1493. unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
  1494. uint64_t Scale = SrcSize / ResSize;
  1495. // Earlier transforms ensure that the index has type IntPtrType, which
  1496. // considerably simplifies the logic by eliminating implicit casts.
  1497. assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
  1498. "Index not cast to pointer width?");
  1499. bool NSW;
  1500. if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
  1501. // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
  1502. // If the multiplication NewIdx * Scale may overflow then the new
  1503. // GEP may not be "inbounds".
  1504. Value *NewGEP =
  1505. GEP.isInBounds() && NSW
  1506. ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
  1507. GEP.getName())
  1508. : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
  1509. GEP.getName());
  1510. // The NewGEP must be pointer typed, so must the old one -> BitCast
  1511. return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
  1512. GEP.getType());
  1513. }
  1514. }
  1515. }
  1516. // Similarly, transform things like:
  1517. // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
  1518. // (where tmp = 8*tmp2) into:
  1519. // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
  1520. if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
  1521. // Check that changing to the array element type amounts to dividing the
  1522. // index by a scale factor.
  1523. uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
  1524. uint64_t ArrayEltSize =
  1525. DL.getTypeAllocSize(SrcElTy->getArrayElementType());
  1526. if (ResSize && ArrayEltSize % ResSize == 0) {
  1527. Value *Idx = GEP.getOperand(1);
  1528. unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
  1529. uint64_t Scale = ArrayEltSize / ResSize;
  1530. // Earlier transforms ensure that the index has type IntPtrType, which
  1531. // considerably simplifies the logic by eliminating implicit casts.
  1532. assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
  1533. "Index not cast to pointer width?");
  1534. bool NSW;
  1535. if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
  1536. // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
  1537. // If the multiplication NewIdx * Scale may overflow then the new
  1538. // GEP may not be "inbounds".
  1539. Value *Off[2] = {
  1540. Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
  1541. NewIdx};
  1542. Value *NewGEP = GEP.isInBounds() && NSW
  1543. ? Builder->CreateInBoundsGEP(
  1544. SrcElTy, StrippedPtr, Off, GEP.getName())
  1545. : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
  1546. GEP.getName());
  1547. // The NewGEP must be pointer typed, so must the old one -> BitCast
  1548. return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
  1549. GEP.getType());
  1550. }
  1551. }
  1552. }
  1553. }
  1554. }
  1555. // addrspacecast between types is canonicalized as a bitcast, then an
  1556. // addrspacecast. To take advantage of the below bitcast + struct GEP, look
  1557. // through the addrspacecast.
  1558. if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
  1559. // X = bitcast A addrspace(1)* to B addrspace(1)*
  1560. // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
  1561. // Z = gep Y, <...constant indices...>
  1562. // Into an addrspacecasted GEP of the struct.
  1563. if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
  1564. PtrOp = BC;
  1565. }
  1566. /// See if we can simplify:
  1567. /// X = bitcast A* to B*
  1568. /// Y = gep X, <...constant indices...>
  1569. /// into a gep of the original struct. This is important for SROA and alias
  1570. /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
  1571. if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
  1572. Value *Operand = BCI->getOperand(0);
  1573. PointerType *OpType = cast<PointerType>(Operand->getType());
  1574. unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
  1575. APInt Offset(OffsetBits, 0);
  1576. if (!isa<BitCastInst>(Operand) &&
  1577. GEP.accumulateConstantOffset(DL, Offset)) {
  1578. // If this GEP instruction doesn't move the pointer, just replace the GEP
  1579. // with a bitcast of the real input to the dest type.
  1580. if (!Offset) {
  1581. // If the bitcast is of an allocation, and the allocation will be
  1582. // converted to match the type of the cast, don't touch this.
  1583. if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
  1584. // See if the bitcast simplifies, if so, don't nuke this GEP yet.
  1585. if (Instruction *I = visitBitCast(*BCI)) {
  1586. if (I != BCI) {
  1587. I->takeName(BCI);
  1588. BCI->getParent()->getInstList().insert(BCI, I);
  1589. ReplaceInstUsesWith(*BCI, I);
  1590. }
  1591. return &GEP;
  1592. }
  1593. }
  1594. if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
  1595. return new AddrSpaceCastInst(Operand, GEP.getType());
  1596. return new BitCastInst(Operand, GEP.getType());
  1597. }
  1598. // Otherwise, if the offset is non-zero, we need to find out if there is a
  1599. // field at Offset in 'A's type. If so, we can pull the cast through the
  1600. // GEP.
  1601. SmallVector<Value*, 8> NewIndices;
  1602. if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
  1603. Value *NGEP =
  1604. GEP.isInBounds()
  1605. ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
  1606. : Builder->CreateGEP(nullptr, Operand, NewIndices);
  1607. if (NGEP->getType() == GEP.getType())
  1608. return ReplaceInstUsesWith(GEP, NGEP);
  1609. NGEP->takeName(&GEP);
  1610. if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
  1611. return new AddrSpaceCastInst(NGEP, GEP.getType());
  1612. return new BitCastInst(NGEP, GEP.getType());
  1613. }
  1614. }
  1615. }
  1616. return nullptr;
  1617. }
  1618. static bool
  1619. isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
  1620. const TargetLibraryInfo *TLI) {
  1621. SmallVector<Instruction*, 4> Worklist;
  1622. Worklist.push_back(AI);
  1623. do {
  1624. Instruction *PI = Worklist.pop_back_val();
  1625. for (User *U : PI->users()) {
  1626. Instruction *I = cast<Instruction>(U);
  1627. switch (I->getOpcode()) {
  1628. default:
  1629. // Give up the moment we see something we can't handle.
  1630. return false;
  1631. case Instruction::BitCast:
  1632. case Instruction::GetElementPtr:
  1633. Users.emplace_back(I);
  1634. Worklist.push_back(I);
  1635. continue;
  1636. case Instruction::ICmp: {
  1637. ICmpInst *ICI = cast<ICmpInst>(I);
  1638. // We can fold eq/ne comparisons with null to false/true, respectively.
  1639. if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
  1640. return false;
  1641. Users.emplace_back(I);
  1642. continue;
  1643. }
  1644. case Instruction::Call:
  1645. // Ignore no-op and store intrinsics.
  1646. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  1647. switch (II->getIntrinsicID()) {
  1648. default:
  1649. return false;
  1650. case Intrinsic::memmove:
  1651. case Intrinsic::memcpy:
  1652. case Intrinsic::memset: {
  1653. MemIntrinsic *MI = cast<MemIntrinsic>(II);
  1654. if (MI->isVolatile() || MI->getRawDest() != PI)
  1655. return false;
  1656. }
  1657. // fall through
  1658. case Intrinsic::dbg_declare:
  1659. case Intrinsic::dbg_value:
  1660. case Intrinsic::invariant_start:
  1661. case Intrinsic::invariant_end:
  1662. case Intrinsic::lifetime_start:
  1663. case Intrinsic::lifetime_end:
  1664. case Intrinsic::objectsize:
  1665. Users.emplace_back(I);
  1666. continue;
  1667. }
  1668. }
  1669. if (isFreeCall(I, TLI)) {
  1670. Users.emplace_back(I);
  1671. continue;
  1672. }
  1673. return false;
  1674. case Instruction::Store: {
  1675. StoreInst *SI = cast<StoreInst>(I);
  1676. if (SI->isVolatile() || SI->getPointerOperand() != PI)
  1677. return false;
  1678. Users.emplace_back(I);
  1679. continue;
  1680. }
  1681. }
  1682. llvm_unreachable("missing a return?");
  1683. }
  1684. } while (!Worklist.empty());
  1685. return true;
  1686. }
  1687. Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
  1688. // If we have a malloc call which is only used in any amount of comparisons
  1689. // to null and free calls, delete the calls and replace the comparisons with
  1690. // true or false as appropriate.
  1691. SmallVector<WeakVH, 64> Users;
  1692. if (isAllocSiteRemovable(&MI, Users, TLI)) {
  1693. for (unsigned i = 0, e = Users.size(); i != e; ++i) {
  1694. Instruction *I = cast_or_null<Instruction>(&*Users[i]);
  1695. if (!I) continue;
  1696. if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
  1697. ReplaceInstUsesWith(*C,
  1698. ConstantInt::get(Type::getInt1Ty(C->getContext()),
  1699. C->isFalseWhenEqual()));
  1700. } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
  1701. ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
  1702. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  1703. if (II->getIntrinsicID() == Intrinsic::objectsize) {
  1704. ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
  1705. uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
  1706. ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
  1707. }
  1708. }
  1709. EraseInstFromFunction(*I);
  1710. }
  1711. if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
  1712. // Replace invoke with a NOP intrinsic to maintain the original CFG
  1713. Module *M = II->getParent()->getParent()->getParent();
  1714. Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
  1715. InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
  1716. None, "", II->getParent());
  1717. }
  1718. return EraseInstFromFunction(MI);
  1719. }
  1720. return nullptr;
  1721. }
  1722. /// \brief Move the call to free before a NULL test.
  1723. ///
  1724. /// Check if this free is accessed after its argument has been test
  1725. /// against NULL (property 0).
  1726. /// If yes, it is legal to move this call in its predecessor block.
  1727. ///
  1728. /// The move is performed only if the block containing the call to free
  1729. /// will be removed, i.e.:
  1730. /// 1. it has only one predecessor P, and P has two successors
  1731. /// 2. it contains the call and an unconditional branch
  1732. /// 3. its successor is the same as its predecessor's successor
  1733. ///
  1734. /// The profitability is out-of concern here and this function should
  1735. /// be called only if the caller knows this transformation would be
  1736. /// profitable (e.g., for code size).
  1737. static Instruction *
  1738. tryToMoveFreeBeforeNullTest(CallInst &FI) {
  1739. Value *Op = FI.getArgOperand(0);
  1740. BasicBlock *FreeInstrBB = FI.getParent();
  1741. BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
  1742. // Validate part of constraint #1: Only one predecessor
  1743. // FIXME: We can extend the number of predecessor, but in that case, we
  1744. // would duplicate the call to free in each predecessor and it may
  1745. // not be profitable even for code size.
  1746. if (!PredBB)
  1747. return nullptr;
  1748. // Validate constraint #2: Does this block contains only the call to
  1749. // free and an unconditional branch?
  1750. // FIXME: We could check if we can speculate everything in the
  1751. // predecessor block
  1752. if (FreeInstrBB->size() != 2)
  1753. return nullptr;
  1754. BasicBlock *SuccBB;
  1755. if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
  1756. return nullptr;
  1757. // Validate the rest of constraint #1 by matching on the pred branch.
  1758. TerminatorInst *TI = PredBB->getTerminator();
  1759. BasicBlock *TrueBB, *FalseBB;
  1760. ICmpInst::Predicate Pred;
  1761. if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
  1762. return nullptr;
  1763. if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
  1764. return nullptr;
  1765. // Validate constraint #3: Ensure the null case just falls through.
  1766. if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
  1767. return nullptr;
  1768. assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
  1769. "Broken CFG: missing edge from predecessor to successor");
  1770. FI.moveBefore(TI);
  1771. return &FI;
  1772. }
  1773. Instruction *InstCombiner::visitFree(CallInst &FI) {
  1774. Value *Op = FI.getArgOperand(0);
  1775. // free undef -> unreachable.
  1776. if (isa<UndefValue>(Op)) {
  1777. // Insert a new store to null because we cannot modify the CFG here.
  1778. Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
  1779. UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
  1780. return EraseInstFromFunction(FI);
  1781. }
  1782. // If we have 'free null' delete the instruction. This can happen in stl code
  1783. // when lots of inlining happens.
  1784. if (isa<ConstantPointerNull>(Op))
  1785. return EraseInstFromFunction(FI);
  1786. // If we optimize for code size, try to move the call to free before the null
  1787. // test so that simplify cfg can remove the empty block and dead code
  1788. // elimination the branch. I.e., helps to turn something like:
  1789. // if (foo) free(foo);
  1790. // into
  1791. // free(foo);
  1792. if (MinimizeSize)
  1793. if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
  1794. return I;
  1795. return nullptr;
  1796. }
  1797. Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
  1798. if (RI.getNumOperands() == 0) // ret void
  1799. return nullptr;
  1800. Value *ResultOp = RI.getOperand(0);
  1801. Type *VTy = ResultOp->getType();
  1802. if (!VTy->isIntegerTy())
  1803. return nullptr;
  1804. // There might be assume intrinsics dominating this return that completely
  1805. // determine the value. If so, constant fold it.
  1806. unsigned BitWidth = VTy->getPrimitiveSizeInBits();
  1807. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  1808. computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
  1809. if ((KnownZero|KnownOne).isAllOnesValue())
  1810. RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
  1811. return nullptr;
  1812. }
  1813. Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
  1814. // Change br (not X), label True, label False to: br X, label False, True
  1815. Value *X = nullptr;
  1816. BasicBlock *TrueDest;
  1817. BasicBlock *FalseDest;
  1818. if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
  1819. !isa<Constant>(X)) {
  1820. // Swap Destinations and condition...
  1821. BI.setCondition(X);
  1822. BI.swapSuccessors();
  1823. return &BI;
  1824. }
  1825. // If the condition is irrelevant, remove the use so that other
  1826. // transforms on the condition become more effective.
  1827. if (BI.isConditional() &&
  1828. BI.getSuccessor(0) == BI.getSuccessor(1) &&
  1829. !isa<UndefValue>(BI.getCondition())) {
  1830. BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
  1831. return &BI;
  1832. }
  1833. // Canonicalize fcmp_one -> fcmp_oeq
  1834. FCmpInst::Predicate FPred; Value *Y;
  1835. if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
  1836. TrueDest, FalseDest)) &&
  1837. BI.getCondition()->hasOneUse())
  1838. if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
  1839. FPred == FCmpInst::FCMP_OGE) {
  1840. FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
  1841. Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
  1842. // Swap Destinations and condition.
  1843. BI.swapSuccessors();
  1844. Worklist.Add(Cond);
  1845. return &BI;
  1846. }
  1847. // Canonicalize icmp_ne -> icmp_eq
  1848. ICmpInst::Predicate IPred;
  1849. if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
  1850. TrueDest, FalseDest)) &&
  1851. BI.getCondition()->hasOneUse())
  1852. if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
  1853. IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
  1854. IPred == ICmpInst::ICMP_SGE) {
  1855. ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
  1856. Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
  1857. // Swap Destinations and condition.
  1858. BI.swapSuccessors();
  1859. Worklist.Add(Cond);
  1860. return &BI;
  1861. }
  1862. return nullptr;
  1863. }
  1864. Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
  1865. Value *Cond = SI.getCondition();
  1866. unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
  1867. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  1868. computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
  1869. unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
  1870. unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
  1871. // Compute the number of leading bits we can ignore.
  1872. for (auto &C : SI.cases()) {
  1873. LeadingKnownZeros = std::min(
  1874. LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
  1875. LeadingKnownOnes = std::min(
  1876. LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
  1877. }
  1878. unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
  1879. // Truncate the condition operand if the new type is equal to or larger than
  1880. // the largest legal integer type. We need to be conservative here since
  1881. // x86 generates redundant zero-extension instructions if the operand is
  1882. // truncated to i8 or i16.
  1883. bool TruncCond = false;
  1884. if (NewWidth > 0 && BitWidth > NewWidth &&
  1885. NewWidth >= DL.getLargestLegalIntTypeSize()) {
  1886. TruncCond = true;
  1887. IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
  1888. Builder->SetInsertPoint(&SI);
  1889. Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
  1890. SI.setCondition(NewCond);
  1891. for (auto &C : SI.cases())
  1892. static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
  1893. SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
  1894. }
  1895. if (Instruction *I = dyn_cast<Instruction>(Cond)) {
  1896. if (I->getOpcode() == Instruction::Add)
  1897. if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
  1898. // change 'switch (X+4) case 1:' into 'switch (X) case -3'
  1899. // Skip the first item since that's the default case.
  1900. for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
  1901. i != e; ++i) {
  1902. ConstantInt* CaseVal = i.getCaseValue();
  1903. Constant *LHS = CaseVal;
  1904. if (TruncCond)
  1905. LHS = LeadingKnownZeros
  1906. ? ConstantExpr::getZExt(CaseVal, Cond->getType())
  1907. : ConstantExpr::getSExt(CaseVal, Cond->getType());
  1908. Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
  1909. assert(isa<ConstantInt>(NewCaseVal) &&
  1910. "Result of expression should be constant");
  1911. i.setValue(cast<ConstantInt>(NewCaseVal));
  1912. }
  1913. SI.setCondition(I->getOperand(0));
  1914. Worklist.Add(I);
  1915. return &SI;
  1916. }
  1917. }
  1918. return TruncCond ? &SI : nullptr;
  1919. }
  1920. Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
  1921. Value *Agg = EV.getAggregateOperand();
  1922. if (!EV.hasIndices())
  1923. return ReplaceInstUsesWith(EV, Agg);
  1924. if (Value *V =
  1925. SimplifyExtractValueInst(Agg, EV.getIndices(), DL, TLI, DT, AC))
  1926. return ReplaceInstUsesWith(EV, V);
  1927. if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
  1928. // We're extracting from an insertvalue instruction, compare the indices
  1929. const unsigned *exti, *exte, *insi, *inse;
  1930. for (exti = EV.idx_begin(), insi = IV->idx_begin(),
  1931. exte = EV.idx_end(), inse = IV->idx_end();
  1932. exti != exte && insi != inse;
  1933. ++exti, ++insi) {
  1934. if (*insi != *exti)
  1935. // The insert and extract both reference distinctly different elements.
  1936. // This means the extract is not influenced by the insert, and we can
  1937. // replace the aggregate operand of the extract with the aggregate
  1938. // operand of the insert. i.e., replace
  1939. // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
  1940. // %E = extractvalue { i32, { i32 } } %I, 0
  1941. // with
  1942. // %E = extractvalue { i32, { i32 } } %A, 0
  1943. return ExtractValueInst::Create(IV->getAggregateOperand(),
  1944. EV.getIndices());
  1945. }
  1946. if (exti == exte && insi == inse)
  1947. // Both iterators are at the end: Index lists are identical. Replace
  1948. // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
  1949. // %C = extractvalue { i32, { i32 } } %B, 1, 0
  1950. // with "i32 42"
  1951. return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
  1952. if (exti == exte) {
  1953. // The extract list is a prefix of the insert list. i.e. replace
  1954. // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
  1955. // %E = extractvalue { i32, { i32 } } %I, 1
  1956. // with
  1957. // %X = extractvalue { i32, { i32 } } %A, 1
  1958. // %E = insertvalue { i32 } %X, i32 42, 0
  1959. // by switching the order of the insert and extract (though the
  1960. // insertvalue should be left in, since it may have other uses).
  1961. Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
  1962. EV.getIndices());
  1963. return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
  1964. makeArrayRef(insi, inse));
  1965. }
  1966. if (insi == inse)
  1967. // The insert list is a prefix of the extract list
  1968. // We can simply remove the common indices from the extract and make it
  1969. // operate on the inserted value instead of the insertvalue result.
  1970. // i.e., replace
  1971. // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
  1972. // %E = extractvalue { i32, { i32 } } %I, 1, 0
  1973. // with
  1974. // %E extractvalue { i32 } { i32 42 }, 0
  1975. return ExtractValueInst::Create(IV->getInsertedValueOperand(),
  1976. makeArrayRef(exti, exte));
  1977. }
  1978. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
  1979. // We're extracting from an intrinsic, see if we're the only user, which
  1980. // allows us to simplify multiple result intrinsics to simpler things that
  1981. // just get one value.
  1982. if (II->hasOneUse()) {
  1983. // Check if we're grabbing the overflow bit or the result of a 'with
  1984. // overflow' intrinsic. If it's the latter we can remove the intrinsic
  1985. // and replace it with a traditional binary instruction.
  1986. switch (II->getIntrinsicID()) {
  1987. case Intrinsic::uadd_with_overflow:
  1988. case Intrinsic::sadd_with_overflow:
  1989. if (*EV.idx_begin() == 0) { // Normal result.
  1990. Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
  1991. ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
  1992. EraseInstFromFunction(*II);
  1993. return BinaryOperator::CreateAdd(LHS, RHS);
  1994. }
  1995. // If the normal result of the add is dead, and the RHS is a constant,
  1996. // we can transform this into a range comparison.
  1997. // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
  1998. if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
  1999. if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
  2000. return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
  2001. ConstantExpr::getNot(CI));
  2002. break;
  2003. case Intrinsic::usub_with_overflow:
  2004. case Intrinsic::ssub_with_overflow:
  2005. if (*EV.idx_begin() == 0) { // Normal result.
  2006. Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
  2007. ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
  2008. EraseInstFromFunction(*II);
  2009. return BinaryOperator::CreateSub(LHS, RHS);
  2010. }
  2011. break;
  2012. case Intrinsic::umul_with_overflow:
  2013. case Intrinsic::smul_with_overflow:
  2014. if (*EV.idx_begin() == 0) { // Normal result.
  2015. Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
  2016. ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
  2017. EraseInstFromFunction(*II);
  2018. return BinaryOperator::CreateMul(LHS, RHS);
  2019. }
  2020. break;
  2021. default:
  2022. break;
  2023. }
  2024. }
  2025. }
  2026. if (LoadInst *L = dyn_cast<LoadInst>(Agg))
  2027. // If the (non-volatile) load only has one use, we can rewrite this to a
  2028. // load from a GEP. This reduces the size of the load.
  2029. // FIXME: If a load is used only by extractvalue instructions then this
  2030. // could be done regardless of having multiple uses.
  2031. if (L->isSimple() && L->hasOneUse()) {
  2032. // extractvalue has integer indices, getelementptr has Value*s. Convert.
  2033. SmallVector<Value*, 4> Indices;
  2034. // Prefix an i32 0 since we need the first element.
  2035. Indices.push_back(Builder->getInt32(0));
  2036. for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
  2037. I != E; ++I)
  2038. Indices.push_back(Builder->getInt32(*I));
  2039. // We need to insert these at the location of the old load, not at that of
  2040. // the extractvalue.
  2041. Builder->SetInsertPoint(L->getParent(), L);
  2042. Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
  2043. L->getPointerOperand(), Indices);
  2044. // Returning the load directly will cause the main loop to insert it in
  2045. // the wrong spot, so use ReplaceInstUsesWith().
  2046. return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
  2047. }
  2048. // We could simplify extracts from other values. Note that nested extracts may
  2049. // already be simplified implicitly by the above: extract (extract (insert) )
  2050. // will be translated into extract ( insert ( extract ) ) first and then just
  2051. // the value inserted, if appropriate. Similarly for extracts from single-use
  2052. // loads: extract (extract (load)) will be translated to extract (load (gep))
  2053. // and if again single-use then via load (gep (gep)) to load (gep).
  2054. // However, double extracts from e.g. function arguments or return values
  2055. // aren't handled yet.
  2056. return nullptr;
  2057. }
  2058. /// isCatchAll - Return 'true' if the given typeinfo will match anything.
  2059. static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
  2060. switch (Personality) {
  2061. case EHPersonality::GNU_C:
  2062. // The GCC C EH personality only exists to support cleanups, so it's not
  2063. // clear what the semantics of catch clauses are.
  2064. return false;
  2065. case EHPersonality::Unknown:
  2066. return false;
  2067. case EHPersonality::GNU_Ada:
  2068. // While __gnat_all_others_value will match any Ada exception, it doesn't
  2069. // match foreign exceptions (or didn't, before gcc-4.7).
  2070. return false;
  2071. case EHPersonality::GNU_CXX:
  2072. case EHPersonality::GNU_ObjC:
  2073. case EHPersonality::MSVC_X86SEH:
  2074. case EHPersonality::MSVC_Win64SEH:
  2075. case EHPersonality::MSVC_CXX:
  2076. return TypeInfo->isNullValue();
  2077. }
  2078. llvm_unreachable("invalid enum");
  2079. }
  2080. static bool shorter_filter(const Value *LHS, const Value *RHS) {
  2081. return
  2082. cast<ArrayType>(LHS->getType())->getNumElements()
  2083. <
  2084. cast<ArrayType>(RHS->getType())->getNumElements();
  2085. }
  2086. Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
  2087. // The logic here should be correct for any real-world personality function.
  2088. // However if that turns out not to be true, the offending logic can always
  2089. // be conditioned on the personality function, like the catch-all logic is.
  2090. EHPersonality Personality =
  2091. classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
  2092. // Simplify the list of clauses, eg by removing repeated catch clauses
  2093. // (these are often created by inlining).
  2094. bool MakeNewInstruction = false; // If true, recreate using the following:
  2095. SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
  2096. bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
  2097. SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
  2098. for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
  2099. bool isLastClause = i + 1 == e;
  2100. if (LI.isCatch(i)) {
  2101. // A catch clause.
  2102. Constant *CatchClause = LI.getClause(i);
  2103. Constant *TypeInfo = CatchClause->stripPointerCasts();
  2104. // If we already saw this clause, there is no point in having a second
  2105. // copy of it.
  2106. if (AlreadyCaught.insert(TypeInfo).second) {
  2107. // This catch clause was not already seen.
  2108. NewClauses.push_back(CatchClause);
  2109. } else {
  2110. // Repeated catch clause - drop the redundant copy.
  2111. MakeNewInstruction = true;
  2112. }
  2113. // If this is a catch-all then there is no point in keeping any following
  2114. // clauses or marking the landingpad as having a cleanup.
  2115. if (isCatchAll(Personality, TypeInfo)) {
  2116. if (!isLastClause)
  2117. MakeNewInstruction = true;
  2118. CleanupFlag = false;
  2119. break;
  2120. }
  2121. } else {
  2122. // A filter clause. If any of the filter elements were already caught
  2123. // then they can be dropped from the filter. It is tempting to try to
  2124. // exploit the filter further by saying that any typeinfo that does not
  2125. // occur in the filter can't be caught later (and thus can be dropped).
  2126. // However this would be wrong, since typeinfos can match without being
  2127. // equal (for example if one represents a C++ class, and the other some
  2128. // class derived from it).
  2129. assert(LI.isFilter(i) && "Unsupported landingpad clause!");
  2130. Constant *FilterClause = LI.getClause(i);
  2131. ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
  2132. unsigned NumTypeInfos = FilterType->getNumElements();
  2133. // An empty filter catches everything, so there is no point in keeping any
  2134. // following clauses or marking the landingpad as having a cleanup. By
  2135. // dealing with this case here the following code is made a bit simpler.
  2136. if (!NumTypeInfos) {
  2137. NewClauses.push_back(FilterClause);
  2138. if (!isLastClause)
  2139. MakeNewInstruction = true;
  2140. CleanupFlag = false;
  2141. break;
  2142. }
  2143. bool MakeNewFilter = false; // If true, make a new filter.
  2144. SmallVector<Constant *, 16> NewFilterElts; // New elements.
  2145. if (isa<ConstantAggregateZero>(FilterClause)) {
  2146. // Not an empty filter - it contains at least one null typeinfo.
  2147. assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
  2148. Constant *TypeInfo =
  2149. Constant::getNullValue(FilterType->getElementType());
  2150. // If this typeinfo is a catch-all then the filter can never match.
  2151. if (isCatchAll(Personality, TypeInfo)) {
  2152. // Throw the filter away.
  2153. MakeNewInstruction = true;
  2154. continue;
  2155. }
  2156. // There is no point in having multiple copies of this typeinfo, so
  2157. // discard all but the first copy if there is more than one.
  2158. NewFilterElts.push_back(TypeInfo);
  2159. if (NumTypeInfos > 1)
  2160. MakeNewFilter = true;
  2161. } else {
  2162. ConstantArray *Filter = cast<ConstantArray>(FilterClause);
  2163. SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
  2164. NewFilterElts.reserve(NumTypeInfos);
  2165. // Remove any filter elements that were already caught or that already
  2166. // occurred in the filter. While there, see if any of the elements are
  2167. // catch-alls. If so, the filter can be discarded.
  2168. bool SawCatchAll = false;
  2169. for (unsigned j = 0; j != NumTypeInfos; ++j) {
  2170. Constant *Elt = Filter->getOperand(j);
  2171. Constant *TypeInfo = Elt->stripPointerCasts();
  2172. if (isCatchAll(Personality, TypeInfo)) {
  2173. // This element is a catch-all. Bail out, noting this fact.
  2174. SawCatchAll = true;
  2175. break;
  2176. }
  2177. if (AlreadyCaught.count(TypeInfo))
  2178. // Already caught by an earlier clause, so having it in the filter
  2179. // is pointless.
  2180. continue;
  2181. // There is no point in having multiple copies of the same typeinfo in
  2182. // a filter, so only add it if we didn't already.
  2183. if (SeenInFilter.insert(TypeInfo).second)
  2184. NewFilterElts.push_back(cast<Constant>(Elt));
  2185. }
  2186. // A filter containing a catch-all cannot match anything by definition.
  2187. if (SawCatchAll) {
  2188. // Throw the filter away.
  2189. MakeNewInstruction = true;
  2190. continue;
  2191. }
  2192. // If we dropped something from the filter, make a new one.
  2193. if (NewFilterElts.size() < NumTypeInfos)
  2194. MakeNewFilter = true;
  2195. }
  2196. if (MakeNewFilter) {
  2197. FilterType = ArrayType::get(FilterType->getElementType(),
  2198. NewFilterElts.size());
  2199. FilterClause = ConstantArray::get(FilterType, NewFilterElts);
  2200. MakeNewInstruction = true;
  2201. }
  2202. NewClauses.push_back(FilterClause);
  2203. // If the new filter is empty then it will catch everything so there is
  2204. // no point in keeping any following clauses or marking the landingpad
  2205. // as having a cleanup. The case of the original filter being empty was
  2206. // already handled above.
  2207. if (MakeNewFilter && !NewFilterElts.size()) {
  2208. assert(MakeNewInstruction && "New filter but not a new instruction!");
  2209. CleanupFlag = false;
  2210. break;
  2211. }
  2212. }
  2213. }
  2214. // If several filters occur in a row then reorder them so that the shortest
  2215. // filters come first (those with the smallest number of elements). This is
  2216. // advantageous because shorter filters are more likely to match, speeding up
  2217. // unwinding, but mostly because it increases the effectiveness of the other
  2218. // filter optimizations below.
  2219. for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
  2220. unsigned j;
  2221. // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
  2222. for (j = i; j != e; ++j)
  2223. if (!isa<ArrayType>(NewClauses[j]->getType()))
  2224. break;
  2225. // Check whether the filters are already sorted by length. We need to know
  2226. // if sorting them is actually going to do anything so that we only make a
  2227. // new landingpad instruction if it does.
  2228. for (unsigned k = i; k + 1 < j; ++k)
  2229. if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
  2230. // Not sorted, so sort the filters now. Doing an unstable sort would be
  2231. // correct too but reordering filters pointlessly might confuse users.
  2232. std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
  2233. shorter_filter);
  2234. MakeNewInstruction = true;
  2235. break;
  2236. }
  2237. // Look for the next batch of filters.
  2238. i = j + 1;
  2239. }
  2240. // If typeinfos matched if and only if equal, then the elements of a filter L
  2241. // that occurs later than a filter F could be replaced by the intersection of
  2242. // the elements of F and L. In reality two typeinfos can match without being
  2243. // equal (for example if one represents a C++ class, and the other some class
  2244. // derived from it) so it would be wrong to perform this transform in general.
  2245. // However the transform is correct and useful if F is a subset of L. In that
  2246. // case L can be replaced by F, and thus removed altogether since repeating a
  2247. // filter is pointless. So here we look at all pairs of filters F and L where
  2248. // L follows F in the list of clauses, and remove L if every element of F is
  2249. // an element of L. This can occur when inlining C++ functions with exception
  2250. // specifications.
  2251. for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
  2252. // Examine each filter in turn.
  2253. Value *Filter = NewClauses[i];
  2254. ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
  2255. if (!FTy)
  2256. // Not a filter - skip it.
  2257. continue;
  2258. unsigned FElts = FTy->getNumElements();
  2259. // Examine each filter following this one. Doing this backwards means that
  2260. // we don't have to worry about filters disappearing under us when removed.
  2261. for (unsigned j = NewClauses.size() - 1; j != i; --j) {
  2262. Value *LFilter = NewClauses[j];
  2263. ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
  2264. if (!LTy)
  2265. // Not a filter - skip it.
  2266. continue;
  2267. // If Filter is a subset of LFilter, i.e. every element of Filter is also
  2268. // an element of LFilter, then discard LFilter.
  2269. SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
  2270. // If Filter is empty then it is a subset of LFilter.
  2271. if (!FElts) {
  2272. // Discard LFilter.
  2273. NewClauses.erase(J);
  2274. MakeNewInstruction = true;
  2275. // Move on to the next filter.
  2276. continue;
  2277. }
  2278. unsigned LElts = LTy->getNumElements();
  2279. // If Filter is longer than LFilter then it cannot be a subset of it.
  2280. if (FElts > LElts)
  2281. // Move on to the next filter.
  2282. continue;
  2283. // At this point we know that LFilter has at least one element.
  2284. if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
  2285. // Filter is a subset of LFilter iff Filter contains only zeros (as we
  2286. // already know that Filter is not longer than LFilter).
  2287. if (isa<ConstantAggregateZero>(Filter)) {
  2288. assert(FElts <= LElts && "Should have handled this case earlier!");
  2289. // Discard LFilter.
  2290. NewClauses.erase(J);
  2291. MakeNewInstruction = true;
  2292. }
  2293. // Move on to the next filter.
  2294. continue;
  2295. }
  2296. ConstantArray *LArray = cast<ConstantArray>(LFilter);
  2297. if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
  2298. // Since Filter is non-empty and contains only zeros, it is a subset of
  2299. // LFilter iff LFilter contains a zero.
  2300. assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
  2301. for (unsigned l = 0; l != LElts; ++l)
  2302. if (LArray->getOperand(l)->isNullValue()) {
  2303. // LFilter contains a zero - discard it.
  2304. NewClauses.erase(J);
  2305. MakeNewInstruction = true;
  2306. break;
  2307. }
  2308. // Move on to the next filter.
  2309. continue;
  2310. }
  2311. // At this point we know that both filters are ConstantArrays. Loop over
  2312. // operands to see whether every element of Filter is also an element of
  2313. // LFilter. Since filters tend to be short this is probably faster than
  2314. // using a method that scales nicely.
  2315. ConstantArray *FArray = cast<ConstantArray>(Filter);
  2316. bool AllFound = true;
  2317. for (unsigned f = 0; f != FElts; ++f) {
  2318. Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
  2319. AllFound = false;
  2320. for (unsigned l = 0; l != LElts; ++l) {
  2321. Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
  2322. if (LTypeInfo == FTypeInfo) {
  2323. AllFound = true;
  2324. break;
  2325. }
  2326. }
  2327. if (!AllFound)
  2328. break;
  2329. }
  2330. if (AllFound) {
  2331. // Discard LFilter.
  2332. NewClauses.erase(J);
  2333. MakeNewInstruction = true;
  2334. }
  2335. // Move on to the next filter.
  2336. }
  2337. }
  2338. // If we changed any of the clauses, replace the old landingpad instruction
  2339. // with a new one.
  2340. if (MakeNewInstruction) {
  2341. LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
  2342. NewClauses.size());
  2343. for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
  2344. NLI->addClause(NewClauses[i]);
  2345. // A landing pad with no clauses must have the cleanup flag set. It is
  2346. // theoretically possible, though highly unlikely, that we eliminated all
  2347. // clauses. If so, force the cleanup flag to true.
  2348. if (NewClauses.empty())
  2349. CleanupFlag = true;
  2350. NLI->setCleanup(CleanupFlag);
  2351. return NLI;
  2352. }
  2353. // Even if none of the clauses changed, we may nonetheless have understood
  2354. // that the cleanup flag is pointless. Clear it if so.
  2355. if (LI.isCleanup() != CleanupFlag) {
  2356. assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
  2357. LI.setCleanup(CleanupFlag);
  2358. return &LI;
  2359. }
  2360. return nullptr;
  2361. }
  2362. /// TryToSinkInstruction - Try to move the specified instruction from its
  2363. /// current block into the beginning of DestBlock, which can only happen if it's
  2364. /// safe to move the instruction past all of the instructions between it and the
  2365. /// end of its block.
  2366. static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
  2367. assert(I->hasOneUse() && "Invariants didn't hold!");
  2368. // Cannot move control-flow-involving, volatile loads, vaarg, etc.
  2369. if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
  2370. isa<TerminatorInst>(I))
  2371. return false;
  2372. // Do not sink alloca instructions out of the entry block.
  2373. if (isa<AllocaInst>(I) && I->getParent() ==
  2374. &DestBlock->getParent()->getEntryBlock())
  2375. return false;
  2376. // We can only sink load instructions if there is nothing between the load and
  2377. // the end of block that could change the value.
  2378. if (I->mayReadFromMemory()) {
  2379. for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
  2380. Scan != E; ++Scan)
  2381. if (Scan->mayWriteToMemory())
  2382. return false;
  2383. }
  2384. BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
  2385. I->moveBefore(InsertPos);
  2386. ++NumSunkInst;
  2387. return true;
  2388. }
  2389. bool InstCombiner::run() {
  2390. while (!Worklist.isEmpty()) {
  2391. Instruction *I = Worklist.RemoveOne();
  2392. if (I == nullptr) continue; // skip null values.
  2393. // Check to see if we can DCE the instruction.
  2394. if (isInstructionTriviallyDead(I, TLI)) {
  2395. DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
  2396. EraseInstFromFunction(*I);
  2397. ++NumDeadInst;
  2398. MadeIRChange = true;
  2399. continue;
  2400. }
  2401. // Instruction isn't dead, see if we can constant propagate it.
  2402. if (!I->use_empty() &&
  2403. (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
  2404. if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
  2405. DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
  2406. // Add operands to the worklist.
  2407. ReplaceInstUsesWith(*I, C);
  2408. ++NumConstProp;
  2409. EraseInstFromFunction(*I);
  2410. MadeIRChange = true;
  2411. continue;
  2412. }
  2413. }
  2414. // See if we can trivially sink this instruction to a successor basic block.
  2415. if (I->hasOneUse()) {
  2416. BasicBlock *BB = I->getParent();
  2417. Instruction *UserInst = cast<Instruction>(*I->user_begin());
  2418. BasicBlock *UserParent;
  2419. // Get the block the use occurs in.
  2420. if (PHINode *PN = dyn_cast<PHINode>(UserInst))
  2421. UserParent = PN->getIncomingBlock(*I->use_begin());
  2422. else
  2423. UserParent = UserInst->getParent();
  2424. if (UserParent != BB) {
  2425. bool UserIsSuccessor = false;
  2426. // See if the user is one of our successors.
  2427. for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
  2428. if (*SI == UserParent) {
  2429. UserIsSuccessor = true;
  2430. break;
  2431. }
  2432. // If the user is one of our immediate successors, and if that successor
  2433. // only has us as a predecessors (we'd have to split the critical edge
  2434. // otherwise), we can keep going.
  2435. if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
  2436. // Okay, the CFG is simple enough, try to sink this instruction.
  2437. if (TryToSinkInstruction(I, UserParent)) {
  2438. MadeIRChange = true;
  2439. // We'll add uses of the sunk instruction below, but since sinking
  2440. // can expose opportunities for it's *operands* add them to the
  2441. // worklist
  2442. for (Use &U : I->operands())
  2443. if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
  2444. Worklist.Add(OpI);
  2445. }
  2446. }
  2447. }
  2448. }
  2449. // Now that we have an instruction, try combining it to simplify it.
  2450. Builder->SetInsertPoint(I->getParent(), I);
  2451. Builder->SetCurrentDebugLocation(I->getDebugLoc());
  2452. #ifndef NDEBUG
  2453. std::string OrigI;
  2454. #endif
  2455. DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
  2456. DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
  2457. if (Instruction *Result = visit(*I)) {
  2458. ++NumCombined;
  2459. // Should we replace the old instruction with a new one?
  2460. if (Result != I) {
  2461. DEBUG(dbgs() << "IC: Old = " << *I << '\n'
  2462. << " New = " << *Result << '\n');
  2463. if (I->getDebugLoc())
  2464. Result->setDebugLoc(I->getDebugLoc());
  2465. // Everything uses the new instruction now.
  2466. I->replaceAllUsesWith(Result);
  2467. // Move the name to the new instruction first.
  2468. Result->takeName(I);
  2469. // Push the new instruction and any users onto the worklist.
  2470. Worklist.Add(Result);
  2471. Worklist.AddUsersToWorkList(*Result);
  2472. // Insert the new instruction into the basic block...
  2473. BasicBlock *InstParent = I->getParent();
  2474. BasicBlock::iterator InsertPos = I;
  2475. // If we replace a PHI with something that isn't a PHI, fix up the
  2476. // insertion point.
  2477. if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
  2478. InsertPos = InstParent->getFirstInsertionPt();
  2479. InstParent->getInstList().insert(InsertPos, Result);
  2480. EraseInstFromFunction(*I);
  2481. } else {
  2482. #ifndef NDEBUG
  2483. DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
  2484. << " New = " << *I << '\n');
  2485. #endif
  2486. // If the instruction was modified, it's possible that it is now dead.
  2487. // if so, remove it.
  2488. if (isInstructionTriviallyDead(I, TLI)) {
  2489. EraseInstFromFunction(*I);
  2490. } else {
  2491. Worklist.Add(I);
  2492. Worklist.AddUsersToWorkList(*I);
  2493. }
  2494. }
  2495. MadeIRChange = true;
  2496. }
  2497. }
  2498. Worklist.Zap();
  2499. return MadeIRChange;
  2500. }
  2501. /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
  2502. /// all reachable code to the worklist.
  2503. ///
  2504. /// This has a couple of tricks to make the code faster and more powerful. In
  2505. /// particular, we constant fold and DCE instructions as we go, to avoid adding
  2506. /// them to the worklist (this significantly speeds up instcombine on code where
  2507. /// many instructions are dead or constant). Additionally, if we find a branch
  2508. /// whose condition is a known constant, we only visit the reachable successors.
  2509. ///
  2510. static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
  2511. SmallPtrSetImpl<BasicBlock *> &Visited,
  2512. InstCombineWorklist &ICWorklist,
  2513. const TargetLibraryInfo *TLI) {
  2514. bool MadeIRChange = false;
  2515. SmallVector<BasicBlock*, 256> Worklist;
  2516. Worklist.push_back(BB);
  2517. SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
  2518. DenseMap<ConstantExpr*, Constant*> FoldedConstants;
  2519. do {
  2520. BB = Worklist.pop_back_val();
  2521. // We have now visited this block! If we've already been here, ignore it.
  2522. if (!Visited.insert(BB).second)
  2523. continue;
  2524. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
  2525. Instruction *Inst = BBI++;
  2526. // DCE instruction if trivially dead.
  2527. if (isInstructionTriviallyDead(Inst, TLI)) {
  2528. ++NumDeadInst;
  2529. DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
  2530. Inst->eraseFromParent();
  2531. continue;
  2532. }
  2533. // ConstantProp instruction if trivially constant.
  2534. if (!Inst->use_empty() &&
  2535. (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
  2536. if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
  2537. DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
  2538. << *Inst << '\n');
  2539. Inst->replaceAllUsesWith(C);
  2540. ++NumConstProp;
  2541. Inst->eraseFromParent();
  2542. continue;
  2543. }
  2544. // See if we can constant fold its operands.
  2545. for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
  2546. ++i) {
  2547. ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
  2548. if (CE == nullptr)
  2549. continue;
  2550. Constant *&FoldRes = FoldedConstants[CE];
  2551. if (!FoldRes)
  2552. FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
  2553. if (!FoldRes)
  2554. FoldRes = CE;
  2555. if (FoldRes != CE) {
  2556. *i = FoldRes;
  2557. MadeIRChange = true;
  2558. }
  2559. }
  2560. InstrsForInstCombineWorklist.push_back(Inst);
  2561. }
  2562. // Recursively visit successors. If this is a branch or switch on a
  2563. // constant, only visit the reachable successor.
  2564. TerminatorInst *TI = BB->getTerminator();
  2565. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  2566. if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
  2567. bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
  2568. BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
  2569. Worklist.push_back(ReachableBB);
  2570. continue;
  2571. }
  2572. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  2573. if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
  2574. // See if this is an explicit destination.
  2575. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  2576. i != e; ++i)
  2577. if (i.getCaseValue() == Cond) {
  2578. BasicBlock *ReachableBB = i.getCaseSuccessor();
  2579. Worklist.push_back(ReachableBB);
  2580. continue;
  2581. }
  2582. // Otherwise it is the default destination.
  2583. Worklist.push_back(SI->getDefaultDest());
  2584. continue;
  2585. }
  2586. }
  2587. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  2588. Worklist.push_back(TI->getSuccessor(i));
  2589. } while (!Worklist.empty());
  2590. // Once we've found all of the instructions to add to instcombine's worklist,
  2591. // add them in reverse order. This way instcombine will visit from the top
  2592. // of the function down. This jives well with the way that it adds all uses
  2593. // of instructions to the worklist after doing a transformation, thus avoiding
  2594. // some N^2 behavior in pathological cases.
  2595. ICWorklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
  2596. InstrsForInstCombineWorklist.size());
  2597. return MadeIRChange;
  2598. }
  2599. /// \brief Populate the IC worklist from a function, and prune any dead basic
  2600. /// blocks discovered in the process.
  2601. ///
  2602. /// This also does basic constant propagation and other forward fixing to make
  2603. /// the combiner itself run much faster.
  2604. static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
  2605. TargetLibraryInfo *TLI,
  2606. InstCombineWorklist &ICWorklist) {
  2607. bool MadeIRChange = false;
  2608. // Do a depth-first traversal of the function, populate the worklist with
  2609. // the reachable instructions. Ignore blocks that are not reachable. Keep
  2610. // track of which blocks we visit.
  2611. SmallPtrSet<BasicBlock *, 64> Visited;
  2612. MadeIRChange |=
  2613. AddReachableCodeToWorklist(F.begin(), DL, Visited, ICWorklist, TLI);
  2614. // Do a quick scan over the function. If we find any blocks that are
  2615. // unreachable, remove any instructions inside of them. This prevents
  2616. // the instcombine code from having to deal with some bad special cases.
  2617. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  2618. if (Visited.count(BB))
  2619. continue;
  2620. // Delete the instructions backwards, as it has a reduced likelihood of
  2621. // having to update as many def-use and use-def chains.
  2622. Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
  2623. while (EndInst != BB->begin()) {
  2624. // Delete the next to last instruction.
  2625. BasicBlock::iterator I = EndInst;
  2626. Instruction *Inst = --I;
  2627. if (!Inst->use_empty())
  2628. Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
  2629. if (isa<LandingPadInst>(Inst)) {
  2630. EndInst = Inst;
  2631. continue;
  2632. }
  2633. if (!isa<DbgInfoIntrinsic>(Inst)) {
  2634. ++NumDeadInst;
  2635. MadeIRChange = true;
  2636. }
  2637. Inst->eraseFromParent();
  2638. }
  2639. }
  2640. return MadeIRChange;
  2641. }
  2642. static bool
  2643. combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
  2644. AliasAnalysis *AA, AssumptionCache &AC,
  2645. TargetLibraryInfo &TLI, DominatorTree &DT,
  2646. LoopInfo *LI = nullptr) {
  2647. // Minimizing size?
  2648. bool MinimizeSize = F.hasFnAttribute(Attribute::MinSize);
  2649. auto &DL = F.getParent()->getDataLayout();
  2650. /// Builder - This is an IRBuilder that automatically inserts new
  2651. /// instructions into the worklist when they are created.
  2652. IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
  2653. F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
  2654. // Lower dbg.declare intrinsics otherwise their value may be clobbered
  2655. // by instcombiner.
  2656. bool DbgDeclaresChanged = LowerDbgDeclare(F);
  2657. // Iterate while there is work to do.
  2658. int Iteration = 0;
  2659. for (;;) {
  2660. ++Iteration;
  2661. DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
  2662. << F.getName() << "\n");
  2663. bool Changed = false;
  2664. if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
  2665. Changed = true;
  2666. InstCombiner IC(Worklist, &Builder, MinimizeSize,
  2667. AA, &AC, &TLI, &DT, DL, LI);
  2668. if (IC.run())
  2669. Changed = true;
  2670. if (!Changed)
  2671. break;
  2672. }
  2673. return DbgDeclaresChanged || Iteration > 1;
  2674. }
  2675. PreservedAnalyses InstCombinePass::run(Function &F,
  2676. AnalysisManager<Function> *AM) {
  2677. auto &AC = AM->getResult<AssumptionAnalysis>(F);
  2678. auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
  2679. auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
  2680. auto *LI = AM->getCachedResult<LoopAnalysis>(F);
  2681. // FIXME: The AliasAnalysis is not yet supported in the new pass manager
  2682. if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT, LI))
  2683. // No changes, all analyses are preserved.
  2684. return PreservedAnalyses::all();
  2685. // Mark all the analyses that instcombine updates as preserved.
  2686. // FIXME: Need a way to preserve CFG analyses here!
  2687. PreservedAnalyses PA;
  2688. PA.preserve<DominatorTreeAnalysis>();
  2689. return PA;
  2690. }
  2691. namespace {
  2692. /// \brief The legacy pass manager's instcombine pass.
  2693. ///
  2694. /// This is a basic whole-function wrapper around the instcombine utility. It
  2695. /// will try to combine all instructions in the function.
  2696. class InstructionCombiningPass : public FunctionPass {
  2697. InstCombineWorklist Worklist;
  2698. public:
  2699. static char ID; // Pass identification, replacement for typeid
  2700. InstructionCombiningPass() : FunctionPass(ID) {
  2701. initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
  2702. }
  2703. void getAnalysisUsage(AnalysisUsage &AU) const override;
  2704. bool runOnFunction(Function &F) override;
  2705. };
  2706. }
  2707. void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
  2708. AU.setPreservesCFG();
  2709. AU.addRequired<AliasAnalysis>();
  2710. AU.addRequired<AssumptionCacheTracker>();
  2711. AU.addRequired<TargetLibraryInfoWrapperPass>();
  2712. AU.addRequired<DominatorTreeWrapperPass>();
  2713. AU.addPreserved<DominatorTreeWrapperPass>();
  2714. }
  2715. bool InstructionCombiningPass::runOnFunction(Function &F) {
  2716. if (skipOptnoneFunction(F))
  2717. return false;
  2718. // Required analyses.
  2719. auto AA = &getAnalysis<AliasAnalysis>();
  2720. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  2721. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  2722. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  2723. // Optional analyses.
  2724. auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
  2725. auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
  2726. return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, LI);
  2727. }
  2728. char InstructionCombiningPass::ID = 0;
  2729. INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
  2730. "Combine redundant instructions", false, false)
  2731. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  2732. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  2733. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  2734. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  2735. INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
  2736. "Combine redundant instructions", false, false)
  2737. // Initialization Routines
  2738. void llvm::initializeInstCombine(PassRegistry &Registry) {
  2739. initializeInstructionCombiningPassPass(Registry);
  2740. }
  2741. void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
  2742. initializeInstructionCombiningPassPass(*unwrap(R));
  2743. }
  2744. FunctionPass *llvm::createInstructionCombiningPass() {
  2745. return new InstructionCombiningPass();
  2746. }