SROA.cpp 203 KB

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