SROA.cpp 176 KB

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