SROA.cpp 185 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826
  1. //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. /// This transformation implements the well known scalar replacement of
  10. /// aggregates transformation. It tries to identify promotable elements of an
  11. /// aggregate alloca, and promote them to registers. It will also try to
  12. /// convert uses of an element (or set of elements) of an alloca into a vector
  13. /// or bitfield-style integer scalar if appropriate.
  14. ///
  15. /// It works to do this with minimal slicing of the alloca so that regions
  16. /// which are merely transferred in and out of external memory remain unchanged
  17. /// and are not decomposed to scalar code.
  18. ///
  19. /// Because this also performs alloca promotion, it can be thought of as also
  20. /// serving the purpose of SSA formation. The algorithm iterates on the
  21. /// function until all opportunities for promotion have been realized.
  22. ///
  23. //===----------------------------------------------------------------------===//
  24. #include "llvm/Transforms/Scalar/SROA.h"
  25. #include "llvm/ADT/APInt.h"
  26. #include "llvm/ADT/ArrayRef.h"
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/PointerIntPair.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/SetVector.h"
  31. #include "llvm/ADT/SmallBitVector.h"
  32. #include "llvm/ADT/SmallPtrSet.h"
  33. #include "llvm/ADT/SmallVector.h"
  34. #include "llvm/ADT/Statistic.h"
  35. #include "llvm/ADT/StringRef.h"
  36. #include "llvm/ADT/Twine.h"
  37. #include "llvm/ADT/iterator.h"
  38. #include "llvm/ADT/iterator_range.h"
  39. #include "llvm/Analysis/AssumptionCache.h"
  40. #include "llvm/Analysis/GlobalsModRef.h"
  41. #include "llvm/Analysis/Loads.h"
  42. #include "llvm/Analysis/PtrUseVisitor.h"
  43. #include "llvm/Config/llvm-config.h"
  44. #include "llvm/IR/BasicBlock.h"
  45. #include "llvm/IR/Constant.h"
  46. #include "llvm/IR/ConstantFolder.h"
  47. #include "llvm/IR/Constants.h"
  48. #include "llvm/IR/DIBuilder.h"
  49. #include "llvm/IR/DataLayout.h"
  50. #include "llvm/IR/DebugInfo.h"
  51. #include "llvm/IR/DebugInfoMetadata.h"
  52. #include "llvm/IR/DerivedTypes.h"
  53. #include "llvm/IR/Dominators.h"
  54. #include "llvm/IR/Function.h"
  55. #include "llvm/IR/GetElementPtrTypeIterator.h"
  56. #include "llvm/IR/GlobalAlias.h"
  57. #include "llvm/IR/IRBuilder.h"
  58. #include "llvm/IR/InstVisitor.h"
  59. #include "llvm/IR/InstrTypes.h"
  60. #include "llvm/IR/Instruction.h"
  61. #include "llvm/IR/Instructions.h"
  62. #include "llvm/IR/IntrinsicInst.h"
  63. #include "llvm/IR/Intrinsics.h"
  64. #include "llvm/IR/LLVMContext.h"
  65. #include "llvm/IR/Metadata.h"
  66. #include "llvm/IR/Module.h"
  67. #include "llvm/IR/Operator.h"
  68. #include "llvm/IR/PassManager.h"
  69. #include "llvm/IR/Type.h"
  70. #include "llvm/IR/Use.h"
  71. #include "llvm/IR/User.h"
  72. #include "llvm/IR/Value.h"
  73. #include "llvm/InitializePasses.h"
  74. #include "llvm/Pass.h"
  75. #include "llvm/Support/Casting.h"
  76. #include "llvm/Support/CommandLine.h"
  77. #include "llvm/Support/Compiler.h"
  78. #include "llvm/Support/Debug.h"
  79. #include "llvm/Support/ErrorHandling.h"
  80. #include "llvm/Support/MathExtras.h"
  81. #include "llvm/Support/raw_ostream.h"
  82. #include "llvm/Transforms/Scalar.h"
  83. #include "llvm/Transforms/Utils/Local.h"
  84. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  85. #include <algorithm>
  86. #include <cassert>
  87. #include <chrono>
  88. #include <cstddef>
  89. #include <cstdint>
  90. #include <cstring>
  91. #include <iterator>
  92. #include <string>
  93. #include <tuple>
  94. #include <utility>
  95. #include <vector>
  96. using namespace llvm;
  97. using namespace llvm::sroa;
  98. #define DEBUG_TYPE "sroa"
  99. STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
  100. STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
  101. STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
  102. STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
  103. STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
  104. STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
  105. STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
  106. STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
  107. STATISTIC(NumDeleted, "Number of instructions deleted");
  108. STATISTIC(NumVectorized, "Number of vectorized aggregates");
  109. /// Hidden option to experiment with completely strict handling of inbounds
  110. /// GEPs.
  111. static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
  112. cl::Hidden);
  113. namespace {
  114. /// A custom IRBuilder inserter which prefixes all names, but only in
  115. /// Assert builds.
  116. class IRBuilderPrefixedInserter final : public IRBuilderDefaultInserter {
  117. std::string Prefix;
  118. Twine getNameWithPrefix(const Twine &Name) const {
  119. return Name.isTriviallyEmpty() ? Name : Prefix + Name;
  120. }
  121. public:
  122. void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
  123. void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
  124. BasicBlock::iterator InsertPt) const override {
  125. IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
  126. InsertPt);
  127. }
  128. };
  129. /// Provide a type for IRBuilder that drops names in release builds.
  130. using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
  131. /// A used slice of an alloca.
  132. ///
  133. /// This structure represents a slice of an alloca used by some instruction. It
  134. /// stores both the begin and end offsets of this use, a pointer to the use
  135. /// itself, and a flag indicating whether we can classify the use as splittable
  136. /// or not when forming partitions of the alloca.
  137. class Slice {
  138. /// The beginning offset of the range.
  139. uint64_t BeginOffset = 0;
  140. /// The ending offset, not included in the range.
  141. uint64_t EndOffset = 0;
  142. /// Storage for both the use of this slice and whether it can be
  143. /// split.
  144. PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
  145. public:
  146. Slice() = default;
  147. Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
  148. : BeginOffset(BeginOffset), EndOffset(EndOffset),
  149. UseAndIsSplittable(U, IsSplittable) {}
  150. uint64_t beginOffset() const { return BeginOffset; }
  151. uint64_t endOffset() const { return EndOffset; }
  152. bool isSplittable() const { return UseAndIsSplittable.getInt(); }
  153. void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
  154. Use *getUse() const { return UseAndIsSplittable.getPointer(); }
  155. bool isDead() const { return getUse() == nullptr; }
  156. void kill() { UseAndIsSplittable.setPointer(nullptr); }
  157. /// Support for ordering ranges.
  158. ///
  159. /// This provides an ordering over ranges such that start offsets are
  160. /// always increasing, and within equal start offsets, the end offsets are
  161. /// decreasing. Thus the spanning range comes first in a cluster with the
  162. /// same start position.
  163. bool operator<(const Slice &RHS) const {
  164. if (beginOffset() < RHS.beginOffset())
  165. return true;
  166. if (beginOffset() > RHS.beginOffset())
  167. return false;
  168. if (isSplittable() != RHS.isSplittable())
  169. return !isSplittable();
  170. if (endOffset() > RHS.endOffset())
  171. return true;
  172. return false;
  173. }
  174. /// Support comparison with a single offset to allow binary searches.
  175. friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
  176. uint64_t RHSOffset) {
  177. return LHS.beginOffset() < RHSOffset;
  178. }
  179. friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
  180. const Slice &RHS) {
  181. return LHSOffset < RHS.beginOffset();
  182. }
  183. bool operator==(const Slice &RHS) const {
  184. return isSplittable() == RHS.isSplittable() &&
  185. beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
  186. }
  187. bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
  188. };
  189. } // end anonymous namespace
  190. /// Representation of the alloca slices.
  191. ///
  192. /// This class represents the slices of an alloca which are formed by its
  193. /// various uses. If a pointer escapes, we can't fully build a representation
  194. /// for the slices used and we reflect that in this structure. The uses are
  195. /// stored, sorted by increasing beginning offset and with unsplittable slices
  196. /// starting at a particular offset before splittable slices.
  197. class llvm::sroa::AllocaSlices {
  198. public:
  199. /// Construct the slices of a particular alloca.
  200. AllocaSlices(const DataLayout &DL, AllocaInst &AI);
  201. /// Test whether a pointer to the allocation escapes our analysis.
  202. ///
  203. /// If this is true, the slices are never fully built and should be
  204. /// ignored.
  205. bool isEscaped() const { return PointerEscapingInstr; }
  206. /// Support for iterating over the slices.
  207. /// @{
  208. using iterator = SmallVectorImpl<Slice>::iterator;
  209. using range = iterator_range<iterator>;
  210. iterator begin() { return Slices.begin(); }
  211. iterator end() { return Slices.end(); }
  212. using const_iterator = SmallVectorImpl<Slice>::const_iterator;
  213. using const_range = iterator_range<const_iterator>;
  214. const_iterator begin() const { return Slices.begin(); }
  215. const_iterator end() const { return Slices.end(); }
  216. /// @}
  217. /// Erase a range of slices.
  218. void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
  219. /// Insert new slices for this alloca.
  220. ///
  221. /// This moves the slices into the alloca's slices collection, and re-sorts
  222. /// everything so that the usual ordering properties of the alloca's slices
  223. /// hold.
  224. void insert(ArrayRef<Slice> NewSlices) {
  225. int OldSize = Slices.size();
  226. Slices.append(NewSlices.begin(), NewSlices.end());
  227. auto SliceI = Slices.begin() + OldSize;
  228. llvm::sort(SliceI, Slices.end());
  229. std::inplace_merge(Slices.begin(), SliceI, Slices.end());
  230. }
  231. // Forward declare the iterator and range accessor for walking the
  232. // partitions.
  233. class partition_iterator;
  234. iterator_range<partition_iterator> partitions();
  235. /// Access the dead users for this alloca.
  236. ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
  237. /// Access Uses that should be dropped if the alloca is promotable.
  238. ArrayRef<Use *> getDeadUsesIfPromotable() const {
  239. return DeadUseIfPromotable;
  240. }
  241. /// Access the dead operands referring to this alloca.
  242. ///
  243. /// These are operands which have cannot actually be used to refer to the
  244. /// alloca as they are outside its range and the user doesn't correct for
  245. /// that. These mostly consist of PHI node inputs and the like which we just
  246. /// need to replace with undef.
  247. ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
  248. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  249. void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
  250. void printSlice(raw_ostream &OS, const_iterator I,
  251. StringRef Indent = " ") const;
  252. void printUse(raw_ostream &OS, const_iterator I,
  253. StringRef Indent = " ") const;
  254. void print(raw_ostream &OS) const;
  255. void dump(const_iterator I) const;
  256. void dump() const;
  257. #endif
  258. private:
  259. template <typename DerivedT, typename RetT = void> class BuilderBase;
  260. class SliceBuilder;
  261. friend class AllocaSlices::SliceBuilder;
  262. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  263. /// Handle to alloca instruction to simplify method interfaces.
  264. AllocaInst &AI;
  265. #endif
  266. /// The instruction responsible for this alloca not having a known set
  267. /// of slices.
  268. ///
  269. /// When an instruction (potentially) escapes the pointer to the alloca, we
  270. /// store a pointer to that here and abort trying to form slices of the
  271. /// alloca. This will be null if the alloca slices are analyzed successfully.
  272. Instruction *PointerEscapingInstr;
  273. /// The slices of the alloca.
  274. ///
  275. /// We store a vector of the slices formed by uses of the alloca here. This
  276. /// vector is sorted by increasing begin offset, and then the unsplittable
  277. /// slices before the splittable ones. See the Slice inner class for more
  278. /// details.
  279. SmallVector<Slice, 8> Slices;
  280. /// Instructions which will become dead if we rewrite the alloca.
  281. ///
  282. /// Note that these are not separated by slice. This is because we expect an
  283. /// alloca to be completely rewritten or not rewritten at all. If rewritten,
  284. /// all these instructions can simply be removed and replaced with poison as
  285. /// they come from outside of the allocated space.
  286. SmallVector<Instruction *, 8> DeadUsers;
  287. /// Uses which will become dead if can promote the alloca.
  288. SmallVector<Use *, 8> DeadUseIfPromotable;
  289. /// Operands which will become dead if we rewrite the alloca.
  290. ///
  291. /// These are operands that in their particular use can be replaced with
  292. /// poison when we rewrite the alloca. These show up in out-of-bounds inputs
  293. /// to PHI nodes and the like. They aren't entirely dead (there might be
  294. /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
  295. /// want to swap this particular input for poison to simplify the use lists of
  296. /// the alloca.
  297. SmallVector<Use *, 8> DeadOperands;
  298. };
  299. /// A partition of the slices.
  300. ///
  301. /// An ephemeral representation for a range of slices which can be viewed as
  302. /// a partition of the alloca. This range represents a span of the alloca's
  303. /// memory which cannot be split, and provides access to all of the slices
  304. /// overlapping some part of the partition.
  305. ///
  306. /// Objects of this type are produced by traversing the alloca's slices, but
  307. /// are only ephemeral and not persistent.
  308. class llvm::sroa::Partition {
  309. private:
  310. friend class AllocaSlices;
  311. friend class AllocaSlices::partition_iterator;
  312. using iterator = AllocaSlices::iterator;
  313. /// The beginning and ending offsets of the alloca for this
  314. /// partition.
  315. uint64_t BeginOffset = 0, EndOffset = 0;
  316. /// The start and end iterators of this partition.
  317. iterator SI, SJ;
  318. /// A collection of split slice tails overlapping the partition.
  319. SmallVector<Slice *, 4> SplitTails;
  320. /// Raw constructor builds an empty partition starting and ending at
  321. /// the given iterator.
  322. Partition(iterator SI) : SI(SI), SJ(SI) {}
  323. public:
  324. /// The start offset of this partition.
  325. ///
  326. /// All of the contained slices start at or after this offset.
  327. uint64_t beginOffset() const { return BeginOffset; }
  328. /// The end offset of this partition.
  329. ///
  330. /// All of the contained slices end at or before this offset.
  331. uint64_t endOffset() const { return EndOffset; }
  332. /// The size of the partition.
  333. ///
  334. /// Note that this can never be zero.
  335. uint64_t size() const {
  336. assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
  337. return EndOffset - BeginOffset;
  338. }
  339. /// Test whether this partition contains no slices, and merely spans
  340. /// a region occupied by split slices.
  341. bool empty() const { return SI == SJ; }
  342. /// \name Iterate slices that start within the partition.
  343. /// These may be splittable or unsplittable. They have a begin offset >= the
  344. /// partition begin offset.
  345. /// @{
  346. // FIXME: We should probably define a "concat_iterator" helper and use that
  347. // to stitch together pointee_iterators over the split tails and the
  348. // contiguous iterators of the partition. That would give a much nicer
  349. // interface here. We could then additionally expose filtered iterators for
  350. // split, unsplit, and unsplittable splices based on the usage patterns.
  351. iterator begin() const { return SI; }
  352. iterator end() const { return SJ; }
  353. /// @}
  354. /// Get the sequence of split slice tails.
  355. ///
  356. /// These tails are of slices which start before this partition but are
  357. /// split and overlap into the partition. We accumulate these while forming
  358. /// partitions.
  359. ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
  360. };
  361. /// An iterator over partitions of the alloca's slices.
  362. ///
  363. /// This iterator implements the core algorithm for partitioning the alloca's
  364. /// slices. It is a forward iterator as we don't support backtracking for
  365. /// efficiency reasons, and re-use a single storage area to maintain the
  366. /// current set of split slices.
  367. ///
  368. /// It is templated on the slice iterator type to use so that it can operate
  369. /// with either const or non-const slice iterators.
  370. class AllocaSlices::partition_iterator
  371. : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
  372. Partition> {
  373. friend class AllocaSlices;
  374. /// Most of the state for walking the partitions is held in a class
  375. /// with a nice interface for examining them.
  376. Partition P;
  377. /// We need to keep the end of the slices to know when to stop.
  378. AllocaSlices::iterator SE;
  379. /// We also need to keep track of the maximum split end offset seen.
  380. /// FIXME: Do we really?
  381. uint64_t MaxSplitSliceEndOffset = 0;
  382. /// Sets the partition to be empty at given iterator, and sets the
  383. /// end iterator.
  384. partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
  385. : P(SI), SE(SE) {
  386. // If not already at the end, advance our state to form the initial
  387. // partition.
  388. if (SI != SE)
  389. advance();
  390. }
  391. /// Advance the iterator to the next partition.
  392. ///
  393. /// Requires that the iterator not be at the end of the slices.
  394. void advance() {
  395. assert((P.SI != SE || !P.SplitTails.empty()) &&
  396. "Cannot advance past the end of the slices!");
  397. // Clear out any split uses which have ended.
  398. if (!P.SplitTails.empty()) {
  399. if (P.EndOffset >= MaxSplitSliceEndOffset) {
  400. // If we've finished all splits, this is easy.
  401. P.SplitTails.clear();
  402. MaxSplitSliceEndOffset = 0;
  403. } else {
  404. // Remove the uses which have ended in the prior partition. This
  405. // cannot change the max split slice end because we just checked that
  406. // the prior partition ended prior to that max.
  407. llvm::erase_if(P.SplitTails,
  408. [&](Slice *S) { return S->endOffset() <= P.EndOffset; });
  409. assert(llvm::any_of(P.SplitTails,
  410. [&](Slice *S) {
  411. return S->endOffset() == MaxSplitSliceEndOffset;
  412. }) &&
  413. "Could not find the current max split slice offset!");
  414. assert(llvm::all_of(P.SplitTails,
  415. [&](Slice *S) {
  416. return S->endOffset() <= MaxSplitSliceEndOffset;
  417. }) &&
  418. "Max split slice end offset is not actually the max!");
  419. }
  420. }
  421. // If P.SI is already at the end, then we've cleared the split tail and
  422. // now have an end iterator.
  423. if (P.SI == SE) {
  424. assert(P.SplitTails.empty() && "Failed to clear the split slices!");
  425. return;
  426. }
  427. // If we had a non-empty partition previously, set up the state for
  428. // subsequent partitions.
  429. if (P.SI != P.SJ) {
  430. // Accumulate all the splittable slices which started in the old
  431. // partition into the split list.
  432. for (Slice &S : P)
  433. if (S.isSplittable() && S.endOffset() > P.EndOffset) {
  434. P.SplitTails.push_back(&S);
  435. MaxSplitSliceEndOffset =
  436. std::max(S.endOffset(), MaxSplitSliceEndOffset);
  437. }
  438. // Start from the end of the previous partition.
  439. P.SI = P.SJ;
  440. // If P.SI is now at the end, we at most have a tail of split slices.
  441. if (P.SI == SE) {
  442. P.BeginOffset = P.EndOffset;
  443. P.EndOffset = MaxSplitSliceEndOffset;
  444. return;
  445. }
  446. // If the we have split slices and the next slice is after a gap and is
  447. // not splittable immediately form an empty partition for the split
  448. // slices up until the next slice begins.
  449. if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
  450. !P.SI->isSplittable()) {
  451. P.BeginOffset = P.EndOffset;
  452. P.EndOffset = P.SI->beginOffset();
  453. return;
  454. }
  455. }
  456. // OK, we need to consume new slices. Set the end offset based on the
  457. // current slice, and step SJ past it. The beginning offset of the
  458. // partition is the beginning offset of the next slice unless we have
  459. // pre-existing split slices that are continuing, in which case we begin
  460. // at the prior end offset.
  461. P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
  462. P.EndOffset = P.SI->endOffset();
  463. ++P.SJ;
  464. // There are two strategies to form a partition based on whether the
  465. // partition starts with an unsplittable slice or a splittable slice.
  466. if (!P.SI->isSplittable()) {
  467. // When we're forming an unsplittable region, it must always start at
  468. // the first slice and will extend through its end.
  469. assert(P.BeginOffset == P.SI->beginOffset());
  470. // Form a partition including all of the overlapping slices with this
  471. // unsplittable slice.
  472. while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
  473. if (!P.SJ->isSplittable())
  474. P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
  475. ++P.SJ;
  476. }
  477. // We have a partition across a set of overlapping unsplittable
  478. // partitions.
  479. return;
  480. }
  481. // If we're starting with a splittable slice, then we need to form
  482. // a synthetic partition spanning it and any other overlapping splittable
  483. // splices.
  484. assert(P.SI->isSplittable() && "Forming a splittable partition!");
  485. // Collect all of the overlapping splittable slices.
  486. while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
  487. P.SJ->isSplittable()) {
  488. P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
  489. ++P.SJ;
  490. }
  491. // Back upiP.EndOffset if we ended the span early when encountering an
  492. // unsplittable slice. This synthesizes the early end offset of
  493. // a partition spanning only splittable slices.
  494. if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
  495. assert(!P.SJ->isSplittable());
  496. P.EndOffset = P.SJ->beginOffset();
  497. }
  498. }
  499. public:
  500. bool operator==(const partition_iterator &RHS) const {
  501. assert(SE == RHS.SE &&
  502. "End iterators don't match between compared partition iterators!");
  503. // The observed positions of partitions is marked by the P.SI iterator and
  504. // the emptiness of the split slices. The latter is only relevant when
  505. // P.SI == SE, as the end iterator will additionally have an empty split
  506. // slices list, but the prior may have the same P.SI and a tail of split
  507. // slices.
  508. if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
  509. assert(P.SJ == RHS.P.SJ &&
  510. "Same set of slices formed two different sized partitions!");
  511. assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
  512. "Same slice position with differently sized non-empty split "
  513. "slice tails!");
  514. return true;
  515. }
  516. return false;
  517. }
  518. partition_iterator &operator++() {
  519. advance();
  520. return *this;
  521. }
  522. Partition &operator*() { return P; }
  523. };
  524. /// A forward range over the partitions of the alloca's slices.
  525. ///
  526. /// This accesses an iterator range over the partitions of the alloca's
  527. /// slices. It computes these partitions on the fly based on the overlapping
  528. /// offsets of the slices and the ability to split them. It will visit "empty"
  529. /// partitions to cover regions of the alloca only accessed via split
  530. /// slices.
  531. iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
  532. return make_range(partition_iterator(begin(), end()),
  533. partition_iterator(end(), end()));
  534. }
  535. static Value *foldSelectInst(SelectInst &SI) {
  536. // If the condition being selected on is a constant or the same value is
  537. // being selected between, fold the select. Yes this does (rarely) happen
  538. // early on.
  539. if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
  540. return SI.getOperand(1 + CI->isZero());
  541. if (SI.getOperand(1) == SI.getOperand(2))
  542. return SI.getOperand(1);
  543. return nullptr;
  544. }
  545. /// A helper that folds a PHI node or a select.
  546. static Value *foldPHINodeOrSelectInst(Instruction &I) {
  547. if (PHINode *PN = dyn_cast<PHINode>(&I)) {
  548. // If PN merges together the same value, return that value.
  549. return PN->hasConstantValue();
  550. }
  551. return foldSelectInst(cast<SelectInst>(I));
  552. }
  553. /// Builder for the alloca slices.
  554. ///
  555. /// This class builds a set of alloca slices by recursively visiting the uses
  556. /// of an alloca and making a slice for each load and store at each offset.
  557. class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
  558. friend class PtrUseVisitor<SliceBuilder>;
  559. friend class InstVisitor<SliceBuilder>;
  560. using Base = PtrUseVisitor<SliceBuilder>;
  561. const uint64_t AllocSize;
  562. AllocaSlices &AS;
  563. SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
  564. SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
  565. /// Set to de-duplicate dead instructions found in the use walk.
  566. SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
  567. public:
  568. SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
  569. : PtrUseVisitor<SliceBuilder>(DL),
  570. AllocSize(DL.getTypeAllocSize(AI.getAllocatedType()).getFixedSize()),
  571. AS(AS) {}
  572. private:
  573. void markAsDead(Instruction &I) {
  574. if (VisitedDeadInsts.insert(&I).second)
  575. AS.DeadUsers.push_back(&I);
  576. }
  577. void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
  578. bool IsSplittable = false) {
  579. // Completely skip uses which have a zero size or start either before or
  580. // past the end of the allocation.
  581. if (Size == 0 || Offset.uge(AllocSize)) {
  582. LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"
  583. << Offset
  584. << " which has zero size or starts outside of the "
  585. << AllocSize << " byte alloca:\n"
  586. << " alloca: " << AS.AI << "\n"
  587. << " use: " << I << "\n");
  588. return markAsDead(I);
  589. }
  590. uint64_t BeginOffset = Offset.getZExtValue();
  591. uint64_t EndOffset = BeginOffset + Size;
  592. // Clamp the end offset to the end of the allocation. Note that this is
  593. // formulated to handle even the case where "BeginOffset + Size" overflows.
  594. // This may appear superficially to be something we could ignore entirely,
  595. // but that is not so! There may be widened loads or PHI-node uses where
  596. // some instructions are dead but not others. We can't completely ignore
  597. // them, and so have to record at least the information here.
  598. assert(AllocSize >= BeginOffset); // Established above.
  599. if (Size > AllocSize - BeginOffset) {
  600. LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"
  601. << Offset << " to remain within the " << AllocSize
  602. << " byte alloca:\n"
  603. << " alloca: " << AS.AI << "\n"
  604. << " use: " << I << "\n");
  605. EndOffset = AllocSize;
  606. }
  607. AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
  608. }
  609. void visitBitCastInst(BitCastInst &BC) {
  610. if (BC.use_empty())
  611. return markAsDead(BC);
  612. return Base::visitBitCastInst(BC);
  613. }
  614. void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
  615. if (ASC.use_empty())
  616. return markAsDead(ASC);
  617. return Base::visitAddrSpaceCastInst(ASC);
  618. }
  619. void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
  620. if (GEPI.use_empty())
  621. return markAsDead(GEPI);
  622. if (SROAStrictInbounds && GEPI.isInBounds()) {
  623. // FIXME: This is a manually un-factored variant of the basic code inside
  624. // of GEPs with checking of the inbounds invariant specified in the
  625. // langref in a very strict sense. If we ever want to enable
  626. // SROAStrictInbounds, this code should be factored cleanly into
  627. // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
  628. // by writing out the code here where we have the underlying allocation
  629. // size readily available.
  630. APInt GEPOffset = Offset;
  631. const DataLayout &DL = GEPI.getModule()->getDataLayout();
  632. for (gep_type_iterator GTI = gep_type_begin(GEPI),
  633. GTE = gep_type_end(GEPI);
  634. GTI != GTE; ++GTI) {
  635. ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
  636. if (!OpC)
  637. break;
  638. // Handle a struct index, which adds its field offset to the pointer.
  639. if (StructType *STy = GTI.getStructTypeOrNull()) {
  640. unsigned ElementIdx = OpC->getZExtValue();
  641. const StructLayout *SL = DL.getStructLayout(STy);
  642. GEPOffset +=
  643. APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
  644. } else {
  645. // For array or vector indices, scale the index by the size of the
  646. // type.
  647. APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
  648. GEPOffset +=
  649. Index *
  650. APInt(Offset.getBitWidth(),
  651. DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize());
  652. }
  653. // If this index has computed an intermediate pointer which is not
  654. // inbounds, then the result of the GEP is a poison value and we can
  655. // delete it and all uses.
  656. if (GEPOffset.ugt(AllocSize))
  657. return markAsDead(GEPI);
  658. }
  659. }
  660. return Base::visitGetElementPtrInst(GEPI);
  661. }
  662. void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
  663. uint64_t Size, bool IsVolatile) {
  664. // We allow splitting of non-volatile loads and stores where the type is an
  665. // integer type. These may be used to implement 'memcpy' or other "transfer
  666. // of bits" patterns.
  667. bool IsSplittable =
  668. Ty->isIntegerTy() && !IsVolatile && DL.typeSizeEqualsStoreSize(Ty);
  669. insertUse(I, Offset, Size, IsSplittable);
  670. }
  671. void visitLoadInst(LoadInst &LI) {
  672. assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
  673. "All simple FCA loads should have been pre-split");
  674. if (!IsOffsetKnown)
  675. return PI.setAborted(&LI);
  676. if (LI.isVolatile() &&
  677. LI.getPointerAddressSpace() != DL.getAllocaAddrSpace())
  678. return PI.setAborted(&LI);
  679. if (isa<ScalableVectorType>(LI.getType()))
  680. return PI.setAborted(&LI);
  681. uint64_t Size = DL.getTypeStoreSize(LI.getType()).getFixedSize();
  682. return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
  683. }
  684. void visitStoreInst(StoreInst &SI) {
  685. Value *ValOp = SI.getValueOperand();
  686. if (ValOp == *U)
  687. return PI.setEscapedAndAborted(&SI);
  688. if (!IsOffsetKnown)
  689. return PI.setAborted(&SI);
  690. if (SI.isVolatile() &&
  691. SI.getPointerAddressSpace() != DL.getAllocaAddrSpace())
  692. return PI.setAborted(&SI);
  693. if (isa<ScalableVectorType>(ValOp->getType()))
  694. return PI.setAborted(&SI);
  695. uint64_t Size = DL.getTypeStoreSize(ValOp->getType()).getFixedSize();
  696. // If this memory access can be shown to *statically* extend outside the
  697. // bounds of the allocation, it's behavior is undefined, so simply
  698. // ignore it. Note that this is more strict than the generic clamping
  699. // behavior of insertUse. We also try to handle cases which might run the
  700. // risk of overflow.
  701. // FIXME: We should instead consider the pointer to have escaped if this
  702. // function is being instrumented for addressing bugs or race conditions.
  703. if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
  704. LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
  705. << Offset << " which extends past the end of the "
  706. << AllocSize << " byte alloca:\n"
  707. << " alloca: " << AS.AI << "\n"
  708. << " use: " << SI << "\n");
  709. return markAsDead(SI);
  710. }
  711. assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
  712. "All simple FCA stores should have been pre-split");
  713. handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
  714. }
  715. void visitMemSetInst(MemSetInst &II) {
  716. assert(II.getRawDest() == *U && "Pointer use is not the destination?");
  717. ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
  718. if ((Length && Length->getValue() == 0) ||
  719. (IsOffsetKnown && Offset.uge(AllocSize)))
  720. // Zero-length mem transfer intrinsics can be ignored entirely.
  721. return markAsDead(II);
  722. if (!IsOffsetKnown)
  723. return PI.setAborted(&II);
  724. // Don't replace this with a store with a different address space. TODO:
  725. // Use a store with the casted new alloca?
  726. if (II.isVolatile() && II.getDestAddressSpace() != DL.getAllocaAddrSpace())
  727. return PI.setAborted(&II);
  728. insertUse(II, Offset, Length ? Length->getLimitedValue()
  729. : AllocSize - Offset.getLimitedValue(),
  730. (bool)Length);
  731. }
  732. void visitMemTransferInst(MemTransferInst &II) {
  733. ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
  734. if (Length && Length->getValue() == 0)
  735. // Zero-length mem transfer intrinsics can be ignored entirely.
  736. return markAsDead(II);
  737. // Because we can visit these intrinsics twice, also check to see if the
  738. // first time marked this instruction as dead. If so, skip it.
  739. if (VisitedDeadInsts.count(&II))
  740. return;
  741. if (!IsOffsetKnown)
  742. return PI.setAborted(&II);
  743. // Don't replace this with a load/store with a different address space.
  744. // TODO: Use a store with the casted new alloca?
  745. if (II.isVolatile() &&
  746. (II.getDestAddressSpace() != DL.getAllocaAddrSpace() ||
  747. II.getSourceAddressSpace() != DL.getAllocaAddrSpace()))
  748. return PI.setAborted(&II);
  749. // This side of the transfer is completely out-of-bounds, and so we can
  750. // nuke the entire transfer. However, we also need to nuke the other side
  751. // if already added to our partitions.
  752. // FIXME: Yet another place we really should bypass this when
  753. // instrumenting for ASan.
  754. if (Offset.uge(AllocSize)) {
  755. SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
  756. MemTransferSliceMap.find(&II);
  757. if (MTPI != MemTransferSliceMap.end())
  758. AS.Slices[MTPI->second].kill();
  759. return markAsDead(II);
  760. }
  761. uint64_t RawOffset = Offset.getLimitedValue();
  762. uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
  763. // Check for the special case where the same exact value is used for both
  764. // source and dest.
  765. if (*U == II.getRawDest() && *U == II.getRawSource()) {
  766. // For non-volatile transfers this is a no-op.
  767. if (!II.isVolatile())
  768. return markAsDead(II);
  769. return insertUse(II, Offset, Size, /*IsSplittable=*/false);
  770. }
  771. // If we have seen both source and destination for a mem transfer, then
  772. // they both point to the same alloca.
  773. bool Inserted;
  774. SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
  775. std::tie(MTPI, Inserted) =
  776. MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
  777. unsigned PrevIdx = MTPI->second;
  778. if (!Inserted) {
  779. Slice &PrevP = AS.Slices[PrevIdx];
  780. // Check if the begin offsets match and this is a non-volatile transfer.
  781. // In that case, we can completely elide the transfer.
  782. if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
  783. PrevP.kill();
  784. return markAsDead(II);
  785. }
  786. // Otherwise we have an offset transfer within the same alloca. We can't
  787. // split those.
  788. PrevP.makeUnsplittable();
  789. }
  790. // Insert the use now that we've fixed up the splittable nature.
  791. insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
  792. // Check that we ended up with a valid index in the map.
  793. assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
  794. "Map index doesn't point back to a slice with this user.");
  795. }
  796. // Disable SRoA for any intrinsics except for lifetime invariants and
  797. // invariant group.
  798. // FIXME: What about debug intrinsics? This matches old behavior, but
  799. // doesn't make sense.
  800. void visitIntrinsicInst(IntrinsicInst &II) {
  801. if (II.isDroppable()) {
  802. AS.DeadUseIfPromotable.push_back(U);
  803. return;
  804. }
  805. if (!IsOffsetKnown)
  806. return PI.setAborted(&II);
  807. if (II.isLifetimeStartOrEnd()) {
  808. ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
  809. uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
  810. Length->getLimitedValue());
  811. insertUse(II, Offset, Size, true);
  812. return;
  813. }
  814. if (II.isLaunderOrStripInvariantGroup()) {
  815. enqueueUsers(II);
  816. return;
  817. }
  818. Base::visitIntrinsicInst(II);
  819. }
  820. Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
  821. // We consider any PHI or select that results in a direct load or store of
  822. // the same offset to be a viable use for slicing purposes. These uses
  823. // are considered unsplittable and the size is the maximum loaded or stored
  824. // size.
  825. SmallPtrSet<Instruction *, 4> Visited;
  826. SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
  827. Visited.insert(Root);
  828. Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
  829. const DataLayout &DL = Root->getModule()->getDataLayout();
  830. // If there are no loads or stores, the access is dead. We mark that as
  831. // a size zero access.
  832. Size = 0;
  833. do {
  834. Instruction *I, *UsedI;
  835. std::tie(UsedI, I) = Uses.pop_back_val();
  836. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  837. Size = std::max(Size,
  838. DL.getTypeStoreSize(LI->getType()).getFixedSize());
  839. continue;
  840. }
  841. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  842. Value *Op = SI->getOperand(0);
  843. if (Op == UsedI)
  844. return SI;
  845. Size = std::max(Size,
  846. DL.getTypeStoreSize(Op->getType()).getFixedSize());
  847. continue;
  848. }
  849. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
  850. if (!GEP->hasAllZeroIndices())
  851. return GEP;
  852. } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
  853. !isa<SelectInst>(I) && !isa<AddrSpaceCastInst>(I)) {
  854. return I;
  855. }
  856. for (User *U : I->users())
  857. if (Visited.insert(cast<Instruction>(U)).second)
  858. Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
  859. } while (!Uses.empty());
  860. return nullptr;
  861. }
  862. void visitPHINodeOrSelectInst(Instruction &I) {
  863. assert(isa<PHINode>(I) || isa<SelectInst>(I));
  864. if (I.use_empty())
  865. return markAsDead(I);
  866. // If this is a PHI node before a catchswitch, we cannot insert any non-PHI
  867. // instructions in this BB, which may be required during rewriting. Bail out
  868. // on these cases.
  869. if (isa<PHINode>(I) &&
  870. I.getParent()->getFirstInsertionPt() == I.getParent()->end())
  871. return PI.setAborted(&I);
  872. // TODO: We could use SimplifyInstruction here to fold PHINodes and
  873. // SelectInsts. However, doing so requires to change the current
  874. // dead-operand-tracking mechanism. For instance, suppose neither loading
  875. // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
  876. // trap either. However, if we simply replace %U with undef using the
  877. // current dead-operand-tracking mechanism, "load (select undef, undef,
  878. // %other)" may trap because the select may return the first operand
  879. // "undef".
  880. if (Value *Result = foldPHINodeOrSelectInst(I)) {
  881. if (Result == *U)
  882. // If the result of the constant fold will be the pointer, recurse
  883. // through the PHI/select as if we had RAUW'ed it.
  884. enqueueUsers(I);
  885. else
  886. // Otherwise the operand to the PHI/select is dead, and we can replace
  887. // it with poison.
  888. AS.DeadOperands.push_back(U);
  889. return;
  890. }
  891. if (!IsOffsetKnown)
  892. return PI.setAborted(&I);
  893. // See if we already have computed info on this node.
  894. uint64_t &Size = PHIOrSelectSizes[&I];
  895. if (!Size) {
  896. // This is a new PHI/Select, check for an unsafe use of it.
  897. if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
  898. return PI.setAborted(UnsafeI);
  899. }
  900. // For PHI and select operands outside the alloca, we can't nuke the entire
  901. // phi or select -- the other side might still be relevant, so we special
  902. // case them here and use a separate structure to track the operands
  903. // themselves which should be replaced with poison.
  904. // FIXME: This should instead be escaped in the event we're instrumenting
  905. // for address sanitization.
  906. if (Offset.uge(AllocSize)) {
  907. AS.DeadOperands.push_back(U);
  908. return;
  909. }
  910. insertUse(I, Offset, Size);
  911. }
  912. void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
  913. void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
  914. /// Disable SROA entirely if there are unhandled users of the alloca.
  915. void visitInstruction(Instruction &I) { PI.setAborted(&I); }
  916. };
  917. AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
  918. :
  919. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  920. AI(AI),
  921. #endif
  922. PointerEscapingInstr(nullptr) {
  923. SliceBuilder PB(DL, AI, *this);
  924. SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
  925. if (PtrI.isEscaped() || PtrI.isAborted()) {
  926. // FIXME: We should sink the escape vs. abort info into the caller nicely,
  927. // possibly by just storing the PtrInfo in the AllocaSlices.
  928. PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
  929. : PtrI.getAbortingInst();
  930. assert(PointerEscapingInstr && "Did not track a bad instruction");
  931. return;
  932. }
  933. llvm::erase_if(Slices, [](const Slice &S) { return S.isDead(); });
  934. // Sort the uses. This arranges for the offsets to be in ascending order,
  935. // and the sizes to be in descending order.
  936. llvm::stable_sort(Slices);
  937. }
  938. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  939. void AllocaSlices::print(raw_ostream &OS, const_iterator I,
  940. StringRef Indent) const {
  941. printSlice(OS, I, Indent);
  942. OS << "\n";
  943. printUse(OS, I, Indent);
  944. }
  945. void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
  946. StringRef Indent) const {
  947. OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
  948. << " slice #" << (I - begin())
  949. << (I->isSplittable() ? " (splittable)" : "");
  950. }
  951. void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
  952. StringRef Indent) const {
  953. OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
  954. }
  955. void AllocaSlices::print(raw_ostream &OS) const {
  956. if (PointerEscapingInstr) {
  957. OS << "Can't analyze slices for alloca: " << AI << "\n"
  958. << " A pointer to this alloca escaped by:\n"
  959. << " " << *PointerEscapingInstr << "\n";
  960. return;
  961. }
  962. OS << "Slices of alloca: " << AI << "\n";
  963. for (const_iterator I = begin(), E = end(); I != E; ++I)
  964. print(OS, I);
  965. }
  966. LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
  967. print(dbgs(), I);
  968. }
  969. LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
  970. #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  971. /// Walk the range of a partitioning looking for a common type to cover this
  972. /// sequence of slices.
  973. static std::pair<Type *, IntegerType *>
  974. findCommonType(AllocaSlices::const_iterator B, AllocaSlices::const_iterator E,
  975. uint64_t EndOffset) {
  976. Type *Ty = nullptr;
  977. bool TyIsCommon = true;
  978. IntegerType *ITy = nullptr;
  979. // Note that we need to look at *every* alloca slice's Use to ensure we
  980. // always get consistent results regardless of the order of slices.
  981. for (AllocaSlices::const_iterator I = B; I != E; ++I) {
  982. Use *U = I->getUse();
  983. if (isa<IntrinsicInst>(*U->getUser()))
  984. continue;
  985. if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
  986. continue;
  987. Type *UserTy = nullptr;
  988. if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
  989. UserTy = LI->getType();
  990. } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
  991. UserTy = SI->getValueOperand()->getType();
  992. }
  993. if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
  994. // If the type is larger than the partition, skip it. We only encounter
  995. // this for split integer operations where we want to use the type of the
  996. // entity causing the split. Also skip if the type is not a byte width
  997. // multiple.
  998. if (UserITy->getBitWidth() % 8 != 0 ||
  999. UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
  1000. continue;
  1001. // Track the largest bitwidth integer type used in this way in case there
  1002. // is no common type.
  1003. if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
  1004. ITy = UserITy;
  1005. }
  1006. // To avoid depending on the order of slices, Ty and TyIsCommon must not
  1007. // depend on types skipped above.
  1008. if (!UserTy || (Ty && Ty != UserTy))
  1009. TyIsCommon = false; // Give up on anything but an iN type.
  1010. else
  1011. Ty = UserTy;
  1012. }
  1013. return {TyIsCommon ? Ty : nullptr, ITy};
  1014. }
  1015. /// PHI instructions that use an alloca and are subsequently loaded can be
  1016. /// rewritten to load both input pointers in the pred blocks and then PHI the
  1017. /// results, allowing the load of the alloca to be promoted.
  1018. /// From this:
  1019. /// %P2 = phi [i32* %Alloca, i32* %Other]
  1020. /// %V = load i32* %P2
  1021. /// to:
  1022. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  1023. /// ...
  1024. /// %V2 = load i32* %Other
  1025. /// ...
  1026. /// %V = phi [i32 %V1, i32 %V2]
  1027. ///
  1028. /// We can do this to a select if its only uses are loads and if the operands
  1029. /// to the select can be loaded unconditionally.
  1030. ///
  1031. /// FIXME: This should be hoisted into a generic utility, likely in
  1032. /// Transforms/Util/Local.h
  1033. static bool isSafePHIToSpeculate(PHINode &PN) {
  1034. const DataLayout &DL = PN.getModule()->getDataLayout();
  1035. // For now, we can only do this promotion if the load is in the same block
  1036. // as the PHI, and if there are no stores between the phi and load.
  1037. // TODO: Allow recursive phi users.
  1038. // TODO: Allow stores.
  1039. BasicBlock *BB = PN.getParent();
  1040. Align MaxAlign;
  1041. uint64_t APWidth = DL.getIndexTypeSizeInBits(PN.getType());
  1042. APInt MaxSize(APWidth, 0);
  1043. bool HaveLoad = false;
  1044. for (User *U : PN.users()) {
  1045. LoadInst *LI = dyn_cast<LoadInst>(U);
  1046. if (!LI || !LI->isSimple())
  1047. return false;
  1048. // For now we only allow loads in the same block as the PHI. This is
  1049. // a common case that happens when instcombine merges two loads through
  1050. // a PHI.
  1051. if (LI->getParent() != BB)
  1052. return false;
  1053. // Ensure that there are no instructions between the PHI and the load that
  1054. // could store.
  1055. for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
  1056. if (BBI->mayWriteToMemory())
  1057. return false;
  1058. uint64_t Size = DL.getTypeStoreSize(LI->getType()).getFixedSize();
  1059. MaxAlign = std::max(MaxAlign, LI->getAlign());
  1060. MaxSize = MaxSize.ult(Size) ? APInt(APWidth, Size) : MaxSize;
  1061. HaveLoad = true;
  1062. }
  1063. if (!HaveLoad)
  1064. return false;
  1065. // We can only transform this if it is safe to push the loads into the
  1066. // predecessor blocks. The only thing to watch out for is that we can't put
  1067. // a possibly trapping load in the predecessor if it is a critical edge.
  1068. for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
  1069. Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator();
  1070. Value *InVal = PN.getIncomingValue(Idx);
  1071. // If the value is produced by the terminator of the predecessor (an
  1072. // invoke) or it has side-effects, there is no valid place to put a load
  1073. // in the predecessor.
  1074. if (TI == InVal || TI->mayHaveSideEffects())
  1075. return false;
  1076. // If the predecessor has a single successor, then the edge isn't
  1077. // critical.
  1078. if (TI->getNumSuccessors() == 1)
  1079. continue;
  1080. // If this pointer is always safe to load, or if we can prove that there
  1081. // is already a load in the block, then we can move the load to the pred
  1082. // block.
  1083. if (isSafeToLoadUnconditionally(InVal, MaxAlign, MaxSize, DL, TI))
  1084. continue;
  1085. return false;
  1086. }
  1087. return true;
  1088. }
  1089. static void speculatePHINodeLoads(IRBuilderTy &IRB, PHINode &PN) {
  1090. LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
  1091. LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
  1092. Type *LoadTy = SomeLoad->getType();
  1093. IRB.SetInsertPoint(&PN);
  1094. PHINode *NewPN = IRB.CreatePHI(LoadTy, PN.getNumIncomingValues(),
  1095. PN.getName() + ".sroa.speculated");
  1096. // Get the AA tags and alignment to use from one of the loads. It does not
  1097. // matter which one we get and if any differ.
  1098. AAMDNodes AATags = SomeLoad->getAAMetadata();
  1099. Align Alignment = SomeLoad->getAlign();
  1100. // Rewrite all loads of the PN to use the new PHI.
  1101. while (!PN.use_empty()) {
  1102. LoadInst *LI = cast<LoadInst>(PN.user_back());
  1103. LI->replaceAllUsesWith(NewPN);
  1104. LI->eraseFromParent();
  1105. }
  1106. // Inject loads into all of the pred blocks.
  1107. DenseMap<BasicBlock*, Value*> InjectedLoads;
  1108. for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
  1109. BasicBlock *Pred = PN.getIncomingBlock(Idx);
  1110. Value *InVal = PN.getIncomingValue(Idx);
  1111. // A PHI node is allowed to have multiple (duplicated) entries for the same
  1112. // basic block, as long as the value is the same. So if we already injected
  1113. // a load in the predecessor, then we should reuse the same load for all
  1114. // duplicated entries.
  1115. if (Value* V = InjectedLoads.lookup(Pred)) {
  1116. NewPN->addIncoming(V, Pred);
  1117. continue;
  1118. }
  1119. Instruction *TI = Pred->getTerminator();
  1120. IRB.SetInsertPoint(TI);
  1121. LoadInst *Load = IRB.CreateAlignedLoad(
  1122. LoadTy, InVal, Alignment,
  1123. (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
  1124. ++NumLoadsSpeculated;
  1125. if (AATags)
  1126. Load->setAAMetadata(AATags);
  1127. NewPN->addIncoming(Load, Pred);
  1128. InjectedLoads[Pred] = Load;
  1129. }
  1130. LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
  1131. PN.eraseFromParent();
  1132. }
  1133. /// Select instructions that use an alloca and are subsequently loaded can be
  1134. /// rewritten to load both input pointers and then select between the result,
  1135. /// allowing the load of the alloca to be promoted.
  1136. /// From this:
  1137. /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
  1138. /// %V = load i32* %P2
  1139. /// to:
  1140. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  1141. /// %V2 = load i32* %Other
  1142. /// %V = select i1 %cond, i32 %V1, i32 %V2
  1143. ///
  1144. /// We can do this to a select if its only uses are loads and if the operand
  1145. /// to the select can be loaded unconditionally. If found an intervening bitcast
  1146. /// with a single use of the load, allow the promotion.
  1147. static bool isSafeSelectToSpeculate(SelectInst &SI) {
  1148. Value *TValue = SI.getTrueValue();
  1149. Value *FValue = SI.getFalseValue();
  1150. const DataLayout &DL = SI.getModule()->getDataLayout();
  1151. for (User *U : SI.users()) {
  1152. LoadInst *LI;
  1153. BitCastInst *BC = dyn_cast<BitCastInst>(U);
  1154. if (BC && BC->hasOneUse())
  1155. LI = dyn_cast<LoadInst>(*BC->user_begin());
  1156. else
  1157. LI = dyn_cast<LoadInst>(U);
  1158. if (!LI || !LI->isSimple())
  1159. return false;
  1160. // Both operands to the select need to be dereferenceable, either
  1161. // absolutely (e.g. allocas) or at this point because we can see other
  1162. // accesses to it.
  1163. if (!isSafeToLoadUnconditionally(TValue, LI->getType(),
  1164. LI->getAlign(), DL, LI))
  1165. return false;
  1166. if (!isSafeToLoadUnconditionally(FValue, LI->getType(),
  1167. LI->getAlign(), DL, LI))
  1168. return false;
  1169. }
  1170. return true;
  1171. }
  1172. static void speculateSelectInstLoads(IRBuilderTy &IRB, SelectInst &SI) {
  1173. LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
  1174. IRB.SetInsertPoint(&SI);
  1175. Value *TV = SI.getTrueValue();
  1176. Value *FV = SI.getFalseValue();
  1177. // Replace the loads of the select with a select of two loads.
  1178. while (!SI.use_empty()) {
  1179. LoadInst *LI;
  1180. BitCastInst *BC = dyn_cast<BitCastInst>(SI.user_back());
  1181. if (BC) {
  1182. assert(BC->hasOneUse() && "Bitcast should have a single use.");
  1183. LI = cast<LoadInst>(BC->user_back());
  1184. } else {
  1185. LI = cast<LoadInst>(SI.user_back());
  1186. }
  1187. assert(LI->isSimple() && "We only speculate simple loads");
  1188. IRB.SetInsertPoint(LI);
  1189. Value *NewTV =
  1190. BC ? IRB.CreateBitCast(TV, BC->getType(), TV->getName() + ".sroa.cast")
  1191. : TV;
  1192. Value *NewFV =
  1193. BC ? IRB.CreateBitCast(FV, BC->getType(), FV->getName() + ".sroa.cast")
  1194. : FV;
  1195. LoadInst *TL = IRB.CreateLoad(LI->getType(), NewTV,
  1196. LI->getName() + ".sroa.speculate.load.true");
  1197. LoadInst *FL = IRB.CreateLoad(LI->getType(), NewFV,
  1198. LI->getName() + ".sroa.speculate.load.false");
  1199. NumLoadsSpeculated += 2;
  1200. // Transfer alignment and AA info if present.
  1201. TL->setAlignment(LI->getAlign());
  1202. FL->setAlignment(LI->getAlign());
  1203. AAMDNodes Tags = LI->getAAMetadata();
  1204. if (Tags) {
  1205. TL->setAAMetadata(Tags);
  1206. FL->setAAMetadata(Tags);
  1207. }
  1208. Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
  1209. LI->getName() + ".sroa.speculated");
  1210. LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n");
  1211. LI->replaceAllUsesWith(V);
  1212. LI->eraseFromParent();
  1213. if (BC)
  1214. BC->eraseFromParent();
  1215. }
  1216. SI.eraseFromParent();
  1217. }
  1218. /// Build a GEP out of a base pointer and indices.
  1219. ///
  1220. /// This will return the BasePtr if that is valid, or build a new GEP
  1221. /// instruction using the IRBuilder if GEP-ing is needed.
  1222. static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
  1223. SmallVectorImpl<Value *> &Indices,
  1224. const Twine &NamePrefix) {
  1225. if (Indices.empty())
  1226. return BasePtr;
  1227. // A single zero index is a no-op, so check for this and avoid building a GEP
  1228. // in that case.
  1229. if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
  1230. return BasePtr;
  1231. // buildGEP() is only called for non-opaque pointers.
  1232. return IRB.CreateInBoundsGEP(
  1233. BasePtr->getType()->getNonOpaquePointerElementType(), BasePtr, Indices,
  1234. NamePrefix + "sroa_idx");
  1235. }
  1236. /// Get a natural GEP off of the BasePtr walking through Ty toward
  1237. /// TargetTy without changing the offset of the pointer.
  1238. ///
  1239. /// This routine assumes we've already established a properly offset GEP with
  1240. /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
  1241. /// zero-indices down through type layers until we find one the same as
  1242. /// TargetTy. If we can't find one with the same type, we at least try to use
  1243. /// one with the same size. If none of that works, we just produce the GEP as
  1244. /// indicated by Indices to have the correct offset.
  1245. static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
  1246. Value *BasePtr, Type *Ty, Type *TargetTy,
  1247. SmallVectorImpl<Value *> &Indices,
  1248. const Twine &NamePrefix) {
  1249. if (Ty == TargetTy)
  1250. return buildGEP(IRB, BasePtr, Indices, NamePrefix);
  1251. // Offset size to use for the indices.
  1252. unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType());
  1253. // See if we can descend into a struct and locate a field with the correct
  1254. // type.
  1255. unsigned NumLayers = 0;
  1256. Type *ElementTy = Ty;
  1257. do {
  1258. if (ElementTy->isPointerTy())
  1259. break;
  1260. if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
  1261. ElementTy = ArrayTy->getElementType();
  1262. Indices.push_back(IRB.getIntN(OffsetSize, 0));
  1263. } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
  1264. ElementTy = VectorTy->getElementType();
  1265. Indices.push_back(IRB.getInt32(0));
  1266. } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
  1267. if (STy->element_begin() == STy->element_end())
  1268. break; // Nothing left to descend into.
  1269. ElementTy = *STy->element_begin();
  1270. Indices.push_back(IRB.getInt32(0));
  1271. } else {
  1272. break;
  1273. }
  1274. ++NumLayers;
  1275. } while (ElementTy != TargetTy);
  1276. if (ElementTy != TargetTy)
  1277. Indices.erase(Indices.end() - NumLayers, Indices.end());
  1278. return buildGEP(IRB, BasePtr, Indices, NamePrefix);
  1279. }
  1280. /// Get a natural GEP from a base pointer to a particular offset and
  1281. /// resulting in a particular type.
  1282. ///
  1283. /// The goal is to produce a "natural" looking GEP that works with the existing
  1284. /// composite types to arrive at the appropriate offset and element type for
  1285. /// a pointer. TargetTy is the element type the returned GEP should point-to if
  1286. /// possible. We recurse by decreasing Offset, adding the appropriate index to
  1287. /// Indices, and setting Ty to the result subtype.
  1288. ///
  1289. /// If no natural GEP can be constructed, this function returns null.
  1290. static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
  1291. Value *Ptr, APInt Offset, Type *TargetTy,
  1292. SmallVectorImpl<Value *> &Indices,
  1293. const Twine &NamePrefix) {
  1294. PointerType *Ty = cast<PointerType>(Ptr->getType());
  1295. // Don't consider any GEPs through an i8* as natural unless the TargetTy is
  1296. // an i8.
  1297. if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
  1298. return nullptr;
  1299. Type *ElementTy = Ty->getNonOpaquePointerElementType();
  1300. if (!ElementTy->isSized())
  1301. return nullptr; // We can't GEP through an unsized element.
  1302. SmallVector<APInt> IntIndices = DL.getGEPIndicesForOffset(ElementTy, Offset);
  1303. if (Offset != 0)
  1304. return nullptr;
  1305. for (const APInt &Index : IntIndices)
  1306. Indices.push_back(IRB.getInt(Index));
  1307. return getNaturalGEPWithType(IRB, DL, Ptr, ElementTy, TargetTy, Indices,
  1308. NamePrefix);
  1309. }
  1310. /// Compute an adjusted pointer from Ptr by Offset bytes where the
  1311. /// resulting pointer has PointerTy.
  1312. ///
  1313. /// This tries very hard to compute a "natural" GEP which arrives at the offset
  1314. /// and produces the pointer type desired. Where it cannot, it will try to use
  1315. /// the natural GEP to arrive at the offset and bitcast to the type. Where that
  1316. /// fails, it will try to use an existing i8* and GEP to the byte offset and
  1317. /// bitcast to the type.
  1318. ///
  1319. /// The strategy for finding the more natural GEPs is to peel off layers of the
  1320. /// pointer, walking back through bit casts and GEPs, searching for a base
  1321. /// pointer from which we can compute a natural GEP with the desired
  1322. /// properties. The algorithm tries to fold as many constant indices into
  1323. /// a single GEP as possible, thus making each GEP more independent of the
  1324. /// surrounding code.
  1325. static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
  1326. APInt Offset, Type *PointerTy,
  1327. const Twine &NamePrefix) {
  1328. // Create i8 GEP for opaque pointers.
  1329. if (Ptr->getType()->isOpaquePointerTy()) {
  1330. if (Offset != 0)
  1331. Ptr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Ptr, IRB.getInt(Offset),
  1332. NamePrefix + "sroa_idx");
  1333. return IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr, PointerTy,
  1334. NamePrefix + "sroa_cast");
  1335. }
  1336. // Even though we don't look through PHI nodes, we could be called on an
  1337. // instruction in an unreachable block, which may be on a cycle.
  1338. SmallPtrSet<Value *, 4> Visited;
  1339. Visited.insert(Ptr);
  1340. SmallVector<Value *, 4> Indices;
  1341. // We may end up computing an offset pointer that has the wrong type. If we
  1342. // never are able to compute one directly that has the correct type, we'll
  1343. // fall back to it, so keep it and the base it was computed from around here.
  1344. Value *OffsetPtr = nullptr;
  1345. Value *OffsetBasePtr;
  1346. // Remember any i8 pointer we come across to re-use if we need to do a raw
  1347. // byte offset.
  1348. Value *Int8Ptr = nullptr;
  1349. APInt Int8PtrOffset(Offset.getBitWidth(), 0);
  1350. PointerType *TargetPtrTy = cast<PointerType>(PointerTy);
  1351. Type *TargetTy = TargetPtrTy->getNonOpaquePointerElementType();
  1352. // As `addrspacecast` is , `Ptr` (the storage pointer) may have different
  1353. // address space from the expected `PointerTy` (the pointer to be used).
  1354. // Adjust the pointer type based the original storage pointer.
  1355. auto AS = cast<PointerType>(Ptr->getType())->getAddressSpace();
  1356. PointerTy = TargetTy->getPointerTo(AS);
  1357. do {
  1358. // First fold any existing GEPs into the offset.
  1359. while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
  1360. APInt GEPOffset(Offset.getBitWidth(), 0);
  1361. if (!GEP->accumulateConstantOffset(DL, GEPOffset))
  1362. break;
  1363. Offset += GEPOffset;
  1364. Ptr = GEP->getPointerOperand();
  1365. if (!Visited.insert(Ptr).second)
  1366. break;
  1367. }
  1368. // See if we can perform a natural GEP here.
  1369. Indices.clear();
  1370. if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
  1371. Indices, NamePrefix)) {
  1372. // If we have a new natural pointer at the offset, clear out any old
  1373. // offset pointer we computed. Unless it is the base pointer or
  1374. // a non-instruction, we built a GEP we don't need. Zap it.
  1375. if (OffsetPtr && OffsetPtr != OffsetBasePtr)
  1376. if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
  1377. assert(I->use_empty() && "Built a GEP with uses some how!");
  1378. I->eraseFromParent();
  1379. }
  1380. OffsetPtr = P;
  1381. OffsetBasePtr = Ptr;
  1382. // If we also found a pointer of the right type, we're done.
  1383. if (P->getType() == PointerTy)
  1384. break;
  1385. }
  1386. // Stash this pointer if we've found an i8*.
  1387. if (Ptr->getType()->isIntegerTy(8)) {
  1388. Int8Ptr = Ptr;
  1389. Int8PtrOffset = Offset;
  1390. }
  1391. // Peel off a layer of the pointer and update the offset appropriately.
  1392. if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
  1393. Ptr = cast<Operator>(Ptr)->getOperand(0);
  1394. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
  1395. if (GA->isInterposable())
  1396. break;
  1397. Ptr = GA->getAliasee();
  1398. } else {
  1399. break;
  1400. }
  1401. assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
  1402. } while (Visited.insert(Ptr).second);
  1403. if (!OffsetPtr) {
  1404. if (!Int8Ptr) {
  1405. Int8Ptr = IRB.CreateBitCast(
  1406. Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
  1407. NamePrefix + "sroa_raw_cast");
  1408. Int8PtrOffset = Offset;
  1409. }
  1410. OffsetPtr = Int8PtrOffset == 0
  1411. ? Int8Ptr
  1412. : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
  1413. IRB.getInt(Int8PtrOffset),
  1414. NamePrefix + "sroa_raw_idx");
  1415. }
  1416. Ptr = OffsetPtr;
  1417. // On the off chance we were targeting i8*, guard the bitcast here.
  1418. if (cast<PointerType>(Ptr->getType()) != TargetPtrTy) {
  1419. Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr,
  1420. TargetPtrTy,
  1421. NamePrefix + "sroa_cast");
  1422. }
  1423. return Ptr;
  1424. }
  1425. /// Compute the adjusted alignment for a load or store from an offset.
  1426. static Align getAdjustedAlignment(Instruction *I, uint64_t Offset) {
  1427. return commonAlignment(getLoadStoreAlignment(I), Offset);
  1428. }
  1429. /// Test whether we can convert a value from the old to the new type.
  1430. ///
  1431. /// This predicate should be used to guard calls to convertValue in order to
  1432. /// ensure that we only try to convert viable values. The strategy is that we
  1433. /// will peel off single element struct and array wrappings to get to an
  1434. /// underlying value, and convert that value.
  1435. static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
  1436. if (OldTy == NewTy)
  1437. return true;
  1438. // For integer types, we can't handle any bit-width differences. This would
  1439. // break both vector conversions with extension and introduce endianness
  1440. // issues when in conjunction with loads and stores.
  1441. if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
  1442. assert(cast<IntegerType>(OldTy)->getBitWidth() !=
  1443. cast<IntegerType>(NewTy)->getBitWidth() &&
  1444. "We can't have the same bitwidth for different int types");
  1445. return false;
  1446. }
  1447. if (DL.getTypeSizeInBits(NewTy).getFixedSize() !=
  1448. DL.getTypeSizeInBits(OldTy).getFixedSize())
  1449. return false;
  1450. if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
  1451. return false;
  1452. // We can convert pointers to integers and vice-versa. Same for vectors
  1453. // of pointers and integers.
  1454. OldTy = OldTy->getScalarType();
  1455. NewTy = NewTy->getScalarType();
  1456. if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
  1457. if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
  1458. unsigned OldAS = OldTy->getPointerAddressSpace();
  1459. unsigned NewAS = NewTy->getPointerAddressSpace();
  1460. // Convert pointers if they are pointers from the same address space or
  1461. // different integral (not non-integral) address spaces with the same
  1462. // pointer size.
  1463. return OldAS == NewAS ||
  1464. (!DL.isNonIntegralAddressSpace(OldAS) &&
  1465. !DL.isNonIntegralAddressSpace(NewAS) &&
  1466. DL.getPointerSize(OldAS) == DL.getPointerSize(NewAS));
  1467. }
  1468. // We can convert integers to integral pointers, but not to non-integral
  1469. // pointers.
  1470. if (OldTy->isIntegerTy())
  1471. return !DL.isNonIntegralPointerType(NewTy);
  1472. // We can convert integral pointers to integers, but non-integral pointers
  1473. // need to remain pointers.
  1474. if (!DL.isNonIntegralPointerType(OldTy))
  1475. return NewTy->isIntegerTy();
  1476. return false;
  1477. }
  1478. return true;
  1479. }
  1480. /// Generic routine to convert an SSA value to a value of a different
  1481. /// type.
  1482. ///
  1483. /// This will try various different casting techniques, such as bitcasts,
  1484. /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
  1485. /// two types for viability with this routine.
  1486. static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
  1487. Type *NewTy) {
  1488. Type *OldTy = V->getType();
  1489. assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
  1490. if (OldTy == NewTy)
  1491. return V;
  1492. assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
  1493. "Integer types must be the exact same to convert.");
  1494. // See if we need inttoptr for this type pair. May require additional bitcast.
  1495. if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
  1496. // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
  1497. // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
  1498. // Expand <4 x i32> to <2 x i8*> --> <4 x i32> to <2 x i64> to <2 x i8*>
  1499. // Directly handle i64 to i8*
  1500. return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
  1501. NewTy);
  1502. }
  1503. // See if we need ptrtoint for this type pair. May require additional bitcast.
  1504. if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
  1505. // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
  1506. // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
  1507. // Expand <2 x i8*> to <4 x i32> --> <2 x i8*> to <2 x i64> to <4 x i32>
  1508. // Expand i8* to i64 --> i8* to i64 to i64
  1509. return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
  1510. NewTy);
  1511. }
  1512. if (OldTy->isPtrOrPtrVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
  1513. unsigned OldAS = OldTy->getPointerAddressSpace();
  1514. unsigned NewAS = NewTy->getPointerAddressSpace();
  1515. // To convert pointers with different address spaces (they are already
  1516. // checked convertible, i.e. they have the same pointer size), so far we
  1517. // cannot use `bitcast` (which has restrict on the same address space) or
  1518. // `addrspacecast` (which is not always no-op casting). Instead, use a pair
  1519. // of no-op `ptrtoint`/`inttoptr` casts through an integer with the same bit
  1520. // size.
  1521. if (OldAS != NewAS) {
  1522. assert(DL.getPointerSize(OldAS) == DL.getPointerSize(NewAS));
  1523. return IRB.CreateIntToPtr(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
  1524. NewTy);
  1525. }
  1526. }
  1527. return IRB.CreateBitCast(V, NewTy);
  1528. }
  1529. /// Test whether the given slice use can be promoted to a vector.
  1530. ///
  1531. /// This function is called to test each entry in a partition which is slated
  1532. /// for a single slice.
  1533. static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
  1534. VectorType *Ty,
  1535. uint64_t ElementSize,
  1536. const DataLayout &DL) {
  1537. // First validate the slice offsets.
  1538. uint64_t BeginOffset =
  1539. std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
  1540. uint64_t BeginIndex = BeginOffset / ElementSize;
  1541. if (BeginIndex * ElementSize != BeginOffset ||
  1542. BeginIndex >= cast<FixedVectorType>(Ty)->getNumElements())
  1543. return false;
  1544. uint64_t EndOffset =
  1545. std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
  1546. uint64_t EndIndex = EndOffset / ElementSize;
  1547. if (EndIndex * ElementSize != EndOffset ||
  1548. EndIndex > cast<FixedVectorType>(Ty)->getNumElements())
  1549. return false;
  1550. assert(EndIndex > BeginIndex && "Empty vector!");
  1551. uint64_t NumElements = EndIndex - BeginIndex;
  1552. Type *SliceTy = (NumElements == 1)
  1553. ? Ty->getElementType()
  1554. : FixedVectorType::get(Ty->getElementType(), NumElements);
  1555. Type *SplitIntTy =
  1556. Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
  1557. Use *U = S.getUse();
  1558. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
  1559. if (MI->isVolatile())
  1560. return false;
  1561. if (!S.isSplittable())
  1562. return false; // Skip any unsplittable intrinsics.
  1563. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
  1564. if (!II->isLifetimeStartOrEnd() && !II->isDroppable())
  1565. return false;
  1566. } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
  1567. if (LI->isVolatile())
  1568. return false;
  1569. Type *LTy = LI->getType();
  1570. // Disable vector promotion when there are loads or stores of an FCA.
  1571. if (LTy->isStructTy())
  1572. return false;
  1573. if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
  1574. assert(LTy->isIntegerTy());
  1575. LTy = SplitIntTy;
  1576. }
  1577. if (!canConvertValue(DL, SliceTy, LTy))
  1578. return false;
  1579. } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
  1580. if (SI->isVolatile())
  1581. return false;
  1582. Type *STy = SI->getValueOperand()->getType();
  1583. // Disable vector promotion when there are loads or stores of an FCA.
  1584. if (STy->isStructTy())
  1585. return false;
  1586. if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
  1587. assert(STy->isIntegerTy());
  1588. STy = SplitIntTy;
  1589. }
  1590. if (!canConvertValue(DL, STy, SliceTy))
  1591. return false;
  1592. } else {
  1593. return false;
  1594. }
  1595. return true;
  1596. }
  1597. /// Test whether the given alloca partitioning and range of slices can be
  1598. /// promoted to a vector.
  1599. ///
  1600. /// This is a quick test to check whether we can rewrite a particular alloca
  1601. /// partition (and its newly formed alloca) into a vector alloca with only
  1602. /// whole-vector loads and stores such that it could be promoted to a vector
  1603. /// SSA value. We only can ensure this for a limited set of operations, and we
  1604. /// don't want to do the rewrites unless we are confident that the result will
  1605. /// be promotable, so we have an early test here.
  1606. static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
  1607. // Collect the candidate types for vector-based promotion. Also track whether
  1608. // we have different element types.
  1609. SmallVector<VectorType *, 4> CandidateTys;
  1610. Type *CommonEltTy = nullptr;
  1611. bool HaveCommonEltTy = true;
  1612. auto CheckCandidateType = [&](Type *Ty) {
  1613. if (auto *VTy = dyn_cast<VectorType>(Ty)) {
  1614. // Return if bitcast to vectors is different for total size in bits.
  1615. if (!CandidateTys.empty()) {
  1616. VectorType *V = CandidateTys[0];
  1617. if (DL.getTypeSizeInBits(VTy).getFixedSize() !=
  1618. DL.getTypeSizeInBits(V).getFixedSize()) {
  1619. CandidateTys.clear();
  1620. return;
  1621. }
  1622. }
  1623. CandidateTys.push_back(VTy);
  1624. if (!CommonEltTy)
  1625. CommonEltTy = VTy->getElementType();
  1626. else if (CommonEltTy != VTy->getElementType())
  1627. HaveCommonEltTy = false;
  1628. }
  1629. };
  1630. // Consider any loads or stores that are the exact size of the slice.
  1631. for (const Slice &S : P)
  1632. if (S.beginOffset() == P.beginOffset() &&
  1633. S.endOffset() == P.endOffset()) {
  1634. if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
  1635. CheckCandidateType(LI->getType());
  1636. else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
  1637. CheckCandidateType(SI->getValueOperand()->getType());
  1638. }
  1639. // If we didn't find a vector type, nothing to do here.
  1640. if (CandidateTys.empty())
  1641. return nullptr;
  1642. // Remove non-integer vector types if we had multiple common element types.
  1643. // FIXME: It'd be nice to replace them with integer vector types, but we can't
  1644. // do that until all the backends are known to produce good code for all
  1645. // integer vector types.
  1646. if (!HaveCommonEltTy) {
  1647. llvm::erase_if(CandidateTys, [](VectorType *VTy) {
  1648. return !VTy->getElementType()->isIntegerTy();
  1649. });
  1650. // If there were no integer vector types, give up.
  1651. if (CandidateTys.empty())
  1652. return nullptr;
  1653. // Rank the remaining candidate vector types. This is easy because we know
  1654. // they're all integer vectors. We sort by ascending number of elements.
  1655. auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
  1656. (void)DL;
  1657. assert(DL.getTypeSizeInBits(RHSTy).getFixedSize() ==
  1658. DL.getTypeSizeInBits(LHSTy).getFixedSize() &&
  1659. "Cannot have vector types of different sizes!");
  1660. assert(RHSTy->getElementType()->isIntegerTy() &&
  1661. "All non-integer types eliminated!");
  1662. assert(LHSTy->getElementType()->isIntegerTy() &&
  1663. "All non-integer types eliminated!");
  1664. return cast<FixedVectorType>(RHSTy)->getNumElements() <
  1665. cast<FixedVectorType>(LHSTy)->getNumElements();
  1666. };
  1667. llvm::sort(CandidateTys, RankVectorTypes);
  1668. CandidateTys.erase(
  1669. std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
  1670. CandidateTys.end());
  1671. } else {
  1672. // The only way to have the same element type in every vector type is to
  1673. // have the same vector type. Check that and remove all but one.
  1674. #ifndef NDEBUG
  1675. for (VectorType *VTy : CandidateTys) {
  1676. assert(VTy->getElementType() == CommonEltTy &&
  1677. "Unaccounted for element type!");
  1678. assert(VTy == CandidateTys[0] &&
  1679. "Different vector types with the same element type!");
  1680. }
  1681. #endif
  1682. CandidateTys.resize(1);
  1683. }
  1684. // Try each vector type, and return the one which works.
  1685. auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
  1686. uint64_t ElementSize =
  1687. DL.getTypeSizeInBits(VTy->getElementType()).getFixedSize();
  1688. // While the definition of LLVM vectors is bitpacked, we don't support sizes
  1689. // that aren't byte sized.
  1690. if (ElementSize % 8)
  1691. return false;
  1692. assert((DL.getTypeSizeInBits(VTy).getFixedSize() % 8) == 0 &&
  1693. "vector size not a multiple of element size?");
  1694. ElementSize /= 8;
  1695. for (const Slice &S : P)
  1696. if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
  1697. return false;
  1698. for (const Slice *S : P.splitSliceTails())
  1699. if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
  1700. return false;
  1701. return true;
  1702. };
  1703. for (VectorType *VTy : CandidateTys)
  1704. if (CheckVectorTypeForPromotion(VTy))
  1705. return VTy;
  1706. return nullptr;
  1707. }
  1708. /// Test whether a slice of an alloca is valid for integer widening.
  1709. ///
  1710. /// This implements the necessary checking for the \c isIntegerWideningViable
  1711. /// test below on a single slice of the alloca.
  1712. static bool isIntegerWideningViableForSlice(const Slice &S,
  1713. uint64_t AllocBeginOffset,
  1714. Type *AllocaTy,
  1715. const DataLayout &DL,
  1716. bool &WholeAllocaOp) {
  1717. uint64_t Size = DL.getTypeStoreSize(AllocaTy).getFixedSize();
  1718. uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
  1719. uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
  1720. // We can't reasonably handle cases where the load or store extends past
  1721. // the end of the alloca's type and into its padding.
  1722. if (RelEnd > Size)
  1723. return false;
  1724. Use *U = S.getUse();
  1725. if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
  1726. if (LI->isVolatile())
  1727. return false;
  1728. // We can't handle loads that extend past the allocated memory.
  1729. if (DL.getTypeStoreSize(LI->getType()).getFixedSize() > Size)
  1730. return false;
  1731. // So far, AllocaSliceRewriter does not support widening split slice tails
  1732. // in rewriteIntegerLoad.
  1733. if (S.beginOffset() < AllocBeginOffset)
  1734. return false;
  1735. // Note that we don't count vector loads or stores as whole-alloca
  1736. // operations which enable integer widening because we would prefer to use
  1737. // vector widening instead.
  1738. if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
  1739. WholeAllocaOp = true;
  1740. if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
  1741. if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedSize())
  1742. return false;
  1743. } else if (RelBegin != 0 || RelEnd != Size ||
  1744. !canConvertValue(DL, AllocaTy, LI->getType())) {
  1745. // Non-integer loads need to be convertible from the alloca type so that
  1746. // they are promotable.
  1747. return false;
  1748. }
  1749. } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
  1750. Type *ValueTy = SI->getValueOperand()->getType();
  1751. if (SI->isVolatile())
  1752. return false;
  1753. // We can't handle stores that extend past the allocated memory.
  1754. if (DL.getTypeStoreSize(ValueTy).getFixedSize() > Size)
  1755. return false;
  1756. // So far, AllocaSliceRewriter does not support widening split slice tails
  1757. // in rewriteIntegerStore.
  1758. if (S.beginOffset() < AllocBeginOffset)
  1759. return false;
  1760. // Note that we don't count vector loads or stores as whole-alloca
  1761. // operations which enable integer widening because we would prefer to use
  1762. // vector widening instead.
  1763. if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
  1764. WholeAllocaOp = true;
  1765. if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
  1766. if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedSize())
  1767. return false;
  1768. } else if (RelBegin != 0 || RelEnd != Size ||
  1769. !canConvertValue(DL, ValueTy, AllocaTy)) {
  1770. // Non-integer stores need to be convertible to the alloca type so that
  1771. // they are promotable.
  1772. return false;
  1773. }
  1774. } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
  1775. if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
  1776. return false;
  1777. if (!S.isSplittable())
  1778. return false; // Skip any unsplittable intrinsics.
  1779. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
  1780. if (!II->isLifetimeStartOrEnd() && !II->isDroppable())
  1781. return false;
  1782. } else {
  1783. return false;
  1784. }
  1785. return true;
  1786. }
  1787. /// Test whether the given alloca partition's integer operations can be
  1788. /// widened to promotable ones.
  1789. ///
  1790. /// This is a quick test to check whether we can rewrite the integer loads and
  1791. /// stores to a particular alloca into wider loads and stores and be able to
  1792. /// promote the resulting alloca.
  1793. static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
  1794. const DataLayout &DL) {
  1795. uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy).getFixedSize();
  1796. // Don't create integer types larger than the maximum bitwidth.
  1797. if (SizeInBits > IntegerType::MAX_INT_BITS)
  1798. return false;
  1799. // Don't try to handle allocas with bit-padding.
  1800. if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy).getFixedSize())
  1801. return false;
  1802. // We need to ensure that an integer type with the appropriate bitwidth can
  1803. // be converted to the alloca type, whatever that is. We don't want to force
  1804. // the alloca itself to have an integer type if there is a more suitable one.
  1805. Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
  1806. if (!canConvertValue(DL, AllocaTy, IntTy) ||
  1807. !canConvertValue(DL, IntTy, AllocaTy))
  1808. return false;
  1809. // While examining uses, we ensure that the alloca has a covering load or
  1810. // store. We don't want to widen the integer operations only to fail to
  1811. // promote due to some other unsplittable entry (which we may make splittable
  1812. // later). However, if there are only splittable uses, go ahead and assume
  1813. // that we cover the alloca.
  1814. // FIXME: We shouldn't consider split slices that happen to start in the
  1815. // partition here...
  1816. bool WholeAllocaOp = P.empty() && DL.isLegalInteger(SizeInBits);
  1817. for (const Slice &S : P)
  1818. if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
  1819. WholeAllocaOp))
  1820. return false;
  1821. for (const Slice *S : P.splitSliceTails())
  1822. if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
  1823. WholeAllocaOp))
  1824. return false;
  1825. return WholeAllocaOp;
  1826. }
  1827. static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
  1828. IntegerType *Ty, uint64_t Offset,
  1829. const Twine &Name) {
  1830. LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
  1831. IntegerType *IntTy = cast<IntegerType>(V->getType());
  1832. assert(DL.getTypeStoreSize(Ty).getFixedSize() + Offset <=
  1833. DL.getTypeStoreSize(IntTy).getFixedSize() &&
  1834. "Element extends past full value");
  1835. uint64_t ShAmt = 8 * Offset;
  1836. if (DL.isBigEndian())
  1837. ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedSize() -
  1838. DL.getTypeStoreSize(Ty).getFixedSize() - Offset);
  1839. if (ShAmt) {
  1840. V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
  1841. LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
  1842. }
  1843. assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
  1844. "Cannot extract to a larger integer!");
  1845. if (Ty != IntTy) {
  1846. V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
  1847. LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n");
  1848. }
  1849. return V;
  1850. }
  1851. static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
  1852. Value *V, uint64_t Offset, const Twine &Name) {
  1853. IntegerType *IntTy = cast<IntegerType>(Old->getType());
  1854. IntegerType *Ty = cast<IntegerType>(V->getType());
  1855. assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
  1856. "Cannot insert a larger integer!");
  1857. LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
  1858. if (Ty != IntTy) {
  1859. V = IRB.CreateZExt(V, IntTy, Name + ".ext");
  1860. LLVM_DEBUG(dbgs() << " extended: " << *V << "\n");
  1861. }
  1862. assert(DL.getTypeStoreSize(Ty).getFixedSize() + Offset <=
  1863. DL.getTypeStoreSize(IntTy).getFixedSize() &&
  1864. "Element store outside of alloca store");
  1865. uint64_t ShAmt = 8 * Offset;
  1866. if (DL.isBigEndian())
  1867. ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedSize() -
  1868. DL.getTypeStoreSize(Ty).getFixedSize() - Offset);
  1869. if (ShAmt) {
  1870. V = IRB.CreateShl(V, ShAmt, Name + ".shift");
  1871. LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
  1872. }
  1873. if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
  1874. APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
  1875. Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
  1876. LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n");
  1877. V = IRB.CreateOr(Old, V, Name + ".insert");
  1878. LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n");
  1879. }
  1880. return V;
  1881. }
  1882. static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
  1883. unsigned EndIndex, const Twine &Name) {
  1884. auto *VecTy = cast<FixedVectorType>(V->getType());
  1885. unsigned NumElements = EndIndex - BeginIndex;
  1886. assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
  1887. if (NumElements == VecTy->getNumElements())
  1888. return V;
  1889. if (NumElements == 1) {
  1890. V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
  1891. Name + ".extract");
  1892. LLVM_DEBUG(dbgs() << " extract: " << *V << "\n");
  1893. return V;
  1894. }
  1895. SmallVector<int, 8> Mask;
  1896. Mask.reserve(NumElements);
  1897. for (unsigned i = BeginIndex; i != EndIndex; ++i)
  1898. Mask.push_back(i);
  1899. V = IRB.CreateShuffleVector(V, Mask, Name + ".extract");
  1900. LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
  1901. return V;
  1902. }
  1903. static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
  1904. unsigned BeginIndex, const Twine &Name) {
  1905. VectorType *VecTy = cast<VectorType>(Old->getType());
  1906. assert(VecTy && "Can only insert a vector into a vector");
  1907. VectorType *Ty = dyn_cast<VectorType>(V->getType());
  1908. if (!Ty) {
  1909. // Single element to insert.
  1910. V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
  1911. Name + ".insert");
  1912. LLVM_DEBUG(dbgs() << " insert: " << *V << "\n");
  1913. return V;
  1914. }
  1915. assert(cast<FixedVectorType>(Ty)->getNumElements() <=
  1916. cast<FixedVectorType>(VecTy)->getNumElements() &&
  1917. "Too many elements!");
  1918. if (cast<FixedVectorType>(Ty)->getNumElements() ==
  1919. cast<FixedVectorType>(VecTy)->getNumElements()) {
  1920. assert(V->getType() == VecTy && "Vector type mismatch");
  1921. return V;
  1922. }
  1923. unsigned EndIndex = BeginIndex + cast<FixedVectorType>(Ty)->getNumElements();
  1924. // When inserting a smaller vector into the larger to store, we first
  1925. // use a shuffle vector to widen it with undef elements, and then
  1926. // a second shuffle vector to select between the loaded vector and the
  1927. // incoming vector.
  1928. SmallVector<int, 8> Mask;
  1929. Mask.reserve(cast<FixedVectorType>(VecTy)->getNumElements());
  1930. for (unsigned i = 0; i != cast<FixedVectorType>(VecTy)->getNumElements(); ++i)
  1931. if (i >= BeginIndex && i < EndIndex)
  1932. Mask.push_back(i - BeginIndex);
  1933. else
  1934. Mask.push_back(-1);
  1935. V = IRB.CreateShuffleVector(V, Mask, Name + ".expand");
  1936. LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
  1937. SmallVector<Constant *, 8> Mask2;
  1938. Mask2.reserve(cast<FixedVectorType>(VecTy)->getNumElements());
  1939. for (unsigned i = 0; i != cast<FixedVectorType>(VecTy)->getNumElements(); ++i)
  1940. Mask2.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
  1941. V = IRB.CreateSelect(ConstantVector::get(Mask2), V, Old, Name + "blend");
  1942. LLVM_DEBUG(dbgs() << " blend: " << *V << "\n");
  1943. return V;
  1944. }
  1945. /// Visitor to rewrite instructions using p particular slice of an alloca
  1946. /// to use a new alloca.
  1947. ///
  1948. /// Also implements the rewriting to vector-based accesses when the partition
  1949. /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
  1950. /// lives here.
  1951. class llvm::sroa::AllocaSliceRewriter
  1952. : public InstVisitor<AllocaSliceRewriter, bool> {
  1953. // Befriend the base class so it can delegate to private visit methods.
  1954. friend class InstVisitor<AllocaSliceRewriter, bool>;
  1955. using Base = InstVisitor<AllocaSliceRewriter, bool>;
  1956. const DataLayout &DL;
  1957. AllocaSlices &AS;
  1958. SROAPass &Pass;
  1959. AllocaInst &OldAI, &NewAI;
  1960. const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
  1961. Type *NewAllocaTy;
  1962. // This is a convenience and flag variable that will be null unless the new
  1963. // alloca's integer operations should be widened to this integer type due to
  1964. // passing isIntegerWideningViable above. If it is non-null, the desired
  1965. // integer type will be stored here for easy access during rewriting.
  1966. IntegerType *IntTy;
  1967. // If we are rewriting an alloca partition which can be written as pure
  1968. // vector operations, we stash extra information here. When VecTy is
  1969. // non-null, we have some strict guarantees about the rewritten alloca:
  1970. // - The new alloca is exactly the size of the vector type here.
  1971. // - The accesses all either map to the entire vector or to a single
  1972. // element.
  1973. // - The set of accessing instructions is only one of those handled above
  1974. // in isVectorPromotionViable. Generally these are the same access kinds
  1975. // which are promotable via mem2reg.
  1976. VectorType *VecTy;
  1977. Type *ElementTy;
  1978. uint64_t ElementSize;
  1979. // The original offset of the slice currently being rewritten relative to
  1980. // the original alloca.
  1981. uint64_t BeginOffset = 0;
  1982. uint64_t EndOffset = 0;
  1983. // The new offsets of the slice currently being rewritten relative to the
  1984. // original alloca.
  1985. uint64_t NewBeginOffset = 0, NewEndOffset = 0;
  1986. uint64_t SliceSize = 0;
  1987. bool IsSplittable = false;
  1988. bool IsSplit = false;
  1989. Use *OldUse = nullptr;
  1990. Instruction *OldPtr = nullptr;
  1991. // Track post-rewrite users which are PHI nodes and Selects.
  1992. SmallSetVector<PHINode *, 8> &PHIUsers;
  1993. SmallSetVector<SelectInst *, 8> &SelectUsers;
  1994. // Utility IR builder, whose name prefix is setup for each visited use, and
  1995. // the insertion point is set to point to the user.
  1996. IRBuilderTy IRB;
  1997. public:
  1998. AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROAPass &Pass,
  1999. AllocaInst &OldAI, AllocaInst &NewAI,
  2000. uint64_t NewAllocaBeginOffset,
  2001. uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
  2002. VectorType *PromotableVecTy,
  2003. SmallSetVector<PHINode *, 8> &PHIUsers,
  2004. SmallSetVector<SelectInst *, 8> &SelectUsers)
  2005. : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
  2006. NewAllocaBeginOffset(NewAllocaBeginOffset),
  2007. NewAllocaEndOffset(NewAllocaEndOffset),
  2008. NewAllocaTy(NewAI.getAllocatedType()),
  2009. IntTy(
  2010. IsIntegerPromotable
  2011. ? Type::getIntNTy(NewAI.getContext(),
  2012. DL.getTypeSizeInBits(NewAI.getAllocatedType())
  2013. .getFixedSize())
  2014. : nullptr),
  2015. VecTy(PromotableVecTy),
  2016. ElementTy(VecTy ? VecTy->getElementType() : nullptr),
  2017. ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy).getFixedSize() / 8
  2018. : 0),
  2019. PHIUsers(PHIUsers), SelectUsers(SelectUsers),
  2020. IRB(NewAI.getContext(), ConstantFolder()) {
  2021. if (VecTy) {
  2022. assert((DL.getTypeSizeInBits(ElementTy).getFixedSize() % 8) == 0 &&
  2023. "Only multiple-of-8 sized vector elements are viable");
  2024. ++NumVectorized;
  2025. }
  2026. assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
  2027. }
  2028. bool visit(AllocaSlices::const_iterator I) {
  2029. bool CanSROA = true;
  2030. BeginOffset = I->beginOffset();
  2031. EndOffset = I->endOffset();
  2032. IsSplittable = I->isSplittable();
  2033. IsSplit =
  2034. BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
  2035. LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
  2036. LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
  2037. LLVM_DEBUG(dbgs() << "\n");
  2038. // Compute the intersecting offset range.
  2039. assert(BeginOffset < NewAllocaEndOffset);
  2040. assert(EndOffset > NewAllocaBeginOffset);
  2041. NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
  2042. NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
  2043. SliceSize = NewEndOffset - NewBeginOffset;
  2044. OldUse = I->getUse();
  2045. OldPtr = cast<Instruction>(OldUse->get());
  2046. Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
  2047. IRB.SetInsertPoint(OldUserI);
  2048. IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
  2049. IRB.getInserter().SetNamePrefix(
  2050. Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
  2051. CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
  2052. if (VecTy || IntTy)
  2053. assert(CanSROA);
  2054. return CanSROA;
  2055. }
  2056. private:
  2057. // Make sure the other visit overloads are visible.
  2058. using Base::visit;
  2059. // Every instruction which can end up as a user must have a rewrite rule.
  2060. bool visitInstruction(Instruction &I) {
  2061. LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
  2062. llvm_unreachable("No rewrite rule for this instruction!");
  2063. }
  2064. Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
  2065. // Note that the offset computation can use BeginOffset or NewBeginOffset
  2066. // interchangeably for unsplit slices.
  2067. assert(IsSplit || BeginOffset == NewBeginOffset);
  2068. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2069. #ifndef NDEBUG
  2070. StringRef OldName = OldPtr->getName();
  2071. // Skip through the last '.sroa.' component of the name.
  2072. size_t LastSROAPrefix = OldName.rfind(".sroa.");
  2073. if (LastSROAPrefix != StringRef::npos) {
  2074. OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
  2075. // Look for an SROA slice index.
  2076. size_t IndexEnd = OldName.find_first_not_of("0123456789");
  2077. if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
  2078. // Strip the index and look for the offset.
  2079. OldName = OldName.substr(IndexEnd + 1);
  2080. size_t OffsetEnd = OldName.find_first_not_of("0123456789");
  2081. if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
  2082. // Strip the offset.
  2083. OldName = OldName.substr(OffsetEnd + 1);
  2084. }
  2085. }
  2086. // Strip any SROA suffixes as well.
  2087. OldName = OldName.substr(0, OldName.find(".sroa_"));
  2088. #endif
  2089. return getAdjustedPtr(IRB, DL, &NewAI,
  2090. APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
  2091. PointerTy,
  2092. #ifndef NDEBUG
  2093. Twine(OldName) + "."
  2094. #else
  2095. Twine()
  2096. #endif
  2097. );
  2098. }
  2099. /// Compute suitable alignment to access this slice of the *new*
  2100. /// alloca.
  2101. ///
  2102. /// You can optionally pass a type to this routine and if that type's ABI
  2103. /// alignment is itself suitable, this will return zero.
  2104. Align getSliceAlign() {
  2105. return commonAlignment(NewAI.getAlign(),
  2106. NewBeginOffset - NewAllocaBeginOffset);
  2107. }
  2108. unsigned getIndex(uint64_t Offset) {
  2109. assert(VecTy && "Can only call getIndex when rewriting a vector");
  2110. uint64_t RelOffset = Offset - NewAllocaBeginOffset;
  2111. assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
  2112. uint32_t Index = RelOffset / ElementSize;
  2113. assert(Index * ElementSize == RelOffset);
  2114. return Index;
  2115. }
  2116. void deleteIfTriviallyDead(Value *V) {
  2117. Instruction *I = cast<Instruction>(V);
  2118. if (isInstructionTriviallyDead(I))
  2119. Pass.DeadInsts.push_back(I);
  2120. }
  2121. Value *rewriteVectorizedLoadInst(LoadInst &LI) {
  2122. unsigned BeginIndex = getIndex(NewBeginOffset);
  2123. unsigned EndIndex = getIndex(NewEndOffset);
  2124. assert(EndIndex > BeginIndex && "Empty vector!");
  2125. LoadInst *Load = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2126. NewAI.getAlign(), "load");
  2127. Load->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
  2128. LLVMContext::MD_access_group});
  2129. return extractVector(IRB, Load, BeginIndex, EndIndex, "vec");
  2130. }
  2131. Value *rewriteIntegerLoad(LoadInst &LI) {
  2132. assert(IntTy && "We cannot insert an integer to the alloca");
  2133. assert(!LI.isVolatile());
  2134. Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2135. NewAI.getAlign(), "load");
  2136. V = convertValue(DL, IRB, V, IntTy);
  2137. assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
  2138. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2139. if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
  2140. IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
  2141. V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
  2142. }
  2143. // It is possible that the extracted type is not the load type. This
  2144. // happens if there is a load past the end of the alloca, and as
  2145. // a consequence the slice is narrower but still a candidate for integer
  2146. // lowering. To handle this case, we just zero extend the extracted
  2147. // integer.
  2148. assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
  2149. "Can only handle an extract for an overly wide load");
  2150. if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
  2151. V = IRB.CreateZExt(V, LI.getType());
  2152. return V;
  2153. }
  2154. bool visitLoadInst(LoadInst &LI) {
  2155. LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
  2156. Value *OldOp = LI.getOperand(0);
  2157. assert(OldOp == OldPtr);
  2158. AAMDNodes AATags = LI.getAAMetadata();
  2159. unsigned AS = LI.getPointerAddressSpace();
  2160. Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
  2161. : LI.getType();
  2162. const bool IsLoadPastEnd =
  2163. DL.getTypeStoreSize(TargetTy).getFixedSize() > SliceSize;
  2164. bool IsPtrAdjusted = false;
  2165. Value *V;
  2166. if (VecTy) {
  2167. V = rewriteVectorizedLoadInst(LI);
  2168. } else if (IntTy && LI.getType()->isIntegerTy()) {
  2169. V = rewriteIntegerLoad(LI);
  2170. } else if (NewBeginOffset == NewAllocaBeginOffset &&
  2171. NewEndOffset == NewAllocaEndOffset &&
  2172. (canConvertValue(DL, NewAllocaTy, TargetTy) ||
  2173. (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
  2174. TargetTy->isIntegerTy()))) {
  2175. LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2176. NewAI.getAlign(), LI.isVolatile(),
  2177. LI.getName());
  2178. if (AATags)
  2179. NewLI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
  2180. if (LI.isVolatile())
  2181. NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
  2182. if (NewLI->isAtomic())
  2183. NewLI->setAlignment(LI.getAlign());
  2184. // Any !nonnull metadata or !range metadata on the old load is also valid
  2185. // on the new load. This is even true in some cases even when the loads
  2186. // are different types, for example by mapping !nonnull metadata to
  2187. // !range metadata by modeling the null pointer constant converted to the
  2188. // integer type.
  2189. // FIXME: Add support for range metadata here. Currently the utilities
  2190. // for this don't propagate range metadata in trivial cases from one
  2191. // integer load to another, don't handle non-addrspace-0 null pointers
  2192. // correctly, and don't have any support for mapping ranges as the
  2193. // integer type becomes winder or narrower.
  2194. if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
  2195. copyNonnullMetadata(LI, N, *NewLI);
  2196. // Try to preserve nonnull metadata
  2197. V = NewLI;
  2198. // If this is an integer load past the end of the slice (which means the
  2199. // bytes outside the slice are undef or this load is dead) just forcibly
  2200. // fix the integer size with correct handling of endianness.
  2201. if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
  2202. if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
  2203. if (AITy->getBitWidth() < TITy->getBitWidth()) {
  2204. V = IRB.CreateZExt(V, TITy, "load.ext");
  2205. if (DL.isBigEndian())
  2206. V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
  2207. "endian_shift");
  2208. }
  2209. } else {
  2210. Type *LTy = TargetTy->getPointerTo(AS);
  2211. LoadInst *NewLI =
  2212. IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy),
  2213. getSliceAlign(), LI.isVolatile(), LI.getName());
  2214. if (AATags)
  2215. NewLI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
  2216. if (LI.isVolatile())
  2217. NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
  2218. NewLI->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
  2219. LLVMContext::MD_access_group});
  2220. V = NewLI;
  2221. IsPtrAdjusted = true;
  2222. }
  2223. V = convertValue(DL, IRB, V, TargetTy);
  2224. if (IsSplit) {
  2225. assert(!LI.isVolatile());
  2226. assert(LI.getType()->isIntegerTy() &&
  2227. "Only integer type loads and stores are split");
  2228. assert(SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedSize() &&
  2229. "Split load isn't smaller than original load");
  2230. assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
  2231. "Non-byte-multiple bit width");
  2232. // Move the insertion point just past the load so that we can refer to it.
  2233. IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
  2234. // Create a placeholder value with the same type as LI to use as the
  2235. // basis for the new value. This allows us to replace the uses of LI with
  2236. // the computed value, and then replace the placeholder with LI, leaving
  2237. // LI only used for this computation.
  2238. Value *Placeholder = new LoadInst(
  2239. LI.getType(), PoisonValue::get(LI.getType()->getPointerTo(AS)), "",
  2240. false, Align(1));
  2241. V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
  2242. "insert");
  2243. LI.replaceAllUsesWith(V);
  2244. Placeholder->replaceAllUsesWith(&LI);
  2245. Placeholder->deleteValue();
  2246. } else {
  2247. LI.replaceAllUsesWith(V);
  2248. }
  2249. Pass.DeadInsts.push_back(&LI);
  2250. deleteIfTriviallyDead(OldOp);
  2251. LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
  2252. return !LI.isVolatile() && !IsPtrAdjusted;
  2253. }
  2254. bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
  2255. AAMDNodes AATags) {
  2256. if (V->getType() != VecTy) {
  2257. unsigned BeginIndex = getIndex(NewBeginOffset);
  2258. unsigned EndIndex = getIndex(NewEndOffset);
  2259. assert(EndIndex > BeginIndex && "Empty vector!");
  2260. unsigned NumElements = EndIndex - BeginIndex;
  2261. assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
  2262. "Too many elements!");
  2263. Type *SliceTy = (NumElements == 1)
  2264. ? ElementTy
  2265. : FixedVectorType::get(ElementTy, NumElements);
  2266. if (V->getType() != SliceTy)
  2267. V = convertValue(DL, IRB, V, SliceTy);
  2268. // Mix in the existing elements.
  2269. Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2270. NewAI.getAlign(), "load");
  2271. V = insertVector(IRB, Old, V, BeginIndex, "vec");
  2272. }
  2273. StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
  2274. Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
  2275. LLVMContext::MD_access_group});
  2276. if (AATags)
  2277. Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
  2278. Pass.DeadInsts.push_back(&SI);
  2279. LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
  2280. return true;
  2281. }
  2282. bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
  2283. assert(IntTy && "We cannot extract an integer from the alloca");
  2284. assert(!SI.isVolatile());
  2285. if (DL.getTypeSizeInBits(V->getType()).getFixedSize() !=
  2286. IntTy->getBitWidth()) {
  2287. Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2288. NewAI.getAlign(), "oldload");
  2289. Old = convertValue(DL, IRB, Old, IntTy);
  2290. assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
  2291. uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
  2292. V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
  2293. }
  2294. V = convertValue(DL, IRB, V, NewAllocaTy);
  2295. StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign());
  2296. Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
  2297. LLVMContext::MD_access_group});
  2298. if (AATags)
  2299. Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
  2300. Pass.DeadInsts.push_back(&SI);
  2301. LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
  2302. return true;
  2303. }
  2304. bool visitStoreInst(StoreInst &SI) {
  2305. LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
  2306. Value *OldOp = SI.getOperand(1);
  2307. assert(OldOp == OldPtr);
  2308. AAMDNodes AATags = SI.getAAMetadata();
  2309. Value *V = SI.getValueOperand();
  2310. // Strip all inbounds GEPs and pointer casts to try to dig out any root
  2311. // alloca that should be re-examined after promoting this alloca.
  2312. if (V->getType()->isPointerTy())
  2313. if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
  2314. Pass.PostPromotionWorklist.insert(AI);
  2315. if (SliceSize < DL.getTypeStoreSize(V->getType()).getFixedSize()) {
  2316. assert(!SI.isVolatile());
  2317. assert(V->getType()->isIntegerTy() &&
  2318. "Only integer type loads and stores are split");
  2319. assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
  2320. "Non-byte-multiple bit width");
  2321. IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
  2322. V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
  2323. "extract");
  2324. }
  2325. if (VecTy)
  2326. return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
  2327. if (IntTy && V->getType()->isIntegerTy())
  2328. return rewriteIntegerStore(V, SI, AATags);
  2329. const bool IsStorePastEnd =
  2330. DL.getTypeStoreSize(V->getType()).getFixedSize() > SliceSize;
  2331. StoreInst *NewSI;
  2332. if (NewBeginOffset == NewAllocaBeginOffset &&
  2333. NewEndOffset == NewAllocaEndOffset &&
  2334. (canConvertValue(DL, V->getType(), NewAllocaTy) ||
  2335. (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
  2336. V->getType()->isIntegerTy()))) {
  2337. // If this is an integer store past the end of slice (and thus the bytes
  2338. // past that point are irrelevant or this is unreachable), truncate the
  2339. // value prior to storing.
  2340. if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
  2341. if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
  2342. if (VITy->getBitWidth() > AITy->getBitWidth()) {
  2343. if (DL.isBigEndian())
  2344. V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
  2345. "endian_shift");
  2346. V = IRB.CreateTrunc(V, AITy, "load.trunc");
  2347. }
  2348. V = convertValue(DL, IRB, V, NewAllocaTy);
  2349. NewSI =
  2350. IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign(), SI.isVolatile());
  2351. } else {
  2352. unsigned AS = SI.getPointerAddressSpace();
  2353. Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
  2354. NewSI =
  2355. IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(), SI.isVolatile());
  2356. }
  2357. NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
  2358. LLVMContext::MD_access_group});
  2359. if (AATags)
  2360. NewSI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
  2361. if (SI.isVolatile())
  2362. NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
  2363. if (NewSI->isAtomic())
  2364. NewSI->setAlignment(SI.getAlign());
  2365. Pass.DeadInsts.push_back(&SI);
  2366. deleteIfTriviallyDead(OldOp);
  2367. LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
  2368. return NewSI->getPointerOperand() == &NewAI &&
  2369. NewSI->getValueOperand()->getType() == NewAllocaTy &&
  2370. !SI.isVolatile();
  2371. }
  2372. /// Compute an integer value from splatting an i8 across the given
  2373. /// number of bytes.
  2374. ///
  2375. /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
  2376. /// call this routine.
  2377. /// FIXME: Heed the advice above.
  2378. ///
  2379. /// \param V The i8 value to splat.
  2380. /// \param Size The number of bytes in the output (assuming i8 is one byte)
  2381. Value *getIntegerSplat(Value *V, unsigned Size) {
  2382. assert(Size > 0 && "Expected a positive number of bytes.");
  2383. IntegerType *VTy = cast<IntegerType>(V->getType());
  2384. assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
  2385. if (Size == 1)
  2386. return V;
  2387. Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
  2388. V = IRB.CreateMul(
  2389. IRB.CreateZExt(V, SplatIntTy, "zext"),
  2390. ConstantExpr::getUDiv(
  2391. Constant::getAllOnesValue(SplatIntTy),
  2392. ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
  2393. SplatIntTy)),
  2394. "isplat");
  2395. return V;
  2396. }
  2397. /// Compute a vector splat for a given element value.
  2398. Value *getVectorSplat(Value *V, unsigned NumElements) {
  2399. V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
  2400. LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
  2401. return V;
  2402. }
  2403. bool visitMemSetInst(MemSetInst &II) {
  2404. LLVM_DEBUG(dbgs() << " original: " << II << "\n");
  2405. assert(II.getRawDest() == OldPtr);
  2406. AAMDNodes AATags = II.getAAMetadata();
  2407. // If the memset has a variable size, it cannot be split, just adjust the
  2408. // pointer to the new alloca.
  2409. if (!isa<ConstantInt>(II.getLength())) {
  2410. assert(!IsSplit);
  2411. assert(NewBeginOffset == BeginOffset);
  2412. II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
  2413. II.setDestAlignment(getSliceAlign());
  2414. deleteIfTriviallyDead(OldPtr);
  2415. return false;
  2416. }
  2417. // Record this instruction for deletion.
  2418. Pass.DeadInsts.push_back(&II);
  2419. Type *AllocaTy = NewAI.getAllocatedType();
  2420. Type *ScalarTy = AllocaTy->getScalarType();
  2421. const bool CanContinue = [&]() {
  2422. if (VecTy || IntTy)
  2423. return true;
  2424. if (BeginOffset > NewAllocaBeginOffset ||
  2425. EndOffset < NewAllocaEndOffset)
  2426. return false;
  2427. // Length must be in range for FixedVectorType.
  2428. auto *C = cast<ConstantInt>(II.getLength());
  2429. const uint64_t Len = C->getLimitedValue();
  2430. if (Len > std::numeric_limits<unsigned>::max())
  2431. return false;
  2432. auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
  2433. auto *SrcTy = FixedVectorType::get(Int8Ty, Len);
  2434. return canConvertValue(DL, SrcTy, AllocaTy) &&
  2435. DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy).getFixedSize());
  2436. }();
  2437. // If this doesn't map cleanly onto the alloca type, and that type isn't
  2438. // a single value type, just emit a memset.
  2439. if (!CanContinue) {
  2440. Type *SizeTy = II.getLength()->getType();
  2441. Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
  2442. CallInst *New = IRB.CreateMemSet(
  2443. getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
  2444. MaybeAlign(getSliceAlign()), II.isVolatile());
  2445. if (AATags)
  2446. New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
  2447. LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
  2448. return false;
  2449. }
  2450. // If we can represent this as a simple value, we have to build the actual
  2451. // value to store, which requires expanding the byte present in memset to
  2452. // a sensible representation for the alloca type. This is essentially
  2453. // splatting the byte to a sufficiently wide integer, splatting it across
  2454. // any desired vector width, and bitcasting to the final type.
  2455. Value *V;
  2456. if (VecTy) {
  2457. // If this is a memset of a vectorized alloca, insert it.
  2458. assert(ElementTy == ScalarTy);
  2459. unsigned BeginIndex = getIndex(NewBeginOffset);
  2460. unsigned EndIndex = getIndex(NewEndOffset);
  2461. assert(EndIndex > BeginIndex && "Empty vector!");
  2462. unsigned NumElements = EndIndex - BeginIndex;
  2463. assert(NumElements <= cast<FixedVectorType>(VecTy)->getNumElements() &&
  2464. "Too many elements!");
  2465. Value *Splat = getIntegerSplat(
  2466. II.getValue(), DL.getTypeSizeInBits(ElementTy).getFixedSize() / 8);
  2467. Splat = convertValue(DL, IRB, Splat, ElementTy);
  2468. if (NumElements > 1)
  2469. Splat = getVectorSplat(Splat, NumElements);
  2470. Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2471. NewAI.getAlign(), "oldload");
  2472. V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
  2473. } else if (IntTy) {
  2474. // If this is a memset on an alloca where we can widen stores, insert the
  2475. // set integer.
  2476. assert(!II.isVolatile());
  2477. uint64_t Size = NewEndOffset - NewBeginOffset;
  2478. V = getIntegerSplat(II.getValue(), Size);
  2479. if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
  2480. EndOffset != NewAllocaBeginOffset)) {
  2481. Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2482. NewAI.getAlign(), "oldload");
  2483. Old = convertValue(DL, IRB, Old, IntTy);
  2484. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2485. V = insertInteger(DL, IRB, Old, V, Offset, "insert");
  2486. } else {
  2487. assert(V->getType() == IntTy &&
  2488. "Wrong type for an alloca wide integer!");
  2489. }
  2490. V = convertValue(DL, IRB, V, AllocaTy);
  2491. } else {
  2492. // Established these invariants above.
  2493. assert(NewBeginOffset == NewAllocaBeginOffset);
  2494. assert(NewEndOffset == NewAllocaEndOffset);
  2495. V = getIntegerSplat(II.getValue(),
  2496. DL.getTypeSizeInBits(ScalarTy).getFixedSize() / 8);
  2497. if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
  2498. V = getVectorSplat(
  2499. V, cast<FixedVectorType>(AllocaVecTy)->getNumElements());
  2500. V = convertValue(DL, IRB, V, AllocaTy);
  2501. }
  2502. StoreInst *New =
  2503. IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign(), II.isVolatile());
  2504. New->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
  2505. LLVMContext::MD_access_group});
  2506. if (AATags)
  2507. New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
  2508. LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
  2509. return !II.isVolatile();
  2510. }
  2511. bool visitMemTransferInst(MemTransferInst &II) {
  2512. // Rewriting of memory transfer instructions can be a bit tricky. We break
  2513. // them into two categories: split intrinsics and unsplit intrinsics.
  2514. LLVM_DEBUG(dbgs() << " original: " << II << "\n");
  2515. AAMDNodes AATags = II.getAAMetadata();
  2516. bool IsDest = &II.getRawDestUse() == OldUse;
  2517. assert((IsDest && II.getRawDest() == OldPtr) ||
  2518. (!IsDest && II.getRawSource() == OldPtr));
  2519. MaybeAlign SliceAlign = getSliceAlign();
  2520. // For unsplit intrinsics, we simply modify the source and destination
  2521. // pointers in place. This isn't just an optimization, it is a matter of
  2522. // correctness. With unsplit intrinsics we may be dealing with transfers
  2523. // within a single alloca before SROA ran, or with transfers that have
  2524. // a variable length. We may also be dealing with memmove instead of
  2525. // memcpy, and so simply updating the pointers is the necessary for us to
  2526. // update both source and dest of a single call.
  2527. if (!IsSplittable) {
  2528. Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2529. if (IsDest) {
  2530. II.setDest(AdjustedPtr);
  2531. II.setDestAlignment(SliceAlign);
  2532. }
  2533. else {
  2534. II.setSource(AdjustedPtr);
  2535. II.setSourceAlignment(SliceAlign);
  2536. }
  2537. LLVM_DEBUG(dbgs() << " to: " << II << "\n");
  2538. deleteIfTriviallyDead(OldPtr);
  2539. return false;
  2540. }
  2541. // For split transfer intrinsics we have an incredibly useful assurance:
  2542. // the source and destination do not reside within the same alloca, and at
  2543. // least one of them does not escape. This means that we can replace
  2544. // memmove with memcpy, and we don't need to worry about all manner of
  2545. // downsides to splitting and transforming the operations.
  2546. // If this doesn't map cleanly onto the alloca type, and that type isn't
  2547. // a single value type, just emit a memcpy.
  2548. bool EmitMemCpy =
  2549. !VecTy && !IntTy &&
  2550. (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
  2551. SliceSize !=
  2552. DL.getTypeStoreSize(NewAI.getAllocatedType()).getFixedSize() ||
  2553. !NewAI.getAllocatedType()->isSingleValueType());
  2554. // If we're just going to emit a memcpy, the alloca hasn't changed, and the
  2555. // size hasn't been shrunk based on analysis of the viable range, this is
  2556. // a no-op.
  2557. if (EmitMemCpy && &OldAI == &NewAI) {
  2558. // Ensure the start lines up.
  2559. assert(NewBeginOffset == BeginOffset);
  2560. // Rewrite the size as needed.
  2561. if (NewEndOffset != EndOffset)
  2562. II.setLength(ConstantInt::get(II.getLength()->getType(),
  2563. NewEndOffset - NewBeginOffset));
  2564. return false;
  2565. }
  2566. // Record this instruction for deletion.
  2567. Pass.DeadInsts.push_back(&II);
  2568. // Strip all inbounds GEPs and pointer casts to try to dig out any root
  2569. // alloca that should be re-examined after rewriting this instruction.
  2570. Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
  2571. if (AllocaInst *AI =
  2572. dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
  2573. assert(AI != &OldAI && AI != &NewAI &&
  2574. "Splittable transfers cannot reach the same alloca on both ends.");
  2575. Pass.Worklist.insert(AI);
  2576. }
  2577. Type *OtherPtrTy = OtherPtr->getType();
  2578. unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
  2579. // Compute the relative offset for the other pointer within the transfer.
  2580. unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
  2581. APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
  2582. Align OtherAlign =
  2583. (IsDest ? II.getSourceAlign() : II.getDestAlign()).valueOrOne();
  2584. OtherAlign =
  2585. commonAlignment(OtherAlign, OtherOffset.zextOrTrunc(64).getZExtValue());
  2586. if (EmitMemCpy) {
  2587. // Compute the other pointer, folding as much as possible to produce
  2588. // a single, simple GEP in most cases.
  2589. OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
  2590. OtherPtr->getName() + ".");
  2591. Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2592. Type *SizeTy = II.getLength()->getType();
  2593. Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
  2594. Value *DestPtr, *SrcPtr;
  2595. MaybeAlign DestAlign, SrcAlign;
  2596. // Note: IsDest is true iff we're copying into the new alloca slice
  2597. if (IsDest) {
  2598. DestPtr = OurPtr;
  2599. DestAlign = SliceAlign;
  2600. SrcPtr = OtherPtr;
  2601. SrcAlign = OtherAlign;
  2602. } else {
  2603. DestPtr = OtherPtr;
  2604. DestAlign = OtherAlign;
  2605. SrcPtr = OurPtr;
  2606. SrcAlign = SliceAlign;
  2607. }
  2608. CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
  2609. Size, II.isVolatile());
  2610. if (AATags)
  2611. New->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
  2612. LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
  2613. return false;
  2614. }
  2615. bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
  2616. NewEndOffset == NewAllocaEndOffset;
  2617. uint64_t Size = NewEndOffset - NewBeginOffset;
  2618. unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
  2619. unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
  2620. unsigned NumElements = EndIndex - BeginIndex;
  2621. IntegerType *SubIntTy =
  2622. IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
  2623. // Reset the other pointer type to match the register type we're going to
  2624. // use, but using the address space of the original other pointer.
  2625. Type *OtherTy;
  2626. if (VecTy && !IsWholeAlloca) {
  2627. if (NumElements == 1)
  2628. OtherTy = VecTy->getElementType();
  2629. else
  2630. OtherTy = FixedVectorType::get(VecTy->getElementType(), NumElements);
  2631. } else if (IntTy && !IsWholeAlloca) {
  2632. OtherTy = SubIntTy;
  2633. } else {
  2634. OtherTy = NewAllocaTy;
  2635. }
  2636. OtherPtrTy = OtherTy->getPointerTo(OtherAS);
  2637. Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
  2638. OtherPtr->getName() + ".");
  2639. MaybeAlign SrcAlign = OtherAlign;
  2640. Value *DstPtr = &NewAI;
  2641. MaybeAlign DstAlign = SliceAlign;
  2642. if (!IsDest) {
  2643. std::swap(SrcPtr, DstPtr);
  2644. std::swap(SrcAlign, DstAlign);
  2645. }
  2646. Value *Src;
  2647. if (VecTy && !IsWholeAlloca && !IsDest) {
  2648. Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2649. NewAI.getAlign(), "load");
  2650. Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
  2651. } else if (IntTy && !IsWholeAlloca && !IsDest) {
  2652. Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2653. NewAI.getAlign(), "load");
  2654. Src = convertValue(DL, IRB, Src, IntTy);
  2655. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2656. Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
  2657. } else {
  2658. LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
  2659. II.isVolatile(), "copyload");
  2660. Load->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
  2661. LLVMContext::MD_access_group});
  2662. if (AATags)
  2663. Load->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
  2664. Src = Load;
  2665. }
  2666. if (VecTy && !IsWholeAlloca && IsDest) {
  2667. Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2668. NewAI.getAlign(), "oldload");
  2669. Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
  2670. } else if (IntTy && !IsWholeAlloca && IsDest) {
  2671. Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
  2672. NewAI.getAlign(), "oldload");
  2673. Old = convertValue(DL, IRB, Old, IntTy);
  2674. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2675. Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
  2676. Src = convertValue(DL, IRB, Src, NewAllocaTy);
  2677. }
  2678. StoreInst *Store = cast<StoreInst>(
  2679. IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
  2680. Store->copyMetadata(II, {LLVMContext::MD_mem_parallel_loop_access,
  2681. LLVMContext::MD_access_group});
  2682. if (AATags)
  2683. Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
  2684. LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
  2685. return !II.isVolatile();
  2686. }
  2687. bool visitIntrinsicInst(IntrinsicInst &II) {
  2688. assert((II.isLifetimeStartOrEnd() || II.isDroppable()) &&
  2689. "Unexpected intrinsic!");
  2690. LLVM_DEBUG(dbgs() << " original: " << II << "\n");
  2691. // Record this instruction for deletion.
  2692. Pass.DeadInsts.push_back(&II);
  2693. if (II.isDroppable()) {
  2694. assert(II.getIntrinsicID() == Intrinsic::assume && "Expected assume");
  2695. // TODO For now we forget assumed information, this can be improved.
  2696. OldPtr->dropDroppableUsesIn(II);
  2697. return true;
  2698. }
  2699. assert(II.getArgOperand(1) == OldPtr);
  2700. // Lifetime intrinsics are only promotable if they cover the whole alloca.
  2701. // Therefore, we drop lifetime intrinsics which don't cover the whole
  2702. // alloca.
  2703. // (In theory, intrinsics which partially cover an alloca could be
  2704. // promoted, but PromoteMemToReg doesn't handle that case.)
  2705. // FIXME: Check whether the alloca is promotable before dropping the
  2706. // lifetime intrinsics?
  2707. if (NewBeginOffset != NewAllocaBeginOffset ||
  2708. NewEndOffset != NewAllocaEndOffset)
  2709. return true;
  2710. ConstantInt *Size =
  2711. ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
  2712. NewEndOffset - NewBeginOffset);
  2713. // Lifetime intrinsics always expect an i8* so directly get such a pointer
  2714. // for the new alloca slice.
  2715. Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace());
  2716. Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
  2717. Value *New;
  2718. if (II.getIntrinsicID() == Intrinsic::lifetime_start)
  2719. New = IRB.CreateLifetimeStart(Ptr, Size);
  2720. else
  2721. New = IRB.CreateLifetimeEnd(Ptr, Size);
  2722. (void)New;
  2723. LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
  2724. return true;
  2725. }
  2726. void fixLoadStoreAlign(Instruction &Root) {
  2727. // This algorithm implements the same visitor loop as
  2728. // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
  2729. // or store found.
  2730. SmallPtrSet<Instruction *, 4> Visited;
  2731. SmallVector<Instruction *, 4> Uses;
  2732. Visited.insert(&Root);
  2733. Uses.push_back(&Root);
  2734. do {
  2735. Instruction *I = Uses.pop_back_val();
  2736. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  2737. LI->setAlignment(std::min(LI->getAlign(), getSliceAlign()));
  2738. continue;
  2739. }
  2740. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  2741. SI->setAlignment(std::min(SI->getAlign(), getSliceAlign()));
  2742. continue;
  2743. }
  2744. assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) ||
  2745. isa<PHINode>(I) || isa<SelectInst>(I) ||
  2746. isa<GetElementPtrInst>(I));
  2747. for (User *U : I->users())
  2748. if (Visited.insert(cast<Instruction>(U)).second)
  2749. Uses.push_back(cast<Instruction>(U));
  2750. } while (!Uses.empty());
  2751. }
  2752. bool visitPHINode(PHINode &PN) {
  2753. LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
  2754. assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
  2755. assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
  2756. // We would like to compute a new pointer in only one place, but have it be
  2757. // as local as possible to the PHI. To do that, we re-use the location of
  2758. // the old pointer, which necessarily must be in the right position to
  2759. // dominate the PHI.
  2760. IRBuilderBase::InsertPointGuard Guard(IRB);
  2761. if (isa<PHINode>(OldPtr))
  2762. IRB.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
  2763. else
  2764. IRB.SetInsertPoint(OldPtr);
  2765. IRB.SetCurrentDebugLocation(OldPtr->getDebugLoc());
  2766. Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2767. // Replace the operands which were using the old pointer.
  2768. std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
  2769. LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
  2770. deleteIfTriviallyDead(OldPtr);
  2771. // Fix the alignment of any loads or stores using this PHI node.
  2772. fixLoadStoreAlign(PN);
  2773. // PHIs can't be promoted on their own, but often can be speculated. We
  2774. // check the speculation outside of the rewriter so that we see the
  2775. // fully-rewritten alloca.
  2776. PHIUsers.insert(&PN);
  2777. return true;
  2778. }
  2779. bool visitSelectInst(SelectInst &SI) {
  2780. LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
  2781. assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
  2782. "Pointer isn't an operand!");
  2783. assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
  2784. assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
  2785. Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2786. // Replace the operands which were using the old pointer.
  2787. if (SI.getOperand(1) == OldPtr)
  2788. SI.setOperand(1, NewPtr);
  2789. if (SI.getOperand(2) == OldPtr)
  2790. SI.setOperand(2, NewPtr);
  2791. LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
  2792. deleteIfTriviallyDead(OldPtr);
  2793. // Fix the alignment of any loads or stores using this select.
  2794. fixLoadStoreAlign(SI);
  2795. // Selects can't be promoted on their own, but often can be speculated. We
  2796. // check the speculation outside of the rewriter so that we see the
  2797. // fully-rewritten alloca.
  2798. SelectUsers.insert(&SI);
  2799. return true;
  2800. }
  2801. };
  2802. namespace {
  2803. /// Visitor to rewrite aggregate loads and stores as scalar.
  2804. ///
  2805. /// This pass aggressively rewrites all aggregate loads and stores on
  2806. /// a particular pointer (or any pointer derived from it which we can identify)
  2807. /// with scalar loads and stores.
  2808. class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
  2809. // Befriend the base class so it can delegate to private visit methods.
  2810. friend class InstVisitor<AggLoadStoreRewriter, bool>;
  2811. /// Queue of pointer uses to analyze and potentially rewrite.
  2812. SmallVector<Use *, 8> Queue;
  2813. /// Set to prevent us from cycling with phi nodes and loops.
  2814. SmallPtrSet<User *, 8> Visited;
  2815. /// The current pointer use being rewritten. This is used to dig up the used
  2816. /// value (as opposed to the user).
  2817. Use *U = nullptr;
  2818. /// Used to calculate offsets, and hence alignment, of subobjects.
  2819. const DataLayout &DL;
  2820. IRBuilderTy &IRB;
  2821. public:
  2822. AggLoadStoreRewriter(const DataLayout &DL, IRBuilderTy &IRB)
  2823. : DL(DL), IRB(IRB) {}
  2824. /// Rewrite loads and stores through a pointer and all pointers derived from
  2825. /// it.
  2826. bool rewrite(Instruction &I) {
  2827. LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
  2828. enqueueUsers(I);
  2829. bool Changed = false;
  2830. while (!Queue.empty()) {
  2831. U = Queue.pop_back_val();
  2832. Changed |= visit(cast<Instruction>(U->getUser()));
  2833. }
  2834. return Changed;
  2835. }
  2836. private:
  2837. /// Enqueue all the users of the given instruction for further processing.
  2838. /// This uses a set to de-duplicate users.
  2839. void enqueueUsers(Instruction &I) {
  2840. for (Use &U : I.uses())
  2841. if (Visited.insert(U.getUser()).second)
  2842. Queue.push_back(&U);
  2843. }
  2844. // Conservative default is to not rewrite anything.
  2845. bool visitInstruction(Instruction &I) { return false; }
  2846. /// Generic recursive split emission class.
  2847. template <typename Derived> class OpSplitter {
  2848. protected:
  2849. /// The builder used to form new instructions.
  2850. IRBuilderTy &IRB;
  2851. /// The indices which to be used with insert- or extractvalue to select the
  2852. /// appropriate value within the aggregate.
  2853. SmallVector<unsigned, 4> Indices;
  2854. /// The indices to a GEP instruction which will move Ptr to the correct slot
  2855. /// within the aggregate.
  2856. SmallVector<Value *, 4> GEPIndices;
  2857. /// The base pointer of the original op, used as a base for GEPing the
  2858. /// split operations.
  2859. Value *Ptr;
  2860. /// The base pointee type being GEPed into.
  2861. Type *BaseTy;
  2862. /// Known alignment of the base pointer.
  2863. Align BaseAlign;
  2864. /// To calculate offset of each component so we can correctly deduce
  2865. /// alignments.
  2866. const DataLayout &DL;
  2867. /// Initialize the splitter with an insertion point, Ptr and start with a
  2868. /// single zero GEP index.
  2869. OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
  2870. Align BaseAlign, const DataLayout &DL, IRBuilderTy &IRB)
  2871. : IRB(IRB), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr), BaseTy(BaseTy),
  2872. BaseAlign(BaseAlign), DL(DL) {
  2873. IRB.SetInsertPoint(InsertionPoint);
  2874. }
  2875. public:
  2876. /// Generic recursive split emission routine.
  2877. ///
  2878. /// This method recursively splits an aggregate op (load or store) into
  2879. /// scalar or vector ops. It splits recursively until it hits a single value
  2880. /// and emits that single value operation via the template argument.
  2881. ///
  2882. /// The logic of this routine relies on GEPs and insertvalue and
  2883. /// extractvalue all operating with the same fundamental index list, merely
  2884. /// formatted differently (GEPs need actual values).
  2885. ///
  2886. /// \param Ty The type being split recursively into smaller ops.
  2887. /// \param Agg The aggregate value being built up or stored, depending on
  2888. /// whether this is splitting a load or a store respectively.
  2889. void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
  2890. if (Ty->isSingleValueType()) {
  2891. unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
  2892. return static_cast<Derived *>(this)->emitFunc(
  2893. Ty, Agg, commonAlignment(BaseAlign, Offset), Name);
  2894. }
  2895. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  2896. unsigned OldSize = Indices.size();
  2897. (void)OldSize;
  2898. for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
  2899. ++Idx) {
  2900. assert(Indices.size() == OldSize && "Did not return to the old size");
  2901. Indices.push_back(Idx);
  2902. GEPIndices.push_back(IRB.getInt32(Idx));
  2903. emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
  2904. GEPIndices.pop_back();
  2905. Indices.pop_back();
  2906. }
  2907. return;
  2908. }
  2909. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  2910. unsigned OldSize = Indices.size();
  2911. (void)OldSize;
  2912. for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
  2913. ++Idx) {
  2914. assert(Indices.size() == OldSize && "Did not return to the old size");
  2915. Indices.push_back(Idx);
  2916. GEPIndices.push_back(IRB.getInt32(Idx));
  2917. emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
  2918. GEPIndices.pop_back();
  2919. Indices.pop_back();
  2920. }
  2921. return;
  2922. }
  2923. llvm_unreachable("Only arrays and structs are aggregate loadable types");
  2924. }
  2925. };
  2926. struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
  2927. AAMDNodes AATags;
  2928. LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
  2929. AAMDNodes AATags, Align BaseAlign, const DataLayout &DL,
  2930. IRBuilderTy &IRB)
  2931. : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, DL,
  2932. IRB),
  2933. AATags(AATags) {}
  2934. /// Emit a leaf load of a single value. This is called at the leaves of the
  2935. /// recursive emission to actually load values.
  2936. void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
  2937. assert(Ty->isSingleValueType());
  2938. // Load the single value and insert it using the indices.
  2939. Value *GEP =
  2940. IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
  2941. LoadInst *Load =
  2942. IRB.CreateAlignedLoad(Ty, GEP, Alignment, Name + ".load");
  2943. APInt Offset(
  2944. DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
  2945. if (AATags &&
  2946. GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset))
  2947. Load->setAAMetadata(AATags.shift(Offset.getZExtValue()));
  2948. Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
  2949. LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
  2950. }
  2951. };
  2952. bool visitLoadInst(LoadInst &LI) {
  2953. assert(LI.getPointerOperand() == *U);
  2954. if (!LI.isSimple() || LI.getType()->isSingleValueType())
  2955. return false;
  2956. // We have an aggregate being loaded, split it apart.
  2957. LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
  2958. LoadOpSplitter Splitter(&LI, *U, LI.getType(), LI.getAAMetadata(),
  2959. getAdjustedAlignment(&LI, 0), DL, IRB);
  2960. Value *V = PoisonValue::get(LI.getType());
  2961. Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
  2962. Visited.erase(&LI);
  2963. LI.replaceAllUsesWith(V);
  2964. LI.eraseFromParent();
  2965. return true;
  2966. }
  2967. struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
  2968. StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
  2969. AAMDNodes AATags, Align BaseAlign, const DataLayout &DL,
  2970. IRBuilderTy &IRB)
  2971. : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
  2972. DL, IRB),
  2973. AATags(AATags) {}
  2974. AAMDNodes AATags;
  2975. /// Emit a leaf store of a single value. This is called at the leaves of the
  2976. /// recursive emission to actually produce stores.
  2977. void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) {
  2978. assert(Ty->isSingleValueType());
  2979. // Extract the single value and store it using the indices.
  2980. //
  2981. // The gep and extractvalue values are factored out of the CreateStore
  2982. // call to make the output independent of the argument evaluation order.
  2983. Value *ExtractValue =
  2984. IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
  2985. Value *InBoundsGEP =
  2986. IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
  2987. StoreInst *Store =
  2988. IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment);
  2989. APInt Offset(
  2990. DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()), 0);
  2991. if (AATags &&
  2992. GEPOperator::accumulateConstantOffset(BaseTy, GEPIndices, DL, Offset))
  2993. Store->setAAMetadata(AATags.shift(Offset.getZExtValue()));
  2994. LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
  2995. }
  2996. };
  2997. bool visitStoreInst(StoreInst &SI) {
  2998. if (!SI.isSimple() || SI.getPointerOperand() != *U)
  2999. return false;
  3000. Value *V = SI.getValueOperand();
  3001. if (V->getType()->isSingleValueType())
  3002. return false;
  3003. // We have an aggregate being stored, split it apart.
  3004. LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
  3005. StoreOpSplitter Splitter(&SI, *U, V->getType(), SI.getAAMetadata(),
  3006. getAdjustedAlignment(&SI, 0), DL, IRB);
  3007. Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
  3008. Visited.erase(&SI);
  3009. SI.eraseFromParent();
  3010. return true;
  3011. }
  3012. bool visitBitCastInst(BitCastInst &BC) {
  3013. enqueueUsers(BC);
  3014. return false;
  3015. }
  3016. bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
  3017. enqueueUsers(ASC);
  3018. return false;
  3019. }
  3020. // Fold gep (select cond, ptr1, ptr2) => select cond, gep(ptr1), gep(ptr2)
  3021. bool foldGEPSelect(GetElementPtrInst &GEPI) {
  3022. if (!GEPI.hasAllConstantIndices())
  3023. return false;
  3024. SelectInst *Sel = cast<SelectInst>(GEPI.getPointerOperand());
  3025. LLVM_DEBUG(dbgs() << " Rewriting gep(select) -> select(gep):"
  3026. << "\n original: " << *Sel
  3027. << "\n " << GEPI);
  3028. IRB.SetInsertPoint(&GEPI);
  3029. SmallVector<Value *, 4> Index(GEPI.indices());
  3030. bool IsInBounds = GEPI.isInBounds();
  3031. Type *Ty = GEPI.getSourceElementType();
  3032. Value *True = Sel->getTrueValue();
  3033. Value *NTrue =
  3034. IsInBounds
  3035. ? IRB.CreateInBoundsGEP(Ty, True, Index,
  3036. True->getName() + ".sroa.gep")
  3037. : IRB.CreateGEP(Ty, True, Index, True->getName() + ".sroa.gep");
  3038. Value *False = Sel->getFalseValue();
  3039. Value *NFalse =
  3040. IsInBounds
  3041. ? IRB.CreateInBoundsGEP(Ty, False, Index,
  3042. False->getName() + ".sroa.gep")
  3043. : IRB.CreateGEP(Ty, False, Index, False->getName() + ".sroa.gep");
  3044. Value *NSel = IRB.CreateSelect(Sel->getCondition(), NTrue, NFalse,
  3045. Sel->getName() + ".sroa.sel");
  3046. Visited.erase(&GEPI);
  3047. GEPI.replaceAllUsesWith(NSel);
  3048. GEPI.eraseFromParent();
  3049. Instruction *NSelI = cast<Instruction>(NSel);
  3050. Visited.insert(NSelI);
  3051. enqueueUsers(*NSelI);
  3052. LLVM_DEBUG(dbgs() << "\n to: " << *NTrue
  3053. << "\n " << *NFalse
  3054. << "\n " << *NSel << '\n');
  3055. return true;
  3056. }
  3057. // Fold gep (phi ptr1, ptr2) => phi gep(ptr1), gep(ptr2)
  3058. bool foldGEPPhi(GetElementPtrInst &GEPI) {
  3059. if (!GEPI.hasAllConstantIndices())
  3060. return false;
  3061. PHINode *PHI = cast<PHINode>(GEPI.getPointerOperand());
  3062. if (GEPI.getParent() != PHI->getParent() ||
  3063. llvm::any_of(PHI->incoming_values(), [](Value *In)
  3064. { Instruction *I = dyn_cast<Instruction>(In);
  3065. return !I || isa<GetElementPtrInst>(I) || isa<PHINode>(I) ||
  3066. succ_empty(I->getParent()) ||
  3067. !I->getParent()->isLegalToHoistInto();
  3068. }))
  3069. return false;
  3070. LLVM_DEBUG(dbgs() << " Rewriting gep(phi) -> phi(gep):"
  3071. << "\n original: " << *PHI
  3072. << "\n " << GEPI
  3073. << "\n to: ");
  3074. SmallVector<Value *, 4> Index(GEPI.indices());
  3075. bool IsInBounds = GEPI.isInBounds();
  3076. IRB.SetInsertPoint(GEPI.getParent()->getFirstNonPHI());
  3077. PHINode *NewPN = IRB.CreatePHI(GEPI.getType(), PHI->getNumIncomingValues(),
  3078. PHI->getName() + ".sroa.phi");
  3079. for (unsigned I = 0, E = PHI->getNumIncomingValues(); I != E; ++I) {
  3080. BasicBlock *B = PHI->getIncomingBlock(I);
  3081. Value *NewVal = nullptr;
  3082. int Idx = NewPN->getBasicBlockIndex(B);
  3083. if (Idx >= 0) {
  3084. NewVal = NewPN->getIncomingValue(Idx);
  3085. } else {
  3086. Instruction *In = cast<Instruction>(PHI->getIncomingValue(I));
  3087. IRB.SetInsertPoint(In->getParent(), std::next(In->getIterator()));
  3088. Type *Ty = GEPI.getSourceElementType();
  3089. NewVal = IsInBounds ? IRB.CreateInBoundsGEP(Ty, In, Index,
  3090. In->getName() + ".sroa.gep")
  3091. : IRB.CreateGEP(Ty, In, Index,
  3092. In->getName() + ".sroa.gep");
  3093. }
  3094. NewPN->addIncoming(NewVal, B);
  3095. }
  3096. Visited.erase(&GEPI);
  3097. GEPI.replaceAllUsesWith(NewPN);
  3098. GEPI.eraseFromParent();
  3099. Visited.insert(NewPN);
  3100. enqueueUsers(*NewPN);
  3101. LLVM_DEBUG(for (Value *In : NewPN->incoming_values())
  3102. dbgs() << "\n " << *In;
  3103. dbgs() << "\n " << *NewPN << '\n');
  3104. return true;
  3105. }
  3106. bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
  3107. if (isa<SelectInst>(GEPI.getPointerOperand()) &&
  3108. foldGEPSelect(GEPI))
  3109. return true;
  3110. if (isa<PHINode>(GEPI.getPointerOperand()) &&
  3111. foldGEPPhi(GEPI))
  3112. return true;
  3113. enqueueUsers(GEPI);
  3114. return false;
  3115. }
  3116. bool visitPHINode(PHINode &PN) {
  3117. enqueueUsers(PN);
  3118. return false;
  3119. }
  3120. bool visitSelectInst(SelectInst &SI) {
  3121. enqueueUsers(SI);
  3122. return false;
  3123. }
  3124. };
  3125. } // end anonymous namespace
  3126. /// Strip aggregate type wrapping.
  3127. ///
  3128. /// This removes no-op aggregate types wrapping an underlying type. It will
  3129. /// strip as many layers of types as it can without changing either the type
  3130. /// size or the allocated size.
  3131. static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
  3132. if (Ty->isSingleValueType())
  3133. return Ty;
  3134. uint64_t AllocSize = DL.getTypeAllocSize(Ty).getFixedSize();
  3135. uint64_t TypeSize = DL.getTypeSizeInBits(Ty).getFixedSize();
  3136. Type *InnerTy;
  3137. if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
  3138. InnerTy = ArrTy->getElementType();
  3139. } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
  3140. const StructLayout *SL = DL.getStructLayout(STy);
  3141. unsigned Index = SL->getElementContainingOffset(0);
  3142. InnerTy = STy->getElementType(Index);
  3143. } else {
  3144. return Ty;
  3145. }
  3146. if (AllocSize > DL.getTypeAllocSize(InnerTy).getFixedSize() ||
  3147. TypeSize > DL.getTypeSizeInBits(InnerTy).getFixedSize())
  3148. return Ty;
  3149. return stripAggregateTypeWrapping(DL, InnerTy);
  3150. }
  3151. /// Try to find a partition of the aggregate type passed in for a given
  3152. /// offset and size.
  3153. ///
  3154. /// This recurses through the aggregate type and tries to compute a subtype
  3155. /// based on the offset and size. When the offset and size span a sub-section
  3156. /// of an array, it will even compute a new array type for that sub-section,
  3157. /// and the same for structs.
  3158. ///
  3159. /// Note that this routine is very strict and tries to find a partition of the
  3160. /// type which produces the *exact* right offset and size. It is not forgiving
  3161. /// when the size or offset cause either end of type-based partition to be off.
  3162. /// Also, this is a best-effort routine. It is reasonable to give up and not
  3163. /// return a type if necessary.
  3164. static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
  3165. uint64_t Size) {
  3166. if (Offset == 0 && DL.getTypeAllocSize(Ty).getFixedSize() == Size)
  3167. return stripAggregateTypeWrapping(DL, Ty);
  3168. if (Offset > DL.getTypeAllocSize(Ty).getFixedSize() ||
  3169. (DL.getTypeAllocSize(Ty).getFixedSize() - Offset) < Size)
  3170. return nullptr;
  3171. if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
  3172. Type *ElementTy;
  3173. uint64_t TyNumElements;
  3174. if (auto *AT = dyn_cast<ArrayType>(Ty)) {
  3175. ElementTy = AT->getElementType();
  3176. TyNumElements = AT->getNumElements();
  3177. } else {
  3178. // FIXME: This isn't right for vectors with non-byte-sized or
  3179. // non-power-of-two sized elements.
  3180. auto *VT = cast<FixedVectorType>(Ty);
  3181. ElementTy = VT->getElementType();
  3182. TyNumElements = VT->getNumElements();
  3183. }
  3184. uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedSize();
  3185. uint64_t NumSkippedElements = Offset / ElementSize;
  3186. if (NumSkippedElements >= TyNumElements)
  3187. return nullptr;
  3188. Offset -= NumSkippedElements * ElementSize;
  3189. // First check if we need to recurse.
  3190. if (Offset > 0 || Size < ElementSize) {
  3191. // Bail if the partition ends in a different array element.
  3192. if ((Offset + Size) > ElementSize)
  3193. return nullptr;
  3194. // Recurse through the element type trying to peel off offset bytes.
  3195. return getTypePartition(DL, ElementTy, Offset, Size);
  3196. }
  3197. assert(Offset == 0);
  3198. if (Size == ElementSize)
  3199. return stripAggregateTypeWrapping(DL, ElementTy);
  3200. assert(Size > ElementSize);
  3201. uint64_t NumElements = Size / ElementSize;
  3202. if (NumElements * ElementSize != Size)
  3203. return nullptr;
  3204. return ArrayType::get(ElementTy, NumElements);
  3205. }
  3206. StructType *STy = dyn_cast<StructType>(Ty);
  3207. if (!STy)
  3208. return nullptr;
  3209. const StructLayout *SL = DL.getStructLayout(STy);
  3210. if (Offset >= SL->getSizeInBytes())
  3211. return nullptr;
  3212. uint64_t EndOffset = Offset + Size;
  3213. if (EndOffset > SL->getSizeInBytes())
  3214. return nullptr;
  3215. unsigned Index = SL->getElementContainingOffset(Offset);
  3216. Offset -= SL->getElementOffset(Index);
  3217. Type *ElementTy = STy->getElementType(Index);
  3218. uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedSize();
  3219. if (Offset >= ElementSize)
  3220. return nullptr; // The offset points into alignment padding.
  3221. // See if any partition must be contained by the element.
  3222. if (Offset > 0 || Size < ElementSize) {
  3223. if ((Offset + Size) > ElementSize)
  3224. return nullptr;
  3225. return getTypePartition(DL, ElementTy, Offset, Size);
  3226. }
  3227. assert(Offset == 0);
  3228. if (Size == ElementSize)
  3229. return stripAggregateTypeWrapping(DL, ElementTy);
  3230. StructType::element_iterator EI = STy->element_begin() + Index,
  3231. EE = STy->element_end();
  3232. if (EndOffset < SL->getSizeInBytes()) {
  3233. unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
  3234. if (Index == EndIndex)
  3235. return nullptr; // Within a single element and its padding.
  3236. // Don't try to form "natural" types if the elements don't line up with the
  3237. // expected size.
  3238. // FIXME: We could potentially recurse down through the last element in the
  3239. // sub-struct to find a natural end point.
  3240. if (SL->getElementOffset(EndIndex) != EndOffset)
  3241. return nullptr;
  3242. assert(Index < EndIndex);
  3243. EE = STy->element_begin() + EndIndex;
  3244. }
  3245. // Try to build up a sub-structure.
  3246. StructType *SubTy =
  3247. StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
  3248. const StructLayout *SubSL = DL.getStructLayout(SubTy);
  3249. if (Size != SubSL->getSizeInBytes())
  3250. return nullptr; // The sub-struct doesn't have quite the size needed.
  3251. return SubTy;
  3252. }
  3253. /// Pre-split loads and stores to simplify rewriting.
  3254. ///
  3255. /// We want to break up the splittable load+store pairs as much as
  3256. /// possible. This is important to do as a preprocessing step, as once we
  3257. /// start rewriting the accesses to partitions of the alloca we lose the
  3258. /// necessary information to correctly split apart paired loads and stores
  3259. /// which both point into this alloca. The case to consider is something like
  3260. /// the following:
  3261. ///
  3262. /// %a = alloca [12 x i8]
  3263. /// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
  3264. /// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
  3265. /// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
  3266. /// %iptr1 = bitcast i8* %gep1 to i64*
  3267. /// %iptr2 = bitcast i8* %gep2 to i64*
  3268. /// %fptr1 = bitcast i8* %gep1 to float*
  3269. /// %fptr2 = bitcast i8* %gep2 to float*
  3270. /// %fptr3 = bitcast i8* %gep3 to float*
  3271. /// store float 0.0, float* %fptr1
  3272. /// store float 1.0, float* %fptr2
  3273. /// %v = load i64* %iptr1
  3274. /// store i64 %v, i64* %iptr2
  3275. /// %f1 = load float* %fptr2
  3276. /// %f2 = load float* %fptr3
  3277. ///
  3278. /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
  3279. /// promote everything so we recover the 2 SSA values that should have been
  3280. /// there all along.
  3281. ///
  3282. /// \returns true if any changes are made.
  3283. bool SROAPass::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
  3284. LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
  3285. // Track the loads and stores which are candidates for pre-splitting here, in
  3286. // the order they first appear during the partition scan. These give stable
  3287. // iteration order and a basis for tracking which loads and stores we
  3288. // actually split.
  3289. SmallVector<LoadInst *, 4> Loads;
  3290. SmallVector<StoreInst *, 4> Stores;
  3291. // We need to accumulate the splits required of each load or store where we
  3292. // can find them via a direct lookup. This is important to cross-check loads
  3293. // and stores against each other. We also track the slice so that we can kill
  3294. // all the slices that end up split.
  3295. struct SplitOffsets {
  3296. Slice *S;
  3297. std::vector<uint64_t> Splits;
  3298. };
  3299. SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
  3300. // Track loads out of this alloca which cannot, for any reason, be pre-split.
  3301. // This is important as we also cannot pre-split stores of those loads!
  3302. // FIXME: This is all pretty gross. It means that we can be more aggressive
  3303. // in pre-splitting when the load feeding the store happens to come from
  3304. // a separate alloca. Put another way, the effectiveness of SROA would be
  3305. // decreased by a frontend which just concatenated all of its local allocas
  3306. // into one big flat alloca. But defeating such patterns is exactly the job
  3307. // SROA is tasked with! Sadly, to not have this discrepancy we would have
  3308. // change store pre-splitting to actually force pre-splitting of the load
  3309. // that feeds it *and all stores*. That makes pre-splitting much harder, but
  3310. // maybe it would make it more principled?
  3311. SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
  3312. LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
  3313. for (auto &P : AS.partitions()) {
  3314. for (Slice &S : P) {
  3315. Instruction *I = cast<Instruction>(S.getUse()->getUser());
  3316. if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
  3317. // If this is a load we have to track that it can't participate in any
  3318. // pre-splitting. If this is a store of a load we have to track that
  3319. // that load also can't participate in any pre-splitting.
  3320. if (auto *LI = dyn_cast<LoadInst>(I))
  3321. UnsplittableLoads.insert(LI);
  3322. else if (auto *SI = dyn_cast<StoreInst>(I))
  3323. if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
  3324. UnsplittableLoads.insert(LI);
  3325. continue;
  3326. }
  3327. assert(P.endOffset() > S.beginOffset() &&
  3328. "Empty or backwards partition!");
  3329. // Determine if this is a pre-splittable slice.
  3330. if (auto *LI = dyn_cast<LoadInst>(I)) {
  3331. assert(!LI->isVolatile() && "Cannot split volatile loads!");
  3332. // The load must be used exclusively to store into other pointers for
  3333. // us to be able to arbitrarily pre-split it. The stores must also be
  3334. // simple to avoid changing semantics.
  3335. auto IsLoadSimplyStored = [](LoadInst *LI) {
  3336. for (User *LU : LI->users()) {
  3337. auto *SI = dyn_cast<StoreInst>(LU);
  3338. if (!SI || !SI->isSimple())
  3339. return false;
  3340. }
  3341. return true;
  3342. };
  3343. if (!IsLoadSimplyStored(LI)) {
  3344. UnsplittableLoads.insert(LI);
  3345. continue;
  3346. }
  3347. Loads.push_back(LI);
  3348. } else if (auto *SI = dyn_cast<StoreInst>(I)) {
  3349. if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
  3350. // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
  3351. continue;
  3352. auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
  3353. if (!StoredLoad || !StoredLoad->isSimple())
  3354. continue;
  3355. assert(!SI->isVolatile() && "Cannot split volatile stores!");
  3356. Stores.push_back(SI);
  3357. } else {
  3358. // Other uses cannot be pre-split.
  3359. continue;
  3360. }
  3361. // Record the initial split.
  3362. LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
  3363. auto &Offsets = SplitOffsetsMap[I];
  3364. assert(Offsets.Splits.empty() &&
  3365. "Should not have splits the first time we see an instruction!");
  3366. Offsets.S = &S;
  3367. Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
  3368. }
  3369. // Now scan the already split slices, and add a split for any of them which
  3370. // we're going to pre-split.
  3371. for (Slice *S : P.splitSliceTails()) {
  3372. auto SplitOffsetsMapI =
  3373. SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
  3374. if (SplitOffsetsMapI == SplitOffsetsMap.end())
  3375. continue;
  3376. auto &Offsets = SplitOffsetsMapI->second;
  3377. assert(Offsets.S == S && "Found a mismatched slice!");
  3378. assert(!Offsets.Splits.empty() &&
  3379. "Cannot have an empty set of splits on the second partition!");
  3380. assert(Offsets.Splits.back() ==
  3381. P.beginOffset() - Offsets.S->beginOffset() &&
  3382. "Previous split does not end where this one begins!");
  3383. // Record each split. The last partition's end isn't needed as the size
  3384. // of the slice dictates that.
  3385. if (S->endOffset() > P.endOffset())
  3386. Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
  3387. }
  3388. }
  3389. // We may have split loads where some of their stores are split stores. For
  3390. // such loads and stores, we can only pre-split them if their splits exactly
  3391. // match relative to their starting offset. We have to verify this prior to
  3392. // any rewriting.
  3393. llvm::erase_if(Stores, [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
  3394. // Lookup the load we are storing in our map of split
  3395. // offsets.
  3396. auto *LI = cast<LoadInst>(SI->getValueOperand());
  3397. // If it was completely unsplittable, then we're done,
  3398. // and this store can't be pre-split.
  3399. if (UnsplittableLoads.count(LI))
  3400. return true;
  3401. auto LoadOffsetsI = SplitOffsetsMap.find(LI);
  3402. if (LoadOffsetsI == SplitOffsetsMap.end())
  3403. return false; // Unrelated loads are definitely safe.
  3404. auto &LoadOffsets = LoadOffsetsI->second;
  3405. // Now lookup the store's offsets.
  3406. auto &StoreOffsets = SplitOffsetsMap[SI];
  3407. // If the relative offsets of each split in the load and
  3408. // store match exactly, then we can split them and we
  3409. // don't need to remove them here.
  3410. if (LoadOffsets.Splits == StoreOffsets.Splits)
  3411. return false;
  3412. LLVM_DEBUG(dbgs() << " Mismatched splits for load and store:\n"
  3413. << " " << *LI << "\n"
  3414. << " " << *SI << "\n");
  3415. // We've found a store and load that we need to split
  3416. // with mismatched relative splits. Just give up on them
  3417. // and remove both instructions from our list of
  3418. // candidates.
  3419. UnsplittableLoads.insert(LI);
  3420. return true;
  3421. });
  3422. // Now we have to go *back* through all the stores, because a later store may
  3423. // have caused an earlier store's load to become unsplittable and if it is
  3424. // unsplittable for the later store, then we can't rely on it being split in
  3425. // the earlier store either.
  3426. llvm::erase_if(Stores, [&UnsplittableLoads](StoreInst *SI) {
  3427. auto *LI = cast<LoadInst>(SI->getValueOperand());
  3428. return UnsplittableLoads.count(LI);
  3429. });
  3430. // Once we've established all the loads that can't be split for some reason,
  3431. // filter any that made it into our list out.
  3432. llvm::erase_if(Loads, [&UnsplittableLoads](LoadInst *LI) {
  3433. return UnsplittableLoads.count(LI);
  3434. });
  3435. // If no loads or stores are left, there is no pre-splitting to be done for
  3436. // this alloca.
  3437. if (Loads.empty() && Stores.empty())
  3438. return false;
  3439. // From here on, we can't fail and will be building new accesses, so rig up
  3440. // an IR builder.
  3441. IRBuilderTy IRB(&AI);
  3442. // Collect the new slices which we will merge into the alloca slices.
  3443. SmallVector<Slice, 4> NewSlices;
  3444. // Track any allocas we end up splitting loads and stores for so we iterate
  3445. // on them.
  3446. SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
  3447. // At this point, we have collected all of the loads and stores we can
  3448. // pre-split, and the specific splits needed for them. We actually do the
  3449. // splitting in a specific order in order to handle when one of the loads in
  3450. // the value operand to one of the stores.
  3451. //
  3452. // First, we rewrite all of the split loads, and just accumulate each split
  3453. // load in a parallel structure. We also build the slices for them and append
  3454. // them to the alloca slices.
  3455. SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
  3456. std::vector<LoadInst *> SplitLoads;
  3457. const DataLayout &DL = AI.getModule()->getDataLayout();
  3458. for (LoadInst *LI : Loads) {
  3459. SplitLoads.clear();
  3460. IntegerType *Ty = cast<IntegerType>(LI->getType());
  3461. assert(Ty->getBitWidth() % 8 == 0);
  3462. uint64_t LoadSize = Ty->getBitWidth() / 8;
  3463. assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
  3464. auto &Offsets = SplitOffsetsMap[LI];
  3465. assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
  3466. "Slice size should always match load size exactly!");
  3467. uint64_t BaseOffset = Offsets.S->beginOffset();
  3468. assert(BaseOffset + LoadSize > BaseOffset &&
  3469. "Cannot represent alloca access size using 64-bit integers!");
  3470. Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
  3471. IRB.SetInsertPoint(LI);
  3472. LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
  3473. uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
  3474. int Idx = 0, Size = Offsets.Splits.size();
  3475. for (;;) {
  3476. auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
  3477. auto AS = LI->getPointerAddressSpace();
  3478. auto *PartPtrTy = PartTy->getPointerTo(AS);
  3479. LoadInst *PLoad = IRB.CreateAlignedLoad(
  3480. PartTy,
  3481. getAdjustedPtr(IRB, DL, BasePtr,
  3482. APInt(DL.getIndexSizeInBits(AS), PartOffset),
  3483. PartPtrTy, BasePtr->getName() + "."),
  3484. getAdjustedAlignment(LI, PartOffset),
  3485. /*IsVolatile*/ false, LI->getName());
  3486. PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
  3487. LLVMContext::MD_access_group});
  3488. // Append this load onto the list of split loads so we can find it later
  3489. // to rewrite the stores.
  3490. SplitLoads.push_back(PLoad);
  3491. // Now build a new slice for the alloca.
  3492. NewSlices.push_back(
  3493. Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
  3494. &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
  3495. /*IsSplittable*/ false));
  3496. LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
  3497. << ", " << NewSlices.back().endOffset()
  3498. << "): " << *PLoad << "\n");
  3499. // See if we've handled all the splits.
  3500. if (Idx >= Size)
  3501. break;
  3502. // Setup the next partition.
  3503. PartOffset = Offsets.Splits[Idx];
  3504. ++Idx;
  3505. PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
  3506. }
  3507. // Now that we have the split loads, do the slow walk over all uses of the
  3508. // load and rewrite them as split stores, or save the split loads to use
  3509. // below if the store is going to be split there anyways.
  3510. bool DeferredStores = false;
  3511. for (User *LU : LI->users()) {
  3512. StoreInst *SI = cast<StoreInst>(LU);
  3513. if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
  3514. DeferredStores = true;
  3515. LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
  3516. << "\n");
  3517. continue;
  3518. }
  3519. Value *StoreBasePtr = SI->getPointerOperand();
  3520. IRB.SetInsertPoint(SI);
  3521. LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
  3522. for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
  3523. LoadInst *PLoad = SplitLoads[Idx];
  3524. uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
  3525. auto *PartPtrTy =
  3526. PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
  3527. auto AS = SI->getPointerAddressSpace();
  3528. StoreInst *PStore = IRB.CreateAlignedStore(
  3529. PLoad,
  3530. getAdjustedPtr(IRB, DL, StoreBasePtr,
  3531. APInt(DL.getIndexSizeInBits(AS), PartOffset),
  3532. PartPtrTy, StoreBasePtr->getName() + "."),
  3533. getAdjustedAlignment(SI, PartOffset),
  3534. /*IsVolatile*/ false);
  3535. PStore->copyMetadata(*SI, {LLVMContext::MD_mem_parallel_loop_access,
  3536. LLVMContext::MD_access_group});
  3537. LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
  3538. }
  3539. // We want to immediately iterate on any allocas impacted by splitting
  3540. // this store, and we have to track any promotable alloca (indicated by
  3541. // a direct store) as needing to be resplit because it is no longer
  3542. // promotable.
  3543. if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
  3544. ResplitPromotableAllocas.insert(OtherAI);
  3545. Worklist.insert(OtherAI);
  3546. } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
  3547. StoreBasePtr->stripInBoundsOffsets())) {
  3548. Worklist.insert(OtherAI);
  3549. }
  3550. // Mark the original store as dead.
  3551. DeadInsts.push_back(SI);
  3552. }
  3553. // Save the split loads if there are deferred stores among the users.
  3554. if (DeferredStores)
  3555. SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
  3556. // Mark the original load as dead and kill the original slice.
  3557. DeadInsts.push_back(LI);
  3558. Offsets.S->kill();
  3559. }
  3560. // Second, we rewrite all of the split stores. At this point, we know that
  3561. // all loads from this alloca have been split already. For stores of such
  3562. // loads, we can simply look up the pre-existing split loads. For stores of
  3563. // other loads, we split those loads first and then write split stores of
  3564. // them.
  3565. for (StoreInst *SI : Stores) {
  3566. auto *LI = cast<LoadInst>(SI->getValueOperand());
  3567. IntegerType *Ty = cast<IntegerType>(LI->getType());
  3568. assert(Ty->getBitWidth() % 8 == 0);
  3569. uint64_t StoreSize = Ty->getBitWidth() / 8;
  3570. assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
  3571. auto &Offsets = SplitOffsetsMap[SI];
  3572. assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
  3573. "Slice size should always match load size exactly!");
  3574. uint64_t BaseOffset = Offsets.S->beginOffset();
  3575. assert(BaseOffset + StoreSize > BaseOffset &&
  3576. "Cannot represent alloca access size using 64-bit integers!");
  3577. Value *LoadBasePtr = LI->getPointerOperand();
  3578. Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
  3579. LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
  3580. // Check whether we have an already split load.
  3581. auto SplitLoadsMapI = SplitLoadsMap.find(LI);
  3582. std::vector<LoadInst *> *SplitLoads = nullptr;
  3583. if (SplitLoadsMapI != SplitLoadsMap.end()) {
  3584. SplitLoads = &SplitLoadsMapI->second;
  3585. assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
  3586. "Too few split loads for the number of splits in the store!");
  3587. } else {
  3588. LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
  3589. }
  3590. uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
  3591. int Idx = 0, Size = Offsets.Splits.size();
  3592. for (;;) {
  3593. auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
  3594. auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
  3595. auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
  3596. // Either lookup a split load or create one.
  3597. LoadInst *PLoad;
  3598. if (SplitLoads) {
  3599. PLoad = (*SplitLoads)[Idx];
  3600. } else {
  3601. IRB.SetInsertPoint(LI);
  3602. auto AS = LI->getPointerAddressSpace();
  3603. PLoad = IRB.CreateAlignedLoad(
  3604. PartTy,
  3605. getAdjustedPtr(IRB, DL, LoadBasePtr,
  3606. APInt(DL.getIndexSizeInBits(AS), PartOffset),
  3607. LoadPartPtrTy, LoadBasePtr->getName() + "."),
  3608. getAdjustedAlignment(LI, PartOffset),
  3609. /*IsVolatile*/ false, LI->getName());
  3610. PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
  3611. LLVMContext::MD_access_group});
  3612. }
  3613. // And store this partition.
  3614. IRB.SetInsertPoint(SI);
  3615. auto AS = SI->getPointerAddressSpace();
  3616. StoreInst *PStore = IRB.CreateAlignedStore(
  3617. PLoad,
  3618. getAdjustedPtr(IRB, DL, StoreBasePtr,
  3619. APInt(DL.getIndexSizeInBits(AS), PartOffset),
  3620. StorePartPtrTy, StoreBasePtr->getName() + "."),
  3621. getAdjustedAlignment(SI, PartOffset),
  3622. /*IsVolatile*/ false);
  3623. PStore->copyMetadata(*SI, {LLVMContext::MD_mem_parallel_loop_access,
  3624. LLVMContext::MD_access_group});
  3625. // Now build a new slice for the alloca.
  3626. NewSlices.push_back(
  3627. Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
  3628. &PStore->getOperandUse(PStore->getPointerOperandIndex()),
  3629. /*IsSplittable*/ false));
  3630. LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
  3631. << ", " << NewSlices.back().endOffset()
  3632. << "): " << *PStore << "\n");
  3633. if (!SplitLoads) {
  3634. LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
  3635. }
  3636. // See if we've finished all the splits.
  3637. if (Idx >= Size)
  3638. break;
  3639. // Setup the next partition.
  3640. PartOffset = Offsets.Splits[Idx];
  3641. ++Idx;
  3642. PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
  3643. }
  3644. // We want to immediately iterate on any allocas impacted by splitting
  3645. // this load, which is only relevant if it isn't a load of this alloca and
  3646. // thus we didn't already split the loads above. We also have to keep track
  3647. // of any promotable allocas we split loads on as they can no longer be
  3648. // promoted.
  3649. if (!SplitLoads) {
  3650. if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
  3651. assert(OtherAI != &AI && "We can't re-split our own alloca!");
  3652. ResplitPromotableAllocas.insert(OtherAI);
  3653. Worklist.insert(OtherAI);
  3654. } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
  3655. LoadBasePtr->stripInBoundsOffsets())) {
  3656. assert(OtherAI != &AI && "We can't re-split our own alloca!");
  3657. Worklist.insert(OtherAI);
  3658. }
  3659. }
  3660. // Mark the original store as dead now that we've split it up and kill its
  3661. // slice. Note that we leave the original load in place unless this store
  3662. // was its only use. It may in turn be split up if it is an alloca load
  3663. // for some other alloca, but it may be a normal load. This may introduce
  3664. // redundant loads, but where those can be merged the rest of the optimizer
  3665. // should handle the merging, and this uncovers SSA splits which is more
  3666. // important. In practice, the original loads will almost always be fully
  3667. // split and removed eventually, and the splits will be merged by any
  3668. // trivial CSE, including instcombine.
  3669. if (LI->hasOneUse()) {
  3670. assert(*LI->user_begin() == SI && "Single use isn't this store!");
  3671. DeadInsts.push_back(LI);
  3672. }
  3673. DeadInsts.push_back(SI);
  3674. Offsets.S->kill();
  3675. }
  3676. // Remove the killed slices that have ben pre-split.
  3677. llvm::erase_if(AS, [](const Slice &S) { return S.isDead(); });
  3678. // Insert our new slices. This will sort and merge them into the sorted
  3679. // sequence.
  3680. AS.insert(NewSlices);
  3681. LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
  3682. #ifndef NDEBUG
  3683. for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
  3684. LLVM_DEBUG(AS.print(dbgs(), I, " "));
  3685. #endif
  3686. // Finally, don't try to promote any allocas that new require re-splitting.
  3687. // They have already been added to the worklist above.
  3688. llvm::erase_if(PromotableAllocas, [&](AllocaInst *AI) {
  3689. return ResplitPromotableAllocas.count(AI);
  3690. });
  3691. return true;
  3692. }
  3693. /// Rewrite an alloca partition's users.
  3694. ///
  3695. /// This routine drives both of the rewriting goals of the SROA pass. It tries
  3696. /// to rewrite uses of an alloca partition to be conducive for SSA value
  3697. /// promotion. If the partition needs a new, more refined alloca, this will
  3698. /// build that new alloca, preserving as much type information as possible, and
  3699. /// rewrite the uses of the old alloca to point at the new one and have the
  3700. /// appropriate new offsets. It also evaluates how successful the rewrite was
  3701. /// at enabling promotion and if it was successful queues the alloca to be
  3702. /// promoted.
  3703. AllocaInst *SROAPass::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
  3704. Partition &P) {
  3705. // Try to compute a friendly type for this partition of the alloca. This
  3706. // won't always succeed, in which case we fall back to a legal integer type
  3707. // or an i8 array of an appropriate size.
  3708. Type *SliceTy = nullptr;
  3709. const DataLayout &DL = AI.getModule()->getDataLayout();
  3710. std::pair<Type *, IntegerType *> CommonUseTy =
  3711. findCommonType(P.begin(), P.end(), P.endOffset());
  3712. // Do all uses operate on the same type?
  3713. if (CommonUseTy.first)
  3714. if (DL.getTypeAllocSize(CommonUseTy.first).getFixedSize() >= P.size())
  3715. SliceTy = CommonUseTy.first;
  3716. // If not, can we find an appropriate subtype in the original allocated type?
  3717. if (!SliceTy)
  3718. if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
  3719. P.beginOffset(), P.size()))
  3720. SliceTy = TypePartitionTy;
  3721. // If still not, can we use the largest bitwidth integer type used?
  3722. if (!SliceTy && CommonUseTy.second)
  3723. if (DL.getTypeAllocSize(CommonUseTy.second).getFixedSize() >= P.size())
  3724. SliceTy = CommonUseTy.second;
  3725. if ((!SliceTy || (SliceTy->isArrayTy() &&
  3726. SliceTy->getArrayElementType()->isIntegerTy())) &&
  3727. DL.isLegalInteger(P.size() * 8))
  3728. SliceTy = Type::getIntNTy(*C, P.size() * 8);
  3729. if (!SliceTy)
  3730. SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
  3731. assert(DL.getTypeAllocSize(SliceTy).getFixedSize() >= P.size());
  3732. bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
  3733. VectorType *VecTy =
  3734. IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
  3735. if (VecTy)
  3736. SliceTy = VecTy;
  3737. // Check for the case where we're going to rewrite to a new alloca of the
  3738. // exact same type as the original, and with the same access offsets. In that
  3739. // case, re-use the existing alloca, but still run through the rewriter to
  3740. // perform phi and select speculation.
  3741. // P.beginOffset() can be non-zero even with the same type in a case with
  3742. // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
  3743. AllocaInst *NewAI;
  3744. if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
  3745. NewAI = &AI;
  3746. // FIXME: We should be able to bail at this point with "nothing changed".
  3747. // FIXME: We might want to defer PHI speculation until after here.
  3748. // FIXME: return nullptr;
  3749. } else {
  3750. // Make sure the alignment is compatible with P.beginOffset().
  3751. const Align Alignment = commonAlignment(AI.getAlign(), P.beginOffset());
  3752. // If we will get at least this much alignment from the type alone, leave
  3753. // the alloca's alignment unconstrained.
  3754. const bool IsUnconstrained = Alignment <= DL.getABITypeAlign(SliceTy);
  3755. NewAI = new AllocaInst(
  3756. SliceTy, AI.getType()->getAddressSpace(), nullptr,
  3757. IsUnconstrained ? DL.getPrefTypeAlign(SliceTy) : Alignment,
  3758. AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
  3759. // Copy the old AI debug location over to the new one.
  3760. NewAI->setDebugLoc(AI.getDebugLoc());
  3761. ++NumNewAllocas;
  3762. }
  3763. LLVM_DEBUG(dbgs() << "Rewriting alloca partition "
  3764. << "[" << P.beginOffset() << "," << P.endOffset()
  3765. << ") to: " << *NewAI << "\n");
  3766. // Track the high watermark on the worklist as it is only relevant for
  3767. // promoted allocas. We will reset it to this point if the alloca is not in
  3768. // fact scheduled for promotion.
  3769. unsigned PPWOldSize = PostPromotionWorklist.size();
  3770. unsigned NumUses = 0;
  3771. SmallSetVector<PHINode *, 8> PHIUsers;
  3772. SmallSetVector<SelectInst *, 8> SelectUsers;
  3773. AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
  3774. P.endOffset(), IsIntegerPromotable, VecTy,
  3775. PHIUsers, SelectUsers);
  3776. bool Promotable = true;
  3777. for (Slice *S : P.splitSliceTails()) {
  3778. Promotable &= Rewriter.visit(S);
  3779. ++NumUses;
  3780. }
  3781. for (Slice &S : P) {
  3782. Promotable &= Rewriter.visit(&S);
  3783. ++NumUses;
  3784. }
  3785. NumAllocaPartitionUses += NumUses;
  3786. MaxUsesPerAllocaPartition.updateMax(NumUses);
  3787. // Now that we've processed all the slices in the new partition, check if any
  3788. // PHIs or Selects would block promotion.
  3789. for (PHINode *PHI : PHIUsers)
  3790. if (!isSafePHIToSpeculate(*PHI)) {
  3791. Promotable = false;
  3792. PHIUsers.clear();
  3793. SelectUsers.clear();
  3794. break;
  3795. }
  3796. for (SelectInst *Sel : SelectUsers)
  3797. if (!isSafeSelectToSpeculate(*Sel)) {
  3798. Promotable = false;
  3799. PHIUsers.clear();
  3800. SelectUsers.clear();
  3801. break;
  3802. }
  3803. if (Promotable) {
  3804. for (Use *U : AS.getDeadUsesIfPromotable()) {
  3805. auto *OldInst = dyn_cast<Instruction>(U->get());
  3806. Value::dropDroppableUse(*U);
  3807. if (OldInst)
  3808. if (isInstructionTriviallyDead(OldInst))
  3809. DeadInsts.push_back(OldInst);
  3810. }
  3811. if (PHIUsers.empty() && SelectUsers.empty()) {
  3812. // Promote the alloca.
  3813. PromotableAllocas.push_back(NewAI);
  3814. } else {
  3815. // If we have either PHIs or Selects to speculate, add them to those
  3816. // worklists and re-queue the new alloca so that we promote in on the
  3817. // next iteration.
  3818. for (PHINode *PHIUser : PHIUsers)
  3819. SpeculatablePHIs.insert(PHIUser);
  3820. for (SelectInst *SelectUser : SelectUsers)
  3821. SpeculatableSelects.insert(SelectUser);
  3822. Worklist.insert(NewAI);
  3823. }
  3824. } else {
  3825. // Drop any post-promotion work items if promotion didn't happen.
  3826. while (PostPromotionWorklist.size() > PPWOldSize)
  3827. PostPromotionWorklist.pop_back();
  3828. // We couldn't promote and we didn't create a new partition, nothing
  3829. // happened.
  3830. if (NewAI == &AI)
  3831. return nullptr;
  3832. // If we can't promote the alloca, iterate on it to check for new
  3833. // refinements exposed by splitting the current alloca. Don't iterate on an
  3834. // alloca which didn't actually change and didn't get promoted.
  3835. Worklist.insert(NewAI);
  3836. }
  3837. return NewAI;
  3838. }
  3839. /// Walks the slices of an alloca and form partitions based on them,
  3840. /// rewriting each of their uses.
  3841. bool SROAPass::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
  3842. if (AS.begin() == AS.end())
  3843. return false;
  3844. unsigned NumPartitions = 0;
  3845. bool Changed = false;
  3846. const DataLayout &DL = AI.getModule()->getDataLayout();
  3847. // First try to pre-split loads and stores.
  3848. Changed |= presplitLoadsAndStores(AI, AS);
  3849. // Now that we have identified any pre-splitting opportunities,
  3850. // mark loads and stores unsplittable except for the following case.
  3851. // We leave a slice splittable if all other slices are disjoint or fully
  3852. // included in the slice, such as whole-alloca loads and stores.
  3853. // If we fail to split these during pre-splitting, we want to force them
  3854. // to be rewritten into a partition.
  3855. bool IsSorted = true;
  3856. uint64_t AllocaSize =
  3857. DL.getTypeAllocSize(AI.getAllocatedType()).getFixedSize();
  3858. const uint64_t MaxBitVectorSize = 1024;
  3859. if (AllocaSize <= MaxBitVectorSize) {
  3860. // If a byte boundary is included in any load or store, a slice starting or
  3861. // ending at the boundary is not splittable.
  3862. SmallBitVector SplittableOffset(AllocaSize + 1, true);
  3863. for (Slice &S : AS)
  3864. for (unsigned O = S.beginOffset() + 1;
  3865. O < S.endOffset() && O < AllocaSize; O++)
  3866. SplittableOffset.reset(O);
  3867. for (Slice &S : AS) {
  3868. if (!S.isSplittable())
  3869. continue;
  3870. if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
  3871. (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
  3872. continue;
  3873. if (isa<LoadInst>(S.getUse()->getUser()) ||
  3874. isa<StoreInst>(S.getUse()->getUser())) {
  3875. S.makeUnsplittable();
  3876. IsSorted = false;
  3877. }
  3878. }
  3879. }
  3880. else {
  3881. // We only allow whole-alloca splittable loads and stores
  3882. // for a large alloca to avoid creating too large BitVector.
  3883. for (Slice &S : AS) {
  3884. if (!S.isSplittable())
  3885. continue;
  3886. if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
  3887. continue;
  3888. if (isa<LoadInst>(S.getUse()->getUser()) ||
  3889. isa<StoreInst>(S.getUse()->getUser())) {
  3890. S.makeUnsplittable();
  3891. IsSorted = false;
  3892. }
  3893. }
  3894. }
  3895. if (!IsSorted)
  3896. llvm::sort(AS);
  3897. /// Describes the allocas introduced by rewritePartition in order to migrate
  3898. /// the debug info.
  3899. struct Fragment {
  3900. AllocaInst *Alloca;
  3901. uint64_t Offset;
  3902. uint64_t Size;
  3903. Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
  3904. : Alloca(AI), Offset(O), Size(S) {}
  3905. };
  3906. SmallVector<Fragment, 4> Fragments;
  3907. // Rewrite each partition.
  3908. for (auto &P : AS.partitions()) {
  3909. if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
  3910. Changed = true;
  3911. if (NewAI != &AI) {
  3912. uint64_t SizeOfByte = 8;
  3913. uint64_t AllocaSize =
  3914. DL.getTypeSizeInBits(NewAI->getAllocatedType()).getFixedSize();
  3915. // Don't include any padding.
  3916. uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
  3917. Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
  3918. }
  3919. }
  3920. ++NumPartitions;
  3921. }
  3922. NumAllocaPartitions += NumPartitions;
  3923. MaxPartitionsPerAlloca.updateMax(NumPartitions);
  3924. // Migrate debug information from the old alloca to the new alloca(s)
  3925. // and the individual partitions.
  3926. TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
  3927. for (DbgVariableIntrinsic *DbgDeclare : DbgDeclares) {
  3928. auto *Expr = DbgDeclare->getExpression();
  3929. DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
  3930. uint64_t AllocaSize =
  3931. DL.getTypeSizeInBits(AI.getAllocatedType()).getFixedSize();
  3932. for (auto Fragment : Fragments) {
  3933. // Create a fragment expression describing the new partition or reuse AI's
  3934. // expression if there is only one partition.
  3935. auto *FragmentExpr = Expr;
  3936. if (Fragment.Size < AllocaSize || Expr->isFragment()) {
  3937. // If this alloca is already a scalar replacement of a larger aggregate,
  3938. // Fragment.Offset describes the offset inside the scalar.
  3939. auto ExprFragment = Expr->getFragmentInfo();
  3940. uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
  3941. uint64_t Start = Offset + Fragment.Offset;
  3942. uint64_t Size = Fragment.Size;
  3943. if (ExprFragment) {
  3944. uint64_t AbsEnd =
  3945. ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
  3946. if (Start >= AbsEnd)
  3947. // No need to describe a SROAed padding.
  3948. continue;
  3949. Size = std::min(Size, AbsEnd - Start);
  3950. }
  3951. // The new, smaller fragment is stenciled out from the old fragment.
  3952. if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
  3953. assert(Start >= OrigFragment->OffsetInBits &&
  3954. "new fragment is outside of original fragment");
  3955. Start -= OrigFragment->OffsetInBits;
  3956. }
  3957. // The alloca may be larger than the variable.
  3958. auto VarSize = DbgDeclare->getVariable()->getSizeInBits();
  3959. if (VarSize) {
  3960. if (Size > *VarSize)
  3961. Size = *VarSize;
  3962. if (Size == 0 || Start + Size > *VarSize)
  3963. continue;
  3964. }
  3965. // Avoid creating a fragment expression that covers the entire variable.
  3966. if (!VarSize || *VarSize != Size) {
  3967. if (auto E =
  3968. DIExpression::createFragmentExpression(Expr, Start, Size))
  3969. FragmentExpr = *E;
  3970. else
  3971. continue;
  3972. }
  3973. }
  3974. // Remove any existing intrinsics on the new alloca describing
  3975. // the variable fragment.
  3976. for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca)) {
  3977. auto SameVariableFragment = [](const DbgVariableIntrinsic *LHS,
  3978. const DbgVariableIntrinsic *RHS) {
  3979. return LHS->getVariable() == RHS->getVariable() &&
  3980. LHS->getDebugLoc()->getInlinedAt() ==
  3981. RHS->getDebugLoc()->getInlinedAt();
  3982. };
  3983. if (SameVariableFragment(OldDII, DbgDeclare))
  3984. OldDII->eraseFromParent();
  3985. }
  3986. DIB.insertDeclare(Fragment.Alloca, DbgDeclare->getVariable(), FragmentExpr,
  3987. DbgDeclare->getDebugLoc(), &AI);
  3988. }
  3989. }
  3990. return Changed;
  3991. }
  3992. /// Clobber a use with poison, deleting the used value if it becomes dead.
  3993. void SROAPass::clobberUse(Use &U) {
  3994. Value *OldV = U;
  3995. // Replace the use with an poison value.
  3996. U = PoisonValue::get(OldV->getType());
  3997. // Check for this making an instruction dead. We have to garbage collect
  3998. // all the dead instructions to ensure the uses of any alloca end up being
  3999. // minimal.
  4000. if (Instruction *OldI = dyn_cast<Instruction>(OldV))
  4001. if (isInstructionTriviallyDead(OldI)) {
  4002. DeadInsts.push_back(OldI);
  4003. }
  4004. }
  4005. /// Analyze an alloca for SROA.
  4006. ///
  4007. /// This analyzes the alloca to ensure we can reason about it, builds
  4008. /// the slices of the alloca, and then hands it off to be split and
  4009. /// rewritten as needed.
  4010. bool SROAPass::runOnAlloca(AllocaInst &AI) {
  4011. LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
  4012. ++NumAllocasAnalyzed;
  4013. // Special case dead allocas, as they're trivial.
  4014. if (AI.use_empty()) {
  4015. AI.eraseFromParent();
  4016. return true;
  4017. }
  4018. const DataLayout &DL = AI.getModule()->getDataLayout();
  4019. // Skip alloca forms that this analysis can't handle.
  4020. auto *AT = AI.getAllocatedType();
  4021. if (AI.isArrayAllocation() || !AT->isSized() || isa<ScalableVectorType>(AT) ||
  4022. DL.getTypeAllocSize(AT).getFixedSize() == 0)
  4023. return false;
  4024. bool Changed = false;
  4025. // First, split any FCA loads and stores touching this alloca to promote
  4026. // better splitting and promotion opportunities.
  4027. IRBuilderTy IRB(&AI);
  4028. AggLoadStoreRewriter AggRewriter(DL, IRB);
  4029. Changed |= AggRewriter.rewrite(AI);
  4030. // Build the slices using a recursive instruction-visiting builder.
  4031. AllocaSlices AS(DL, AI);
  4032. LLVM_DEBUG(AS.print(dbgs()));
  4033. if (AS.isEscaped())
  4034. return Changed;
  4035. // Delete all the dead users of this alloca before splitting and rewriting it.
  4036. for (Instruction *DeadUser : AS.getDeadUsers()) {
  4037. // Free up everything used by this instruction.
  4038. for (Use &DeadOp : DeadUser->operands())
  4039. clobberUse(DeadOp);
  4040. // Now replace the uses of this instruction.
  4041. DeadUser->replaceAllUsesWith(PoisonValue::get(DeadUser->getType()));
  4042. // And mark it for deletion.
  4043. DeadInsts.push_back(DeadUser);
  4044. Changed = true;
  4045. }
  4046. for (Use *DeadOp : AS.getDeadOperands()) {
  4047. clobberUse(*DeadOp);
  4048. Changed = true;
  4049. }
  4050. // No slices to split. Leave the dead alloca for a later pass to clean up.
  4051. if (AS.begin() == AS.end())
  4052. return Changed;
  4053. Changed |= splitAlloca(AI, AS);
  4054. LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
  4055. while (!SpeculatablePHIs.empty())
  4056. speculatePHINodeLoads(IRB, *SpeculatablePHIs.pop_back_val());
  4057. LLVM_DEBUG(dbgs() << " Speculating Selects\n");
  4058. while (!SpeculatableSelects.empty())
  4059. speculateSelectInstLoads(IRB, *SpeculatableSelects.pop_back_val());
  4060. return Changed;
  4061. }
  4062. /// Delete the dead instructions accumulated in this run.
  4063. ///
  4064. /// Recursively deletes the dead instructions we've accumulated. This is done
  4065. /// at the very end to maximize locality of the recursive delete and to
  4066. /// minimize the problems of invalidated instruction pointers as such pointers
  4067. /// are used heavily in the intermediate stages of the algorithm.
  4068. ///
  4069. /// We also record the alloca instructions deleted here so that they aren't
  4070. /// subsequently handed to mem2reg to promote.
  4071. bool SROAPass::deleteDeadInstructions(
  4072. SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
  4073. bool Changed = false;
  4074. while (!DeadInsts.empty()) {
  4075. Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
  4076. if (!I) continue;
  4077. LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
  4078. // If the instruction is an alloca, find the possible dbg.declare connected
  4079. // to it, and remove it too. We must do this before calling RAUW or we will
  4080. // not be able to find it.
  4081. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
  4082. DeletedAllocas.insert(AI);
  4083. for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
  4084. OldDII->eraseFromParent();
  4085. }
  4086. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  4087. for (Use &Operand : I->operands())
  4088. if (Instruction *U = dyn_cast<Instruction>(Operand)) {
  4089. // Zero out the operand and see if it becomes trivially dead.
  4090. Operand = nullptr;
  4091. if (isInstructionTriviallyDead(U))
  4092. DeadInsts.push_back(U);
  4093. }
  4094. ++NumDeleted;
  4095. I->eraseFromParent();
  4096. Changed = true;
  4097. }
  4098. return Changed;
  4099. }
  4100. /// Promote the allocas, using the best available technique.
  4101. ///
  4102. /// This attempts to promote whatever allocas have been identified as viable in
  4103. /// the PromotableAllocas list. If that list is empty, there is nothing to do.
  4104. /// This function returns whether any promotion occurred.
  4105. bool SROAPass::promoteAllocas(Function &F) {
  4106. if (PromotableAllocas.empty())
  4107. return false;
  4108. NumPromoted += PromotableAllocas.size();
  4109. LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
  4110. PromoteMemToReg(PromotableAllocas, *DT, AC);
  4111. PromotableAllocas.clear();
  4112. return true;
  4113. }
  4114. PreservedAnalyses SROAPass::runImpl(Function &F, DominatorTree &RunDT,
  4115. AssumptionCache &RunAC) {
  4116. LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
  4117. C = &F.getContext();
  4118. DT = &RunDT;
  4119. AC = &RunAC;
  4120. BasicBlock &EntryBB = F.getEntryBlock();
  4121. for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
  4122. I != E; ++I) {
  4123. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
  4124. if (isa<ScalableVectorType>(AI->getAllocatedType())) {
  4125. if (isAllocaPromotable(AI))
  4126. PromotableAllocas.push_back(AI);
  4127. } else {
  4128. Worklist.insert(AI);
  4129. }
  4130. }
  4131. }
  4132. bool Changed = false;
  4133. // A set of deleted alloca instruction pointers which should be removed from
  4134. // the list of promotable allocas.
  4135. SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
  4136. do {
  4137. while (!Worklist.empty()) {
  4138. Changed |= runOnAlloca(*Worklist.pop_back_val());
  4139. Changed |= deleteDeadInstructions(DeletedAllocas);
  4140. // Remove the deleted allocas from various lists so that we don't try to
  4141. // continue processing them.
  4142. if (!DeletedAllocas.empty()) {
  4143. auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
  4144. Worklist.remove_if(IsInSet);
  4145. PostPromotionWorklist.remove_if(IsInSet);
  4146. llvm::erase_if(PromotableAllocas, IsInSet);
  4147. DeletedAllocas.clear();
  4148. }
  4149. }
  4150. Changed |= promoteAllocas(F);
  4151. Worklist = PostPromotionWorklist;
  4152. PostPromotionWorklist.clear();
  4153. } while (!Worklist.empty());
  4154. if (!Changed)
  4155. return PreservedAnalyses::all();
  4156. PreservedAnalyses PA;
  4157. PA.preserveSet<CFGAnalyses>();
  4158. return PA;
  4159. }
  4160. PreservedAnalyses SROAPass::run(Function &F, FunctionAnalysisManager &AM) {
  4161. return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
  4162. AM.getResult<AssumptionAnalysis>(F));
  4163. }
  4164. /// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
  4165. ///
  4166. /// This is in the llvm namespace purely to allow it to be a friend of the \c
  4167. /// SROA pass.
  4168. class llvm::sroa::SROALegacyPass : public FunctionPass {
  4169. /// The SROA implementation.
  4170. SROAPass Impl;
  4171. public:
  4172. static char ID;
  4173. SROALegacyPass() : FunctionPass(ID) {
  4174. initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
  4175. }
  4176. bool runOnFunction(Function &F) override {
  4177. if (skipFunction(F))
  4178. return false;
  4179. auto PA = Impl.runImpl(
  4180. F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
  4181. getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
  4182. return !PA.areAllPreserved();
  4183. }
  4184. void getAnalysisUsage(AnalysisUsage &AU) const override {
  4185. AU.addRequired<AssumptionCacheTracker>();
  4186. AU.addRequired<DominatorTreeWrapperPass>();
  4187. AU.addPreserved<GlobalsAAWrapperPass>();
  4188. AU.setPreservesCFG();
  4189. }
  4190. StringRef getPassName() const override { return "SROA"; }
  4191. };
  4192. char SROALegacyPass::ID = 0;
  4193. FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
  4194. INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
  4195. "Scalar Replacement Of Aggregates", false, false)
  4196. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  4197. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  4198. INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
  4199. false, false)