LoopStrengthReduce.cpp 185 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036
  1. //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This transformation analyzes and transforms the induction variables (and
  11. // computations derived from them) into forms suitable for efficient execution
  12. // on the target.
  13. //
  14. // This pass performs a strength reduction on array references inside loops that
  15. // have as one or more of their components the loop induction variable, it
  16. // rewrites expressions to take advantage of scaled-index addressing modes
  17. // available on the target, and it performs a variety of other optimizations
  18. // related to loop induction variables.
  19. //
  20. // Terminology note: this code has a lot of handling for "post-increment" or
  21. // "post-inc" users. This is not talking about post-increment addressing modes;
  22. // it is instead talking about code like this:
  23. //
  24. // %i = phi [ 0, %entry ], [ %i.next, %latch ]
  25. // ...
  26. // %i.next = add %i, 1
  27. // %c = icmp eq %i.next, %n
  28. //
  29. // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
  30. // it's useful to think about these as the same register, with some uses using
  31. // the value of the register before the add and some using it after. In this
  32. // example, the icmp is a post-increment user, since it uses %i.next, which is
  33. // the value of the induction variable after the increment. The other common
  34. // case of post-increment users is users outside the loop.
  35. //
  36. // TODO: More sophistication in the way Formulae are generated and filtered.
  37. //
  38. // TODO: Handle multiple loops at a time.
  39. //
  40. // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
  41. // of a GlobalValue?
  42. //
  43. // TODO: When truncation is free, truncate ICmp users' operands to make it a
  44. // smaller encoding (on x86 at least).
  45. //
  46. // TODO: When a negated register is used by an add (such as in a list of
  47. // multiple base registers, or as the increment expression in an addrec),
  48. // we may not actually need both reg and (-1 * reg) in registers; the
  49. // negation can be implemented by using a sub instead of an add. The
  50. // lack of support for taking this into consideration when making
  51. // register pressure decisions is partly worked around by the "Special"
  52. // use kind.
  53. //
  54. //===----------------------------------------------------------------------===//
  55. #include "llvm/Transforms/Scalar.h"
  56. #include "llvm/ADT/DenseSet.h"
  57. #include "llvm/ADT/Hashing.h"
  58. #include "llvm/ADT/STLExtras.h"
  59. #include "llvm/ADT/SetVector.h"
  60. #include "llvm/ADT/SmallBitVector.h"
  61. #include "llvm/Analysis/IVUsers.h"
  62. #include "llvm/Analysis/LoopPass.h"
  63. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  64. #include "llvm/Analysis/TargetTransformInfo.h"
  65. #include "llvm/IR/Constants.h"
  66. #include "llvm/IR/DerivedTypes.h"
  67. #include "llvm/IR/Dominators.h"
  68. #include "llvm/IR/Instructions.h"
  69. #include "llvm/IR/IntrinsicInst.h"
  70. #include "llvm/IR/Module.h"
  71. #include "llvm/IR/ValueHandle.h"
  72. #include "llvm/Support/CommandLine.h"
  73. #include "llvm/Support/Debug.h"
  74. #include "llvm/Support/raw_ostream.h"
  75. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  76. #include "llvm/Transforms/Utils/Local.h"
  77. #include <algorithm>
  78. #include <memory> // HLSL Change
  79. using namespace llvm;
  80. #define DEBUG_TYPE "loop-reduce"
  81. /// MaxIVUsers is an arbitrary threshold that provides an early opportunitiy for
  82. /// bail out. This threshold is far beyond the number of users that LSR can
  83. /// conceivably solve, so it should not affect generated code, but catches the
  84. /// worst cases before LSR burns too much compile time and stack space.
  85. static const unsigned MaxIVUsers = 200;
  86. // Temporary flag to cleanup congruent phis after LSR phi expansion.
  87. // It's currently disabled until we can determine whether it's truly useful or
  88. // not. The flag should be removed after the v3.0 release.
  89. // This is now needed for ivchains.
  90. static cl::opt<bool> EnablePhiElim(
  91. "enable-lsr-phielim", cl::Hidden, cl::init(true),
  92. cl::desc("Enable LSR phi elimination"));
  93. #ifndef NDEBUG
  94. // Stress test IV chain generation.
  95. static cl::opt<bool> StressIVChain(
  96. "stress-ivchain", cl::Hidden, cl::init(false),
  97. cl::desc("Stress test LSR IV chains"));
  98. #else
  99. static bool StressIVChain = false;
  100. #endif
  101. namespace {
  102. /// RegSortData - This class holds data which is used to order reuse candidates.
  103. class RegSortData {
  104. public:
  105. /// UsedByIndices - This represents the set of LSRUse indices which reference
  106. /// a particular register.
  107. SmallBitVector UsedByIndices;
  108. void print(raw_ostream &OS) const;
  109. void dump() const;
  110. };
  111. }
  112. void RegSortData::print(raw_ostream &OS) const {
  113. OS << "[NumUses=" << UsedByIndices.count() << ']';
  114. }
  115. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  116. void RegSortData::dump() const {
  117. print(errs()); errs() << '\n';
  118. }
  119. #endif
  120. namespace {
  121. /// RegUseTracker - Map register candidates to information about how they are
  122. /// used.
  123. class RegUseTracker {
  124. typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
  125. RegUsesTy RegUsesMap;
  126. SmallVector<const SCEV *, 16> RegSequence;
  127. public:
  128. void CountRegister(const SCEV *Reg, size_t LUIdx);
  129. void DropRegister(const SCEV *Reg, size_t LUIdx);
  130. void SwapAndDropUse(size_t LUIdx, size_t LastLUIdx);
  131. bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
  132. const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
  133. void clear();
  134. typedef SmallVectorImpl<const SCEV *>::iterator iterator;
  135. typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
  136. iterator begin() { return RegSequence.begin(); }
  137. iterator end() { return RegSequence.end(); }
  138. const_iterator begin() const { return RegSequence.begin(); }
  139. const_iterator end() const { return RegSequence.end(); }
  140. };
  141. }
  142. void
  143. RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
  144. std::pair<RegUsesTy::iterator, bool> Pair =
  145. RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
  146. RegSortData &RSD = Pair.first->second;
  147. if (Pair.second)
  148. RegSequence.push_back(Reg);
  149. RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
  150. RSD.UsedByIndices.set(LUIdx);
  151. }
  152. void
  153. RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
  154. RegUsesTy::iterator It = RegUsesMap.find(Reg);
  155. assert(It != RegUsesMap.end());
  156. RegSortData &RSD = It->second;
  157. assert(RSD.UsedByIndices.size() > LUIdx);
  158. RSD.UsedByIndices.reset(LUIdx);
  159. }
  160. void
  161. RegUseTracker::SwapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
  162. assert(LUIdx <= LastLUIdx);
  163. // Update RegUses. The data structure is not optimized for this purpose;
  164. // we must iterate through it and update each of the bit vectors.
  165. for (auto &Pair : RegUsesMap) {
  166. SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
  167. if (LUIdx < UsedByIndices.size())
  168. UsedByIndices[LUIdx] =
  169. LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : 0;
  170. UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
  171. }
  172. }
  173. bool
  174. RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
  175. RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
  176. if (I == RegUsesMap.end())
  177. return false;
  178. const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
  179. int i = UsedByIndices.find_first();
  180. if (i == -1) return false;
  181. if ((size_t)i != LUIdx) return true;
  182. return UsedByIndices.find_next(i) != -1;
  183. }
  184. const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
  185. RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
  186. assert(I != RegUsesMap.end() && "Unknown register!");
  187. return I->second.UsedByIndices;
  188. }
  189. void RegUseTracker::clear() {
  190. RegUsesMap.clear();
  191. RegSequence.clear();
  192. }
  193. namespace {
  194. /// Formula - This class holds information that describes a formula for
  195. /// computing satisfying a use. It may include broken-out immediates and scaled
  196. /// registers.
  197. struct Formula {
  198. /// Global base address used for complex addressing.
  199. GlobalValue *BaseGV;
  200. /// Base offset for complex addressing.
  201. int64_t BaseOffset;
  202. /// Whether any complex addressing has a base register.
  203. bool HasBaseReg;
  204. /// The scale of any complex addressing.
  205. int64_t Scale;
  206. /// BaseRegs - The list of "base" registers for this use. When this is
  207. /// non-empty. The canonical representation of a formula is
  208. /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
  209. /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
  210. /// #1 enforces that the scaled register is always used when at least two
  211. /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
  212. /// #2 enforces that 1 * reg is reg.
  213. /// This invariant can be temporarly broken while building a formula.
  214. /// However, every formula inserted into the LSRInstance must be in canonical
  215. /// form.
  216. SmallVector<const SCEV *, 4> BaseRegs;
  217. /// ScaledReg - The 'scaled' register for this use. This should be non-null
  218. /// when Scale is not zero.
  219. const SCEV *ScaledReg;
  220. /// UnfoldedOffset - An additional constant offset which added near the
  221. /// use. This requires a temporary register, but the offset itself can
  222. /// live in an add immediate field rather than a register.
  223. int64_t UnfoldedOffset;
  224. Formula()
  225. : BaseGV(nullptr), BaseOffset(0), HasBaseReg(false), Scale(0),
  226. ScaledReg(nullptr), UnfoldedOffset(0) {}
  227. void InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
  228. bool isCanonical() const;
  229. void Canonicalize();
  230. bool Unscale();
  231. size_t getNumRegs() const;
  232. Type *getType() const;
  233. void DeleteBaseReg(const SCEV *&S);
  234. bool referencesReg(const SCEV *S) const;
  235. bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
  236. const RegUseTracker &RegUses) const;
  237. void print(raw_ostream &OS) const;
  238. void dump() const;
  239. };
  240. }
  241. /// DoInitialMatch - Recursion helper for InitialMatch.
  242. static void DoInitialMatch(const SCEV *S, Loop *L,
  243. SmallVectorImpl<const SCEV *> &Good,
  244. SmallVectorImpl<const SCEV *> &Bad,
  245. ScalarEvolution &SE) {
  246. // Collect expressions which properly dominate the loop header.
  247. if (SE.properlyDominates(S, L->getHeader())) {
  248. Good.push_back(S);
  249. return;
  250. }
  251. // Look at add operands.
  252. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  253. for (const SCEV *S : Add->operands())
  254. DoInitialMatch(S, L, Good, Bad, SE);
  255. return;
  256. }
  257. // Look at addrec operands.
  258. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
  259. if (!AR->getStart()->isZero()) {
  260. DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
  261. DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
  262. AR->getStepRecurrence(SE),
  263. // FIXME: AR->getNoWrapFlags()
  264. AR->getLoop(), SCEV::FlagAnyWrap),
  265. L, Good, Bad, SE);
  266. return;
  267. }
  268. // Handle a multiplication by -1 (negation) if it didn't fold.
  269. if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
  270. if (Mul->getOperand(0)->isAllOnesValue()) {
  271. SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
  272. const SCEV *NewMul = SE.getMulExpr(Ops);
  273. SmallVector<const SCEV *, 4> MyGood;
  274. SmallVector<const SCEV *, 4> MyBad;
  275. DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
  276. const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
  277. SE.getEffectiveSCEVType(NewMul->getType())));
  278. for (const SCEV *S : MyGood)
  279. Good.push_back(SE.getMulExpr(NegOne, S));
  280. for (const SCEV *S : MyBad)
  281. Bad.push_back(SE.getMulExpr(NegOne, S));
  282. return;
  283. }
  284. // Ok, we can't do anything interesting. Just stuff the whole thing into a
  285. // register and hope for the best.
  286. Bad.push_back(S);
  287. }
  288. /// InitialMatch - Incorporate loop-variant parts of S into this Formula,
  289. /// attempting to keep all loop-invariant and loop-computable values in a
  290. /// single base register.
  291. void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
  292. SmallVector<const SCEV *, 4> Good;
  293. SmallVector<const SCEV *, 4> Bad;
  294. DoInitialMatch(S, L, Good, Bad, SE);
  295. if (!Good.empty()) {
  296. const SCEV *Sum = SE.getAddExpr(Good);
  297. if (!Sum->isZero())
  298. BaseRegs.push_back(Sum);
  299. HasBaseReg = true;
  300. }
  301. if (!Bad.empty()) {
  302. const SCEV *Sum = SE.getAddExpr(Bad);
  303. if (!Sum->isZero())
  304. BaseRegs.push_back(Sum);
  305. HasBaseReg = true;
  306. }
  307. Canonicalize();
  308. }
  309. /// \brief Check whether or not this formula statisfies the canonical
  310. /// representation.
  311. /// \see Formula::BaseRegs.
  312. bool Formula::isCanonical() const {
  313. if (ScaledReg)
  314. return Scale != 1 || !BaseRegs.empty();
  315. return BaseRegs.size() <= 1;
  316. }
  317. /// \brief Helper method to morph a formula into its canonical representation.
  318. /// \see Formula::BaseRegs.
  319. /// Every formula having more than one base register, must use the ScaledReg
  320. /// field. Otherwise, we would have to do special cases everywhere in LSR
  321. /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
  322. /// On the other hand, 1*reg should be canonicalized into reg.
  323. void Formula::Canonicalize() {
  324. if (isCanonical())
  325. return;
  326. // So far we did not need this case. This is easy to implement but it is
  327. // useless to maintain dead code. Beside it could hurt compile time.
  328. assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
  329. // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
  330. ScaledReg = BaseRegs.back();
  331. BaseRegs.pop_back();
  332. Scale = 1;
  333. size_t BaseRegsSize = BaseRegs.size();
  334. size_t Try = 0;
  335. // If ScaledReg is an invariant, try to find a variant expression.
  336. while (Try < BaseRegsSize && !isa<SCEVAddRecExpr>(ScaledReg))
  337. std::swap(ScaledReg, BaseRegs[Try++]);
  338. }
  339. /// \brief Get rid of the scale in the formula.
  340. /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
  341. /// \return true if it was possible to get rid of the scale, false otherwise.
  342. /// \note After this operation the formula may not be in the canonical form.
  343. bool Formula::Unscale() {
  344. if (Scale != 1)
  345. return false;
  346. Scale = 0;
  347. BaseRegs.push_back(ScaledReg);
  348. ScaledReg = nullptr;
  349. return true;
  350. }
  351. /// getNumRegs - Return the total number of register operands used by this
  352. /// formula. This does not include register uses implied by non-constant
  353. /// addrec strides.
  354. size_t Formula::getNumRegs() const {
  355. return !!ScaledReg + BaseRegs.size();
  356. }
  357. /// getType - Return the type of this formula, if it has one, or null
  358. /// otherwise. This type is meaningless except for the bit size.
  359. Type *Formula::getType() const {
  360. return !BaseRegs.empty() ? BaseRegs.front()->getType() :
  361. ScaledReg ? ScaledReg->getType() :
  362. BaseGV ? BaseGV->getType() :
  363. nullptr;
  364. }
  365. /// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
  366. void Formula::DeleteBaseReg(const SCEV *&S) {
  367. if (&S != &BaseRegs.back())
  368. std::swap(S, BaseRegs.back());
  369. BaseRegs.pop_back();
  370. }
  371. /// referencesReg - Test if this formula references the given register.
  372. bool Formula::referencesReg(const SCEV *S) const {
  373. return S == ScaledReg ||
  374. std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
  375. }
  376. /// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
  377. /// which are used by uses other than the use with the given index.
  378. bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
  379. const RegUseTracker &RegUses) const {
  380. if (ScaledReg)
  381. if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
  382. return true;
  383. for (const SCEV *BaseReg : BaseRegs)
  384. if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
  385. return true;
  386. return false;
  387. }
  388. void Formula::print(raw_ostream &OS) const {
  389. bool First = true;
  390. if (BaseGV) {
  391. if (!First) OS << " + "; else First = false;
  392. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  393. }
  394. if (BaseOffset != 0) {
  395. if (!First) OS << " + "; else First = false;
  396. OS << BaseOffset;
  397. }
  398. for (const SCEV *BaseReg : BaseRegs) {
  399. if (!First) OS << " + "; else First = false;
  400. OS << "reg(" << *BaseReg << ')';
  401. }
  402. if (HasBaseReg && BaseRegs.empty()) {
  403. if (!First) OS << " + "; else First = false;
  404. OS << "**error: HasBaseReg**";
  405. } else if (!HasBaseReg && !BaseRegs.empty()) {
  406. if (!First) OS << " + "; else First = false;
  407. OS << "**error: !HasBaseReg**";
  408. }
  409. if (Scale != 0) {
  410. if (!First) OS << " + "; else First = false;
  411. OS << Scale << "*reg(";
  412. if (ScaledReg)
  413. OS << *ScaledReg;
  414. else
  415. OS << "<unknown>";
  416. OS << ')';
  417. }
  418. if (UnfoldedOffset != 0) {
  419. if (!First) OS << " + ";
  420. OS << "imm(" << UnfoldedOffset << ')';
  421. }
  422. }
  423. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  424. void Formula::dump() const {
  425. print(errs()); errs() << '\n';
  426. }
  427. #endif
  428. /// isAddRecSExtable - Return true if the given addrec can be sign-extended
  429. /// without changing its value.
  430. static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
  431. Type *WideTy =
  432. IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
  433. return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
  434. }
  435. /// isAddSExtable - Return true if the given add can be sign-extended
  436. /// without changing its value.
  437. static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
  438. Type *WideTy =
  439. IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
  440. return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
  441. }
  442. /// isMulSExtable - Return true if the given mul can be sign-extended
  443. /// without changing its value.
  444. static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
  445. Type *WideTy =
  446. IntegerType::get(SE.getContext(),
  447. SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
  448. return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
  449. }
  450. /// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
  451. /// and if the remainder is known to be zero, or null otherwise. If
  452. /// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
  453. /// to Y, ignoring that the multiplication may overflow, which is useful when
  454. /// the result will be used in a context where the most significant bits are
  455. /// ignored.
  456. static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
  457. ScalarEvolution &SE,
  458. bool IgnoreSignificantBits = false) {
  459. // Handle the trivial case, which works for any SCEV type.
  460. if (LHS == RHS)
  461. return SE.getConstant(LHS->getType(), 1);
  462. // Handle a few RHS special cases.
  463. const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
  464. if (RC) {
  465. const APInt &RA = RC->getValue()->getValue();
  466. // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
  467. // some folding.
  468. if (RA.isAllOnesValue())
  469. return SE.getMulExpr(LHS, RC);
  470. // Handle x /s 1 as x.
  471. if (RA == 1)
  472. return LHS;
  473. }
  474. // Check for a division of a constant by a constant.
  475. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
  476. if (!RC)
  477. return nullptr;
  478. const APInt &LA = C->getValue()->getValue();
  479. const APInt &RA = RC->getValue()->getValue();
  480. if (LA.srem(RA) != 0)
  481. return nullptr;
  482. return SE.getConstant(LA.sdiv(RA));
  483. }
  484. // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
  485. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
  486. if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
  487. const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
  488. IgnoreSignificantBits);
  489. if (!Step) return nullptr;
  490. const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
  491. IgnoreSignificantBits);
  492. if (!Start) return nullptr;
  493. // FlagNW is independent of the start value, step direction, and is
  494. // preserved with smaller magnitude steps.
  495. // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
  496. return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
  497. }
  498. return nullptr;
  499. }
  500. // Distribute the sdiv over add operands, if the add doesn't overflow.
  501. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
  502. if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
  503. SmallVector<const SCEV *, 8> Ops;
  504. for (const SCEV *S : Add->operands()) {
  505. const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);
  506. if (!Op) return nullptr;
  507. Ops.push_back(Op);
  508. }
  509. return SE.getAddExpr(Ops);
  510. }
  511. return nullptr;
  512. }
  513. // Check for a multiply operand that we can pull RHS out of.
  514. if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
  515. if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
  516. SmallVector<const SCEV *, 4> Ops;
  517. bool Found = false;
  518. for (const SCEV *S : Mul->operands()) {
  519. if (!Found)
  520. if (const SCEV *Q = getExactSDiv(S, RHS, SE,
  521. IgnoreSignificantBits)) {
  522. S = Q;
  523. Found = true;
  524. }
  525. Ops.push_back(S);
  526. }
  527. return Found ? SE.getMulExpr(Ops) : nullptr;
  528. }
  529. return nullptr;
  530. }
  531. // Otherwise we don't know.
  532. return nullptr;
  533. }
  534. /// ExtractImmediate - If S involves the addition of a constant integer value,
  535. /// return that integer value, and mutate S to point to a new SCEV with that
  536. /// value excluded.
  537. static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
  538. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
  539. if (C->getValue()->getValue().getMinSignedBits() <= 64) {
  540. S = SE.getConstant(C->getType(), 0);
  541. return C->getValue()->getSExtValue();
  542. }
  543. } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  544. SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
  545. int64_t Result = ExtractImmediate(NewOps.front(), SE);
  546. if (Result != 0)
  547. S = SE.getAddExpr(NewOps);
  548. return Result;
  549. } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  550. SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
  551. int64_t Result = ExtractImmediate(NewOps.front(), SE);
  552. if (Result != 0)
  553. S = SE.getAddRecExpr(NewOps, AR->getLoop(),
  554. // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
  555. SCEV::FlagAnyWrap);
  556. return Result;
  557. }
  558. return 0;
  559. }
  560. /// ExtractSymbol - If S involves the addition of a GlobalValue address,
  561. /// return that symbol, and mutate S to point to a new SCEV with that
  562. /// value excluded.
  563. static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
  564. if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
  565. if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
  566. S = SE.getConstant(GV->getType(), 0);
  567. return GV;
  568. }
  569. } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  570. SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
  571. GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
  572. if (Result)
  573. S = SE.getAddExpr(NewOps);
  574. return Result;
  575. } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  576. SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
  577. GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
  578. if (Result)
  579. S = SE.getAddRecExpr(NewOps, AR->getLoop(),
  580. // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
  581. SCEV::FlagAnyWrap);
  582. return Result;
  583. }
  584. return nullptr;
  585. }
  586. /// isAddressUse - Returns true if the specified instruction is using the
  587. /// specified value as an address.
  588. static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
  589. bool isAddress = isa<LoadInst>(Inst);
  590. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  591. if (SI->getOperand(1) == OperandVal)
  592. isAddress = true;
  593. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  594. // Addressing modes can also be folded into prefetches and a variety
  595. // of intrinsics.
  596. switch (II->getIntrinsicID()) {
  597. default: break;
  598. case Intrinsic::prefetch:
  599. #if 0 // HLSL Change - remove platform intrinsics
  600. case Intrinsic::x86_sse_storeu_ps:
  601. case Intrinsic::x86_sse2_storeu_pd:
  602. case Intrinsic::x86_sse2_storeu_dq:
  603. case Intrinsic::x86_sse2_storel_dq:
  604. #endif // HLSL Change - remove platform intrinsics
  605. if (II->getArgOperand(0) == OperandVal)
  606. isAddress = true;
  607. break;
  608. }
  609. }
  610. return isAddress;
  611. }
  612. /// getAccessType - Return the type of the memory being accessed.
  613. static Type *getAccessType(const Instruction *Inst) {
  614. Type *AccessTy = Inst->getType();
  615. if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
  616. AccessTy = SI->getOperand(0)->getType();
  617. else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  618. // Addressing modes can also be folded into prefetches and a variety
  619. // of intrinsics.
  620. #if 0 // HLSL Change - remove platform intrinsics
  621. switch (II->getIntrinsicID()) {
  622. default: break;
  623. case Intrinsic::x86_sse_storeu_ps:
  624. case Intrinsic::x86_sse2_storeu_pd:
  625. case Intrinsic::x86_sse2_storeu_dq:
  626. case Intrinsic::x86_sse2_storel_dq:
  627. AccessTy = II->getArgOperand(0)->getType();
  628. break;
  629. }
  630. #endif // HLSL Change - remove platform intrinsics
  631. }
  632. // All pointers have the same requirements, so canonicalize them to an
  633. // arbitrary pointer type to minimize variation.
  634. if (PointerType *PTy = dyn_cast<PointerType>(AccessTy))
  635. AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
  636. PTy->getAddressSpace());
  637. return AccessTy;
  638. }
  639. /// isExistingPhi - Return true if this AddRec is already a phi in its loop.
  640. static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
  641. for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
  642. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  643. if (SE.isSCEVable(PN->getType()) &&
  644. (SE.getEffectiveSCEVType(PN->getType()) ==
  645. SE.getEffectiveSCEVType(AR->getType())) &&
  646. SE.getSCEV(PN) == AR)
  647. return true;
  648. }
  649. return false;
  650. }
  651. /// Check if expanding this expression is likely to incur significant cost. This
  652. /// is tricky because SCEV doesn't track which expressions are actually computed
  653. /// by the current IR.
  654. ///
  655. /// We currently allow expansion of IV increments that involve adds,
  656. /// multiplication by constants, and AddRecs from existing phis.
  657. ///
  658. /// TODO: Allow UDivExpr if we can find an existing IV increment that is an
  659. /// obvious multiple of the UDivExpr.
  660. static bool isHighCostExpansion(const SCEV *S,
  661. SmallPtrSetImpl<const SCEV*> &Processed,
  662. ScalarEvolution &SE) {
  663. // Zero/One operand expressions
  664. switch (S->getSCEVType()) {
  665. case scUnknown:
  666. case scConstant:
  667. return false;
  668. case scTruncate:
  669. return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
  670. Processed, SE);
  671. case scZeroExtend:
  672. return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
  673. Processed, SE);
  674. case scSignExtend:
  675. return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
  676. Processed, SE);
  677. }
  678. if (!Processed.insert(S).second)
  679. return false;
  680. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  681. for (const SCEV *S : Add->operands()) {
  682. if (isHighCostExpansion(S, Processed, SE))
  683. return true;
  684. }
  685. return false;
  686. }
  687. if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
  688. if (Mul->getNumOperands() == 2) {
  689. // Multiplication by a constant is ok
  690. if (isa<SCEVConstant>(Mul->getOperand(0)))
  691. return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
  692. // If we have the value of one operand, check if an existing
  693. // multiplication already generates this expression.
  694. if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
  695. Value *UVal = U->getValue();
  696. for (User *UR : UVal->users()) {
  697. // If U is a constant, it may be used by a ConstantExpr.
  698. Instruction *UI = dyn_cast<Instruction>(UR);
  699. if (UI && UI->getOpcode() == Instruction::Mul &&
  700. SE.isSCEVable(UI->getType())) {
  701. return SE.getSCEV(UI) == Mul;
  702. }
  703. }
  704. }
  705. }
  706. }
  707. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  708. if (isExistingPhi(AR, SE))
  709. return false;
  710. }
  711. // Fow now, consider any other type of expression (div/mul/min/max) high cost.
  712. return true;
  713. }
  714. /// DeleteTriviallyDeadInstructions - If any of the instructions is the
  715. /// specified set are trivially dead, delete them and see if this makes any of
  716. /// their operands subsequently dead.
  717. static bool
  718. DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
  719. bool Changed = false;
  720. while (!DeadInsts.empty()) {
  721. Value *V = DeadInsts.pop_back_val();
  722. Instruction *I = dyn_cast_or_null<Instruction>(V);
  723. if (!I || !isInstructionTriviallyDead(I))
  724. continue;
  725. for (Use &O : I->operands())
  726. if (Instruction *U = dyn_cast<Instruction>(O)) {
  727. O = nullptr;
  728. if (U->use_empty())
  729. DeadInsts.emplace_back(U);
  730. }
  731. I->eraseFromParent();
  732. Changed = true;
  733. }
  734. return Changed;
  735. }
  736. namespace {
  737. class LSRUse;
  738. }
  739. /// \brief Check if the addressing mode defined by \p F is completely
  740. /// folded in \p LU at isel time.
  741. /// This includes address-mode folding and special icmp tricks.
  742. /// This function returns true if \p LU can accommodate what \p F
  743. /// defines and up to 1 base + 1 scaled + offset.
  744. /// In other words, if \p F has several base registers, this function may
  745. /// still return true. Therefore, users still need to account for
  746. /// additional base registers and/or unfolded offsets to derive an
  747. /// accurate cost model.
  748. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  749. const LSRUse &LU, const Formula &F);
  750. // Get the cost of the scaling factor used in F for LU.
  751. static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
  752. const LSRUse &LU, const Formula &F);
  753. namespace {
  754. /// Cost - This class is used to measure and compare candidate formulae.
  755. class Cost {
  756. /// TODO: Some of these could be merged. Also, a lexical ordering
  757. /// isn't always optimal.
  758. unsigned NumRegs;
  759. unsigned AddRecCost;
  760. unsigned NumIVMuls;
  761. unsigned NumBaseAdds;
  762. unsigned ImmCost;
  763. unsigned SetupCost;
  764. unsigned ScaleCost;
  765. public:
  766. Cost()
  767. : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
  768. SetupCost(0), ScaleCost(0) {}
  769. bool operator<(const Cost &Other) const;
  770. void Lose();
  771. #ifndef NDEBUG
  772. // Once any of the metrics loses, they must all remain losers.
  773. bool isValid() {
  774. return ((NumRegs | AddRecCost | NumIVMuls | NumBaseAdds
  775. | ImmCost | SetupCost | ScaleCost) != ~0u)
  776. || ((NumRegs & AddRecCost & NumIVMuls & NumBaseAdds
  777. & ImmCost & SetupCost & ScaleCost) == ~0u);
  778. }
  779. #endif
  780. bool isLoser() {
  781. assert(isValid() && "invalid cost");
  782. return NumRegs == ~0u;
  783. }
  784. void RateFormula(const TargetTransformInfo &TTI,
  785. const Formula &F,
  786. SmallPtrSetImpl<const SCEV *> &Regs,
  787. const DenseSet<const SCEV *> &VisitedRegs,
  788. const Loop *L,
  789. const SmallVectorImpl<int64_t> &Offsets,
  790. ScalarEvolution &SE, DominatorTree &DT,
  791. const LSRUse &LU,
  792. SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
  793. void print(raw_ostream &OS) const;
  794. void dump() const;
  795. private:
  796. void RateRegister(const SCEV *Reg,
  797. SmallPtrSetImpl<const SCEV *> &Regs,
  798. const Loop *L,
  799. ScalarEvolution &SE, DominatorTree &DT);
  800. void RatePrimaryRegister(const SCEV *Reg,
  801. SmallPtrSetImpl<const SCEV *> &Regs,
  802. const Loop *L,
  803. ScalarEvolution &SE, DominatorTree &DT,
  804. SmallPtrSetImpl<const SCEV *> *LoserRegs);
  805. };
  806. }
  807. /// RateRegister - Tally up interesting quantities from the given register.
  808. void Cost::RateRegister(const SCEV *Reg,
  809. SmallPtrSetImpl<const SCEV *> &Regs,
  810. const Loop *L,
  811. ScalarEvolution &SE, DominatorTree &DT) {
  812. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
  813. // If this is an addrec for another loop, don't second-guess its addrec phi
  814. // nodes. LSR isn't currently smart enough to reason about more than one
  815. // loop at a time. LSR has already run on inner loops, will not run on outer
  816. // loops, and cannot be expected to change sibling loops.
  817. if (AR->getLoop() != L) {
  818. // If the AddRec exists, consider it's register free and leave it alone.
  819. if (isExistingPhi(AR, SE))
  820. return;
  821. // Otherwise, do not consider this formula at all.
  822. Lose();
  823. return;
  824. }
  825. AddRecCost += 1; /// TODO: This should be a function of the stride.
  826. // Add the step value register, if it needs one.
  827. // TODO: The non-affine case isn't precisely modeled here.
  828. if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
  829. if (!Regs.count(AR->getOperand(1))) {
  830. RateRegister(AR->getOperand(1), Regs, L, SE, DT);
  831. if (isLoser())
  832. return;
  833. }
  834. }
  835. }
  836. ++NumRegs;
  837. // Rough heuristic; favor registers which don't require extra setup
  838. // instructions in the preheader.
  839. if (!isa<SCEVUnknown>(Reg) &&
  840. !isa<SCEVConstant>(Reg) &&
  841. !(isa<SCEVAddRecExpr>(Reg) &&
  842. (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
  843. isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
  844. ++SetupCost;
  845. NumIVMuls += isa<SCEVMulExpr>(Reg) &&
  846. SE.hasComputableLoopEvolution(Reg, L);
  847. }
  848. /// RatePrimaryRegister - Record this register in the set. If we haven't seen it
  849. /// before, rate it. Optional LoserRegs provides a way to declare any formula
  850. /// that refers to one of those regs an instant loser.
  851. void Cost::RatePrimaryRegister(const SCEV *Reg,
  852. SmallPtrSetImpl<const SCEV *> &Regs,
  853. const Loop *L,
  854. ScalarEvolution &SE, DominatorTree &DT,
  855. SmallPtrSetImpl<const SCEV *> *LoserRegs) {
  856. if (LoserRegs && LoserRegs->count(Reg)) {
  857. Lose();
  858. return;
  859. }
  860. if (Regs.insert(Reg).second) {
  861. RateRegister(Reg, Regs, L, SE, DT);
  862. if (LoserRegs && isLoser())
  863. LoserRegs->insert(Reg);
  864. }
  865. }
  866. void Cost::RateFormula(const TargetTransformInfo &TTI,
  867. const Formula &F,
  868. SmallPtrSetImpl<const SCEV *> &Regs,
  869. const DenseSet<const SCEV *> &VisitedRegs,
  870. const Loop *L,
  871. const SmallVectorImpl<int64_t> &Offsets,
  872. ScalarEvolution &SE, DominatorTree &DT,
  873. const LSRUse &LU,
  874. SmallPtrSetImpl<const SCEV *> *LoserRegs) {
  875. assert(F.isCanonical() && "Cost is accurate only for canonical formula");
  876. // Tally up the registers.
  877. if (const SCEV *ScaledReg = F.ScaledReg) {
  878. if (VisitedRegs.count(ScaledReg)) {
  879. Lose();
  880. return;
  881. }
  882. RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs);
  883. if (isLoser())
  884. return;
  885. }
  886. for (const SCEV *BaseReg : F.BaseRegs) {
  887. if (VisitedRegs.count(BaseReg)) {
  888. Lose();
  889. return;
  890. }
  891. RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
  892. if (isLoser())
  893. return;
  894. }
  895. // Determine how many (unfolded) adds we'll need inside the loop.
  896. size_t NumBaseParts = F.getNumRegs();
  897. if (NumBaseParts > 1)
  898. // Do not count the base and a possible second register if the target
  899. // allows to fold 2 registers.
  900. NumBaseAdds +=
  901. NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F)));
  902. NumBaseAdds += (F.UnfoldedOffset != 0);
  903. // Accumulate non-free scaling amounts.
  904. ScaleCost += getScalingFactorCost(TTI, LU, F);
  905. // Tally up the non-zero immediates.
  906. for (int64_t O : Offsets) {
  907. int64_t Offset = (uint64_t)O + F.BaseOffset;
  908. if (F.BaseGV)
  909. ImmCost += 64; // Handle symbolic values conservatively.
  910. // TODO: This should probably be the pointer size.
  911. else if (Offset != 0)
  912. ImmCost += APInt(64, Offset, true).getMinSignedBits();
  913. }
  914. assert(isValid() && "invalid cost");
  915. }
  916. /// Lose - Set this cost to a losing value.
  917. void Cost::Lose() {
  918. NumRegs = ~0u;
  919. AddRecCost = ~0u;
  920. NumIVMuls = ~0u;
  921. NumBaseAdds = ~0u;
  922. ImmCost = ~0u;
  923. SetupCost = ~0u;
  924. ScaleCost = ~0u;
  925. }
  926. /// operator< - Choose the lower cost.
  927. bool Cost::operator<(const Cost &Other) const {
  928. return std::tie(NumRegs, AddRecCost, NumIVMuls, NumBaseAdds, ScaleCost,
  929. ImmCost, SetupCost) <
  930. std::tie(Other.NumRegs, Other.AddRecCost, Other.NumIVMuls,
  931. Other.NumBaseAdds, Other.ScaleCost, Other.ImmCost,
  932. Other.SetupCost);
  933. }
  934. void Cost::print(raw_ostream &OS) const {
  935. OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
  936. if (AddRecCost != 0)
  937. OS << ", with addrec cost " << AddRecCost;
  938. if (NumIVMuls != 0)
  939. OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
  940. if (NumBaseAdds != 0)
  941. OS << ", plus " << NumBaseAdds << " base add"
  942. << (NumBaseAdds == 1 ? "" : "s");
  943. if (ScaleCost != 0)
  944. OS << ", plus " << ScaleCost << " scale cost";
  945. if (ImmCost != 0)
  946. OS << ", plus " << ImmCost << " imm cost";
  947. if (SetupCost != 0)
  948. OS << ", plus " << SetupCost << " setup cost";
  949. }
  950. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  951. void Cost::dump() const {
  952. print(errs()); errs() << '\n';
  953. }
  954. #endif
  955. namespace {
  956. /// LSRFixup - An operand value in an instruction which is to be replaced
  957. /// with some equivalent, possibly strength-reduced, replacement.
  958. struct LSRFixup {
  959. /// UserInst - The instruction which will be updated.
  960. Instruction *UserInst;
  961. /// OperandValToReplace - The operand of the instruction which will
  962. /// be replaced. The operand may be used more than once; every instance
  963. /// will be replaced.
  964. Value *OperandValToReplace;
  965. /// PostIncLoops - If this user is to use the post-incremented value of an
  966. /// induction variable, this variable is non-null and holds the loop
  967. /// associated with the induction variable.
  968. PostIncLoopSet PostIncLoops;
  969. /// LUIdx - The index of the LSRUse describing the expression which
  970. /// this fixup needs, minus an offset (below).
  971. size_t LUIdx;
  972. /// Offset - A constant offset to be added to the LSRUse expression.
  973. /// This allows multiple fixups to share the same LSRUse with different
  974. /// offsets, for example in an unrolled loop.
  975. int64_t Offset;
  976. bool isUseFullyOutsideLoop(const Loop *L) const;
  977. LSRFixup();
  978. void print(raw_ostream &OS) const;
  979. void dump() const;
  980. };
  981. }
  982. LSRFixup::LSRFixup()
  983. : UserInst(nullptr), OperandValToReplace(nullptr), LUIdx(~size_t(0)),
  984. Offset(0) {}
  985. /// isUseFullyOutsideLoop - Test whether this fixup always uses its
  986. /// value outside of the given loop.
  987. bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
  988. // PHI nodes use their value in their incoming blocks.
  989. if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
  990. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  991. if (PN->getIncomingValue(i) == OperandValToReplace &&
  992. L->contains(PN->getIncomingBlock(i)))
  993. return false;
  994. return true;
  995. }
  996. return !L->contains(UserInst);
  997. }
  998. void LSRFixup::print(raw_ostream &OS) const {
  999. OS << "UserInst=";
  1000. // Store is common and interesting enough to be worth special-casing.
  1001. if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
  1002. OS << "store ";
  1003. Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
  1004. } else if (UserInst->getType()->isVoidTy())
  1005. OS << UserInst->getOpcodeName();
  1006. else
  1007. UserInst->printAsOperand(OS, /*PrintType=*/false);
  1008. OS << ", OperandValToReplace=";
  1009. OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
  1010. for (const Loop *PIL : PostIncLoops) {
  1011. OS << ", PostIncLoop=";
  1012. PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
  1013. }
  1014. if (LUIdx != ~size_t(0))
  1015. OS << ", LUIdx=" << LUIdx;
  1016. if (Offset != 0)
  1017. OS << ", Offset=" << Offset;
  1018. }
  1019. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1020. void LSRFixup::dump() const {
  1021. print(errs()); errs() << '\n';
  1022. }
  1023. #endif
  1024. namespace {
  1025. /// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
  1026. /// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
  1027. struct UniquifierDenseMapInfo {
  1028. static SmallVector<const SCEV *, 4> getEmptyKey() {
  1029. SmallVector<const SCEV *, 4> V;
  1030. V.push_back(reinterpret_cast<const SCEV *>(-1));
  1031. return V;
  1032. }
  1033. static SmallVector<const SCEV *, 4> getTombstoneKey() {
  1034. SmallVector<const SCEV *, 4> V;
  1035. V.push_back(reinterpret_cast<const SCEV *>(-2));
  1036. return V;
  1037. }
  1038. static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
  1039. return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
  1040. }
  1041. static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
  1042. const SmallVector<const SCEV *, 4> &RHS) {
  1043. return LHS == RHS;
  1044. }
  1045. };
  1046. /// LSRUse - This class holds the state that LSR keeps for each use in
  1047. /// IVUsers, as well as uses invented by LSR itself. It includes information
  1048. /// about what kinds of things can be folded into the user, information about
  1049. /// the user itself, and information about how the use may be satisfied.
  1050. /// TODO: Represent multiple users of the same expression in common?
  1051. class LSRUse {
  1052. DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
  1053. public:
  1054. /// KindType - An enum for a kind of use, indicating what types of
  1055. /// scaled and immediate operands it might support.
  1056. enum KindType {
  1057. Basic, ///< A normal use, with no folding.
  1058. Special, ///< A special case of basic, allowing -1 scales.
  1059. Address, ///< An address use; folding according to TargetLowering
  1060. ICmpZero ///< An equality icmp with both operands folded into one.
  1061. // TODO: Add a generic icmp too?
  1062. };
  1063. typedef PointerIntPair<const SCEV *, 2, KindType> SCEVUseKindPair;
  1064. KindType Kind;
  1065. Type *AccessTy;
  1066. SmallVector<int64_t, 8> Offsets;
  1067. int64_t MinOffset;
  1068. int64_t MaxOffset;
  1069. /// AllFixupsOutsideLoop - This records whether all of the fixups using this
  1070. /// LSRUse are outside of the loop, in which case some special-case heuristics
  1071. /// may be used.
  1072. bool AllFixupsOutsideLoop;
  1073. /// RigidFormula is set to true to guarantee that this use will be associated
  1074. /// with a single formula--the one that initially matched. Some SCEV
  1075. /// expressions cannot be expanded. This allows LSR to consider the registers
  1076. /// used by those expressions without the need to expand them later after
  1077. /// changing the formula.
  1078. bool RigidFormula;
  1079. /// WidestFixupType - This records the widest use type for any fixup using
  1080. /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
  1081. /// max fixup widths to be equivalent, because the narrower one may be relying
  1082. /// on the implicit truncation to truncate away bogus bits.
  1083. Type *WidestFixupType;
  1084. /// Formulae - A list of ways to build a value that can satisfy this user.
  1085. /// After the list is populated, one of these is selected heuristically and
  1086. /// used to formulate a replacement for OperandValToReplace in UserInst.
  1087. SmallVector<Formula, 12> Formulae;
  1088. /// Regs - The set of register candidates used by all formulae in this LSRUse.
  1089. SmallPtrSet<const SCEV *, 4> Regs;
  1090. LSRUse(KindType K, Type *T) : Kind(K), AccessTy(T),
  1091. MinOffset(INT64_MAX),
  1092. MaxOffset(INT64_MIN),
  1093. AllFixupsOutsideLoop(true),
  1094. RigidFormula(false),
  1095. WidestFixupType(nullptr) {}
  1096. bool HasFormulaWithSameRegs(const Formula &F) const;
  1097. bool InsertFormula(const Formula &F);
  1098. void DeleteFormula(Formula &F);
  1099. void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
  1100. void print(raw_ostream &OS) const;
  1101. void dump() const;
  1102. };
  1103. }
  1104. /// HasFormula - Test whether this use as a formula which has the same
  1105. /// registers as the given formula.
  1106. bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
  1107. SmallVector<const SCEV *, 4> Key = F.BaseRegs;
  1108. if (F.ScaledReg) Key.push_back(F.ScaledReg);
  1109. // Unstable sort by host order ok, because this is only used for uniquifying.
  1110. std::sort(Key.begin(), Key.end());
  1111. return Uniquifier.count(Key);
  1112. }
  1113. /// InsertFormula - If the given formula has not yet been inserted, add it to
  1114. /// the list, and return true. Return false otherwise.
  1115. /// The formula must be in canonical form.
  1116. bool LSRUse::InsertFormula(const Formula &F) {
  1117. assert(F.isCanonical() && "Invalid canonical representation");
  1118. if (!Formulae.empty() && RigidFormula)
  1119. return false;
  1120. SmallVector<const SCEV *, 4> Key = F.BaseRegs;
  1121. if (F.ScaledReg) Key.push_back(F.ScaledReg);
  1122. // Unstable sort by host order ok, because this is only used for uniquifying.
  1123. std::sort(Key.begin(), Key.end());
  1124. if (!Uniquifier.insert(Key).second)
  1125. return false;
  1126. // Using a register to hold the value of 0 is not profitable.
  1127. assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
  1128. "Zero allocated in a scaled register!");
  1129. #ifndef NDEBUG
  1130. for (const SCEV *BaseReg : F.BaseRegs)
  1131. assert(!BaseReg->isZero() && "Zero allocated in a base register!");
  1132. #endif
  1133. // Add the formula to the list.
  1134. Formulae.push_back(F);
  1135. // Record registers now being used by this use.
  1136. Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
  1137. if (F.ScaledReg)
  1138. Regs.insert(F.ScaledReg);
  1139. return true;
  1140. }
  1141. /// DeleteFormula - Remove the given formula from this use's list.
  1142. void LSRUse::DeleteFormula(Formula &F) {
  1143. if (&F != &Formulae.back())
  1144. std::swap(F, Formulae.back());
  1145. Formulae.pop_back();
  1146. }
  1147. /// RecomputeRegs - Recompute the Regs field, and update RegUses.
  1148. void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
  1149. // Now that we've filtered out some formulae, recompute the Regs set.
  1150. SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
  1151. Regs.clear();
  1152. for (const Formula &F : Formulae) {
  1153. if (F.ScaledReg) Regs.insert(F.ScaledReg);
  1154. Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
  1155. }
  1156. // Update the RegTracker.
  1157. for (const SCEV *S : OldRegs)
  1158. if (!Regs.count(S))
  1159. RegUses.DropRegister(S, LUIdx);
  1160. }
  1161. void LSRUse::print(raw_ostream &OS) const {
  1162. OS << "LSR Use: Kind=";
  1163. switch (Kind) {
  1164. case Basic: OS << "Basic"; break;
  1165. case Special: OS << "Special"; break;
  1166. case ICmpZero: OS << "ICmpZero"; break;
  1167. case Address:
  1168. OS << "Address of ";
  1169. if (AccessTy->isPointerTy())
  1170. OS << "pointer"; // the full pointer type could be really verbose
  1171. else
  1172. OS << *AccessTy;
  1173. }
  1174. OS << ", Offsets={";
  1175. bool NeedComma = false;
  1176. for (int64_t O : Offsets) {
  1177. if (NeedComma) OS << ',';
  1178. OS << O;
  1179. NeedComma = true;
  1180. }
  1181. OS << '}';
  1182. if (AllFixupsOutsideLoop)
  1183. OS << ", all-fixups-outside-loop";
  1184. if (WidestFixupType)
  1185. OS << ", widest fixup type: " << *WidestFixupType;
  1186. }
  1187. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1188. void LSRUse::dump() const {
  1189. print(errs()); errs() << '\n';
  1190. }
  1191. #endif
  1192. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  1193. LSRUse::KindType Kind, Type *AccessTy,
  1194. GlobalValue *BaseGV, int64_t BaseOffset,
  1195. bool HasBaseReg, int64_t Scale) {
  1196. switch (Kind) {
  1197. case LSRUse::Address:
  1198. return TTI.isLegalAddressingMode(AccessTy, BaseGV, BaseOffset, HasBaseReg, Scale);
  1199. case LSRUse::ICmpZero:
  1200. // There's not even a target hook for querying whether it would be legal to
  1201. // fold a GV into an ICmp.
  1202. if (BaseGV)
  1203. return false;
  1204. // ICmp only has two operands; don't allow more than two non-trivial parts.
  1205. if (Scale != 0 && HasBaseReg && BaseOffset != 0)
  1206. return false;
  1207. // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
  1208. // putting the scaled register in the other operand of the icmp.
  1209. if (Scale != 0 && Scale != -1)
  1210. return false;
  1211. // If we have low-level target information, ask the target if it can fold an
  1212. // integer immediate on an icmp.
  1213. if (BaseOffset != 0) {
  1214. // We have one of:
  1215. // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
  1216. // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
  1217. // Offs is the ICmp immediate.
  1218. if (Scale == 0)
  1219. // The cast does the right thing with INT64_MIN.
  1220. BaseOffset = -(uint64_t)BaseOffset;
  1221. return TTI.isLegalICmpImmediate(BaseOffset);
  1222. }
  1223. // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
  1224. return true;
  1225. case LSRUse::Basic:
  1226. // Only handle single-register values.
  1227. return !BaseGV && Scale == 0 && BaseOffset == 0;
  1228. case LSRUse::Special:
  1229. // Special case Basic to handle -1 scales.
  1230. return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
  1231. }
  1232. llvm_unreachable("Invalid LSRUse Kind!");
  1233. }
  1234. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  1235. int64_t MinOffset, int64_t MaxOffset,
  1236. LSRUse::KindType Kind, Type *AccessTy,
  1237. GlobalValue *BaseGV, int64_t BaseOffset,
  1238. bool HasBaseReg, int64_t Scale) {
  1239. // Check for overflow.
  1240. if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
  1241. (MinOffset > 0))
  1242. return false;
  1243. MinOffset = (uint64_t)BaseOffset + MinOffset;
  1244. if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
  1245. (MaxOffset > 0))
  1246. return false;
  1247. MaxOffset = (uint64_t)BaseOffset + MaxOffset;
  1248. return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
  1249. HasBaseReg, Scale) &&
  1250. isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
  1251. HasBaseReg, Scale);
  1252. }
  1253. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  1254. int64_t MinOffset, int64_t MaxOffset,
  1255. LSRUse::KindType Kind, Type *AccessTy,
  1256. const Formula &F) {
  1257. // For the purpose of isAMCompletelyFolded either having a canonical formula
  1258. // or a scale not equal to zero is correct.
  1259. // Problems may arise from non canonical formulae having a scale == 0.
  1260. // Strictly speaking it would best to just rely on canonical formulae.
  1261. // However, when we generate the scaled formulae, we first check that the
  1262. // scaling factor is profitable before computing the actual ScaledReg for
  1263. // compile time sake.
  1264. assert((F.isCanonical() || F.Scale != 0));
  1265. return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
  1266. F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
  1267. }
  1268. /// isLegalUse - Test whether we know how to expand the current formula.
  1269. static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
  1270. int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
  1271. GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg,
  1272. int64_t Scale) {
  1273. // We know how to expand completely foldable formulae.
  1274. return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
  1275. BaseOffset, HasBaseReg, Scale) ||
  1276. // Or formulae that use a base register produced by a sum of base
  1277. // registers.
  1278. (Scale == 1 &&
  1279. isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
  1280. BaseGV, BaseOffset, true, 0));
  1281. }
  1282. static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
  1283. int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
  1284. const Formula &F) {
  1285. return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
  1286. F.BaseOffset, F.HasBaseReg, F.Scale);
  1287. }
  1288. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  1289. const LSRUse &LU, const Formula &F) {
  1290. return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
  1291. LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
  1292. F.Scale);
  1293. }
  1294. static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
  1295. const LSRUse &LU, const Formula &F) {
  1296. if (!F.Scale)
  1297. return 0;
  1298. // If the use is not completely folded in that instruction, we will have to
  1299. // pay an extra cost only for scale != 1.
  1300. if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
  1301. LU.AccessTy, F))
  1302. return F.Scale != 1;
  1303. switch (LU.Kind) {
  1304. case LSRUse::Address: {
  1305. // Check the scaling factor cost with both the min and max offsets.
  1306. int ScaleCostMinOffset =
  1307. TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
  1308. F.BaseOffset + LU.MinOffset,
  1309. F.HasBaseReg, F.Scale);
  1310. int ScaleCostMaxOffset =
  1311. TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
  1312. F.BaseOffset + LU.MaxOffset,
  1313. F.HasBaseReg, F.Scale);
  1314. assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
  1315. "Legal addressing mode has an illegal cost!");
  1316. return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
  1317. }
  1318. case LSRUse::ICmpZero:
  1319. case LSRUse::Basic:
  1320. case LSRUse::Special:
  1321. // The use is completely folded, i.e., everything is folded into the
  1322. // instruction.
  1323. return 0;
  1324. }
  1325. llvm_unreachable("Invalid LSRUse Kind!");
  1326. }
  1327. static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
  1328. LSRUse::KindType Kind, Type *AccessTy,
  1329. GlobalValue *BaseGV, int64_t BaseOffset,
  1330. bool HasBaseReg) {
  1331. // Fast-path: zero is always foldable.
  1332. if (BaseOffset == 0 && !BaseGV) return true;
  1333. // Conservatively, create an address with an immediate and a
  1334. // base and a scale.
  1335. int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
  1336. // Canonicalize a scale of 1 to a base register if the formula doesn't
  1337. // already have a base register.
  1338. if (!HasBaseReg && Scale == 1) {
  1339. Scale = 0;
  1340. HasBaseReg = true;
  1341. }
  1342. return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
  1343. HasBaseReg, Scale);
  1344. }
  1345. static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
  1346. ScalarEvolution &SE, int64_t MinOffset,
  1347. int64_t MaxOffset, LSRUse::KindType Kind,
  1348. Type *AccessTy, const SCEV *S, bool HasBaseReg) {
  1349. // Fast-path: zero is always foldable.
  1350. if (S->isZero()) return true;
  1351. // Conservatively, create an address with an immediate and a
  1352. // base and a scale.
  1353. int64_t BaseOffset = ExtractImmediate(S, SE);
  1354. GlobalValue *BaseGV = ExtractSymbol(S, SE);
  1355. // If there's anything else involved, it's not foldable.
  1356. if (!S->isZero()) return false;
  1357. // Fast-path: zero is always foldable.
  1358. if (BaseOffset == 0 && !BaseGV) return true;
  1359. // Conservatively, create an address with an immediate and a
  1360. // base and a scale.
  1361. int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
  1362. return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
  1363. BaseOffset, HasBaseReg, Scale);
  1364. }
  1365. namespace {
  1366. /// IVInc - An individual increment in a Chain of IV increments.
  1367. /// Relate an IV user to an expression that computes the IV it uses from the IV
  1368. /// used by the previous link in the Chain.
  1369. ///
  1370. /// For the head of a chain, IncExpr holds the absolute SCEV expression for the
  1371. /// original IVOperand. The head of the chain's IVOperand is only valid during
  1372. /// chain collection, before LSR replaces IV users. During chain generation,
  1373. /// IncExpr can be used to find the new IVOperand that computes the same
  1374. /// expression.
  1375. struct IVInc {
  1376. Instruction *UserInst;
  1377. Value* IVOperand;
  1378. const SCEV *IncExpr;
  1379. IVInc(Instruction *U, Value *O, const SCEV *E):
  1380. UserInst(U), IVOperand(O), IncExpr(E) {}
  1381. };
  1382. // IVChain - The list of IV increments in program order.
  1383. // We typically add the head of a chain without finding subsequent links.
  1384. struct IVChain {
  1385. SmallVector<IVInc,1> Incs;
  1386. const SCEV *ExprBase;
  1387. IVChain() : ExprBase(nullptr) {}
  1388. IVChain(const IVInc &Head, const SCEV *Base)
  1389. : Incs(1, Head), ExprBase(Base) {}
  1390. typedef SmallVectorImpl<IVInc>::const_iterator const_iterator;
  1391. // begin - return the first increment in the chain.
  1392. const_iterator begin() const {
  1393. assert(!Incs.empty());
  1394. return std::next(Incs.begin());
  1395. }
  1396. const_iterator end() const {
  1397. return Incs.end();
  1398. }
  1399. // hasIncs - Returns true if this chain contains any increments.
  1400. bool hasIncs() const { return Incs.size() >= 2; }
  1401. // add - Add an IVInc to the end of this chain.
  1402. void add(const IVInc &X) { Incs.push_back(X); }
  1403. // tailUserInst - Returns the last UserInst in the chain.
  1404. Instruction *tailUserInst() const { return Incs.back().UserInst; }
  1405. // isProfitableIncrement - Returns true if IncExpr can be profitably added to
  1406. // this chain.
  1407. bool isProfitableIncrement(const SCEV *OperExpr,
  1408. const SCEV *IncExpr,
  1409. ScalarEvolution&);
  1410. };
  1411. /// ChainUsers - Helper for CollectChains to track multiple IV increment uses.
  1412. /// Distinguish between FarUsers that definitely cross IV increments and
  1413. /// NearUsers that may be used between IV increments.
  1414. struct ChainUsers {
  1415. SmallPtrSet<Instruction*, 4> FarUsers;
  1416. SmallPtrSet<Instruction*, 4> NearUsers;
  1417. };
  1418. /// LSRInstance - This class holds state for the main loop strength reduction
  1419. /// logic.
  1420. class LSRInstance {
  1421. IVUsers &IU;
  1422. ScalarEvolution &SE;
  1423. DominatorTree &DT;
  1424. LoopInfo &LI;
  1425. const TargetTransformInfo &TTI;
  1426. Loop *const L;
  1427. bool Changed;
  1428. /// IVIncInsertPos - This is the insert position that the current loop's
  1429. /// induction variable increment should be placed. In simple loops, this is
  1430. /// the latch block's terminator. But in more complicated cases, this is a
  1431. /// position which will dominate all the in-loop post-increment users.
  1432. Instruction *IVIncInsertPos;
  1433. /// Factors - Interesting factors between use strides.
  1434. SmallSetVector<int64_t, 8> Factors;
  1435. /// Types - Interesting use types, to facilitate truncation reuse.
  1436. SmallSetVector<Type *, 4> Types;
  1437. /// Fixups - The list of operands which are to be replaced.
  1438. SmallVector<LSRFixup, 16> Fixups;
  1439. /// Uses - The list of interesting uses.
  1440. SmallVector<LSRUse, 16> Uses;
  1441. /// RegUses - Track which uses use which register candidates.
  1442. RegUseTracker RegUses;
  1443. // Limit the number of chains to avoid quadratic behavior. We don't expect to
  1444. // have more than a few IV increment chains in a loop. Missing a Chain falls
  1445. // back to normal LSR behavior for those uses.
  1446. static const unsigned MaxChains = 8;
  1447. /// IVChainVec - IV users can form a chain of IV increments.
  1448. SmallVector<IVChain, MaxChains> IVChainVec;
  1449. /// IVIncSet - IV users that belong to profitable IVChains.
  1450. SmallPtrSet<Use*, MaxChains> IVIncSet;
  1451. void OptimizeShadowIV();
  1452. bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
  1453. ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
  1454. void OptimizeLoopTermCond();
  1455. void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
  1456. SmallVectorImpl<ChainUsers> &ChainUsersVec);
  1457. void FinalizeChain(IVChain &Chain);
  1458. void CollectChains();
  1459. void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
  1460. SmallVectorImpl<WeakVH> &DeadInsts);
  1461. void CollectInterestingTypesAndFactors();
  1462. void CollectFixupsAndInitialFormulae();
  1463. LSRFixup &getNewFixup() {
  1464. Fixups.push_back(LSRFixup());
  1465. return Fixups.back();
  1466. }
  1467. // Support for sharing of LSRUses between LSRFixups.
  1468. typedef DenseMap<LSRUse::SCEVUseKindPair, size_t> UseMapTy;
  1469. UseMapTy UseMap;
  1470. bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
  1471. LSRUse::KindType Kind, Type *AccessTy);
  1472. std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
  1473. LSRUse::KindType Kind,
  1474. Type *AccessTy);
  1475. void DeleteUse(LSRUse &LU, size_t LUIdx);
  1476. LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
  1477. void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
  1478. void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
  1479. void CountRegisters(const Formula &F, size_t LUIdx);
  1480. bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
  1481. void CollectLoopInvariantFixupsAndFormulae();
  1482. void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
  1483. unsigned Depth = 0);
  1484. void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
  1485. const Formula &Base, unsigned Depth,
  1486. size_t Idx, bool IsScaledReg = false);
  1487. void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
  1488. void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
  1489. const Formula &Base, size_t Idx,
  1490. bool IsScaledReg = false);
  1491. void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
  1492. void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
  1493. const Formula &Base,
  1494. const SmallVectorImpl<int64_t> &Worklist,
  1495. size_t Idx, bool IsScaledReg = false);
  1496. void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
  1497. void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
  1498. void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
  1499. void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
  1500. void GenerateCrossUseConstantOffsets();
  1501. void GenerateAllReuseFormulae();
  1502. void FilterOutUndesirableDedicatedRegisters();
  1503. size_t EstimateSearchSpaceComplexity() const;
  1504. void NarrowSearchSpaceByDetectingSupersets();
  1505. void NarrowSearchSpaceByCollapsingUnrolledCode();
  1506. void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
  1507. void NarrowSearchSpaceByPickingWinnerRegs();
  1508. void NarrowSearchSpaceUsingHeuristics();
  1509. void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
  1510. Cost &SolutionCost,
  1511. SmallVectorImpl<const Formula *> &Workspace,
  1512. const Cost &CurCost,
  1513. const SmallPtrSet<const SCEV *, 16> &CurRegs,
  1514. DenseSet<const SCEV *> &VisitedRegs) const;
  1515. void Solve(SmallVectorImpl<const Formula *> &Solution) const;
  1516. BasicBlock::iterator
  1517. HoistInsertPosition(BasicBlock::iterator IP,
  1518. const SmallVectorImpl<Instruction *> &Inputs) const;
  1519. BasicBlock::iterator
  1520. AdjustInsertPositionForExpand(BasicBlock::iterator IP,
  1521. const LSRFixup &LF,
  1522. const LSRUse &LU,
  1523. SCEVExpander &Rewriter) const;
  1524. Value *Expand(const LSRFixup &LF,
  1525. const Formula &F,
  1526. BasicBlock::iterator IP,
  1527. SCEVExpander &Rewriter,
  1528. SmallVectorImpl<WeakVH> &DeadInsts) const;
  1529. void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
  1530. const Formula &F,
  1531. SCEVExpander &Rewriter,
  1532. SmallVectorImpl<WeakVH> &DeadInsts,
  1533. Pass *P) const;
  1534. void Rewrite(const LSRFixup &LF,
  1535. const Formula &F,
  1536. SCEVExpander &Rewriter,
  1537. SmallVectorImpl<WeakVH> &DeadInsts,
  1538. Pass *P) const;
  1539. void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
  1540. Pass *P);
  1541. public:
  1542. LSRInstance(Loop *L, Pass *P);
  1543. bool getChanged() const { return Changed; }
  1544. void print_factors_and_types(raw_ostream &OS) const;
  1545. void print_fixups(raw_ostream &OS) const;
  1546. void print_uses(raw_ostream &OS) const;
  1547. void print(raw_ostream &OS) const;
  1548. void dump() const;
  1549. };
  1550. }
  1551. /// OptimizeShadowIV - If IV is used in a int-to-float cast
  1552. /// inside the loop then try to eliminate the cast operation.
  1553. void LSRInstance::OptimizeShadowIV() {
  1554. const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
  1555. if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
  1556. return;
  1557. for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
  1558. UI != E; /* empty */) {
  1559. IVUsers::const_iterator CandidateUI = UI;
  1560. ++UI;
  1561. Instruction *ShadowUse = CandidateUI->getUser();
  1562. Type *DestTy = nullptr;
  1563. bool IsSigned = false;
  1564. /* If shadow use is a int->float cast then insert a second IV
  1565. to eliminate this cast.
  1566. for (unsigned i = 0; i < n; ++i)
  1567. foo((double)i);
  1568. is transformed into
  1569. double d = 0.0;
  1570. for (unsigned i = 0; i < n; ++i, ++d)
  1571. foo(d);
  1572. */
  1573. if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
  1574. IsSigned = false;
  1575. DestTy = UCast->getDestTy();
  1576. }
  1577. else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
  1578. IsSigned = true;
  1579. DestTy = SCast->getDestTy();
  1580. }
  1581. if (!DestTy) continue;
  1582. // If target does not support DestTy natively then do not apply
  1583. // this transformation.
  1584. if (!TTI.isTypeLegal(DestTy)) continue;
  1585. PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
  1586. if (!PH) continue;
  1587. if (PH->getNumIncomingValues() != 2) continue;
  1588. Type *SrcTy = PH->getType();
  1589. int Mantissa = DestTy->getFPMantissaWidth();
  1590. if (Mantissa == -1) continue;
  1591. if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
  1592. continue;
  1593. unsigned Entry, Latch;
  1594. if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
  1595. Entry = 0;
  1596. Latch = 1;
  1597. } else {
  1598. Entry = 1;
  1599. Latch = 0;
  1600. }
  1601. ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
  1602. if (!Init) continue;
  1603. Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
  1604. (double)Init->getSExtValue() :
  1605. (double)Init->getZExtValue());
  1606. BinaryOperator *Incr =
  1607. dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
  1608. if (!Incr) continue;
  1609. if (Incr->getOpcode() != Instruction::Add
  1610. && Incr->getOpcode() != Instruction::Sub)
  1611. continue;
  1612. /* Initialize new IV, double d = 0.0 in above example. */
  1613. ConstantInt *C = nullptr;
  1614. if (Incr->getOperand(0) == PH)
  1615. C = dyn_cast<ConstantInt>(Incr->getOperand(1));
  1616. else if (Incr->getOperand(1) == PH)
  1617. C = dyn_cast<ConstantInt>(Incr->getOperand(0));
  1618. else
  1619. continue;
  1620. if (!C) continue;
  1621. // Ignore negative constants, as the code below doesn't handle them
  1622. // correctly. TODO: Remove this restriction.
  1623. if (!C->getValue().isStrictlyPositive()) continue;
  1624. /* Add new PHINode. */
  1625. PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
  1626. /* create new increment. '++d' in above example. */
  1627. Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
  1628. BinaryOperator *NewIncr =
  1629. BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
  1630. Instruction::FAdd : Instruction::FSub,
  1631. NewPH, CFP, "IV.S.next.", Incr);
  1632. NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
  1633. NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
  1634. /* Remove cast operation */
  1635. ShadowUse->replaceAllUsesWith(NewPH);
  1636. ShadowUse->eraseFromParent();
  1637. Changed = true;
  1638. break;
  1639. }
  1640. }
  1641. /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
  1642. /// set the IV user and stride information and return true, otherwise return
  1643. /// false.
  1644. bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
  1645. for (IVStrideUse &U : IU)
  1646. if (U.getUser() == Cond) {
  1647. // NOTE: we could handle setcc instructions with multiple uses here, but
  1648. // InstCombine does it as well for simple uses, it's not clear that it
  1649. // occurs enough in real life to handle.
  1650. CondUse = &U;
  1651. return true;
  1652. }
  1653. return false;
  1654. }
  1655. /// OptimizeMax - Rewrite the loop's terminating condition if it uses
  1656. /// a max computation.
  1657. ///
  1658. /// This is a narrow solution to a specific, but acute, problem. For loops
  1659. /// like this:
  1660. ///
  1661. /// i = 0;
  1662. /// do {
  1663. /// p[i] = 0.0;
  1664. /// } while (++i < n);
  1665. ///
  1666. /// the trip count isn't just 'n', because 'n' might not be positive. And
  1667. /// unfortunately this can come up even for loops where the user didn't use
  1668. /// a C do-while loop. For example, seemingly well-behaved top-test loops
  1669. /// will commonly be lowered like this:
  1670. //
  1671. /// if (n > 0) {
  1672. /// i = 0;
  1673. /// do {
  1674. /// p[i] = 0.0;
  1675. /// } while (++i < n);
  1676. /// }
  1677. ///
  1678. /// and then it's possible for subsequent optimization to obscure the if
  1679. /// test in such a way that indvars can't find it.
  1680. ///
  1681. /// When indvars can't find the if test in loops like this, it creates a
  1682. /// max expression, which allows it to give the loop a canonical
  1683. /// induction variable:
  1684. ///
  1685. /// i = 0;
  1686. /// max = n < 1 ? 1 : n;
  1687. /// do {
  1688. /// p[i] = 0.0;
  1689. /// } while (++i != max);
  1690. ///
  1691. /// Canonical induction variables are necessary because the loop passes
  1692. /// are designed around them. The most obvious example of this is the
  1693. /// LoopInfo analysis, which doesn't remember trip count values. It
  1694. /// expects to be able to rediscover the trip count each time it is
  1695. /// needed, and it does this using a simple analysis that only succeeds if
  1696. /// the loop has a canonical induction variable.
  1697. ///
  1698. /// However, when it comes time to generate code, the maximum operation
  1699. /// can be quite costly, especially if it's inside of an outer loop.
  1700. ///
  1701. /// This function solves this problem by detecting this type of loop and
  1702. /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
  1703. /// the instructions for the maximum computation.
  1704. ///
  1705. ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
  1706. // Check that the loop matches the pattern we're looking for.
  1707. if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
  1708. Cond->getPredicate() != CmpInst::ICMP_NE)
  1709. return Cond;
  1710. SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
  1711. if (!Sel || !Sel->hasOneUse()) return Cond;
  1712. const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
  1713. if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
  1714. return Cond;
  1715. const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
  1716. // Add one to the backedge-taken count to get the trip count.
  1717. const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
  1718. if (IterationCount != SE.getSCEV(Sel)) return Cond;
  1719. // Check for a max calculation that matches the pattern. There's no check
  1720. // for ICMP_ULE here because the comparison would be with zero, which
  1721. // isn't interesting.
  1722. CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
  1723. const SCEVNAryExpr *Max = nullptr;
  1724. if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
  1725. Pred = ICmpInst::ICMP_SLE;
  1726. Max = S;
  1727. } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
  1728. Pred = ICmpInst::ICMP_SLT;
  1729. Max = S;
  1730. } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
  1731. Pred = ICmpInst::ICMP_ULT;
  1732. Max = U;
  1733. } else {
  1734. // No match; bail.
  1735. return Cond;
  1736. }
  1737. // To handle a max with more than two operands, this optimization would
  1738. // require additional checking and setup.
  1739. if (Max->getNumOperands() != 2)
  1740. return Cond;
  1741. const SCEV *MaxLHS = Max->getOperand(0);
  1742. const SCEV *MaxRHS = Max->getOperand(1);
  1743. // ScalarEvolution canonicalizes constants to the left. For < and >, look
  1744. // for a comparison with 1. For <= and >=, a comparison with zero.
  1745. if (!MaxLHS ||
  1746. (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
  1747. return Cond;
  1748. // Check the relevant induction variable for conformance to
  1749. // the pattern.
  1750. const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
  1751. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
  1752. if (!AR || !AR->isAffine() ||
  1753. AR->getStart() != One ||
  1754. AR->getStepRecurrence(SE) != One)
  1755. return Cond;
  1756. assert(AR->getLoop() == L &&
  1757. "Loop condition operand is an addrec in a different loop!");
  1758. // Check the right operand of the select, and remember it, as it will
  1759. // be used in the new comparison instruction.
  1760. Value *NewRHS = nullptr;
  1761. if (ICmpInst::isTrueWhenEqual(Pred)) {
  1762. // Look for n+1, and grab n.
  1763. if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
  1764. if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
  1765. if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
  1766. NewRHS = BO->getOperand(0);
  1767. if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
  1768. if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
  1769. if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
  1770. NewRHS = BO->getOperand(0);
  1771. if (!NewRHS)
  1772. return Cond;
  1773. } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
  1774. NewRHS = Sel->getOperand(1);
  1775. else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
  1776. NewRHS = Sel->getOperand(2);
  1777. else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
  1778. NewRHS = SU->getValue();
  1779. else
  1780. // Max doesn't match expected pattern.
  1781. return Cond;
  1782. // Determine the new comparison opcode. It may be signed or unsigned,
  1783. // and the original comparison may be either equality or inequality.
  1784. if (Cond->getPredicate() == CmpInst::ICMP_EQ)
  1785. Pred = CmpInst::getInversePredicate(Pred);
  1786. // Ok, everything looks ok to change the condition into an SLT or SGE and
  1787. // delete the max calculation.
  1788. ICmpInst *NewCond =
  1789. new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
  1790. // Delete the max calculation instructions.
  1791. Cond->replaceAllUsesWith(NewCond);
  1792. CondUse->setUser(NewCond);
  1793. Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
  1794. Cond->eraseFromParent();
  1795. Sel->eraseFromParent();
  1796. if (Cmp->use_empty())
  1797. Cmp->eraseFromParent();
  1798. return NewCond;
  1799. }
  1800. /// OptimizeLoopTermCond - Change loop terminating condition to use the
  1801. /// postinc iv when possible.
  1802. void
  1803. LSRInstance::OptimizeLoopTermCond() {
  1804. SmallPtrSet<Instruction *, 4> PostIncs;
  1805. BasicBlock *LatchBlock = L->getLoopLatch();
  1806. SmallVector<BasicBlock*, 8> ExitingBlocks;
  1807. L->getExitingBlocks(ExitingBlocks);
  1808. for (BasicBlock *ExitingBlock : ExitingBlocks) {
  1809. // Get the terminating condition for the loop if possible. If we
  1810. // can, we want to change it to use a post-incremented version of its
  1811. // induction variable, to allow coalescing the live ranges for the IV into
  1812. // one register value.
  1813. BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
  1814. if (!TermBr)
  1815. continue;
  1816. // FIXME: Overly conservative, termination condition could be an 'or' etc..
  1817. if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
  1818. continue;
  1819. // Search IVUsesByStride to find Cond's IVUse if there is one.
  1820. IVStrideUse *CondUse = nullptr;
  1821. ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
  1822. if (!FindIVUserForCond(Cond, CondUse))
  1823. continue;
  1824. // If the trip count is computed in terms of a max (due to ScalarEvolution
  1825. // being unable to find a sufficient guard, for example), change the loop
  1826. // comparison to use SLT or ULT instead of NE.
  1827. // One consequence of doing this now is that it disrupts the count-down
  1828. // optimization. That's not always a bad thing though, because in such
  1829. // cases it may still be worthwhile to avoid a max.
  1830. Cond = OptimizeMax(Cond, CondUse);
  1831. // If this exiting block dominates the latch block, it may also use
  1832. // the post-inc value if it won't be shared with other uses.
  1833. // Check for dominance.
  1834. if (!DT.dominates(ExitingBlock, LatchBlock))
  1835. continue;
  1836. // Conservatively avoid trying to use the post-inc value in non-latch
  1837. // exits if there may be pre-inc users in intervening blocks.
  1838. if (LatchBlock != ExitingBlock)
  1839. for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
  1840. // Test if the use is reachable from the exiting block. This dominator
  1841. // query is a conservative approximation of reachability.
  1842. if (&*UI != CondUse &&
  1843. !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
  1844. // Conservatively assume there may be reuse if the quotient of their
  1845. // strides could be a legal scale.
  1846. const SCEV *A = IU.getStride(*CondUse, L);
  1847. const SCEV *B = IU.getStride(*UI, L);
  1848. if (!A || !B) continue;
  1849. if (SE.getTypeSizeInBits(A->getType()) !=
  1850. SE.getTypeSizeInBits(B->getType())) {
  1851. if (SE.getTypeSizeInBits(A->getType()) >
  1852. SE.getTypeSizeInBits(B->getType()))
  1853. B = SE.getSignExtendExpr(B, A->getType());
  1854. else
  1855. A = SE.getSignExtendExpr(A, B->getType());
  1856. }
  1857. if (const SCEVConstant *D =
  1858. dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
  1859. const ConstantInt *C = D->getValue();
  1860. // Stride of one or negative one can have reuse with non-addresses.
  1861. if (C->isOne() || C->isAllOnesValue())
  1862. goto decline_post_inc;
  1863. // Avoid weird situations.
  1864. if (C->getValue().getMinSignedBits() >= 64 ||
  1865. C->getValue().isMinSignedValue())
  1866. goto decline_post_inc;
  1867. // Check for possible scaled-address reuse.
  1868. Type *AccessTy = getAccessType(UI->getUser());
  1869. int64_t Scale = C->getSExtValue();
  1870. if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
  1871. /*BaseOffset=*/ 0,
  1872. /*HasBaseReg=*/ false, Scale))
  1873. goto decline_post_inc;
  1874. Scale = -Scale;
  1875. if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
  1876. /*BaseOffset=*/ 0,
  1877. /*HasBaseReg=*/ false, Scale))
  1878. goto decline_post_inc;
  1879. }
  1880. }
  1881. DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
  1882. << *Cond << '\n');
  1883. // It's possible for the setcc instruction to be anywhere in the loop, and
  1884. // possible for it to have multiple users. If it is not immediately before
  1885. // the exiting block branch, move it.
  1886. if (&*++BasicBlock::iterator(Cond) != TermBr) {
  1887. if (Cond->hasOneUse()) {
  1888. Cond->moveBefore(TermBr);
  1889. } else {
  1890. // Clone the terminating condition and insert into the loopend.
  1891. ICmpInst *OldCond = Cond;
  1892. Cond = cast<ICmpInst>(Cond->clone());
  1893. Cond->setName(L->getHeader()->getName() + ".termcond");
  1894. ExitingBlock->getInstList().insert(TermBr, Cond);
  1895. // Clone the IVUse, as the old use still exists!
  1896. CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
  1897. TermBr->replaceUsesOfWith(OldCond, Cond);
  1898. }
  1899. }
  1900. // If we get to here, we know that we can transform the setcc instruction to
  1901. // use the post-incremented version of the IV, allowing us to coalesce the
  1902. // live ranges for the IV correctly.
  1903. CondUse->transformToPostInc(L);
  1904. Changed = true;
  1905. PostIncs.insert(Cond);
  1906. decline_post_inc:;
  1907. }
  1908. // Determine an insertion point for the loop induction variable increment. It
  1909. // must dominate all the post-inc comparisons we just set up, and it must
  1910. // dominate the loop latch edge.
  1911. IVIncInsertPos = L->getLoopLatch()->getTerminator();
  1912. for (Instruction *Inst : PostIncs) {
  1913. BasicBlock *BB =
  1914. DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
  1915. Inst->getParent());
  1916. if (BB == Inst->getParent())
  1917. IVIncInsertPos = Inst;
  1918. else if (BB != IVIncInsertPos->getParent())
  1919. IVIncInsertPos = BB->getTerminator();
  1920. }
  1921. }
  1922. /// reconcileNewOffset - Determine if the given use can accommodate a fixup
  1923. /// at the given offset and other details. If so, update the use and
  1924. /// return true.
  1925. bool
  1926. LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
  1927. LSRUse::KindType Kind, Type *AccessTy) {
  1928. int64_t NewMinOffset = LU.MinOffset;
  1929. int64_t NewMaxOffset = LU.MaxOffset;
  1930. Type *NewAccessTy = AccessTy;
  1931. // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
  1932. // something conservative, however this can pessimize in the case that one of
  1933. // the uses will have all its uses outside the loop, for example.
  1934. if (LU.Kind != Kind)
  1935. return false;
  1936. // Check for a mismatched access type, and fall back conservatively as needed.
  1937. // TODO: Be less conservative when the type is similar and can use the same
  1938. // addressing modes.
  1939. if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
  1940. NewAccessTy = Type::getVoidTy(AccessTy->getContext());
  1941. // Conservatively assume HasBaseReg is true for now.
  1942. if (NewOffset < LU.MinOffset) {
  1943. if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
  1944. LU.MaxOffset - NewOffset, HasBaseReg))
  1945. return false;
  1946. NewMinOffset = NewOffset;
  1947. } else if (NewOffset > LU.MaxOffset) {
  1948. if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
  1949. NewOffset - LU.MinOffset, HasBaseReg))
  1950. return false;
  1951. NewMaxOffset = NewOffset;
  1952. }
  1953. // Update the use.
  1954. LU.MinOffset = NewMinOffset;
  1955. LU.MaxOffset = NewMaxOffset;
  1956. LU.AccessTy = NewAccessTy;
  1957. if (NewOffset != LU.Offsets.back())
  1958. LU.Offsets.push_back(NewOffset);
  1959. return true;
  1960. }
  1961. /// getUse - Return an LSRUse index and an offset value for a fixup which
  1962. /// needs the given expression, with the given kind and optional access type.
  1963. /// Either reuse an existing use or create a new one, as needed.
  1964. std::pair<size_t, int64_t>
  1965. LSRInstance::getUse(const SCEV *&Expr,
  1966. LSRUse::KindType Kind, Type *AccessTy) {
  1967. const SCEV *Copy = Expr;
  1968. int64_t Offset = ExtractImmediate(Expr, SE);
  1969. // Basic uses can't accept any offset, for example.
  1970. if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
  1971. Offset, /*HasBaseReg=*/ true)) {
  1972. Expr = Copy;
  1973. Offset = 0;
  1974. }
  1975. std::pair<UseMapTy::iterator, bool> P =
  1976. UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
  1977. if (!P.second) {
  1978. // A use already existed with this base.
  1979. size_t LUIdx = P.first->second;
  1980. LSRUse &LU = Uses[LUIdx];
  1981. if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
  1982. // Reuse this use.
  1983. return std::make_pair(LUIdx, Offset);
  1984. }
  1985. // Create a new use.
  1986. size_t LUIdx = Uses.size();
  1987. P.first->second = LUIdx;
  1988. Uses.push_back(LSRUse(Kind, AccessTy));
  1989. LSRUse &LU = Uses[LUIdx];
  1990. // We don't need to track redundant offsets, but we don't need to go out
  1991. // of our way here to avoid them.
  1992. if (LU.Offsets.empty() || Offset != LU.Offsets.back())
  1993. LU.Offsets.push_back(Offset);
  1994. LU.MinOffset = Offset;
  1995. LU.MaxOffset = Offset;
  1996. return std::make_pair(LUIdx, Offset);
  1997. }
  1998. /// DeleteUse - Delete the given use from the Uses list.
  1999. void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
  2000. if (&LU != &Uses.back())
  2001. std::swap(LU, Uses.back());
  2002. Uses.pop_back();
  2003. // Update RegUses.
  2004. RegUses.SwapAndDropUse(LUIdx, Uses.size());
  2005. }
  2006. /// FindUseWithFormula - Look for a use distinct from OrigLU which is has
  2007. /// a formula that has the same registers as the given formula.
  2008. LSRUse *
  2009. LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
  2010. const LSRUse &OrigLU) {
  2011. // Search all uses for the formula. This could be more clever.
  2012. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  2013. LSRUse &LU = Uses[LUIdx];
  2014. // Check whether this use is close enough to OrigLU, to see whether it's
  2015. // worthwhile looking through its formulae.
  2016. // Ignore ICmpZero uses because they may contain formulae generated by
  2017. // GenerateICmpZeroScales, in which case adding fixup offsets may
  2018. // be invalid.
  2019. if (&LU != &OrigLU &&
  2020. LU.Kind != LSRUse::ICmpZero &&
  2021. LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
  2022. LU.WidestFixupType == OrigLU.WidestFixupType &&
  2023. LU.HasFormulaWithSameRegs(OrigF)) {
  2024. // Scan through this use's formulae.
  2025. for (const Formula &F : LU.Formulae) {
  2026. // Check to see if this formula has the same registers and symbols
  2027. // as OrigF.
  2028. if (F.BaseRegs == OrigF.BaseRegs &&
  2029. F.ScaledReg == OrigF.ScaledReg &&
  2030. F.BaseGV == OrigF.BaseGV &&
  2031. F.Scale == OrigF.Scale &&
  2032. F.UnfoldedOffset == OrigF.UnfoldedOffset) {
  2033. if (F.BaseOffset == 0)
  2034. return &LU;
  2035. // This is the formula where all the registers and symbols matched;
  2036. // there aren't going to be any others. Since we declined it, we
  2037. // can skip the rest of the formulae and proceed to the next LSRUse.
  2038. break;
  2039. }
  2040. }
  2041. }
  2042. }
  2043. // Nothing looked good.
  2044. return nullptr;
  2045. }
  2046. void LSRInstance::CollectInterestingTypesAndFactors() {
  2047. SmallSetVector<const SCEV *, 4> Strides;
  2048. // Collect interesting types and strides.
  2049. SmallVector<const SCEV *, 4> Worklist;
  2050. for (const IVStrideUse &U : IU) {
  2051. const SCEV *Expr = IU.getExpr(U);
  2052. // Collect interesting types.
  2053. Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
  2054. // Add strides for mentioned loops.
  2055. Worklist.push_back(Expr);
  2056. do {
  2057. const SCEV *S = Worklist.pop_back_val();
  2058. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  2059. if (AR->getLoop() == L)
  2060. Strides.insert(AR->getStepRecurrence(SE));
  2061. Worklist.push_back(AR->getStart());
  2062. } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  2063. Worklist.append(Add->op_begin(), Add->op_end());
  2064. }
  2065. } while (!Worklist.empty());
  2066. }
  2067. // Compute interesting factors from the set of interesting strides.
  2068. for (SmallSetVector<const SCEV *, 4>::const_iterator
  2069. I = Strides.begin(), E = Strides.end(); I != E; ++I)
  2070. for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
  2071. std::next(I); NewStrideIter != E; ++NewStrideIter) {
  2072. const SCEV *OldStride = *I;
  2073. const SCEV *NewStride = *NewStrideIter;
  2074. if (SE.getTypeSizeInBits(OldStride->getType()) !=
  2075. SE.getTypeSizeInBits(NewStride->getType())) {
  2076. if (SE.getTypeSizeInBits(OldStride->getType()) >
  2077. SE.getTypeSizeInBits(NewStride->getType()))
  2078. NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
  2079. else
  2080. OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
  2081. }
  2082. if (const SCEVConstant *Factor =
  2083. dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
  2084. SE, true))) {
  2085. if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
  2086. Factors.insert(Factor->getValue()->getValue().getSExtValue());
  2087. } else if (const SCEVConstant *Factor =
  2088. dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
  2089. NewStride,
  2090. SE, true))) {
  2091. if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
  2092. Factors.insert(Factor->getValue()->getValue().getSExtValue());
  2093. }
  2094. }
  2095. // If all uses use the same type, don't bother looking for truncation-based
  2096. // reuse.
  2097. if (Types.size() == 1)
  2098. Types.clear();
  2099. DEBUG(print_factors_and_types(dbgs()));
  2100. }
  2101. /// findIVOperand - Helper for CollectChains that finds an IV operand (computed
  2102. /// by an AddRec in this loop) within [OI,OE) or returns OE. If IVUsers mapped
  2103. /// Instructions to IVStrideUses, we could partially skip this.
  2104. static User::op_iterator
  2105. findIVOperand(User::op_iterator OI, User::op_iterator OE,
  2106. Loop *L, ScalarEvolution &SE) {
  2107. for(; OI != OE; ++OI) {
  2108. if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
  2109. if (!SE.isSCEVable(Oper->getType()))
  2110. continue;
  2111. if (const SCEVAddRecExpr *AR =
  2112. dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
  2113. if (AR->getLoop() == L)
  2114. break;
  2115. }
  2116. }
  2117. }
  2118. return OI;
  2119. }
  2120. /// getWideOperand - IVChain logic must consistenctly peek base TruncInst
  2121. /// operands, so wrap it in a convenient helper.
  2122. static Value *getWideOperand(Value *Oper) {
  2123. if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
  2124. return Trunc->getOperand(0);
  2125. return Oper;
  2126. }
  2127. /// isCompatibleIVType - Return true if we allow an IV chain to include both
  2128. /// types.
  2129. static bool isCompatibleIVType(Value *LVal, Value *RVal) {
  2130. Type *LType = LVal->getType();
  2131. Type *RType = RVal->getType();
  2132. return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy());
  2133. }
  2134. /// getExprBase - Return an approximation of this SCEV expression's "base", or
  2135. /// NULL for any constant. Returning the expression itself is
  2136. /// conservative. Returning a deeper subexpression is more precise and valid as
  2137. /// long as it isn't less complex than another subexpression. For expressions
  2138. /// involving multiple unscaled values, we need to return the pointer-type
  2139. /// SCEVUnknown. This avoids forming chains across objects, such as:
  2140. /// PrevOper==a[i], IVOper==b[i], IVInc==b-a.
  2141. ///
  2142. /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
  2143. /// SCEVUnknown, we simply return the rightmost SCEV operand.
  2144. static const SCEV *getExprBase(const SCEV *S) {
  2145. switch (S->getSCEVType()) {
  2146. default: // uncluding scUnknown.
  2147. return S;
  2148. case scConstant:
  2149. return nullptr;
  2150. case scTruncate:
  2151. return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
  2152. case scZeroExtend:
  2153. return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
  2154. case scSignExtend:
  2155. return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
  2156. case scAddExpr: {
  2157. // Skip over scaled operands (scMulExpr) to follow add operands as long as
  2158. // there's nothing more complex.
  2159. // FIXME: not sure if we want to recognize negation.
  2160. const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
  2161. for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
  2162. E(Add->op_begin()); I != E; ++I) {
  2163. const SCEV *SubExpr = *I;
  2164. if (SubExpr->getSCEVType() == scAddExpr)
  2165. return getExprBase(SubExpr);
  2166. if (SubExpr->getSCEVType() != scMulExpr)
  2167. return SubExpr;
  2168. }
  2169. return S; // all operands are scaled, be conservative.
  2170. }
  2171. case scAddRecExpr:
  2172. return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
  2173. }
  2174. }
  2175. /// Return true if the chain increment is profitable to expand into a loop
  2176. /// invariant value, which may require its own register. A profitable chain
  2177. /// increment will be an offset relative to the same base. We allow such offsets
  2178. /// to potentially be used as chain increment as long as it's not obviously
  2179. /// expensive to expand using real instructions.
  2180. bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
  2181. const SCEV *IncExpr,
  2182. ScalarEvolution &SE) {
  2183. // Aggressively form chains when -stress-ivchain.
  2184. if (StressIVChain)
  2185. return true;
  2186. // Do not replace a constant offset from IV head with a nonconstant IV
  2187. // increment.
  2188. if (!isa<SCEVConstant>(IncExpr)) {
  2189. const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
  2190. if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
  2191. return 0;
  2192. }
  2193. SmallPtrSet<const SCEV*, 8> Processed;
  2194. return !isHighCostExpansion(IncExpr, Processed, SE);
  2195. }
  2196. /// Return true if the number of registers needed for the chain is estimated to
  2197. /// be less than the number required for the individual IV users. First prohibit
  2198. /// any IV users that keep the IV live across increments (the Users set should
  2199. /// be empty). Next count the number and type of increments in the chain.
  2200. ///
  2201. /// Chaining IVs can lead to considerable code bloat if ISEL doesn't
  2202. /// effectively use postinc addressing modes. Only consider it profitable it the
  2203. /// increments can be computed in fewer registers when chained.
  2204. ///
  2205. /// TODO: Consider IVInc free if it's already used in another chains.
  2206. static bool
  2207. isProfitableChain(IVChain &Chain, SmallPtrSetImpl<Instruction*> &Users,
  2208. ScalarEvolution &SE, const TargetTransformInfo &TTI) {
  2209. if (StressIVChain)
  2210. return true;
  2211. if (!Chain.hasIncs())
  2212. return false;
  2213. if (!Users.empty()) {
  2214. DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
  2215. for (Instruction *Inst : Users) {
  2216. dbgs() << " " << *Inst << "\n";
  2217. });
  2218. return false;
  2219. }
  2220. assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
  2221. // The chain itself may require a register, so intialize cost to 1.
  2222. int cost = 1;
  2223. // A complete chain likely eliminates the need for keeping the original IV in
  2224. // a register. LSR does not currently know how to form a complete chain unless
  2225. // the header phi already exists.
  2226. if (isa<PHINode>(Chain.tailUserInst())
  2227. && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
  2228. --cost;
  2229. }
  2230. const SCEV *LastIncExpr = nullptr;
  2231. unsigned NumConstIncrements = 0;
  2232. unsigned NumVarIncrements = 0;
  2233. unsigned NumReusedIncrements = 0;
  2234. for (const IVInc &Inc : Chain) {
  2235. if (Inc.IncExpr->isZero())
  2236. continue;
  2237. // Incrementing by zero or some constant is neutral. We assume constants can
  2238. // be folded into an addressing mode or an add's immediate operand.
  2239. if (isa<SCEVConstant>(Inc.IncExpr)) {
  2240. ++NumConstIncrements;
  2241. continue;
  2242. }
  2243. if (Inc.IncExpr == LastIncExpr)
  2244. ++NumReusedIncrements;
  2245. else
  2246. ++NumVarIncrements;
  2247. LastIncExpr = Inc.IncExpr;
  2248. }
  2249. // An IV chain with a single increment is handled by LSR's postinc
  2250. // uses. However, a chain with multiple increments requires keeping the IV's
  2251. // value live longer than it needs to be if chained.
  2252. if (NumConstIncrements > 1)
  2253. --cost;
  2254. // Materializing increment expressions in the preheader that didn't exist in
  2255. // the original code may cost a register. For example, sign-extended array
  2256. // indices can produce ridiculous increments like this:
  2257. // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
  2258. cost += NumVarIncrements;
  2259. // Reusing variable increments likely saves a register to hold the multiple of
  2260. // the stride.
  2261. cost -= NumReusedIncrements;
  2262. DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
  2263. << "\n");
  2264. return cost < 0;
  2265. }
  2266. /// ChainInstruction - Add this IV user to an existing chain or make it the head
  2267. /// of a new chain.
  2268. void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
  2269. SmallVectorImpl<ChainUsers> &ChainUsersVec) {
  2270. // When IVs are used as types of varying widths, they are generally converted
  2271. // to a wider type with some uses remaining narrow under a (free) trunc.
  2272. Value *const NextIV = getWideOperand(IVOper);
  2273. const SCEV *const OperExpr = SE.getSCEV(NextIV);
  2274. const SCEV *const OperExprBase = getExprBase(OperExpr);
  2275. // Visit all existing chains. Check if its IVOper can be computed as a
  2276. // profitable loop invariant increment from the last link in the Chain.
  2277. unsigned ChainIdx = 0, NChains = IVChainVec.size();
  2278. const SCEV *LastIncExpr = nullptr;
  2279. for (; ChainIdx < NChains; ++ChainIdx) {
  2280. IVChain &Chain = IVChainVec[ChainIdx];
  2281. // Prune the solution space aggressively by checking that both IV operands
  2282. // are expressions that operate on the same unscaled SCEVUnknown. This
  2283. // "base" will be canceled by the subsequent getMinusSCEV call. Checking
  2284. // first avoids creating extra SCEV expressions.
  2285. if (!StressIVChain && Chain.ExprBase != OperExprBase)
  2286. continue;
  2287. Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
  2288. if (!isCompatibleIVType(PrevIV, NextIV))
  2289. continue;
  2290. // A phi node terminates a chain.
  2291. if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
  2292. continue;
  2293. // The increment must be loop-invariant so it can be kept in a register.
  2294. const SCEV *PrevExpr = SE.getSCEV(PrevIV);
  2295. const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
  2296. if (!SE.isLoopInvariant(IncExpr, L))
  2297. continue;
  2298. if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
  2299. LastIncExpr = IncExpr;
  2300. break;
  2301. }
  2302. }
  2303. // If we haven't found a chain, create a new one, unless we hit the max. Don't
  2304. // bother for phi nodes, because they must be last in the chain.
  2305. if (ChainIdx == NChains) {
  2306. if (isa<PHINode>(UserInst))
  2307. return;
  2308. if (NChains >= MaxChains && !StressIVChain) {
  2309. DEBUG(dbgs() << "IV Chain Limit\n");
  2310. return;
  2311. }
  2312. LastIncExpr = OperExpr;
  2313. // IVUsers may have skipped over sign/zero extensions. We don't currently
  2314. // attempt to form chains involving extensions unless they can be hoisted
  2315. // into this loop's AddRec.
  2316. if (!isa<SCEVAddRecExpr>(LastIncExpr))
  2317. return;
  2318. ++NChains;
  2319. IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
  2320. OperExprBase));
  2321. ChainUsersVec.resize(NChains);
  2322. DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
  2323. << ") IV=" << *LastIncExpr << "\n");
  2324. } else {
  2325. DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
  2326. << ") IV+" << *LastIncExpr << "\n");
  2327. // Add this IV user to the end of the chain.
  2328. IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
  2329. }
  2330. IVChain &Chain = IVChainVec[ChainIdx];
  2331. SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
  2332. // This chain's NearUsers become FarUsers.
  2333. if (!LastIncExpr->isZero()) {
  2334. ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
  2335. NearUsers.end());
  2336. NearUsers.clear();
  2337. }
  2338. // All other uses of IVOperand become near uses of the chain.
  2339. // We currently ignore intermediate values within SCEV expressions, assuming
  2340. // they will eventually be used be the current chain, or can be computed
  2341. // from one of the chain increments. To be more precise we could
  2342. // transitively follow its user and only add leaf IV users to the set.
  2343. for (User *U : IVOper->users()) {
  2344. Instruction *OtherUse = dyn_cast<Instruction>(U);
  2345. if (!OtherUse)
  2346. continue;
  2347. // Uses in the chain will no longer be uses if the chain is formed.
  2348. // Include the head of the chain in this iteration (not Chain.begin()).
  2349. IVChain::const_iterator IncIter = Chain.Incs.begin();
  2350. IVChain::const_iterator IncEnd = Chain.Incs.end();
  2351. for( ; IncIter != IncEnd; ++IncIter) {
  2352. if (IncIter->UserInst == OtherUse)
  2353. break;
  2354. }
  2355. if (IncIter != IncEnd)
  2356. continue;
  2357. if (SE.isSCEVable(OtherUse->getType())
  2358. && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
  2359. && IU.isIVUserOrOperand(OtherUse)) {
  2360. continue;
  2361. }
  2362. NearUsers.insert(OtherUse);
  2363. }
  2364. // Since this user is part of the chain, it's no longer considered a use
  2365. // of the chain.
  2366. ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
  2367. }
  2368. /// CollectChains - Populate the vector of Chains.
  2369. ///
  2370. /// This decreases ILP at the architecture level. Targets with ample registers,
  2371. /// multiple memory ports, and no register renaming probably don't want
  2372. /// this. However, such targets should probably disable LSR altogether.
  2373. ///
  2374. /// The job of LSR is to make a reasonable choice of induction variables across
  2375. /// the loop. Subsequent passes can easily "unchain" computation exposing more
  2376. /// ILP *within the loop* if the target wants it.
  2377. ///
  2378. /// Finding the best IV chain is potentially a scheduling problem. Since LSR
  2379. /// will not reorder memory operations, it will recognize this as a chain, but
  2380. /// will generate redundant IV increments. Ideally this would be corrected later
  2381. /// by a smart scheduler:
  2382. /// = A[i]
  2383. /// = A[i+x]
  2384. /// A[i] =
  2385. /// A[i+x] =
  2386. ///
  2387. /// TODO: Walk the entire domtree within this loop, not just the path to the
  2388. /// loop latch. This will discover chains on side paths, but requires
  2389. /// maintaining multiple copies of the Chains state.
  2390. void LSRInstance::CollectChains() {
  2391. DEBUG(dbgs() << "Collecting IV Chains.\n");
  2392. SmallVector<ChainUsers, 8> ChainUsersVec;
  2393. SmallVector<BasicBlock *,8> LatchPath;
  2394. BasicBlock *LoopHeader = L->getHeader();
  2395. for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
  2396. Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
  2397. LatchPath.push_back(Rung->getBlock());
  2398. }
  2399. LatchPath.push_back(LoopHeader);
  2400. // Walk the instruction stream from the loop header to the loop latch.
  2401. for (SmallVectorImpl<BasicBlock *>::reverse_iterator
  2402. BBIter = LatchPath.rbegin(), BBEnd = LatchPath.rend();
  2403. BBIter != BBEnd; ++BBIter) {
  2404. for (BasicBlock::iterator I = (*BBIter)->begin(), E = (*BBIter)->end();
  2405. I != E; ++I) {
  2406. // Skip instructions that weren't seen by IVUsers analysis.
  2407. if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
  2408. continue;
  2409. // Ignore users that are part of a SCEV expression. This way we only
  2410. // consider leaf IV Users. This effectively rediscovers a portion of
  2411. // IVUsers analysis but in program order this time.
  2412. if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
  2413. continue;
  2414. // Remove this instruction from any NearUsers set it may be in.
  2415. for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
  2416. ChainIdx < NChains; ++ChainIdx) {
  2417. ChainUsersVec[ChainIdx].NearUsers.erase(I);
  2418. }
  2419. // Search for operands that can be chained.
  2420. SmallPtrSet<Instruction*, 4> UniqueOperands;
  2421. User::op_iterator IVOpEnd = I->op_end();
  2422. User::op_iterator IVOpIter = findIVOperand(I->op_begin(), IVOpEnd, L, SE);
  2423. while (IVOpIter != IVOpEnd) {
  2424. Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
  2425. if (UniqueOperands.insert(IVOpInst).second)
  2426. ChainInstruction(I, IVOpInst, ChainUsersVec);
  2427. IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
  2428. }
  2429. } // Continue walking down the instructions.
  2430. } // Continue walking down the domtree.
  2431. // Visit phi backedges to determine if the chain can generate the IV postinc.
  2432. for (BasicBlock::iterator I = L->getHeader()->begin();
  2433. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  2434. if (!SE.isSCEVable(PN->getType()))
  2435. continue;
  2436. Instruction *IncV =
  2437. dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
  2438. if (IncV)
  2439. ChainInstruction(PN, IncV, ChainUsersVec);
  2440. }
  2441. // Remove any unprofitable chains.
  2442. unsigned ChainIdx = 0;
  2443. for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
  2444. UsersIdx < NChains; ++UsersIdx) {
  2445. if (!isProfitableChain(IVChainVec[UsersIdx],
  2446. ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
  2447. continue;
  2448. // Preserve the chain at UsesIdx.
  2449. if (ChainIdx != UsersIdx)
  2450. IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
  2451. FinalizeChain(IVChainVec[ChainIdx]);
  2452. ++ChainIdx;
  2453. }
  2454. IVChainVec.resize(ChainIdx);
  2455. }
  2456. void LSRInstance::FinalizeChain(IVChain &Chain) {
  2457. assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
  2458. DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
  2459. for (const IVInc &Inc : Chain) {
  2460. DEBUG(dbgs() << " Inc: " << Inc.UserInst << "\n");
  2461. auto UseI = std::find(Inc.UserInst->op_begin(), Inc.UserInst->op_end(),
  2462. Inc.IVOperand);
  2463. assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
  2464. IVIncSet.insert(UseI);
  2465. }
  2466. }
  2467. /// Return true if the IVInc can be folded into an addressing mode.
  2468. static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
  2469. Value *Operand, const TargetTransformInfo &TTI) {
  2470. const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
  2471. if (!IncConst || !isAddressUse(UserInst, Operand))
  2472. return false;
  2473. if (IncConst->getValue()->getValue().getMinSignedBits() > 64)
  2474. return false;
  2475. int64_t IncOffset = IncConst->getValue()->getSExtValue();
  2476. if (!isAlwaysFoldable(TTI, LSRUse::Address,
  2477. getAccessType(UserInst), /*BaseGV=*/ nullptr,
  2478. IncOffset, /*HaseBaseReg=*/ false))
  2479. return false;
  2480. return true;
  2481. }
  2482. /// GenerateIVChains - Generate an add or subtract for each IVInc in a chain to
  2483. /// materialize the IV user's operand from the previous IV user's operand.
  2484. void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
  2485. SmallVectorImpl<WeakVH> &DeadInsts) {
  2486. // Find the new IVOperand for the head of the chain. It may have been replaced
  2487. // by LSR.
  2488. const IVInc &Head = Chain.Incs[0];
  2489. User::op_iterator IVOpEnd = Head.UserInst->op_end();
  2490. // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
  2491. User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
  2492. IVOpEnd, L, SE);
  2493. Value *IVSrc = nullptr;
  2494. while (IVOpIter != IVOpEnd) {
  2495. IVSrc = getWideOperand(*IVOpIter);
  2496. // If this operand computes the expression that the chain needs, we may use
  2497. // it. (Check this after setting IVSrc which is used below.)
  2498. //
  2499. // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
  2500. // narrow for the chain, so we can no longer use it. We do allow using a
  2501. // wider phi, assuming the LSR checked for free truncation. In that case we
  2502. // should already have a truncate on this operand such that
  2503. // getSCEV(IVSrc) == IncExpr.
  2504. if (SE.getSCEV(*IVOpIter) == Head.IncExpr
  2505. || SE.getSCEV(IVSrc) == Head.IncExpr) {
  2506. break;
  2507. }
  2508. IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
  2509. }
  2510. if (IVOpIter == IVOpEnd) {
  2511. // Gracefully give up on this chain.
  2512. DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
  2513. return;
  2514. }
  2515. DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
  2516. Type *IVTy = IVSrc->getType();
  2517. Type *IntTy = SE.getEffectiveSCEVType(IVTy);
  2518. const SCEV *LeftOverExpr = nullptr;
  2519. for (const IVInc &Inc : Chain) {
  2520. Instruction *InsertPt = Inc.UserInst;
  2521. if (isa<PHINode>(InsertPt))
  2522. InsertPt = L->getLoopLatch()->getTerminator();
  2523. // IVOper will replace the current IV User's operand. IVSrc is the IV
  2524. // value currently held in a register.
  2525. Value *IVOper = IVSrc;
  2526. if (!Inc.IncExpr->isZero()) {
  2527. // IncExpr was the result of subtraction of two narrow values, so must
  2528. // be signed.
  2529. const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);
  2530. LeftOverExpr = LeftOverExpr ?
  2531. SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
  2532. }
  2533. if (LeftOverExpr && !LeftOverExpr->isZero()) {
  2534. // Expand the IV increment.
  2535. Rewriter.clearPostInc();
  2536. Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
  2537. const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
  2538. SE.getUnknown(IncV));
  2539. IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
  2540. // If an IV increment can't be folded, use it as the next IV value.
  2541. if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {
  2542. assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
  2543. IVSrc = IVOper;
  2544. LeftOverExpr = nullptr;
  2545. }
  2546. }
  2547. Type *OperTy = Inc.IVOperand->getType();
  2548. if (IVTy != OperTy) {
  2549. assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
  2550. "cannot extend a chained IV");
  2551. IRBuilder<> Builder(InsertPt);
  2552. IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
  2553. }
  2554. Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
  2555. DeadInsts.emplace_back(Inc.IVOperand);
  2556. }
  2557. // If LSR created a new, wider phi, we may also replace its postinc. We only
  2558. // do this if we also found a wide value for the head of the chain.
  2559. if (isa<PHINode>(Chain.tailUserInst())) {
  2560. for (BasicBlock::iterator I = L->getHeader()->begin();
  2561. PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
  2562. if (!isCompatibleIVType(Phi, IVSrc))
  2563. continue;
  2564. Instruction *PostIncV = dyn_cast<Instruction>(
  2565. Phi->getIncomingValueForBlock(L->getLoopLatch()));
  2566. if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
  2567. continue;
  2568. Value *IVOper = IVSrc;
  2569. Type *PostIncTy = PostIncV->getType();
  2570. if (IVTy != PostIncTy) {
  2571. assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
  2572. IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
  2573. Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
  2574. IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
  2575. }
  2576. Phi->replaceUsesOfWith(PostIncV, IVOper);
  2577. DeadInsts.emplace_back(PostIncV);
  2578. }
  2579. }
  2580. }
  2581. void LSRInstance::CollectFixupsAndInitialFormulae() {
  2582. for (const IVStrideUse &U : IU) {
  2583. Instruction *UserInst = U.getUser();
  2584. // Skip IV users that are part of profitable IV Chains.
  2585. User::op_iterator UseI = std::find(UserInst->op_begin(), UserInst->op_end(),
  2586. U.getOperandValToReplace());
  2587. assert(UseI != UserInst->op_end() && "cannot find IV operand");
  2588. if (IVIncSet.count(UseI))
  2589. continue;
  2590. // Record the uses.
  2591. LSRFixup &LF = getNewFixup();
  2592. LF.UserInst = UserInst;
  2593. LF.OperandValToReplace = U.getOperandValToReplace();
  2594. LF.PostIncLoops = U.getPostIncLoops();
  2595. LSRUse::KindType Kind = LSRUse::Basic;
  2596. Type *AccessTy = nullptr;
  2597. if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
  2598. Kind = LSRUse::Address;
  2599. AccessTy = getAccessType(LF.UserInst);
  2600. }
  2601. const SCEV *S = IU.getExpr(U);
  2602. // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
  2603. // (N - i == 0), and this allows (N - i) to be the expression that we work
  2604. // with rather than just N or i, so we can consider the register
  2605. // requirements for both N and i at the same time. Limiting this code to
  2606. // equality icmps is not a problem because all interesting loops use
  2607. // equality icmps, thanks to IndVarSimplify.
  2608. if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
  2609. if (CI->isEquality()) {
  2610. // Swap the operands if needed to put the OperandValToReplace on the
  2611. // left, for consistency.
  2612. Value *NV = CI->getOperand(1);
  2613. if (NV == LF.OperandValToReplace) {
  2614. CI->setOperand(1, CI->getOperand(0));
  2615. CI->setOperand(0, NV);
  2616. NV = CI->getOperand(1);
  2617. Changed = true;
  2618. }
  2619. // x == y --> x - y == 0
  2620. const SCEV *N = SE.getSCEV(NV);
  2621. if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
  2622. // S is normalized, so normalize N before folding it into S
  2623. // to keep the result normalized.
  2624. N = TransformForPostIncUse(Normalize, N, CI, nullptr,
  2625. LF.PostIncLoops, SE, DT);
  2626. Kind = LSRUse::ICmpZero;
  2627. S = SE.getMinusSCEV(N, S);
  2628. }
  2629. // -1 and the negations of all interesting strides (except the negation
  2630. // of -1) are now also interesting.
  2631. for (size_t i = 0, e = Factors.size(); i != e; ++i)
  2632. if (Factors[i] != -1)
  2633. Factors.insert(-(uint64_t)Factors[i]);
  2634. Factors.insert(-1);
  2635. }
  2636. // Set up the initial formula for this use.
  2637. std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
  2638. LF.LUIdx = P.first;
  2639. LF.Offset = P.second;
  2640. LSRUse &LU = Uses[LF.LUIdx];
  2641. LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
  2642. if (!LU.WidestFixupType ||
  2643. SE.getTypeSizeInBits(LU.WidestFixupType) <
  2644. SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
  2645. LU.WidestFixupType = LF.OperandValToReplace->getType();
  2646. // If this is the first use of this LSRUse, give it a formula.
  2647. if (LU.Formulae.empty()) {
  2648. InsertInitialFormula(S, LU, LF.LUIdx);
  2649. CountRegisters(LU.Formulae.back(), LF.LUIdx);
  2650. }
  2651. }
  2652. DEBUG(print_fixups(dbgs()));
  2653. }
  2654. /// InsertInitialFormula - Insert a formula for the given expression into
  2655. /// the given use, separating out loop-variant portions from loop-invariant
  2656. /// and loop-computable portions.
  2657. void
  2658. LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
  2659. // Mark uses whose expressions cannot be expanded.
  2660. if (!isSafeToExpand(S, SE))
  2661. LU.RigidFormula = true;
  2662. Formula F;
  2663. F.InitialMatch(S, L, SE);
  2664. bool Inserted = InsertFormula(LU, LUIdx, F);
  2665. assert(Inserted && "Initial formula already exists!"); (void)Inserted;
  2666. }
  2667. /// InsertSupplementalFormula - Insert a simple single-register formula for
  2668. /// the given expression into the given use.
  2669. void
  2670. LSRInstance::InsertSupplementalFormula(const SCEV *S,
  2671. LSRUse &LU, size_t LUIdx) {
  2672. Formula F;
  2673. F.BaseRegs.push_back(S);
  2674. F.HasBaseReg = true;
  2675. bool Inserted = InsertFormula(LU, LUIdx, F);
  2676. assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
  2677. }
  2678. /// CountRegisters - Note which registers are used by the given formula,
  2679. /// updating RegUses.
  2680. void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
  2681. if (F.ScaledReg)
  2682. RegUses.CountRegister(F.ScaledReg, LUIdx);
  2683. for (const SCEV *BaseReg : F.BaseRegs)
  2684. RegUses.CountRegister(BaseReg, LUIdx);
  2685. }
  2686. /// InsertFormula - If the given formula has not yet been inserted, add it to
  2687. /// the list, and return true. Return false otherwise.
  2688. bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
  2689. // Do not insert formula that we will not be able to expand.
  2690. assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
  2691. "Formula is illegal");
  2692. if (!LU.InsertFormula(F))
  2693. return false;
  2694. CountRegisters(F, LUIdx);
  2695. return true;
  2696. }
  2697. /// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
  2698. /// loop-invariant values which we're tracking. These other uses will pin these
  2699. /// values in registers, making them less profitable for elimination.
  2700. /// TODO: This currently misses non-constant addrec step registers.
  2701. /// TODO: Should this give more weight to users inside the loop?
  2702. void
  2703. LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
  2704. SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
  2705. SmallPtrSet<const SCEV *, 32> Visited;
  2706. while (!Worklist.empty()) {
  2707. const SCEV *S = Worklist.pop_back_val();
  2708. // Don't process the same SCEV twice
  2709. if (!Visited.insert(S).second)
  2710. continue;
  2711. if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
  2712. Worklist.append(N->op_begin(), N->op_end());
  2713. else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
  2714. Worklist.push_back(C->getOperand());
  2715. else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
  2716. Worklist.push_back(D->getLHS());
  2717. Worklist.push_back(D->getRHS());
  2718. } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
  2719. const Value *V = US->getValue();
  2720. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  2721. // Look for instructions defined outside the loop.
  2722. if (L->contains(Inst)) continue;
  2723. } else if (isa<UndefValue>(V))
  2724. // Undef doesn't have a live range, so it doesn't matter.
  2725. continue;
  2726. for (const Use &U : V->uses()) {
  2727. const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
  2728. // Ignore non-instructions.
  2729. if (!UserInst)
  2730. continue;
  2731. // Ignore instructions in other functions (as can happen with
  2732. // Constants).
  2733. if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
  2734. continue;
  2735. // Ignore instructions not dominated by the loop.
  2736. const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
  2737. UserInst->getParent() :
  2738. cast<PHINode>(UserInst)->getIncomingBlock(
  2739. PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
  2740. if (!DT.dominates(L->getHeader(), UseBB))
  2741. continue;
  2742. // Ignore uses which are part of other SCEV expressions, to avoid
  2743. // analyzing them multiple times.
  2744. if (SE.isSCEVable(UserInst->getType())) {
  2745. const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
  2746. // If the user is a no-op, look through to its uses.
  2747. if (!isa<SCEVUnknown>(UserS))
  2748. continue;
  2749. if (UserS == US) {
  2750. Worklist.push_back(
  2751. SE.getUnknown(const_cast<Instruction *>(UserInst)));
  2752. continue;
  2753. }
  2754. }
  2755. // Ignore icmp instructions which are already being analyzed.
  2756. if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
  2757. unsigned OtherIdx = !U.getOperandNo();
  2758. Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
  2759. if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
  2760. continue;
  2761. }
  2762. LSRFixup &LF = getNewFixup();
  2763. LF.UserInst = const_cast<Instruction *>(UserInst);
  2764. LF.OperandValToReplace = U;
  2765. std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, nullptr);
  2766. LF.LUIdx = P.first;
  2767. LF.Offset = P.second;
  2768. LSRUse &LU = Uses[LF.LUIdx];
  2769. LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
  2770. if (!LU.WidestFixupType ||
  2771. SE.getTypeSizeInBits(LU.WidestFixupType) <
  2772. SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
  2773. LU.WidestFixupType = LF.OperandValToReplace->getType();
  2774. InsertSupplementalFormula(US, LU, LF.LUIdx);
  2775. CountRegisters(LU.Formulae.back(), Uses.size() - 1);
  2776. break;
  2777. }
  2778. }
  2779. }
  2780. }
  2781. /// CollectSubexprs - Split S into subexpressions which can be pulled out into
  2782. /// separate registers. If C is non-null, multiply each subexpression by C.
  2783. ///
  2784. /// Return remainder expression after factoring the subexpressions captured by
  2785. /// Ops. If Ops is complete, return NULL.
  2786. static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
  2787. SmallVectorImpl<const SCEV *> &Ops,
  2788. const Loop *L,
  2789. ScalarEvolution &SE,
  2790. unsigned Depth = 0) {
  2791. // Arbitrarily cap recursion to protect compile time.
  2792. if (Depth >= 3)
  2793. return S;
  2794. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  2795. // Break out add operands.
  2796. for (const SCEV *S : Add->operands()) {
  2797. const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);
  2798. if (Remainder)
  2799. Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
  2800. }
  2801. return nullptr;
  2802. } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  2803. // Split a non-zero base out of an addrec.
  2804. if (AR->getStart()->isZero())
  2805. return S;
  2806. const SCEV *Remainder = CollectSubexprs(AR->getStart(),
  2807. C, Ops, L, SE, Depth+1);
  2808. // Split the non-zero AddRec unless it is part of a nested recurrence that
  2809. // does not pertain to this loop.
  2810. if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
  2811. Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
  2812. Remainder = nullptr;
  2813. }
  2814. if (Remainder != AR->getStart()) {
  2815. if (!Remainder)
  2816. Remainder = SE.getConstant(AR->getType(), 0);
  2817. return SE.getAddRecExpr(Remainder,
  2818. AR->getStepRecurrence(SE),
  2819. AR->getLoop(),
  2820. //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
  2821. SCEV::FlagAnyWrap);
  2822. }
  2823. } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
  2824. // Break (C * (a + b + c)) into C*a + C*b + C*c.
  2825. if (Mul->getNumOperands() != 2)
  2826. return S;
  2827. if (const SCEVConstant *Op0 =
  2828. dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
  2829. C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
  2830. const SCEV *Remainder =
  2831. CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
  2832. if (Remainder)
  2833. Ops.push_back(SE.getMulExpr(C, Remainder));
  2834. return nullptr;
  2835. }
  2836. }
  2837. return S;
  2838. }
  2839. /// \brief Helper function for LSRInstance::GenerateReassociations.
  2840. void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
  2841. const Formula &Base,
  2842. unsigned Depth, size_t Idx,
  2843. bool IsScaledReg) {
  2844. const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
  2845. SmallVector<const SCEV *, 8> AddOps;
  2846. const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
  2847. if (Remainder)
  2848. AddOps.push_back(Remainder);
  2849. if (AddOps.size() == 1)
  2850. return;
  2851. for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
  2852. JE = AddOps.end();
  2853. J != JE; ++J) {
  2854. // Loop-variant "unknown" values are uninteresting; we won't be able to
  2855. // do anything meaningful with them.
  2856. if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
  2857. continue;
  2858. // Don't pull a constant into a register if the constant could be folded
  2859. // into an immediate field.
  2860. if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
  2861. LU.AccessTy, *J, Base.getNumRegs() > 1))
  2862. continue;
  2863. // Collect all operands except *J.
  2864. SmallVector<const SCEV *, 8> InnerAddOps(
  2865. ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
  2866. InnerAddOps.append(std::next(J),
  2867. ((const SmallVector<const SCEV *, 8> &)AddOps).end());
  2868. // Don't leave just a constant behind in a register if the constant could
  2869. // be folded into an immediate field.
  2870. if (InnerAddOps.size() == 1 &&
  2871. isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
  2872. LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
  2873. continue;
  2874. const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
  2875. if (InnerSum->isZero())
  2876. continue;
  2877. Formula F = Base;
  2878. // Add the remaining pieces of the add back into the new formula.
  2879. const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
  2880. if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
  2881. TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
  2882. InnerSumSC->getValue()->getZExtValue())) {
  2883. F.UnfoldedOffset =
  2884. (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
  2885. if (IsScaledReg)
  2886. F.ScaledReg = nullptr;
  2887. else
  2888. F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
  2889. } else if (IsScaledReg)
  2890. F.ScaledReg = InnerSum;
  2891. else
  2892. F.BaseRegs[Idx] = InnerSum;
  2893. // Add J as its own register, or an unfolded immediate.
  2894. const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
  2895. if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
  2896. TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
  2897. SC->getValue()->getZExtValue()))
  2898. F.UnfoldedOffset =
  2899. (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
  2900. else
  2901. F.BaseRegs.push_back(*J);
  2902. // We may have changed the number of register in base regs, adjust the
  2903. // formula accordingly.
  2904. F.Canonicalize();
  2905. if (InsertFormula(LU, LUIdx, F))
  2906. // If that formula hadn't been seen before, recurse to find more like
  2907. // it.
  2908. GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1);
  2909. }
  2910. }
  2911. /// GenerateReassociations - Split out subexpressions from adds and the bases of
  2912. /// addrecs.
  2913. void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
  2914. Formula Base, unsigned Depth) {
  2915. assert(Base.isCanonical() && "Input must be in the canonical form");
  2916. // Arbitrarily cap recursion to protect compile time.
  2917. if (Depth >= 3)
  2918. return;
  2919. for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
  2920. GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
  2921. if (Base.Scale == 1)
  2922. GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
  2923. /* Idx */ -1, /* IsScaledReg */ true);
  2924. }
  2925. /// GenerateCombinations - Generate a formula consisting of all of the
  2926. /// loop-dominating registers added into a single register.
  2927. void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
  2928. Formula Base) {
  2929. // This method is only interesting on a plurality of registers.
  2930. if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
  2931. return;
  2932. // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
  2933. // processing the formula.
  2934. Base.Unscale();
  2935. Formula F = Base;
  2936. F.BaseRegs.clear();
  2937. SmallVector<const SCEV *, 4> Ops;
  2938. for (const SCEV *BaseReg : Base.BaseRegs) {
  2939. if (SE.properlyDominates(BaseReg, L->getHeader()) &&
  2940. !SE.hasComputableLoopEvolution(BaseReg, L))
  2941. Ops.push_back(BaseReg);
  2942. else
  2943. F.BaseRegs.push_back(BaseReg);
  2944. }
  2945. if (Ops.size() > 1) {
  2946. const SCEV *Sum = SE.getAddExpr(Ops);
  2947. // TODO: If Sum is zero, it probably means ScalarEvolution missed an
  2948. // opportunity to fold something. For now, just ignore such cases
  2949. // rather than proceed with zero in a register.
  2950. if (!Sum->isZero()) {
  2951. F.BaseRegs.push_back(Sum);
  2952. F.Canonicalize();
  2953. (void)InsertFormula(LU, LUIdx, F);
  2954. }
  2955. }
  2956. }
  2957. /// \brief Helper function for LSRInstance::GenerateSymbolicOffsets.
  2958. void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
  2959. const Formula &Base, size_t Idx,
  2960. bool IsScaledReg) {
  2961. const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
  2962. GlobalValue *GV = ExtractSymbol(G, SE);
  2963. if (G->isZero() || !GV)
  2964. return;
  2965. Formula F = Base;
  2966. F.BaseGV = GV;
  2967. if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
  2968. return;
  2969. if (IsScaledReg)
  2970. F.ScaledReg = G;
  2971. else
  2972. F.BaseRegs[Idx] = G;
  2973. (void)InsertFormula(LU, LUIdx, F);
  2974. }
  2975. /// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
  2976. void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
  2977. Formula Base) {
  2978. // We can't add a symbolic offset if the address already contains one.
  2979. if (Base.BaseGV) return;
  2980. for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
  2981. GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
  2982. if (Base.Scale == 1)
  2983. GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
  2984. /* IsScaledReg */ true);
  2985. }
  2986. /// \brief Helper function for LSRInstance::GenerateConstantOffsets.
  2987. void LSRInstance::GenerateConstantOffsetsImpl(
  2988. LSRUse &LU, unsigned LUIdx, const Formula &Base,
  2989. const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
  2990. const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
  2991. for (int64_t Offset : Worklist) {
  2992. Formula F = Base;
  2993. F.BaseOffset = (uint64_t)Base.BaseOffset - Offset;
  2994. if (isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind,
  2995. LU.AccessTy, F)) {
  2996. // Add the offset to the base register.
  2997. const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G);
  2998. // If it cancelled out, drop the base register, otherwise update it.
  2999. if (NewG->isZero()) {
  3000. if (IsScaledReg) {
  3001. F.Scale = 0;
  3002. F.ScaledReg = nullptr;
  3003. } else
  3004. F.DeleteBaseReg(F.BaseRegs[Idx]);
  3005. F.Canonicalize();
  3006. } else if (IsScaledReg)
  3007. F.ScaledReg = NewG;
  3008. else
  3009. F.BaseRegs[Idx] = NewG;
  3010. (void)InsertFormula(LU, LUIdx, F);
  3011. }
  3012. }
  3013. int64_t Imm = ExtractImmediate(G, SE);
  3014. if (G->isZero() || Imm == 0)
  3015. return;
  3016. Formula F = Base;
  3017. F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
  3018. if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
  3019. return;
  3020. if (IsScaledReg)
  3021. F.ScaledReg = G;
  3022. else
  3023. F.BaseRegs[Idx] = G;
  3024. (void)InsertFormula(LU, LUIdx, F);
  3025. }
  3026. /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
  3027. void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
  3028. Formula Base) {
  3029. // TODO: For now, just add the min and max offset, because it usually isn't
  3030. // worthwhile looking at everything inbetween.
  3031. SmallVector<int64_t, 2> Worklist;
  3032. Worklist.push_back(LU.MinOffset);
  3033. if (LU.MaxOffset != LU.MinOffset)
  3034. Worklist.push_back(LU.MaxOffset);
  3035. for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
  3036. GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
  3037. if (Base.Scale == 1)
  3038. GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
  3039. /* IsScaledReg */ true);
  3040. }
  3041. /// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
  3042. /// the comparison. For example, x == y -> x*c == y*c.
  3043. void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
  3044. Formula Base) {
  3045. if (LU.Kind != LSRUse::ICmpZero) return;
  3046. // Determine the integer type for the base formula.
  3047. Type *IntTy = Base.getType();
  3048. if (!IntTy) return;
  3049. if (SE.getTypeSizeInBits(IntTy) > 64) return;
  3050. // Don't do this if there is more than one offset.
  3051. if (LU.MinOffset != LU.MaxOffset) return;
  3052. assert(!Base.BaseGV && "ICmpZero use is not legal!");
  3053. // Check each interesting stride.
  3054. for (int64_t Factor : Factors) {
  3055. // Check that the multiplication doesn't overflow.
  3056. if (Base.BaseOffset == INT64_MIN && Factor == -1)
  3057. continue;
  3058. int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
  3059. if (NewBaseOffset / Factor != Base.BaseOffset)
  3060. continue;
  3061. // If the offset will be truncated at this use, check that it is in bounds.
  3062. if (!IntTy->isPointerTy() &&
  3063. !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
  3064. continue;
  3065. // Check that multiplying with the use offset doesn't overflow.
  3066. int64_t Offset = LU.MinOffset;
  3067. if (Offset == INT64_MIN && Factor == -1)
  3068. continue;
  3069. Offset = (uint64_t)Offset * Factor;
  3070. if (Offset / Factor != LU.MinOffset)
  3071. continue;
  3072. // If the offset will be truncated at this use, check that it is in bounds.
  3073. if (!IntTy->isPointerTy() &&
  3074. !ConstantInt::isValueValidForType(IntTy, Offset))
  3075. continue;
  3076. Formula F = Base;
  3077. F.BaseOffset = NewBaseOffset;
  3078. // Check that this scale is legal.
  3079. if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
  3080. continue;
  3081. // Compensate for the use having MinOffset built into it.
  3082. F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
  3083. const SCEV *FactorS = SE.getConstant(IntTy, Factor);
  3084. // Check that multiplying with each base register doesn't overflow.
  3085. for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
  3086. F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
  3087. if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
  3088. goto next;
  3089. }
  3090. // Check that multiplying with the scaled register doesn't overflow.
  3091. if (F.ScaledReg) {
  3092. F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
  3093. if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
  3094. continue;
  3095. }
  3096. // Check that multiplying with the unfolded offset doesn't overflow.
  3097. if (F.UnfoldedOffset != 0) {
  3098. if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
  3099. continue;
  3100. F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
  3101. if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
  3102. continue;
  3103. // If the offset will be truncated, check that it is in bounds.
  3104. if (!IntTy->isPointerTy() &&
  3105. !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
  3106. continue;
  3107. }
  3108. // If we make it here and it's legal, add it.
  3109. (void)InsertFormula(LU, LUIdx, F);
  3110. next:;
  3111. }
  3112. }
  3113. /// GenerateScales - Generate stride factor reuse formulae by making use of
  3114. /// scaled-offset address modes, for example.
  3115. void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
  3116. // Determine the integer type for the base formula.
  3117. Type *IntTy = Base.getType();
  3118. if (!IntTy) return;
  3119. // If this Formula already has a scaled register, we can't add another one.
  3120. // Try to unscale the formula to generate a better scale.
  3121. if (Base.Scale != 0 && !Base.Unscale())
  3122. return;
  3123. assert(Base.Scale == 0 && "Unscale did not did its job!");
  3124. // Check each interesting stride.
  3125. for (int64_t Factor : Factors) {
  3126. Base.Scale = Factor;
  3127. Base.HasBaseReg = Base.BaseRegs.size() > 1;
  3128. // Check whether this scale is going to be legal.
  3129. if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
  3130. Base)) {
  3131. // As a special-case, handle special out-of-loop Basic users specially.
  3132. // TODO: Reconsider this special case.
  3133. if (LU.Kind == LSRUse::Basic &&
  3134. isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
  3135. LU.AccessTy, Base) &&
  3136. LU.AllFixupsOutsideLoop)
  3137. LU.Kind = LSRUse::Special;
  3138. else
  3139. continue;
  3140. }
  3141. // For an ICmpZero, negating a solitary base register won't lead to
  3142. // new solutions.
  3143. if (LU.Kind == LSRUse::ICmpZero &&
  3144. !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
  3145. continue;
  3146. // For each addrec base reg, apply the scale, if possible.
  3147. for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
  3148. if (const SCEVAddRecExpr *AR =
  3149. dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
  3150. const SCEV *FactorS = SE.getConstant(IntTy, Factor);
  3151. if (FactorS->isZero())
  3152. continue;
  3153. // Divide out the factor, ignoring high bits, since we'll be
  3154. // scaling the value back up in the end.
  3155. if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
  3156. // TODO: This could be optimized to avoid all the copying.
  3157. Formula F = Base;
  3158. F.ScaledReg = Quotient;
  3159. F.DeleteBaseReg(F.BaseRegs[i]);
  3160. // The canonical representation of 1*reg is reg, which is already in
  3161. // Base. In that case, do not try to insert the formula, it will be
  3162. // rejected anyway.
  3163. if (F.Scale == 1 && F.BaseRegs.empty())
  3164. continue;
  3165. (void)InsertFormula(LU, LUIdx, F);
  3166. }
  3167. }
  3168. }
  3169. }
  3170. /// GenerateTruncates - Generate reuse formulae from different IV types.
  3171. void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
  3172. // Don't bother truncating symbolic values.
  3173. if (Base.BaseGV) return;
  3174. // Determine the integer type for the base formula.
  3175. Type *DstTy = Base.getType();
  3176. if (!DstTy) return;
  3177. DstTy = SE.getEffectiveSCEVType(DstTy);
  3178. for (Type *SrcTy : Types) {
  3179. if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
  3180. Formula F = Base;
  3181. if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy);
  3182. for (const SCEV *&BaseReg : F.BaseRegs)
  3183. BaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy);
  3184. // TODO: This assumes we've done basic processing on all uses and
  3185. // have an idea what the register usage is.
  3186. if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
  3187. continue;
  3188. (void)InsertFormula(LU, LUIdx, F);
  3189. }
  3190. }
  3191. }
  3192. namespace {
  3193. /// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
  3194. /// defer modifications so that the search phase doesn't have to worry about
  3195. /// the data structures moving underneath it.
  3196. struct WorkItem {
  3197. size_t LUIdx;
  3198. int64_t Imm;
  3199. const SCEV *OrigReg;
  3200. WorkItem(size_t LI, int64_t I, const SCEV *R)
  3201. : LUIdx(LI), Imm(I), OrigReg(R) {}
  3202. void print(raw_ostream &OS) const;
  3203. void dump() const;
  3204. };
  3205. }
  3206. void WorkItem::print(raw_ostream &OS) const {
  3207. OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
  3208. << " , add offset " << Imm;
  3209. }
  3210. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  3211. void WorkItem::dump() const {
  3212. print(errs()); errs() << '\n';
  3213. }
  3214. #endif
  3215. /// GenerateCrossUseConstantOffsets - Look for registers which are a constant
  3216. /// distance apart and try to form reuse opportunities between them.
  3217. void LSRInstance::GenerateCrossUseConstantOffsets() {
  3218. // Group the registers by their value without any added constant offset.
  3219. typedef std::map<int64_t, const SCEV *> ImmMapTy;
  3220. DenseMap<const SCEV *, ImmMapTy> Map;
  3221. DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
  3222. SmallVector<const SCEV *, 8> Sequence;
  3223. for (const SCEV *Use : RegUses) {
  3224. const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.
  3225. int64_t Imm = ExtractImmediate(Reg, SE);
  3226. auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));
  3227. if (Pair.second)
  3228. Sequence.push_back(Reg);
  3229. Pair.first->second.insert(std::make_pair(Imm, Use));
  3230. UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);
  3231. }
  3232. // Now examine each set of registers with the same base value. Build up
  3233. // a list of work to do and do the work in a separate step so that we're
  3234. // not adding formulae and register counts while we're searching.
  3235. SmallVector<WorkItem, 32> WorkItems;
  3236. SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
  3237. for (const SCEV *Reg : Sequence) {
  3238. const ImmMapTy &Imms = Map.find(Reg)->second;
  3239. // It's not worthwhile looking for reuse if there's only one offset.
  3240. if (Imms.size() == 1)
  3241. continue;
  3242. DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
  3243. for (const auto &Entry : Imms)
  3244. dbgs() << ' ' << Entry.first;
  3245. dbgs() << '\n');
  3246. // Examine each offset.
  3247. for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
  3248. J != JE; ++J) {
  3249. const SCEV *OrigReg = J->second;
  3250. int64_t JImm = J->first;
  3251. const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
  3252. if (!isa<SCEVConstant>(OrigReg) &&
  3253. UsedByIndicesMap[Reg].count() == 1) {
  3254. DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
  3255. continue;
  3256. }
  3257. // Conservatively examine offsets between this orig reg a few selected
  3258. // other orig regs.
  3259. ImmMapTy::const_iterator OtherImms[] = {
  3260. Imms.begin(), std::prev(Imms.end()),
  3261. Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) /
  3262. 2)
  3263. };
  3264. for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
  3265. ImmMapTy::const_iterator M = OtherImms[i];
  3266. if (M == J || M == JE) continue;
  3267. // Compute the difference between the two.
  3268. int64_t Imm = (uint64_t)JImm - M->first;
  3269. for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
  3270. LUIdx = UsedByIndices.find_next(LUIdx))
  3271. // Make a memo of this use, offset, and register tuple.
  3272. if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
  3273. WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
  3274. }
  3275. }
  3276. }
  3277. Map.clear();
  3278. Sequence.clear();
  3279. UsedByIndicesMap.clear();
  3280. UniqueItems.clear();
  3281. // Now iterate through the worklist and add new formulae.
  3282. for (const WorkItem &WI : WorkItems) {
  3283. size_t LUIdx = WI.LUIdx;
  3284. LSRUse &LU = Uses[LUIdx];
  3285. int64_t Imm = WI.Imm;
  3286. const SCEV *OrigReg = WI.OrigReg;
  3287. Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
  3288. const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
  3289. unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
  3290. // TODO: Use a more targeted data structure.
  3291. for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
  3292. Formula F = LU.Formulae[L];
  3293. // FIXME: The code for the scaled and unscaled registers looks
  3294. // very similar but slightly different. Investigate if they
  3295. // could be merged. That way, we would not have to unscale the
  3296. // Formula.
  3297. F.Unscale();
  3298. // Use the immediate in the scaled register.
  3299. if (F.ScaledReg == OrigReg) {
  3300. int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
  3301. // Don't create 50 + reg(-50).
  3302. if (F.referencesReg(SE.getSCEV(
  3303. ConstantInt::get(IntTy, -(uint64_t)Offset))))
  3304. continue;
  3305. Formula NewF = F;
  3306. NewF.BaseOffset = Offset;
  3307. if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
  3308. NewF))
  3309. continue;
  3310. NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
  3311. // If the new scale is a constant in a register, and adding the constant
  3312. // value to the immediate would produce a value closer to zero than the
  3313. // immediate itself, then the formula isn't worthwhile.
  3314. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
  3315. if (C->getValue()->isNegative() !=
  3316. (NewF.BaseOffset < 0) &&
  3317. (C->getValue()->getValue().abs() * APInt(BitWidth, F.Scale))
  3318. .ule(std::abs(NewF.BaseOffset)))
  3319. continue;
  3320. // OK, looks good.
  3321. NewF.Canonicalize();
  3322. (void)InsertFormula(LU, LUIdx, NewF);
  3323. } else {
  3324. // Use the immediate in a base register.
  3325. for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
  3326. const SCEV *BaseReg = F.BaseRegs[N];
  3327. if (BaseReg != OrigReg)
  3328. continue;
  3329. Formula NewF = F;
  3330. NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
  3331. if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
  3332. LU.Kind, LU.AccessTy, NewF)) {
  3333. if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
  3334. continue;
  3335. NewF = F;
  3336. NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
  3337. }
  3338. NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
  3339. // If the new formula has a constant in a register, and adding the
  3340. // constant value to the immediate would produce a value closer to
  3341. // zero than the immediate itself, then the formula isn't worthwhile.
  3342. for (const SCEV *NewReg : NewF.BaseRegs)
  3343. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
  3344. if ((C->getValue()->getValue() + NewF.BaseOffset).abs().slt(
  3345. std::abs(NewF.BaseOffset)) &&
  3346. (C->getValue()->getValue() +
  3347. NewF.BaseOffset).countTrailingZeros() >=
  3348. countTrailingZeros<uint64_t>(NewF.BaseOffset))
  3349. goto skip_formula;
  3350. // Ok, looks good.
  3351. NewF.Canonicalize();
  3352. (void)InsertFormula(LU, LUIdx, NewF);
  3353. break;
  3354. skip_formula:;
  3355. }
  3356. }
  3357. }
  3358. }
  3359. }
  3360. /// GenerateAllReuseFormulae - Generate formulae for each use.
  3361. void
  3362. LSRInstance::GenerateAllReuseFormulae() {
  3363. // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
  3364. // queries are more precise.
  3365. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3366. LSRUse &LU = Uses[LUIdx];
  3367. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3368. GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
  3369. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3370. GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
  3371. }
  3372. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3373. LSRUse &LU = Uses[LUIdx];
  3374. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3375. GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
  3376. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3377. GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
  3378. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3379. GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
  3380. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3381. GenerateScales(LU, LUIdx, LU.Formulae[i]);
  3382. }
  3383. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3384. LSRUse &LU = Uses[LUIdx];
  3385. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3386. GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
  3387. }
  3388. GenerateCrossUseConstantOffsets();
  3389. DEBUG(dbgs() << "\n"
  3390. "After generating reuse formulae:\n";
  3391. print_uses(dbgs()));
  3392. }
  3393. /// If there are multiple formulae with the same set of registers used
  3394. /// by other uses, pick the best one and delete the others.
  3395. void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
  3396. DenseSet<const SCEV *> VisitedRegs;
  3397. SmallPtrSet<const SCEV *, 16> Regs;
  3398. SmallPtrSet<const SCEV *, 16> LoserRegs;
  3399. #ifndef NDEBUG
  3400. bool ChangedFormulae = false;
  3401. #endif
  3402. // Collect the best formula for each unique set of shared registers. This
  3403. // is reset for each use.
  3404. typedef DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>
  3405. BestFormulaeTy;
  3406. BestFormulaeTy BestFormulae;
  3407. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3408. LSRUse &LU = Uses[LUIdx];
  3409. DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
  3410. bool Any = false;
  3411. for (size_t FIdx = 0, NumForms = LU.Formulae.size();
  3412. FIdx != NumForms; ++FIdx) {
  3413. Formula &F = LU.Formulae[FIdx];
  3414. // Some formulas are instant losers. For example, they may depend on
  3415. // nonexistent AddRecs from other loops. These need to be filtered
  3416. // immediately, otherwise heuristics could choose them over others leading
  3417. // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
  3418. // avoids the need to recompute this information across formulae using the
  3419. // same bad AddRec. Passing LoserRegs is also essential unless we remove
  3420. // the corresponding bad register from the Regs set.
  3421. Cost CostF;
  3422. Regs.clear();
  3423. CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, LU.Offsets, SE, DT, LU,
  3424. &LoserRegs);
  3425. if (CostF.isLoser()) {
  3426. // During initial formula generation, undesirable formulae are generated
  3427. // by uses within other loops that have some non-trivial address mode or
  3428. // use the postinc form of the IV. LSR needs to provide these formulae
  3429. // as the basis of rediscovering the desired formula that uses an AddRec
  3430. // corresponding to the existing phi. Once all formulae have been
  3431. // generated, these initial losers may be pruned.
  3432. DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
  3433. dbgs() << "\n");
  3434. }
  3435. else {
  3436. SmallVector<const SCEV *, 4> Key;
  3437. for (const SCEV *Reg : F.BaseRegs) {
  3438. if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
  3439. Key.push_back(Reg);
  3440. }
  3441. if (F.ScaledReg &&
  3442. RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
  3443. Key.push_back(F.ScaledReg);
  3444. // Unstable sort by host order ok, because this is only used for
  3445. // uniquifying.
  3446. std::sort(Key.begin(), Key.end());
  3447. std::pair<BestFormulaeTy::const_iterator, bool> P =
  3448. BestFormulae.insert(std::make_pair(Key, FIdx));
  3449. if (P.second)
  3450. continue;
  3451. Formula &Best = LU.Formulae[P.first->second];
  3452. Cost CostBest;
  3453. Regs.clear();
  3454. CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, LU.Offsets, SE,
  3455. DT, LU);
  3456. if (CostF < CostBest)
  3457. std::swap(F, Best);
  3458. DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
  3459. dbgs() << "\n"
  3460. " in favor of formula "; Best.print(dbgs());
  3461. dbgs() << '\n');
  3462. }
  3463. #ifndef NDEBUG
  3464. ChangedFormulae = true;
  3465. #endif
  3466. LU.DeleteFormula(F);
  3467. --FIdx;
  3468. --NumForms;
  3469. Any = true;
  3470. }
  3471. // Now that we've filtered out some formulae, recompute the Regs set.
  3472. if (Any)
  3473. LU.RecomputeRegs(LUIdx, RegUses);
  3474. // Reset this to prepare for the next use.
  3475. BestFormulae.clear();
  3476. }
  3477. DEBUG(if (ChangedFormulae) {
  3478. dbgs() << "\n"
  3479. "After filtering out undesirable candidates:\n";
  3480. print_uses(dbgs());
  3481. });
  3482. }
  3483. // This is a rough guess that seems to work fairly well.
  3484. static const size_t ComplexityLimit = UINT16_MAX;
  3485. /// EstimateSearchSpaceComplexity - Estimate the worst-case number of
  3486. /// solutions the solver might have to consider. It almost never considers
  3487. /// this many solutions because it prune the search space, but the pruning
  3488. /// isn't always sufficient.
  3489. size_t LSRInstance::EstimateSearchSpaceComplexity() const {
  3490. size_t Power = 1;
  3491. for (const LSRUse &LU : Uses) {
  3492. size_t FSize = LU.Formulae.size();
  3493. if (FSize >= ComplexityLimit) {
  3494. Power = ComplexityLimit;
  3495. break;
  3496. }
  3497. Power *= FSize;
  3498. if (Power >= ComplexityLimit)
  3499. break;
  3500. }
  3501. return Power;
  3502. }
  3503. /// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
  3504. /// of the registers of another formula, it won't help reduce register
  3505. /// pressure (though it may not necessarily hurt register pressure); remove
  3506. /// it to simplify the system.
  3507. void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
  3508. if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
  3509. DEBUG(dbgs() << "The search space is too complex.\n");
  3510. DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
  3511. "which use a superset of registers used by other "
  3512. "formulae.\n");
  3513. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3514. LSRUse &LU = Uses[LUIdx];
  3515. bool Any = false;
  3516. for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
  3517. Formula &F = LU.Formulae[i];
  3518. // Look for a formula with a constant or GV in a register. If the use
  3519. // also has a formula with that same value in an immediate field,
  3520. // delete the one that uses a register.
  3521. for (SmallVectorImpl<const SCEV *>::const_iterator
  3522. I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
  3523. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
  3524. Formula NewF = F;
  3525. NewF.BaseOffset += C->getValue()->getSExtValue();
  3526. NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
  3527. (I - F.BaseRegs.begin()));
  3528. if (LU.HasFormulaWithSameRegs(NewF)) {
  3529. DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
  3530. LU.DeleteFormula(F);
  3531. --i;
  3532. --e;
  3533. Any = true;
  3534. break;
  3535. }
  3536. } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
  3537. if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
  3538. if (!F.BaseGV) {
  3539. Formula NewF = F;
  3540. NewF.BaseGV = GV;
  3541. NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
  3542. (I - F.BaseRegs.begin()));
  3543. if (LU.HasFormulaWithSameRegs(NewF)) {
  3544. DEBUG(dbgs() << " Deleting "; F.print(dbgs());
  3545. dbgs() << '\n');
  3546. LU.DeleteFormula(F);
  3547. --i;
  3548. --e;
  3549. Any = true;
  3550. break;
  3551. }
  3552. }
  3553. }
  3554. }
  3555. }
  3556. if (Any)
  3557. LU.RecomputeRegs(LUIdx, RegUses);
  3558. }
  3559. DEBUG(dbgs() << "After pre-selection:\n";
  3560. print_uses(dbgs()));
  3561. }
  3562. }
  3563. /// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
  3564. /// for expressions like A, A+1, A+2, etc., allocate a single register for
  3565. /// them.
  3566. void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
  3567. if (EstimateSearchSpaceComplexity() < ComplexityLimit)
  3568. return;
  3569. DEBUG(dbgs() << "The search space is too complex.\n"
  3570. "Narrowing the search space by assuming that uses separated "
  3571. "by a constant offset will use the same registers.\n");
  3572. // This is especially useful for unrolled loops.
  3573. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3574. LSRUse &LU = Uses[LUIdx];
  3575. for (const Formula &F : LU.Formulae) {
  3576. if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
  3577. continue;
  3578. LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
  3579. if (!LUThatHas)
  3580. continue;
  3581. if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
  3582. LU.Kind, LU.AccessTy))
  3583. continue;
  3584. DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
  3585. LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
  3586. // Update the relocs to reference the new use.
  3587. for (LSRFixup &Fixup : Fixups) {
  3588. if (Fixup.LUIdx == LUIdx) {
  3589. Fixup.LUIdx = LUThatHas - &Uses.front();
  3590. Fixup.Offset += F.BaseOffset;
  3591. // Add the new offset to LUThatHas' offset list.
  3592. if (LUThatHas->Offsets.back() != Fixup.Offset) {
  3593. LUThatHas->Offsets.push_back(Fixup.Offset);
  3594. if (Fixup.Offset > LUThatHas->MaxOffset)
  3595. LUThatHas->MaxOffset = Fixup.Offset;
  3596. if (Fixup.Offset < LUThatHas->MinOffset)
  3597. LUThatHas->MinOffset = Fixup.Offset;
  3598. }
  3599. DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
  3600. }
  3601. if (Fixup.LUIdx == NumUses-1)
  3602. Fixup.LUIdx = LUIdx;
  3603. }
  3604. // Delete formulae from the new use which are no longer legal.
  3605. bool Any = false;
  3606. for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
  3607. Formula &F = LUThatHas->Formulae[i];
  3608. if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
  3609. LUThatHas->Kind, LUThatHas->AccessTy, F)) {
  3610. DEBUG(dbgs() << " Deleting "; F.print(dbgs());
  3611. dbgs() << '\n');
  3612. LUThatHas->DeleteFormula(F);
  3613. --i;
  3614. --e;
  3615. Any = true;
  3616. }
  3617. }
  3618. if (Any)
  3619. LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
  3620. // Delete the old use.
  3621. DeleteUse(LU, LUIdx);
  3622. --LUIdx;
  3623. --NumUses;
  3624. break;
  3625. }
  3626. }
  3627. DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
  3628. }
  3629. /// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call
  3630. /// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
  3631. /// we've done more filtering, as it may be able to find more formulae to
  3632. /// eliminate.
  3633. void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
  3634. if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
  3635. DEBUG(dbgs() << "The search space is too complex.\n");
  3636. DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
  3637. "undesirable dedicated registers.\n");
  3638. FilterOutUndesirableDedicatedRegisters();
  3639. DEBUG(dbgs() << "After pre-selection:\n";
  3640. print_uses(dbgs()));
  3641. }
  3642. }
  3643. /// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
  3644. /// to be profitable, and then in any use which has any reference to that
  3645. /// register, delete all formulae which do not reference that register.
  3646. void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
  3647. // With all other options exhausted, loop until the system is simple
  3648. // enough to handle.
  3649. SmallPtrSet<const SCEV *, 4> Taken;
  3650. while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
  3651. // Ok, we have too many of formulae on our hands to conveniently handle.
  3652. // Use a rough heuristic to thin out the list.
  3653. DEBUG(dbgs() << "The search space is too complex.\n");
  3654. // Pick the register which is used by the most LSRUses, which is likely
  3655. // to be a good reuse register candidate.
  3656. const SCEV *Best = nullptr;
  3657. unsigned BestNum = 0;
  3658. for (const SCEV *Reg : RegUses) {
  3659. if (Taken.count(Reg))
  3660. continue;
  3661. if (!Best)
  3662. Best = Reg;
  3663. else {
  3664. unsigned Count = RegUses.getUsedByIndices(Reg).count();
  3665. if (Count > BestNum) {
  3666. Best = Reg;
  3667. BestNum = Count;
  3668. }
  3669. }
  3670. }
  3671. DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
  3672. << " will yield profitable reuse.\n");
  3673. Taken.insert(Best);
  3674. // In any use with formulae which references this register, delete formulae
  3675. // which don't reference it.
  3676. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3677. LSRUse &LU = Uses[LUIdx];
  3678. if (!LU.Regs.count(Best)) continue;
  3679. bool Any = false;
  3680. for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
  3681. Formula &F = LU.Formulae[i];
  3682. if (!F.referencesReg(Best)) {
  3683. DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
  3684. LU.DeleteFormula(F);
  3685. --e;
  3686. --i;
  3687. Any = true;
  3688. assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
  3689. continue;
  3690. }
  3691. }
  3692. if (Any)
  3693. LU.RecomputeRegs(LUIdx, RegUses);
  3694. }
  3695. DEBUG(dbgs() << "After pre-selection:\n";
  3696. print_uses(dbgs()));
  3697. }
  3698. }
  3699. /// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
  3700. /// formulae to choose from, use some rough heuristics to prune down the number
  3701. /// of formulae. This keeps the main solver from taking an extraordinary amount
  3702. /// of time in some worst-case scenarios.
  3703. void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
  3704. NarrowSearchSpaceByDetectingSupersets();
  3705. NarrowSearchSpaceByCollapsingUnrolledCode();
  3706. NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
  3707. NarrowSearchSpaceByPickingWinnerRegs();
  3708. }
  3709. /// SolveRecurse - This is the recursive solver.
  3710. void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
  3711. Cost &SolutionCost,
  3712. SmallVectorImpl<const Formula *> &Workspace,
  3713. const Cost &CurCost,
  3714. const SmallPtrSet<const SCEV *, 16> &CurRegs,
  3715. DenseSet<const SCEV *> &VisitedRegs) const {
  3716. // Some ideas:
  3717. // - prune more:
  3718. // - use more aggressive filtering
  3719. // - sort the formula so that the most profitable solutions are found first
  3720. // - sort the uses too
  3721. // - search faster:
  3722. // - don't compute a cost, and then compare. compare while computing a cost
  3723. // and bail early.
  3724. // - track register sets with SmallBitVector
  3725. const LSRUse &LU = Uses[Workspace.size()];
  3726. // If this use references any register that's already a part of the
  3727. // in-progress solution, consider it a requirement that a formula must
  3728. // reference that register in order to be considered. This prunes out
  3729. // unprofitable searching.
  3730. SmallSetVector<const SCEV *, 4> ReqRegs;
  3731. for (const SCEV *S : CurRegs)
  3732. if (LU.Regs.count(S))
  3733. ReqRegs.insert(S);
  3734. SmallPtrSet<const SCEV *, 16> NewRegs;
  3735. Cost NewCost;
  3736. for (const Formula &F : LU.Formulae) {
  3737. // Ignore formulae which may not be ideal in terms of register reuse of
  3738. // ReqRegs. The formula should use all required registers before
  3739. // introducing new ones.
  3740. int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
  3741. for (const SCEV *Reg : ReqRegs) {
  3742. if ((F.ScaledReg && F.ScaledReg == Reg) ||
  3743. std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) !=
  3744. F.BaseRegs.end()) {
  3745. --NumReqRegsToFind;
  3746. if (NumReqRegsToFind == 0)
  3747. break;
  3748. }
  3749. }
  3750. if (NumReqRegsToFind != 0) {
  3751. // If none of the formulae satisfied the required registers, then we could
  3752. // clear ReqRegs and try again. Currently, we simply give up in this case.
  3753. continue;
  3754. }
  3755. // Evaluate the cost of the current formula. If it's already worse than
  3756. // the current best, prune the search at that point.
  3757. NewCost = CurCost;
  3758. NewRegs = CurRegs;
  3759. NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT,
  3760. LU);
  3761. if (NewCost < SolutionCost) {
  3762. Workspace.push_back(&F);
  3763. if (Workspace.size() != Uses.size()) {
  3764. SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
  3765. NewRegs, VisitedRegs);
  3766. if (F.getNumRegs() == 1 && Workspace.size() == 1)
  3767. VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
  3768. } else {
  3769. DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
  3770. dbgs() << ".\n Regs:";
  3771. for (const SCEV *S : NewRegs)
  3772. dbgs() << ' ' << *S;
  3773. dbgs() << '\n');
  3774. SolutionCost = NewCost;
  3775. Solution = Workspace;
  3776. }
  3777. Workspace.pop_back();
  3778. }
  3779. }
  3780. }
  3781. /// Solve - Choose one formula from each use. Return the results in the given
  3782. /// Solution vector.
  3783. void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
  3784. SmallVector<const Formula *, 8> Workspace;
  3785. Cost SolutionCost;
  3786. SolutionCost.Lose();
  3787. Cost CurCost;
  3788. SmallPtrSet<const SCEV *, 16> CurRegs;
  3789. DenseSet<const SCEV *> VisitedRegs;
  3790. Workspace.reserve(Uses.size());
  3791. // SolveRecurse does all the work.
  3792. SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
  3793. CurRegs, VisitedRegs);
  3794. if (Solution.empty()) {
  3795. DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
  3796. return;
  3797. }
  3798. // Ok, we've now made all our decisions.
  3799. DEBUG(dbgs() << "\n"
  3800. "The chosen solution requires "; SolutionCost.print(dbgs());
  3801. dbgs() << ":\n";
  3802. for (size_t i = 0, e = Uses.size(); i != e; ++i) {
  3803. dbgs() << " ";
  3804. Uses[i].print(dbgs());
  3805. dbgs() << "\n"
  3806. " ";
  3807. Solution[i]->print(dbgs());
  3808. dbgs() << '\n';
  3809. });
  3810. assert(Solution.size() == Uses.size() && "Malformed solution!");
  3811. }
  3812. /// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
  3813. /// the dominator tree far as we can go while still being dominated by the
  3814. /// input positions. This helps canonicalize the insert position, which
  3815. /// encourages sharing.
  3816. BasicBlock::iterator
  3817. LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
  3818. const SmallVectorImpl<Instruction *> &Inputs)
  3819. const {
  3820. for (;;) {
  3821. const Loop *IPLoop = LI.getLoopFor(IP->getParent());
  3822. unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
  3823. BasicBlock *IDom;
  3824. for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
  3825. if (!Rung) return IP;
  3826. Rung = Rung->getIDom();
  3827. if (!Rung) return IP;
  3828. IDom = Rung->getBlock();
  3829. // Don't climb into a loop though.
  3830. const Loop *IDomLoop = LI.getLoopFor(IDom);
  3831. unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
  3832. if (IDomDepth <= IPLoopDepth &&
  3833. (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
  3834. break;
  3835. }
  3836. bool AllDominate = true;
  3837. Instruction *BetterPos = nullptr;
  3838. Instruction *Tentative = IDom->getTerminator();
  3839. for (Instruction *Inst : Inputs) {
  3840. if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
  3841. AllDominate = false;
  3842. break;
  3843. }
  3844. // Attempt to find an insert position in the middle of the block,
  3845. // instead of at the end, so that it can be used for other expansions.
  3846. if (IDom == Inst->getParent() &&
  3847. (!BetterPos || !DT.dominates(Inst, BetterPos)))
  3848. BetterPos = std::next(BasicBlock::iterator(Inst));
  3849. }
  3850. if (!AllDominate)
  3851. break;
  3852. if (BetterPos)
  3853. IP = BetterPos;
  3854. else
  3855. IP = Tentative;
  3856. }
  3857. return IP;
  3858. }
  3859. /// AdjustInsertPositionForExpand - Determine an input position which will be
  3860. /// dominated by the operands and which will dominate the result.
  3861. BasicBlock::iterator
  3862. LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
  3863. const LSRFixup &LF,
  3864. const LSRUse &LU,
  3865. SCEVExpander &Rewriter) const {
  3866. // Collect some instructions which must be dominated by the
  3867. // expanding replacement. These must be dominated by any operands that
  3868. // will be required in the expansion.
  3869. SmallVector<Instruction *, 4> Inputs;
  3870. if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
  3871. Inputs.push_back(I);
  3872. if (LU.Kind == LSRUse::ICmpZero)
  3873. if (Instruction *I =
  3874. dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
  3875. Inputs.push_back(I);
  3876. if (LF.PostIncLoops.count(L)) {
  3877. if (LF.isUseFullyOutsideLoop(L))
  3878. Inputs.push_back(L->getLoopLatch()->getTerminator());
  3879. else
  3880. Inputs.push_back(IVIncInsertPos);
  3881. }
  3882. // The expansion must also be dominated by the increment positions of any
  3883. // loops it for which it is using post-inc mode.
  3884. for (const Loop *PIL : LF.PostIncLoops) {
  3885. if (PIL == L) continue;
  3886. // Be dominated by the loop exit.
  3887. SmallVector<BasicBlock *, 4> ExitingBlocks;
  3888. PIL->getExitingBlocks(ExitingBlocks);
  3889. if (!ExitingBlocks.empty()) {
  3890. BasicBlock *BB = ExitingBlocks[0];
  3891. for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
  3892. BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
  3893. Inputs.push_back(BB->getTerminator());
  3894. }
  3895. }
  3896. assert(!isa<PHINode>(LowestIP) && !isa<LandingPadInst>(LowestIP)
  3897. && !isa<DbgInfoIntrinsic>(LowestIP) &&
  3898. "Insertion point must be a normal instruction");
  3899. // Then, climb up the immediate dominator tree as far as we can go while
  3900. // still being dominated by the input positions.
  3901. BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
  3902. // Don't insert instructions before PHI nodes.
  3903. while (isa<PHINode>(IP)) ++IP;
  3904. // Ignore landingpad instructions.
  3905. while (isa<LandingPadInst>(IP)) ++IP;
  3906. // Ignore debug intrinsics.
  3907. while (isa<DbgInfoIntrinsic>(IP)) ++IP;
  3908. // Set IP below instructions recently inserted by SCEVExpander. This keeps the
  3909. // IP consistent across expansions and allows the previously inserted
  3910. // instructions to be reused by subsequent expansion.
  3911. while (Rewriter.isInsertedInstruction(IP) && IP != LowestIP) ++IP;
  3912. return IP;
  3913. }
  3914. /// Expand - Emit instructions for the leading candidate expression for this
  3915. /// LSRUse (this is called "expanding").
  3916. Value *LSRInstance::Expand(const LSRFixup &LF,
  3917. const Formula &F,
  3918. BasicBlock::iterator IP,
  3919. SCEVExpander &Rewriter,
  3920. SmallVectorImpl<WeakVH> &DeadInsts) const {
  3921. const LSRUse &LU = Uses[LF.LUIdx];
  3922. if (LU.RigidFormula)
  3923. return LF.OperandValToReplace;
  3924. // Determine an input position which will be dominated by the operands and
  3925. // which will dominate the result.
  3926. IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
  3927. // Inform the Rewriter if we have a post-increment use, so that it can
  3928. // perform an advantageous expansion.
  3929. Rewriter.setPostInc(LF.PostIncLoops);
  3930. // This is the type that the user actually needs.
  3931. Type *OpTy = LF.OperandValToReplace->getType();
  3932. // This will be the type that we'll initially expand to.
  3933. Type *Ty = F.getType();
  3934. if (!Ty)
  3935. // No type known; just expand directly to the ultimate type.
  3936. Ty = OpTy;
  3937. else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
  3938. // Expand directly to the ultimate type if it's the right size.
  3939. Ty = OpTy;
  3940. // This is the type to do integer arithmetic in.
  3941. Type *IntTy = SE.getEffectiveSCEVType(Ty);
  3942. // Build up a list of operands to add together to form the full base.
  3943. SmallVector<const SCEV *, 8> Ops;
  3944. // Expand the BaseRegs portion.
  3945. for (const SCEV *Reg : F.BaseRegs) {
  3946. assert(!Reg->isZero() && "Zero allocated in a base register!");
  3947. // If we're expanding for a post-inc user, make the post-inc adjustment.
  3948. PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
  3949. Reg = TransformForPostIncUse(Denormalize, Reg,
  3950. LF.UserInst, LF.OperandValToReplace,
  3951. Loops, SE, DT);
  3952. Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, IP)));
  3953. }
  3954. // Expand the ScaledReg portion.
  3955. Value *ICmpScaledV = nullptr;
  3956. if (F.Scale != 0) {
  3957. const SCEV *ScaledS = F.ScaledReg;
  3958. // If we're expanding for a post-inc user, make the post-inc adjustment.
  3959. PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
  3960. ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
  3961. LF.UserInst, LF.OperandValToReplace,
  3962. Loops, SE, DT);
  3963. if (LU.Kind == LSRUse::ICmpZero) {
  3964. // Expand ScaleReg as if it was part of the base regs.
  3965. if (F.Scale == 1)
  3966. Ops.push_back(
  3967. SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP)));
  3968. else {
  3969. // An interesting way of "folding" with an icmp is to use a negated
  3970. // scale, which we'll implement by inserting it into the other operand
  3971. // of the icmp.
  3972. assert(F.Scale == -1 &&
  3973. "The only scale supported by ICmpZero uses is -1!");
  3974. ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, IP);
  3975. }
  3976. } else {
  3977. // Otherwise just expand the scaled register and an explicit scale,
  3978. // which is expected to be matched as part of the address.
  3979. // Flush the operand list to suppress SCEVExpander hoisting address modes.
  3980. // Unless the addressing mode will not be folded.
  3981. if (!Ops.empty() && LU.Kind == LSRUse::Address &&
  3982. isAMCompletelyFolded(TTI, LU, F)) {
  3983. Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
  3984. Ops.clear();
  3985. Ops.push_back(SE.getUnknown(FullV));
  3986. }
  3987. ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP));
  3988. if (F.Scale != 1)
  3989. ScaledS =
  3990. SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
  3991. Ops.push_back(ScaledS);
  3992. }
  3993. }
  3994. // Expand the GV portion.
  3995. if (F.BaseGV) {
  3996. // Flush the operand list to suppress SCEVExpander hoisting.
  3997. if (!Ops.empty()) {
  3998. Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
  3999. Ops.clear();
  4000. Ops.push_back(SE.getUnknown(FullV));
  4001. }
  4002. Ops.push_back(SE.getUnknown(F.BaseGV));
  4003. }
  4004. // Flush the operand list to suppress SCEVExpander hoisting of both folded and
  4005. // unfolded offsets. LSR assumes they both live next to their uses.
  4006. if (!Ops.empty()) {
  4007. Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
  4008. Ops.clear();
  4009. Ops.push_back(SE.getUnknown(FullV));
  4010. }
  4011. // Expand the immediate portion.
  4012. int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
  4013. if (Offset != 0) {
  4014. if (LU.Kind == LSRUse::ICmpZero) {
  4015. // The other interesting way of "folding" with an ICmpZero is to use a
  4016. // negated immediate.
  4017. if (!ICmpScaledV)
  4018. ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
  4019. else {
  4020. Ops.push_back(SE.getUnknown(ICmpScaledV));
  4021. ICmpScaledV = ConstantInt::get(IntTy, Offset);
  4022. }
  4023. } else {
  4024. // Just add the immediate values. These again are expected to be matched
  4025. // as part of the address.
  4026. Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
  4027. }
  4028. }
  4029. // Expand the unfolded offset portion.
  4030. int64_t UnfoldedOffset = F.UnfoldedOffset;
  4031. if (UnfoldedOffset != 0) {
  4032. // Just add the immediate values.
  4033. Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
  4034. UnfoldedOffset)));
  4035. }
  4036. // Emit instructions summing all the operands.
  4037. const SCEV *FullS = Ops.empty() ?
  4038. SE.getConstant(IntTy, 0) :
  4039. SE.getAddExpr(Ops);
  4040. Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
  4041. // We're done expanding now, so reset the rewriter.
  4042. Rewriter.clearPostInc();
  4043. // An ICmpZero Formula represents an ICmp which we're handling as a
  4044. // comparison against zero. Now that we've expanded an expression for that
  4045. // form, update the ICmp's other operand.
  4046. if (LU.Kind == LSRUse::ICmpZero) {
  4047. ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
  4048. DeadInsts.emplace_back(CI->getOperand(1));
  4049. assert(!F.BaseGV && "ICmp does not support folding a global value and "
  4050. "a scale at the same time!");
  4051. if (F.Scale == -1) {
  4052. if (ICmpScaledV->getType() != OpTy) {
  4053. Instruction *Cast =
  4054. CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
  4055. OpTy, false),
  4056. ICmpScaledV, OpTy, "tmp", CI);
  4057. ICmpScaledV = Cast;
  4058. }
  4059. CI->setOperand(1, ICmpScaledV);
  4060. } else {
  4061. // A scale of 1 means that the scale has been expanded as part of the
  4062. // base regs.
  4063. assert((F.Scale == 0 || F.Scale == 1) &&
  4064. "ICmp does not support folding a global value and "
  4065. "a scale at the same time!");
  4066. Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
  4067. -(uint64_t)Offset);
  4068. if (C->getType() != OpTy)
  4069. C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
  4070. OpTy, false),
  4071. C, OpTy);
  4072. CI->setOperand(1, C);
  4073. }
  4074. }
  4075. return FullV;
  4076. }
  4077. /// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
  4078. /// of their operands effectively happens in their predecessor blocks, so the
  4079. /// expression may need to be expanded in multiple places.
  4080. void LSRInstance::RewriteForPHI(PHINode *PN,
  4081. const LSRFixup &LF,
  4082. const Formula &F,
  4083. SCEVExpander &Rewriter,
  4084. SmallVectorImpl<WeakVH> &DeadInsts,
  4085. Pass *P) const {
  4086. DenseMap<BasicBlock *, Value *> Inserted;
  4087. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  4088. if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
  4089. BasicBlock *BB = PN->getIncomingBlock(i);
  4090. // If this is a critical edge, split the edge so that we do not insert
  4091. // the code on all predecessor/successor paths. We do this unless this
  4092. // is the canonical backedge for this loop, which complicates post-inc
  4093. // users.
  4094. if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
  4095. !isa<IndirectBrInst>(BB->getTerminator())) {
  4096. BasicBlock *Parent = PN->getParent();
  4097. Loop *PNLoop = LI.getLoopFor(Parent);
  4098. if (!PNLoop || Parent != PNLoop->getHeader()) {
  4099. // Split the critical edge.
  4100. BasicBlock *NewBB = nullptr;
  4101. if (!Parent->isLandingPad()) {
  4102. NewBB = SplitCriticalEdge(BB, Parent,
  4103. CriticalEdgeSplittingOptions(&DT, &LI)
  4104. .setMergeIdenticalEdges()
  4105. .setDontDeleteUselessPHIs());
  4106. } else {
  4107. SmallVector<BasicBlock*, 2> NewBBs;
  4108. SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs,
  4109. /*AliasAnalysis*/ nullptr, &DT, &LI);
  4110. NewBB = NewBBs[0];
  4111. }
  4112. // If NewBB==NULL, then SplitCriticalEdge refused to split because all
  4113. // phi predecessors are identical. The simple thing to do is skip
  4114. // splitting in this case rather than complicate the API.
  4115. if (NewBB) {
  4116. // If PN is outside of the loop and BB is in the loop, we want to
  4117. // move the block to be immediately before the PHI block, not
  4118. // immediately after BB.
  4119. if (L->contains(BB) && !L->contains(PN))
  4120. NewBB->moveBefore(PN->getParent());
  4121. // Splitting the edge can reduce the number of PHI entries we have.
  4122. e = PN->getNumIncomingValues();
  4123. BB = NewBB;
  4124. i = PN->getBasicBlockIndex(BB);
  4125. }
  4126. }
  4127. }
  4128. std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
  4129. Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
  4130. if (!Pair.second)
  4131. PN->setIncomingValue(i, Pair.first->second);
  4132. else {
  4133. Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
  4134. // If this is reuse-by-noop-cast, insert the noop cast.
  4135. Type *OpTy = LF.OperandValToReplace->getType();
  4136. if (FullV->getType() != OpTy)
  4137. FullV =
  4138. CastInst::Create(CastInst::getCastOpcode(FullV, false,
  4139. OpTy, false),
  4140. FullV, LF.OperandValToReplace->getType(),
  4141. "tmp", BB->getTerminator());
  4142. PN->setIncomingValue(i, FullV);
  4143. Pair.first->second = FullV;
  4144. }
  4145. }
  4146. }
  4147. /// Rewrite - Emit instructions for the leading candidate expression for this
  4148. /// LSRUse (this is called "expanding"), and update the UserInst to reference
  4149. /// the newly expanded value.
  4150. void LSRInstance::Rewrite(const LSRFixup &LF,
  4151. const Formula &F,
  4152. SCEVExpander &Rewriter,
  4153. SmallVectorImpl<WeakVH> &DeadInsts,
  4154. Pass *P) const {
  4155. // First, find an insertion point that dominates UserInst. For PHI nodes,
  4156. // find the nearest block which dominates all the relevant uses.
  4157. if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
  4158. RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
  4159. } else {
  4160. Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
  4161. // If this is reuse-by-noop-cast, insert the noop cast.
  4162. Type *OpTy = LF.OperandValToReplace->getType();
  4163. if (FullV->getType() != OpTy) {
  4164. Instruction *Cast =
  4165. CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
  4166. FullV, OpTy, "tmp", LF.UserInst);
  4167. FullV = Cast;
  4168. }
  4169. // Update the user. ICmpZero is handled specially here (for now) because
  4170. // Expand may have updated one of the operands of the icmp already, and
  4171. // its new value may happen to be equal to LF.OperandValToReplace, in
  4172. // which case doing replaceUsesOfWith leads to replacing both operands
  4173. // with the same value. TODO: Reorganize this.
  4174. if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
  4175. LF.UserInst->setOperand(0, FullV);
  4176. else
  4177. LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
  4178. }
  4179. DeadInsts.emplace_back(LF.OperandValToReplace);
  4180. }
  4181. /// ImplementSolution - Rewrite all the fixup locations with new values,
  4182. /// following the chosen solution.
  4183. void
  4184. LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
  4185. Pass *P) {
  4186. // Keep track of instructions we may have made dead, so that
  4187. // we can remove them after we are done working.
  4188. SmallVector<WeakVH, 16> DeadInsts;
  4189. SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(),
  4190. "lsr");
  4191. #ifndef NDEBUG
  4192. Rewriter.setDebugType(DEBUG_TYPE);
  4193. #endif
  4194. Rewriter.disableCanonicalMode();
  4195. Rewriter.enableLSRMode();
  4196. Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
  4197. // Mark phi nodes that terminate chains so the expander tries to reuse them.
  4198. for (const IVChain &Chain : IVChainVec) {
  4199. if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
  4200. Rewriter.setChainedPhi(PN);
  4201. }
  4202. // Expand the new value definitions and update the users.
  4203. for (const LSRFixup &Fixup : Fixups) {
  4204. Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
  4205. Changed = true;
  4206. }
  4207. for (const IVChain &Chain : IVChainVec) {
  4208. GenerateIVChain(Chain, Rewriter, DeadInsts);
  4209. Changed = true;
  4210. }
  4211. // Clean up after ourselves. This must be done before deleting any
  4212. // instructions.
  4213. Rewriter.clear();
  4214. Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
  4215. }
  4216. LSRInstance::LSRInstance(Loop *L, Pass *P)
  4217. : IU(P->getAnalysis<IVUsers>()), SE(P->getAnalysis<ScalarEvolution>()),
  4218. DT(P->getAnalysis<DominatorTreeWrapperPass>().getDomTree()),
  4219. LI(P->getAnalysis<LoopInfoWrapperPass>().getLoopInfo()),
  4220. TTI(P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  4221. *L->getHeader()->getParent())),
  4222. L(L), Changed(false), IVIncInsertPos(nullptr) {
  4223. // If LoopSimplify form is not available, stay out of trouble.
  4224. if (!L->isLoopSimplifyForm())
  4225. return;
  4226. // If there's no interesting work to be done, bail early.
  4227. if (IU.empty()) return;
  4228. // If there's too much analysis to be done, bail early. We won't be able to
  4229. // model the problem anyway.
  4230. unsigned NumUsers = 0;
  4231. for (const IVStrideUse &U : IU) {
  4232. if (++NumUsers > MaxIVUsers) {
  4233. (void)U;
  4234. DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U << "\n");
  4235. return;
  4236. }
  4237. }
  4238. #ifndef NDEBUG
  4239. // All dominating loops must have preheaders, or SCEVExpander may not be able
  4240. // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
  4241. //
  4242. // IVUsers analysis should only create users that are dominated by simple loop
  4243. // headers. Since this loop should dominate all of its users, its user list
  4244. // should be empty if this loop itself is not within a simple loop nest.
  4245. for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
  4246. Rung; Rung = Rung->getIDom()) {
  4247. BasicBlock *BB = Rung->getBlock();
  4248. const Loop *DomLoop = LI.getLoopFor(BB);
  4249. if (DomLoop && DomLoop->getHeader() == BB) {
  4250. assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
  4251. }
  4252. }
  4253. #endif // DEBUG
  4254. DEBUG(dbgs() << "\nLSR on loop ";
  4255. L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
  4256. dbgs() << ":\n");
  4257. // First, perform some low-level loop optimizations.
  4258. OptimizeShadowIV();
  4259. OptimizeLoopTermCond();
  4260. // If loop preparation eliminates all interesting IV users, bail.
  4261. if (IU.empty()) return;
  4262. // Skip nested loops until we can model them better with formulae.
  4263. if (!L->empty()) {
  4264. DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
  4265. return;
  4266. }
  4267. // Start collecting data and preparing for the solver.
  4268. CollectChains();
  4269. CollectInterestingTypesAndFactors();
  4270. CollectFixupsAndInitialFormulae();
  4271. CollectLoopInvariantFixupsAndFormulae();
  4272. assert(!Uses.empty() && "IVUsers reported at least one use");
  4273. DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
  4274. print_uses(dbgs()));
  4275. // Now use the reuse data to generate a bunch of interesting ways
  4276. // to formulate the values needed for the uses.
  4277. GenerateAllReuseFormulae();
  4278. FilterOutUndesirableDedicatedRegisters();
  4279. NarrowSearchSpaceUsingHeuristics();
  4280. SmallVector<const Formula *, 8> Solution;
  4281. Solve(Solution);
  4282. // Release memory that is no longer needed.
  4283. Factors.clear();
  4284. Types.clear();
  4285. RegUses.clear();
  4286. if (Solution.empty())
  4287. return;
  4288. #ifndef NDEBUG
  4289. // Formulae should be legal.
  4290. for (const LSRUse &LU : Uses) {
  4291. for (const Formula &F : LU.Formulae)
  4292. assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
  4293. F) && "Illegal formula generated!");
  4294. };
  4295. #endif
  4296. // Now that we've decided what we want, make it so.
  4297. ImplementSolution(Solution, P);
  4298. }
  4299. void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
  4300. if (Factors.empty() && Types.empty()) return;
  4301. OS << "LSR has identified the following interesting factors and types: ";
  4302. bool First = true;
  4303. for (int64_t Factor : Factors) {
  4304. if (!First) OS << ", ";
  4305. First = false;
  4306. OS << '*' << Factor;
  4307. }
  4308. for (Type *Ty : Types) {
  4309. if (!First) OS << ", ";
  4310. First = false;
  4311. OS << '(' << *Ty << ')';
  4312. }
  4313. OS << '\n';
  4314. }
  4315. void LSRInstance::print_fixups(raw_ostream &OS) const {
  4316. OS << "LSR is examining the following fixup sites:\n";
  4317. for (const LSRFixup &LF : Fixups) {
  4318. dbgs() << " ";
  4319. LF.print(OS);
  4320. OS << '\n';
  4321. }
  4322. }
  4323. void LSRInstance::print_uses(raw_ostream &OS) const {
  4324. OS << "LSR is examining the following uses:\n";
  4325. for (const LSRUse &LU : Uses) {
  4326. dbgs() << " ";
  4327. LU.print(OS);
  4328. OS << '\n';
  4329. for (const Formula &F : LU.Formulae) {
  4330. OS << " ";
  4331. F.print(OS);
  4332. OS << '\n';
  4333. }
  4334. }
  4335. }
  4336. void LSRInstance::print(raw_ostream &OS) const {
  4337. print_factors_and_types(OS);
  4338. print_fixups(OS);
  4339. print_uses(OS);
  4340. }
  4341. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  4342. void LSRInstance::dump() const {
  4343. print(errs()); errs() << '\n';
  4344. }
  4345. #endif
  4346. namespace {
  4347. class LoopStrengthReduce : public LoopPass {
  4348. public:
  4349. static char ID; // Pass ID, replacement for typeid
  4350. LoopStrengthReduce();
  4351. private:
  4352. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  4353. void getAnalysisUsage(AnalysisUsage &AU) const override;
  4354. };
  4355. }
  4356. char LoopStrengthReduce::ID = 0;
  4357. INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
  4358. "Loop Strength Reduction", false, false)
  4359. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  4360. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  4361. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  4362. INITIALIZE_PASS_DEPENDENCY(IVUsers)
  4363. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  4364. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  4365. INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
  4366. "Loop Strength Reduction", false, false)
  4367. Pass *llvm::createLoopStrengthReducePass() {
  4368. return new LoopStrengthReduce();
  4369. }
  4370. LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
  4371. initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
  4372. }
  4373. void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
  4374. // We split critical edges, so we change the CFG. However, we do update
  4375. // many analyses if they are around.
  4376. AU.addPreservedID(LoopSimplifyID);
  4377. AU.addRequired<LoopInfoWrapperPass>();
  4378. AU.addPreserved<LoopInfoWrapperPass>();
  4379. AU.addRequiredID(LoopSimplifyID);
  4380. AU.addRequired<DominatorTreeWrapperPass>();
  4381. AU.addPreserved<DominatorTreeWrapperPass>();
  4382. AU.addRequired<ScalarEvolution>();
  4383. AU.addPreserved<ScalarEvolution>();
  4384. // Requiring LoopSimplify a second time here prevents IVUsers from running
  4385. // twice, since LoopSimplify was invalidated by running ScalarEvolution.
  4386. AU.addRequiredID(LoopSimplifyID);
  4387. AU.addRequired<IVUsers>();
  4388. AU.addPreserved<IVUsers>();
  4389. AU.addRequired<TargetTransformInfoWrapperPass>();
  4390. }
  4391. bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
  4392. if (skipOptnoneFunction(L))
  4393. return false;
  4394. bool Changed = false;
  4395. // Run the main LSR transformation.
  4396. #if 0 // HLSL Change - move LSRInstance to the heap to avoid >16K stack allocation here.
  4397. Changed |= LSRInstance(L, this).getChanged();
  4398. #else
  4399. {
  4400. std::unique_ptr<LSRInstance> instance(new LSRInstance(L, this));
  4401. Changed |= instance->getChanged();
  4402. }
  4403. #endif
  4404. // Remove any extra phis created by processing inner loops.
  4405. Changed |= DeleteDeadPHIs(L->getHeader());
  4406. if (EnablePhiElim && L->isLoopSimplifyForm()) {
  4407. SmallVector<WeakVH, 16> DeadInsts;
  4408. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  4409. SCEVExpander Rewriter(getAnalysis<ScalarEvolution>(), DL, "lsr");
  4410. #ifndef NDEBUG
  4411. Rewriter.setDebugType(DEBUG_TYPE);
  4412. #endif
  4413. unsigned numFolded = Rewriter.replaceCongruentIVs(
  4414. L, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), DeadInsts,
  4415. &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  4416. *L->getHeader()->getParent()));
  4417. if (numFolded) {
  4418. Changed = true;
  4419. DeleteTriviallyDeadInstructions(DeadInsts);
  4420. DeleteDeadPHIs(L->getHeader());
  4421. }
  4422. }
  4423. return Changed;
  4424. }