Attributor.cpp 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830
  1. //===- Attributor.cpp - Module-wide attribute deduction -------------------===//
  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. //
  9. // This file implements an interprocedural pass that deduces and/or propagates
  10. // attributes. This is done in an abstract interpretation style fixpoint
  11. // iteration. See the Attributor.h file comment and the class descriptions in
  12. // that file for more information.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/IPO/Attributor.h"
  16. #include "llvm/ADT/PointerIntPair.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/ADT/TinyPtrVector.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/Analysis/CallGraph.h"
  22. #include "llvm/Analysis/CallGraphSCCPass.h"
  23. #include "llvm/Analysis/InlineCost.h"
  24. #include "llvm/Analysis/MemoryBuiltins.h"
  25. #include "llvm/Analysis/MustExecute.h"
  26. #include "llvm/IR/Attributes.h"
  27. #include "llvm/IR/Constant.h"
  28. #include "llvm/IR/ConstantFold.h"
  29. #include "llvm/IR/Constants.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/GlobalValue.h"
  32. #include "llvm/IR/GlobalVariable.h"
  33. #include "llvm/IR/Instruction.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/IntrinsicInst.h"
  36. #include "llvm/IR/ValueHandle.h"
  37. #include "llvm/InitializePasses.h"
  38. #include "llvm/Support/Casting.h"
  39. #include "llvm/Support/CommandLine.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/DebugCounter.h"
  42. #include "llvm/Support/FileSystem.h"
  43. #include "llvm/Support/GraphWriter.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  46. #include "llvm/Transforms/Utils/Cloning.h"
  47. #include "llvm/Transforms/Utils/Local.h"
  48. #include <cstdint>
  49. #ifdef EXPENSIVE_CHECKS
  50. #include "llvm/IR/Verifier.h"
  51. #endif
  52. #include <cassert>
  53. #include <optional>
  54. #include <string>
  55. using namespace llvm;
  56. #define DEBUG_TYPE "attributor"
  57. #define VERBOSE_DEBUG_TYPE DEBUG_TYPE "-verbose"
  58. DEBUG_COUNTER(ManifestDBGCounter, "attributor-manifest",
  59. "Determine what attributes are manifested in the IR");
  60. STATISTIC(NumFnDeleted, "Number of function deleted");
  61. STATISTIC(NumFnWithExactDefinition,
  62. "Number of functions with exact definitions");
  63. STATISTIC(NumFnWithoutExactDefinition,
  64. "Number of functions without exact definitions");
  65. STATISTIC(NumFnShallowWrappersCreated, "Number of shallow wrappers created");
  66. STATISTIC(NumAttributesTimedOut,
  67. "Number of abstract attributes timed out before fixpoint");
  68. STATISTIC(NumAttributesValidFixpoint,
  69. "Number of abstract attributes in a valid fixpoint state");
  70. STATISTIC(NumAttributesManifested,
  71. "Number of abstract attributes manifested in IR");
  72. // TODO: Determine a good default value.
  73. //
  74. // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
  75. // (when run with the first 5 abstract attributes). The results also indicate
  76. // that we never reach 32 iterations but always find a fixpoint sooner.
  77. //
  78. // This will become more evolved once we perform two interleaved fixpoint
  79. // iterations: bottom-up and top-down.
  80. static cl::opt<unsigned>
  81. SetFixpointIterations("attributor-max-iterations", cl::Hidden,
  82. cl::desc("Maximal number of fixpoint iterations."),
  83. cl::init(32));
  84. static cl::opt<unsigned, true> MaxInitializationChainLengthX(
  85. "attributor-max-initialization-chain-length", cl::Hidden,
  86. cl::desc(
  87. "Maximal number of chained initializations (to avoid stack overflows)"),
  88. cl::location(MaxInitializationChainLength), cl::init(1024));
  89. unsigned llvm::MaxInitializationChainLength;
  90. static cl::opt<bool> VerifyMaxFixpointIterations(
  91. "attributor-max-iterations-verify", cl::Hidden,
  92. cl::desc("Verify that max-iterations is a tight bound for a fixpoint"),
  93. cl::init(false));
  94. static cl::opt<bool> AnnotateDeclarationCallSites(
  95. "attributor-annotate-decl-cs", cl::Hidden,
  96. cl::desc("Annotate call sites of function declarations."), cl::init(false));
  97. static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion",
  98. cl::init(true), cl::Hidden);
  99. static cl::opt<bool>
  100. AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden,
  101. cl::desc("Allow the Attributor to create shallow "
  102. "wrappers for non-exact definitions."),
  103. cl::init(false));
  104. static cl::opt<bool>
  105. AllowDeepWrapper("attributor-allow-deep-wrappers", cl::Hidden,
  106. cl::desc("Allow the Attributor to use IP information "
  107. "derived from non-exact functions via cloning"),
  108. cl::init(false));
  109. // These options can only used for debug builds.
  110. #ifndef NDEBUG
  111. static cl::list<std::string>
  112. SeedAllowList("attributor-seed-allow-list", cl::Hidden,
  113. cl::desc("Comma seperated list of attribute names that are "
  114. "allowed to be seeded."),
  115. cl::CommaSeparated);
  116. static cl::list<std::string> FunctionSeedAllowList(
  117. "attributor-function-seed-allow-list", cl::Hidden,
  118. cl::desc("Comma seperated list of function names that are "
  119. "allowed to be seeded."),
  120. cl::CommaSeparated);
  121. #endif
  122. static cl::opt<bool>
  123. DumpDepGraph("attributor-dump-dep-graph", cl::Hidden,
  124. cl::desc("Dump the dependency graph to dot files."),
  125. cl::init(false));
  126. static cl::opt<std::string> DepGraphDotFileNamePrefix(
  127. "attributor-depgraph-dot-filename-prefix", cl::Hidden,
  128. cl::desc("The prefix used for the CallGraph dot file names."));
  129. static cl::opt<bool> ViewDepGraph("attributor-view-dep-graph", cl::Hidden,
  130. cl::desc("View the dependency graph."),
  131. cl::init(false));
  132. static cl::opt<bool> PrintDependencies("attributor-print-dep", cl::Hidden,
  133. cl::desc("Print attribute dependencies"),
  134. cl::init(false));
  135. static cl::opt<bool> EnableCallSiteSpecific(
  136. "attributor-enable-call-site-specific-deduction", cl::Hidden,
  137. cl::desc("Allow the Attributor to do call site specific analysis"),
  138. cl::init(false));
  139. static cl::opt<bool>
  140. PrintCallGraph("attributor-print-call-graph", cl::Hidden,
  141. cl::desc("Print Attributor's internal call graph"),
  142. cl::init(false));
  143. static cl::opt<bool> SimplifyAllLoads("attributor-simplify-all-loads",
  144. cl::Hidden,
  145. cl::desc("Try to simplify all loads."),
  146. cl::init(true));
  147. /// Logic operators for the change status enum class.
  148. ///
  149. ///{
  150. ChangeStatus llvm::operator|(ChangeStatus L, ChangeStatus R) {
  151. return L == ChangeStatus::CHANGED ? L : R;
  152. }
  153. ChangeStatus &llvm::operator|=(ChangeStatus &L, ChangeStatus R) {
  154. L = L | R;
  155. return L;
  156. }
  157. ChangeStatus llvm::operator&(ChangeStatus L, ChangeStatus R) {
  158. return L == ChangeStatus::UNCHANGED ? L : R;
  159. }
  160. ChangeStatus &llvm::operator&=(ChangeStatus &L, ChangeStatus R) {
  161. L = L & R;
  162. return L;
  163. }
  164. ///}
  165. bool AA::isNoSyncInst(Attributor &A, const Instruction &I,
  166. const AbstractAttribute &QueryingAA) {
  167. // We are looking for volatile instructions or non-relaxed atomics.
  168. if (const auto *CB = dyn_cast<CallBase>(&I)) {
  169. if (CB->hasFnAttr(Attribute::NoSync))
  170. return true;
  171. // Non-convergent and readnone imply nosync.
  172. if (!CB->isConvergent() && !CB->mayReadOrWriteMemory())
  173. return true;
  174. if (AANoSync::isNoSyncIntrinsic(&I))
  175. return true;
  176. const auto &NoSyncAA = A.getAAFor<AANoSync>(
  177. QueryingAA, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL);
  178. return NoSyncAA.isAssumedNoSync();
  179. }
  180. if (!I.mayReadOrWriteMemory())
  181. return true;
  182. return !I.isVolatile() && !AANoSync::isNonRelaxedAtomic(&I);
  183. }
  184. bool AA::isDynamicallyUnique(Attributor &A, const AbstractAttribute &QueryingAA,
  185. const Value &V, bool ForAnalysisOnly) {
  186. // TODO: See the AAInstanceInfo class comment.
  187. if (!ForAnalysisOnly)
  188. return false;
  189. auto &InstanceInfoAA = A.getAAFor<AAInstanceInfo>(
  190. QueryingAA, IRPosition::value(V), DepClassTy::OPTIONAL);
  191. return InstanceInfoAA.isAssumedUniqueForAnalysis();
  192. }
  193. Constant *AA::getInitialValueForObj(Value &Obj, Type &Ty,
  194. const TargetLibraryInfo *TLI,
  195. const DataLayout &DL,
  196. AA::RangeTy *RangePtr) {
  197. if (isa<AllocaInst>(Obj))
  198. return UndefValue::get(&Ty);
  199. if (Constant *Init = getInitialValueOfAllocation(&Obj, TLI, &Ty))
  200. return Init;
  201. auto *GV = dyn_cast<GlobalVariable>(&Obj);
  202. if (!GV)
  203. return nullptr;
  204. if (!GV->hasLocalLinkage() && !(GV->isConstant() && GV->hasInitializer()))
  205. return nullptr;
  206. if (!GV->hasInitializer())
  207. return UndefValue::get(&Ty);
  208. if (RangePtr && !RangePtr->offsetOrSizeAreUnknown()) {
  209. APInt Offset = APInt(64, RangePtr->Offset);
  210. return ConstantFoldLoadFromConst(GV->getInitializer(), &Ty, Offset, DL);
  211. }
  212. return ConstantFoldLoadFromUniformValue(GV->getInitializer(), &Ty);
  213. }
  214. bool AA::isValidInScope(const Value &V, const Function *Scope) {
  215. if (isa<Constant>(V))
  216. return true;
  217. if (auto *I = dyn_cast<Instruction>(&V))
  218. return I->getFunction() == Scope;
  219. if (auto *A = dyn_cast<Argument>(&V))
  220. return A->getParent() == Scope;
  221. return false;
  222. }
  223. bool AA::isValidAtPosition(const AA::ValueAndContext &VAC,
  224. InformationCache &InfoCache) {
  225. if (isa<Constant>(VAC.getValue()) || VAC.getValue() == VAC.getCtxI())
  226. return true;
  227. const Function *Scope = nullptr;
  228. const Instruction *CtxI = VAC.getCtxI();
  229. if (CtxI)
  230. Scope = CtxI->getFunction();
  231. if (auto *A = dyn_cast<Argument>(VAC.getValue()))
  232. return A->getParent() == Scope;
  233. if (auto *I = dyn_cast<Instruction>(VAC.getValue())) {
  234. if (I->getFunction() == Scope) {
  235. if (const DominatorTree *DT =
  236. InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(
  237. *Scope))
  238. return DT->dominates(I, CtxI);
  239. // Local dominance check mostly for the old PM passes.
  240. if (CtxI && I->getParent() == CtxI->getParent())
  241. return llvm::any_of(
  242. make_range(I->getIterator(), I->getParent()->end()),
  243. [&](const Instruction &AfterI) { return &AfterI == CtxI; });
  244. }
  245. }
  246. return false;
  247. }
  248. Value *AA::getWithType(Value &V, Type &Ty) {
  249. if (V.getType() == &Ty)
  250. return &V;
  251. if (isa<PoisonValue>(V))
  252. return PoisonValue::get(&Ty);
  253. if (isa<UndefValue>(V))
  254. return UndefValue::get(&Ty);
  255. if (auto *C = dyn_cast<Constant>(&V)) {
  256. if (C->isNullValue())
  257. return Constant::getNullValue(&Ty);
  258. if (C->getType()->isPointerTy() && Ty.isPointerTy())
  259. return ConstantExpr::getPointerCast(C, &Ty);
  260. if (C->getType()->getPrimitiveSizeInBits() >= Ty.getPrimitiveSizeInBits()) {
  261. if (C->getType()->isIntegerTy() && Ty.isIntegerTy())
  262. return ConstantExpr::getTrunc(C, &Ty, /* OnlyIfReduced */ true);
  263. if (C->getType()->isFloatingPointTy() && Ty.isFloatingPointTy())
  264. return ConstantExpr::getFPTrunc(C, &Ty, /* OnlyIfReduced */ true);
  265. }
  266. }
  267. return nullptr;
  268. }
  269. std::optional<Value *>
  270. AA::combineOptionalValuesInAAValueLatice(const std::optional<Value *> &A,
  271. const std::optional<Value *> &B,
  272. Type *Ty) {
  273. if (A == B)
  274. return A;
  275. if (!B)
  276. return A;
  277. if (*B == nullptr)
  278. return nullptr;
  279. if (!A)
  280. return Ty ? getWithType(**B, *Ty) : nullptr;
  281. if (*A == nullptr)
  282. return nullptr;
  283. if (!Ty)
  284. Ty = (*A)->getType();
  285. if (isa_and_nonnull<UndefValue>(*A))
  286. return getWithType(**B, *Ty);
  287. if (isa<UndefValue>(*B))
  288. return A;
  289. if (*A && *B && *A == getWithType(**B, *Ty))
  290. return A;
  291. return nullptr;
  292. }
  293. template <bool IsLoad, typename Ty>
  294. static bool getPotentialCopiesOfMemoryValue(
  295. Attributor &A, Ty &I, SmallSetVector<Value *, 4> &PotentialCopies,
  296. SmallSetVector<Instruction *, 4> &PotentialValueOrigins,
  297. const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
  298. bool OnlyExact) {
  299. LLVM_DEBUG(dbgs() << "Trying to determine the potential copies of " << I
  300. << " (only exact: " << OnlyExact << ")\n";);
  301. Value &Ptr = *I.getPointerOperand();
  302. // Containers to remember the pointer infos and new copies while we are not
  303. // sure that we can find all of them. If we abort we want to avoid spurious
  304. // dependences and potential copies in the provided container.
  305. SmallVector<const AAPointerInfo *> PIs;
  306. SmallVector<Value *> NewCopies;
  307. SmallVector<Instruction *> NewCopyOrigins;
  308. const auto *TLI =
  309. A.getInfoCache().getTargetLibraryInfoForFunction(*I.getFunction());
  310. auto Pred = [&](Value &Obj) {
  311. LLVM_DEBUG(dbgs() << "Visit underlying object " << Obj << "\n");
  312. if (isa<UndefValue>(&Obj))
  313. return true;
  314. if (isa<ConstantPointerNull>(&Obj)) {
  315. // A null pointer access can be undefined but any offset from null may
  316. // be OK. We do not try to optimize the latter.
  317. if (!NullPointerIsDefined(I.getFunction(),
  318. Ptr.getType()->getPointerAddressSpace()) &&
  319. A.getAssumedSimplified(Ptr, QueryingAA, UsedAssumedInformation,
  320. AA::Interprocedural) == &Obj)
  321. return true;
  322. LLVM_DEBUG(
  323. dbgs() << "Underlying object is a valid nullptr, giving up.\n";);
  324. return false;
  325. }
  326. // TODO: Use assumed noalias return.
  327. if (!isa<AllocaInst>(&Obj) && !isa<GlobalVariable>(&Obj) &&
  328. !(IsLoad ? isAllocationFn(&Obj, TLI) : isNoAliasCall(&Obj))) {
  329. LLVM_DEBUG(dbgs() << "Underlying object is not supported yet: " << Obj
  330. << "\n";);
  331. return false;
  332. }
  333. if (auto *GV = dyn_cast<GlobalVariable>(&Obj))
  334. if (!GV->hasLocalLinkage() &&
  335. !(GV->isConstant() && GV->hasInitializer())) {
  336. LLVM_DEBUG(dbgs() << "Underlying object is global with external "
  337. "linkage, not supported yet: "
  338. << Obj << "\n";);
  339. return false;
  340. }
  341. bool NullOnly = true;
  342. bool NullRequired = false;
  343. auto CheckForNullOnlyAndUndef = [&](std::optional<Value *> V,
  344. bool IsExact) {
  345. if (!V || *V == nullptr)
  346. NullOnly = false;
  347. else if (isa<UndefValue>(*V))
  348. /* No op */;
  349. else if (isa<Constant>(*V) && cast<Constant>(*V)->isNullValue())
  350. NullRequired = !IsExact;
  351. else
  352. NullOnly = false;
  353. };
  354. auto AdjustWrittenValueType = [&](const AAPointerInfo::Access &Acc,
  355. Value &V) {
  356. Value *AdjV = AA::getWithType(V, *I.getType());
  357. if (!AdjV) {
  358. LLVM_DEBUG(dbgs() << "Underlying object written but stored value "
  359. "cannot be converted to read type: "
  360. << *Acc.getRemoteInst() << " : " << *I.getType()
  361. << "\n";);
  362. }
  363. return AdjV;
  364. };
  365. auto CheckAccess = [&](const AAPointerInfo::Access &Acc, bool IsExact) {
  366. if ((IsLoad && !Acc.isWriteOrAssumption()) || (!IsLoad && !Acc.isRead()))
  367. return true;
  368. if (IsLoad && Acc.isWrittenValueYetUndetermined())
  369. return true;
  370. CheckForNullOnlyAndUndef(Acc.getContent(), IsExact);
  371. if (OnlyExact && !IsExact && !NullOnly &&
  372. !isa_and_nonnull<UndefValue>(Acc.getWrittenValue())) {
  373. LLVM_DEBUG(dbgs() << "Non exact access " << *Acc.getRemoteInst()
  374. << ", abort!\n");
  375. return false;
  376. }
  377. if (NullRequired && !NullOnly) {
  378. LLVM_DEBUG(dbgs() << "Required all `null` accesses due to non exact "
  379. "one, however found non-null one: "
  380. << *Acc.getRemoteInst() << ", abort!\n");
  381. return false;
  382. }
  383. if (IsLoad) {
  384. assert(isa<LoadInst>(I) && "Expected load or store instruction only!");
  385. if (!Acc.isWrittenValueUnknown()) {
  386. Value *V = AdjustWrittenValueType(Acc, *Acc.getWrittenValue());
  387. if (!V)
  388. return false;
  389. NewCopies.push_back(V);
  390. NewCopyOrigins.push_back(Acc.getRemoteInst());
  391. return true;
  392. }
  393. auto *SI = dyn_cast<StoreInst>(Acc.getRemoteInst());
  394. if (!SI) {
  395. LLVM_DEBUG(dbgs() << "Underlying object written through a non-store "
  396. "instruction not supported yet: "
  397. << *Acc.getRemoteInst() << "\n";);
  398. return false;
  399. }
  400. Value *V = AdjustWrittenValueType(Acc, *SI->getValueOperand());
  401. if (!V)
  402. return false;
  403. NewCopies.push_back(V);
  404. NewCopyOrigins.push_back(SI);
  405. } else {
  406. assert(isa<StoreInst>(I) && "Expected load or store instruction only!");
  407. auto *LI = dyn_cast<LoadInst>(Acc.getRemoteInst());
  408. if (!LI && OnlyExact) {
  409. LLVM_DEBUG(dbgs() << "Underlying object read through a non-load "
  410. "instruction not supported yet: "
  411. << *Acc.getRemoteInst() << "\n";);
  412. return false;
  413. }
  414. NewCopies.push_back(Acc.getRemoteInst());
  415. }
  416. return true;
  417. };
  418. // If the value has been written to we don't need the initial value of the
  419. // object.
  420. bool HasBeenWrittenTo = false;
  421. AA::RangeTy Range;
  422. auto &PI = A.getAAFor<AAPointerInfo>(QueryingAA, IRPosition::value(Obj),
  423. DepClassTy::NONE);
  424. if (!PI.forallInterferingAccesses(A, QueryingAA, I, CheckAccess,
  425. HasBeenWrittenTo, Range)) {
  426. LLVM_DEBUG(
  427. dbgs()
  428. << "Failed to verify all interfering accesses for underlying object: "
  429. << Obj << "\n");
  430. return false;
  431. }
  432. if (IsLoad && !HasBeenWrittenTo && !Range.isUnassigned()) {
  433. const DataLayout &DL = A.getDataLayout();
  434. Value *InitialValue =
  435. AA::getInitialValueForObj(Obj, *I.getType(), TLI, DL, &Range);
  436. if (!InitialValue) {
  437. LLVM_DEBUG(dbgs() << "Could not determine required initial value of "
  438. "underlying object, abort!\n");
  439. return false;
  440. }
  441. CheckForNullOnlyAndUndef(InitialValue, /* IsExact */ true);
  442. if (NullRequired && !NullOnly) {
  443. LLVM_DEBUG(dbgs() << "Non exact access but initial value that is not "
  444. "null or undef, abort!\n");
  445. return false;
  446. }
  447. NewCopies.push_back(InitialValue);
  448. NewCopyOrigins.push_back(nullptr);
  449. }
  450. PIs.push_back(&PI);
  451. return true;
  452. };
  453. const auto &AAUO = A.getAAFor<AAUnderlyingObjects>(
  454. QueryingAA, IRPosition::value(Ptr), DepClassTy::OPTIONAL);
  455. if (!AAUO.forallUnderlyingObjects(Pred)) {
  456. LLVM_DEBUG(
  457. dbgs() << "Underlying objects stored into could not be determined\n";);
  458. return false;
  459. }
  460. // Only if we were successful collection all potential copies we record
  461. // dependences (on non-fix AAPointerInfo AAs). We also only then modify the
  462. // given PotentialCopies container.
  463. for (const auto *PI : PIs) {
  464. if (!PI->getState().isAtFixpoint())
  465. UsedAssumedInformation = true;
  466. A.recordDependence(*PI, QueryingAA, DepClassTy::OPTIONAL);
  467. }
  468. PotentialCopies.insert(NewCopies.begin(), NewCopies.end());
  469. PotentialValueOrigins.insert(NewCopyOrigins.begin(), NewCopyOrigins.end());
  470. return true;
  471. }
  472. bool AA::getPotentiallyLoadedValues(
  473. Attributor &A, LoadInst &LI, SmallSetVector<Value *, 4> &PotentialValues,
  474. SmallSetVector<Instruction *, 4> &PotentialValueOrigins,
  475. const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
  476. bool OnlyExact) {
  477. return getPotentialCopiesOfMemoryValue</* IsLoad */ true>(
  478. A, LI, PotentialValues, PotentialValueOrigins, QueryingAA,
  479. UsedAssumedInformation, OnlyExact);
  480. }
  481. bool AA::getPotentialCopiesOfStoredValue(
  482. Attributor &A, StoreInst &SI, SmallSetVector<Value *, 4> &PotentialCopies,
  483. const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
  484. bool OnlyExact) {
  485. SmallSetVector<Instruction *, 4> PotentialValueOrigins;
  486. return getPotentialCopiesOfMemoryValue</* IsLoad */ false>(
  487. A, SI, PotentialCopies, PotentialValueOrigins, QueryingAA,
  488. UsedAssumedInformation, OnlyExact);
  489. }
  490. static bool isAssumedReadOnlyOrReadNone(Attributor &A, const IRPosition &IRP,
  491. const AbstractAttribute &QueryingAA,
  492. bool RequireReadNone, bool &IsKnown) {
  493. IRPosition::Kind Kind = IRP.getPositionKind();
  494. if (Kind == IRPosition::IRP_FUNCTION || Kind == IRPosition::IRP_CALL_SITE) {
  495. const auto &MemLocAA =
  496. A.getAAFor<AAMemoryLocation>(QueryingAA, IRP, DepClassTy::NONE);
  497. if (MemLocAA.isAssumedReadNone()) {
  498. IsKnown = MemLocAA.isKnownReadNone();
  499. if (!IsKnown)
  500. A.recordDependence(MemLocAA, QueryingAA, DepClassTy::OPTIONAL);
  501. return true;
  502. }
  503. }
  504. const auto &MemBehaviorAA =
  505. A.getAAFor<AAMemoryBehavior>(QueryingAA, IRP, DepClassTy::NONE);
  506. if (MemBehaviorAA.isAssumedReadNone() ||
  507. (!RequireReadNone && MemBehaviorAA.isAssumedReadOnly())) {
  508. IsKnown = RequireReadNone ? MemBehaviorAA.isKnownReadNone()
  509. : MemBehaviorAA.isKnownReadOnly();
  510. if (!IsKnown)
  511. A.recordDependence(MemBehaviorAA, QueryingAA, DepClassTy::OPTIONAL);
  512. return true;
  513. }
  514. return false;
  515. }
  516. bool AA::isAssumedReadOnly(Attributor &A, const IRPosition &IRP,
  517. const AbstractAttribute &QueryingAA, bool &IsKnown) {
  518. return isAssumedReadOnlyOrReadNone(A, IRP, QueryingAA,
  519. /* RequireReadNone */ false, IsKnown);
  520. }
  521. bool AA::isAssumedReadNone(Attributor &A, const IRPosition &IRP,
  522. const AbstractAttribute &QueryingAA, bool &IsKnown) {
  523. return isAssumedReadOnlyOrReadNone(A, IRP, QueryingAA,
  524. /* RequireReadNone */ true, IsKnown);
  525. }
  526. static bool
  527. isPotentiallyReachable(Attributor &A, const Instruction &FromI,
  528. const Instruction *ToI, const Function &ToFn,
  529. const AbstractAttribute &QueryingAA,
  530. const AA::InstExclusionSetTy *ExclusionSet,
  531. std::function<bool(const Function &F)> GoBackwardsCB) {
  532. LLVM_DEBUG({
  533. dbgs() << "[AA] isPotentiallyReachable @" << ToFn.getName() << " from "
  534. << FromI << " [GBCB: " << bool(GoBackwardsCB) << "][#ExS: "
  535. << (ExclusionSet ? std::to_string(ExclusionSet->size()) : "none")
  536. << "]\n";
  537. if (ExclusionSet)
  538. for (auto *ES : *ExclusionSet)
  539. dbgs() << *ES << "\n";
  540. });
  541. // If we can go arbitrarily backwards we will eventually reach an entry point
  542. // that can reach ToI. Only if a set of blocks through which we cannot go is
  543. // provided, or once we track internal functions not accessible from the
  544. // outside, it makes sense to perform backwards analysis in the absence of a
  545. // GoBackwardsCB.
  546. if (!GoBackwardsCB && !ExclusionSet) {
  547. LLVM_DEBUG(dbgs() << "[AA] check @" << ToFn.getName() << " from " << FromI
  548. << " is not checked backwards and does not have an "
  549. "exclusion set, abort\n");
  550. return true;
  551. }
  552. SmallPtrSet<const Instruction *, 8> Visited;
  553. SmallVector<const Instruction *> Worklist;
  554. Worklist.push_back(&FromI);
  555. while (!Worklist.empty()) {
  556. const Instruction *CurFromI = Worklist.pop_back_val();
  557. if (!Visited.insert(CurFromI).second)
  558. continue;
  559. const Function *FromFn = CurFromI->getFunction();
  560. if (FromFn == &ToFn) {
  561. if (!ToI)
  562. return true;
  563. LLVM_DEBUG(dbgs() << "[AA] check " << *ToI << " from " << *CurFromI
  564. << " intraprocedurally\n");
  565. const auto &ReachabilityAA = A.getAAFor<AAIntraFnReachability>(
  566. QueryingAA, IRPosition::function(ToFn), DepClassTy::OPTIONAL);
  567. bool Result =
  568. ReachabilityAA.isAssumedReachable(A, *CurFromI, *ToI, ExclusionSet);
  569. LLVM_DEBUG(dbgs() << "[AA] " << *CurFromI << " "
  570. << (Result ? "can potentially " : "cannot ") << "reach "
  571. << *ToI << " [Intra]\n");
  572. if (Result)
  573. return true;
  574. }
  575. bool Result = true;
  576. if (!ToFn.isDeclaration() && ToI) {
  577. const auto &ToReachabilityAA = A.getAAFor<AAIntraFnReachability>(
  578. QueryingAA, IRPosition::function(ToFn), DepClassTy::OPTIONAL);
  579. const Instruction &EntryI = ToFn.getEntryBlock().front();
  580. Result =
  581. ToReachabilityAA.isAssumedReachable(A, EntryI, *ToI, ExclusionSet);
  582. LLVM_DEBUG(dbgs() << "[AA] Entry " << EntryI << " of @" << ToFn.getName()
  583. << " " << (Result ? "can potentially " : "cannot ")
  584. << "reach @" << *ToI << " [ToFn]\n");
  585. }
  586. if (Result) {
  587. // The entry of the ToFn can reach the instruction ToI. If the current
  588. // instruction is already known to reach the ToFn.
  589. const auto &FnReachabilityAA = A.getAAFor<AAInterFnReachability>(
  590. QueryingAA, IRPosition::function(*FromFn), DepClassTy::OPTIONAL);
  591. Result = FnReachabilityAA.instructionCanReach(A, *CurFromI, ToFn,
  592. ExclusionSet);
  593. LLVM_DEBUG(dbgs() << "[AA] " << *CurFromI << " in @" << FromFn->getName()
  594. << " " << (Result ? "can potentially " : "cannot ")
  595. << "reach @" << ToFn.getName() << " [FromFn]\n");
  596. if (Result)
  597. return true;
  598. }
  599. // TODO: Check assumed nounwind.
  600. const auto &ReachabilityAA = A.getAAFor<AAIntraFnReachability>(
  601. QueryingAA, IRPosition::function(*FromFn), DepClassTy::OPTIONAL);
  602. auto ReturnInstCB = [&](Instruction &Ret) {
  603. bool Result =
  604. ReachabilityAA.isAssumedReachable(A, *CurFromI, Ret, ExclusionSet);
  605. LLVM_DEBUG(dbgs() << "[AA][Ret] " << *CurFromI << " "
  606. << (Result ? "can potentially " : "cannot ") << "reach "
  607. << Ret << " [Intra]\n");
  608. return !Result;
  609. };
  610. // Check if we can reach returns.
  611. bool UsedAssumedInformation = false;
  612. if (A.checkForAllInstructions(ReturnInstCB, FromFn, QueryingAA,
  613. {Instruction::Ret}, UsedAssumedInformation)) {
  614. LLVM_DEBUG(dbgs() << "[AA] No return is reachable, done\n");
  615. continue;
  616. }
  617. if (!GoBackwardsCB) {
  618. LLVM_DEBUG(dbgs() << "[AA] check @" << ToFn.getName() << " from " << FromI
  619. << " is not checked backwards, abort\n");
  620. return true;
  621. }
  622. // If we do not go backwards from the FromFn we are done here and so far we
  623. // could not find a way to reach ToFn/ToI.
  624. if (!GoBackwardsCB(*FromFn))
  625. continue;
  626. LLVM_DEBUG(dbgs() << "Stepping backwards to the call sites of @"
  627. << FromFn->getName() << "\n");
  628. auto CheckCallSite = [&](AbstractCallSite ACS) {
  629. CallBase *CB = ACS.getInstruction();
  630. if (!CB)
  631. return false;
  632. if (isa<InvokeInst>(CB))
  633. return false;
  634. Instruction *Inst = CB->getNextNonDebugInstruction();
  635. Worklist.push_back(Inst);
  636. return true;
  637. };
  638. Result = !A.checkForAllCallSites(CheckCallSite, *FromFn,
  639. /* RequireAllCallSites */ true,
  640. &QueryingAA, UsedAssumedInformation);
  641. if (Result) {
  642. LLVM_DEBUG(dbgs() << "[AA] stepping back to call sites from " << *CurFromI
  643. << " in @" << FromFn->getName()
  644. << " failed, give up\n");
  645. return true;
  646. }
  647. LLVM_DEBUG(dbgs() << "[AA] stepped back to call sites from " << *CurFromI
  648. << " in @" << FromFn->getName()
  649. << " worklist size is: " << Worklist.size() << "\n");
  650. }
  651. return false;
  652. }
  653. bool AA::isPotentiallyReachable(
  654. Attributor &A, const Instruction &FromI, const Instruction &ToI,
  655. const AbstractAttribute &QueryingAA,
  656. const AA::InstExclusionSetTy *ExclusionSet,
  657. std::function<bool(const Function &F)> GoBackwardsCB) {
  658. const Function *ToFn = ToI.getFunction();
  659. return ::isPotentiallyReachable(A, FromI, &ToI, *ToFn, QueryingAA,
  660. ExclusionSet, GoBackwardsCB);
  661. }
  662. bool AA::isPotentiallyReachable(
  663. Attributor &A, const Instruction &FromI, const Function &ToFn,
  664. const AbstractAttribute &QueryingAA,
  665. const AA::InstExclusionSetTy *ExclusionSet,
  666. std::function<bool(const Function &F)> GoBackwardsCB) {
  667. return ::isPotentiallyReachable(A, FromI, /* ToI */ nullptr, ToFn, QueryingAA,
  668. ExclusionSet, GoBackwardsCB);
  669. }
  670. bool AA::isAssumedThreadLocalObject(Attributor &A, Value &Obj,
  671. const AbstractAttribute &QueryingAA) {
  672. if (isa<UndefValue>(Obj))
  673. return true;
  674. if (isa<AllocaInst>(Obj)) {
  675. InformationCache &InfoCache = A.getInfoCache();
  676. if (!InfoCache.stackIsAccessibleByOtherThreads()) {
  677. LLVM_DEBUG(
  678. dbgs() << "[AA] Object '" << Obj
  679. << "' is thread local; stack objects are thread local.\n");
  680. return true;
  681. }
  682. const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
  683. QueryingAA, IRPosition::value(Obj), DepClassTy::OPTIONAL);
  684. LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj << "' is "
  685. << (NoCaptureAA.isAssumedNoCapture() ? "" : "not")
  686. << " thread local; "
  687. << (NoCaptureAA.isAssumedNoCapture() ? "non-" : "")
  688. << "captured stack object.\n");
  689. return NoCaptureAA.isAssumedNoCapture();
  690. }
  691. if (auto *GV = dyn_cast<GlobalVariable>(&Obj)) {
  692. if (GV->isConstant()) {
  693. LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
  694. << "' is thread local; constant global\n");
  695. return true;
  696. }
  697. if (GV->isThreadLocal()) {
  698. LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
  699. << "' is thread local; thread local global\n");
  700. return true;
  701. }
  702. }
  703. if (A.getInfoCache().targetIsGPU()) {
  704. if (Obj.getType()->getPointerAddressSpace() ==
  705. (int)AA::GPUAddressSpace::Local) {
  706. LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
  707. << "' is thread local; GPU local memory\n");
  708. return true;
  709. }
  710. if (Obj.getType()->getPointerAddressSpace() ==
  711. (int)AA::GPUAddressSpace::Constant) {
  712. LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
  713. << "' is thread local; GPU constant memory\n");
  714. return true;
  715. }
  716. }
  717. LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj << "' is not thread local\n");
  718. return false;
  719. }
  720. bool AA::isPotentiallyAffectedByBarrier(Attributor &A, const Instruction &I,
  721. const AbstractAttribute &QueryingAA) {
  722. if (!I.mayHaveSideEffects() && !I.mayReadFromMemory())
  723. return false;
  724. SmallSetVector<const Value *, 8> Ptrs;
  725. auto AddLocationPtr = [&](std::optional<MemoryLocation> Loc) {
  726. if (!Loc || !Loc->Ptr) {
  727. LLVM_DEBUG(
  728. dbgs() << "[AA] Access to unknown location; -> requires barriers\n");
  729. return false;
  730. }
  731. Ptrs.insert(Loc->Ptr);
  732. return true;
  733. };
  734. if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&I)) {
  735. if (!AddLocationPtr(MemoryLocation::getForDest(MI)))
  736. return true;
  737. if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(&I))
  738. if (!AddLocationPtr(MemoryLocation::getForSource(MTI)))
  739. return true;
  740. } else if (!AddLocationPtr(MemoryLocation::getOrNone(&I)))
  741. return true;
  742. return isPotentiallyAffectedByBarrier(A, Ptrs.getArrayRef(), QueryingAA, &I);
  743. }
  744. bool AA::isPotentiallyAffectedByBarrier(Attributor &A,
  745. ArrayRef<const Value *> Ptrs,
  746. const AbstractAttribute &QueryingAA,
  747. const Instruction *CtxI) {
  748. for (const Value *Ptr : Ptrs) {
  749. if (!Ptr) {
  750. LLVM_DEBUG(dbgs() << "[AA] nullptr; -> requires barriers\n");
  751. return true;
  752. }
  753. auto Pred = [&](Value &Obj) {
  754. if (AA::isAssumedThreadLocalObject(A, Obj, QueryingAA))
  755. return true;
  756. LLVM_DEBUG(dbgs() << "[AA] Access to '" << Obj << "' via '" << *Ptr
  757. << "'; -> requires barrier\n");
  758. return false;
  759. };
  760. const auto &UnderlyingObjsAA = A.getAAFor<AAUnderlyingObjects>(
  761. QueryingAA, IRPosition::value(*Ptr), DepClassTy::OPTIONAL);
  762. if (!UnderlyingObjsAA.forallUnderlyingObjects(Pred))
  763. return true;
  764. }
  765. return false;
  766. }
  767. /// Return true if \p New is equal or worse than \p Old.
  768. static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
  769. if (!Old.isIntAttribute())
  770. return true;
  771. return Old.getValueAsInt() >= New.getValueAsInt();
  772. }
  773. /// Return true if the information provided by \p Attr was added to the
  774. /// attribute list \p Attrs. This is only the case if it was not already present
  775. /// in \p Attrs at the position describe by \p PK and \p AttrIdx.
  776. static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
  777. AttributeList &Attrs, int AttrIdx,
  778. bool ForceReplace = false) {
  779. if (Attr.isEnumAttribute()) {
  780. Attribute::AttrKind Kind = Attr.getKindAsEnum();
  781. if (Attrs.hasAttributeAtIndex(AttrIdx, Kind))
  782. if (!ForceReplace &&
  783. isEqualOrWorse(Attr, Attrs.getAttributeAtIndex(AttrIdx, Kind)))
  784. return false;
  785. Attrs = Attrs.addAttributeAtIndex(Ctx, AttrIdx, Attr);
  786. return true;
  787. }
  788. if (Attr.isStringAttribute()) {
  789. StringRef Kind = Attr.getKindAsString();
  790. if (Attrs.hasAttributeAtIndex(AttrIdx, Kind))
  791. if (!ForceReplace &&
  792. isEqualOrWorse(Attr, Attrs.getAttributeAtIndex(AttrIdx, Kind)))
  793. return false;
  794. Attrs = Attrs.addAttributeAtIndex(Ctx, AttrIdx, Attr);
  795. return true;
  796. }
  797. if (Attr.isIntAttribute()) {
  798. Attribute::AttrKind Kind = Attr.getKindAsEnum();
  799. if (Attrs.hasAttributeAtIndex(AttrIdx, Kind))
  800. if (!ForceReplace &&
  801. isEqualOrWorse(Attr, Attrs.getAttributeAtIndex(AttrIdx, Kind)))
  802. return false;
  803. Attrs = Attrs.removeAttributeAtIndex(Ctx, AttrIdx, Kind);
  804. Attrs = Attrs.addAttributeAtIndex(Ctx, AttrIdx, Attr);
  805. return true;
  806. }
  807. llvm_unreachable("Expected enum or string attribute!");
  808. }
  809. Argument *IRPosition::getAssociatedArgument() const {
  810. if (getPositionKind() == IRP_ARGUMENT)
  811. return cast<Argument>(&getAnchorValue());
  812. // Not an Argument and no argument number means this is not a call site
  813. // argument, thus we cannot find a callback argument to return.
  814. int ArgNo = getCallSiteArgNo();
  815. if (ArgNo < 0)
  816. return nullptr;
  817. // Use abstract call sites to make the connection between the call site
  818. // values and the ones in callbacks. If a callback was found that makes use
  819. // of the underlying call site operand, we want the corresponding callback
  820. // callee argument and not the direct callee argument.
  821. std::optional<Argument *> CBCandidateArg;
  822. SmallVector<const Use *, 4> CallbackUses;
  823. const auto &CB = cast<CallBase>(getAnchorValue());
  824. AbstractCallSite::getCallbackUses(CB, CallbackUses);
  825. for (const Use *U : CallbackUses) {
  826. AbstractCallSite ACS(U);
  827. assert(ACS && ACS.isCallbackCall());
  828. if (!ACS.getCalledFunction())
  829. continue;
  830. for (unsigned u = 0, e = ACS.getNumArgOperands(); u < e; u++) {
  831. // Test if the underlying call site operand is argument number u of the
  832. // callback callee.
  833. if (ACS.getCallArgOperandNo(u) != ArgNo)
  834. continue;
  835. assert(ACS.getCalledFunction()->arg_size() > u &&
  836. "ACS mapped into var-args arguments!");
  837. if (CBCandidateArg) {
  838. CBCandidateArg = nullptr;
  839. break;
  840. }
  841. CBCandidateArg = ACS.getCalledFunction()->getArg(u);
  842. }
  843. }
  844. // If we found a unique callback candidate argument, return it.
  845. if (CBCandidateArg && *CBCandidateArg)
  846. return *CBCandidateArg;
  847. // If no callbacks were found, or none used the underlying call site operand
  848. // exclusively, use the direct callee argument if available.
  849. const Function *Callee = CB.getCalledFunction();
  850. if (Callee && Callee->arg_size() > unsigned(ArgNo))
  851. return Callee->getArg(ArgNo);
  852. return nullptr;
  853. }
  854. ChangeStatus AbstractAttribute::update(Attributor &A) {
  855. ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
  856. if (getState().isAtFixpoint())
  857. return HasChanged;
  858. LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
  859. HasChanged = updateImpl(A);
  860. LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
  861. << "\n");
  862. return HasChanged;
  863. }
  864. ChangeStatus
  865. IRAttributeManifest::manifestAttrs(Attributor &A, const IRPosition &IRP,
  866. const ArrayRef<Attribute> &DeducedAttrs,
  867. bool ForceReplace) {
  868. Function *ScopeFn = IRP.getAnchorScope();
  869. IRPosition::Kind PK = IRP.getPositionKind();
  870. // In the following some generic code that will manifest attributes in
  871. // DeducedAttrs if they improve the current IR. Due to the different
  872. // annotation positions we use the underlying AttributeList interface.
  873. AttributeList Attrs;
  874. switch (PK) {
  875. case IRPosition::IRP_INVALID:
  876. case IRPosition::IRP_FLOAT:
  877. return ChangeStatus::UNCHANGED;
  878. case IRPosition::IRP_ARGUMENT:
  879. case IRPosition::IRP_FUNCTION:
  880. case IRPosition::IRP_RETURNED:
  881. Attrs = ScopeFn->getAttributes();
  882. break;
  883. case IRPosition::IRP_CALL_SITE:
  884. case IRPosition::IRP_CALL_SITE_RETURNED:
  885. case IRPosition::IRP_CALL_SITE_ARGUMENT:
  886. Attrs = cast<CallBase>(IRP.getAnchorValue()).getAttributes();
  887. break;
  888. }
  889. ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
  890. LLVMContext &Ctx = IRP.getAnchorValue().getContext();
  891. for (const Attribute &Attr : DeducedAttrs) {
  892. if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx(), ForceReplace))
  893. continue;
  894. HasChanged = ChangeStatus::CHANGED;
  895. }
  896. if (HasChanged == ChangeStatus::UNCHANGED)
  897. return HasChanged;
  898. switch (PK) {
  899. case IRPosition::IRP_ARGUMENT:
  900. case IRPosition::IRP_FUNCTION:
  901. case IRPosition::IRP_RETURNED:
  902. ScopeFn->setAttributes(Attrs);
  903. break;
  904. case IRPosition::IRP_CALL_SITE:
  905. case IRPosition::IRP_CALL_SITE_RETURNED:
  906. case IRPosition::IRP_CALL_SITE_ARGUMENT:
  907. cast<CallBase>(IRP.getAnchorValue()).setAttributes(Attrs);
  908. break;
  909. case IRPosition::IRP_INVALID:
  910. case IRPosition::IRP_FLOAT:
  911. break;
  912. }
  913. return HasChanged;
  914. }
  915. const IRPosition IRPosition::EmptyKey(DenseMapInfo<void *>::getEmptyKey());
  916. const IRPosition
  917. IRPosition::TombstoneKey(DenseMapInfo<void *>::getTombstoneKey());
  918. SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) {
  919. IRPositions.emplace_back(IRP);
  920. // Helper to determine if operand bundles on a call site are benin or
  921. // potentially problematic. We handle only llvm.assume for now.
  922. auto CanIgnoreOperandBundles = [](const CallBase &CB) {
  923. return (isa<IntrinsicInst>(CB) &&
  924. cast<IntrinsicInst>(CB).getIntrinsicID() == Intrinsic ::assume);
  925. };
  926. const auto *CB = dyn_cast<CallBase>(&IRP.getAnchorValue());
  927. switch (IRP.getPositionKind()) {
  928. case IRPosition::IRP_INVALID:
  929. case IRPosition::IRP_FLOAT:
  930. case IRPosition::IRP_FUNCTION:
  931. return;
  932. case IRPosition::IRP_ARGUMENT:
  933. case IRPosition::IRP_RETURNED:
  934. IRPositions.emplace_back(IRPosition::function(*IRP.getAnchorScope()));
  935. return;
  936. case IRPosition::IRP_CALL_SITE:
  937. assert(CB && "Expected call site!");
  938. // TODO: We need to look at the operand bundles similar to the redirection
  939. // in CallBase.
  940. if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB))
  941. if (const Function *Callee = CB->getCalledFunction())
  942. IRPositions.emplace_back(IRPosition::function(*Callee));
  943. return;
  944. case IRPosition::IRP_CALL_SITE_RETURNED:
  945. assert(CB && "Expected call site!");
  946. // TODO: We need to look at the operand bundles similar to the redirection
  947. // in CallBase.
  948. if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
  949. if (const Function *Callee = CB->getCalledFunction()) {
  950. IRPositions.emplace_back(IRPosition::returned(*Callee));
  951. IRPositions.emplace_back(IRPosition::function(*Callee));
  952. for (const Argument &Arg : Callee->args())
  953. if (Arg.hasReturnedAttr()) {
  954. IRPositions.emplace_back(
  955. IRPosition::callsite_argument(*CB, Arg.getArgNo()));
  956. IRPositions.emplace_back(
  957. IRPosition::value(*CB->getArgOperand(Arg.getArgNo())));
  958. IRPositions.emplace_back(IRPosition::argument(Arg));
  959. }
  960. }
  961. }
  962. IRPositions.emplace_back(IRPosition::callsite_function(*CB));
  963. return;
  964. case IRPosition::IRP_CALL_SITE_ARGUMENT: {
  965. assert(CB && "Expected call site!");
  966. // TODO: We need to look at the operand bundles similar to the redirection
  967. // in CallBase.
  968. if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
  969. const Function *Callee = CB->getCalledFunction();
  970. if (Callee) {
  971. if (Argument *Arg = IRP.getAssociatedArgument())
  972. IRPositions.emplace_back(IRPosition::argument(*Arg));
  973. IRPositions.emplace_back(IRPosition::function(*Callee));
  974. }
  975. }
  976. IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue()));
  977. return;
  978. }
  979. }
  980. }
  981. bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs,
  982. bool IgnoreSubsumingPositions, Attributor *A) const {
  983. SmallVector<Attribute, 4> Attrs;
  984. for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) {
  985. for (Attribute::AttrKind AK : AKs)
  986. if (EquivIRP.getAttrsFromIRAttr(AK, Attrs))
  987. return true;
  988. // The first position returned by the SubsumingPositionIterator is
  989. // always the position itself. If we ignore subsuming positions we
  990. // are done after the first iteration.
  991. if (IgnoreSubsumingPositions)
  992. break;
  993. }
  994. if (A)
  995. for (Attribute::AttrKind AK : AKs)
  996. if (getAttrsFromAssumes(AK, Attrs, *A))
  997. return true;
  998. return false;
  999. }
  1000. void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs,
  1001. SmallVectorImpl<Attribute> &Attrs,
  1002. bool IgnoreSubsumingPositions, Attributor *A) const {
  1003. for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) {
  1004. for (Attribute::AttrKind AK : AKs)
  1005. EquivIRP.getAttrsFromIRAttr(AK, Attrs);
  1006. // The first position returned by the SubsumingPositionIterator is
  1007. // always the position itself. If we ignore subsuming positions we
  1008. // are done after the first iteration.
  1009. if (IgnoreSubsumingPositions)
  1010. break;
  1011. }
  1012. if (A)
  1013. for (Attribute::AttrKind AK : AKs)
  1014. getAttrsFromAssumes(AK, Attrs, *A);
  1015. }
  1016. bool IRPosition::getAttrsFromIRAttr(Attribute::AttrKind AK,
  1017. SmallVectorImpl<Attribute> &Attrs) const {
  1018. if (getPositionKind() == IRP_INVALID || getPositionKind() == IRP_FLOAT)
  1019. return false;
  1020. AttributeList AttrList;
  1021. if (const auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
  1022. AttrList = CB->getAttributes();
  1023. else
  1024. AttrList = getAssociatedFunction()->getAttributes();
  1025. bool HasAttr = AttrList.hasAttributeAtIndex(getAttrIdx(), AK);
  1026. if (HasAttr)
  1027. Attrs.push_back(AttrList.getAttributeAtIndex(getAttrIdx(), AK));
  1028. return HasAttr;
  1029. }
  1030. bool IRPosition::getAttrsFromAssumes(Attribute::AttrKind AK,
  1031. SmallVectorImpl<Attribute> &Attrs,
  1032. Attributor &A) const {
  1033. assert(getPositionKind() != IRP_INVALID && "Did expect a valid position!");
  1034. Value &AssociatedValue = getAssociatedValue();
  1035. const Assume2KnowledgeMap &A2K =
  1036. A.getInfoCache().getKnowledgeMap().lookup({&AssociatedValue, AK});
  1037. // Check if we found any potential assume use, if not we don't need to create
  1038. // explorer iterators.
  1039. if (A2K.empty())
  1040. return false;
  1041. LLVMContext &Ctx = AssociatedValue.getContext();
  1042. unsigned AttrsSize = Attrs.size();
  1043. MustBeExecutedContextExplorer &Explorer =
  1044. A.getInfoCache().getMustBeExecutedContextExplorer();
  1045. auto EIt = Explorer.begin(getCtxI()), EEnd = Explorer.end(getCtxI());
  1046. for (const auto &It : A2K)
  1047. if (Explorer.findInContextOf(It.first, EIt, EEnd))
  1048. Attrs.push_back(Attribute::get(Ctx, AK, It.second.Max));
  1049. return AttrsSize != Attrs.size();
  1050. }
  1051. void IRPosition::verify() {
  1052. #ifdef EXPENSIVE_CHECKS
  1053. switch (getPositionKind()) {
  1054. case IRP_INVALID:
  1055. assert((CBContext == nullptr) &&
  1056. "Invalid position must not have CallBaseContext!");
  1057. assert(!Enc.getOpaqueValue() &&
  1058. "Expected a nullptr for an invalid position!");
  1059. return;
  1060. case IRP_FLOAT:
  1061. assert((!isa<Argument>(&getAssociatedValue())) &&
  1062. "Expected specialized kind for argument values!");
  1063. return;
  1064. case IRP_RETURNED:
  1065. assert(isa<Function>(getAsValuePtr()) &&
  1066. "Expected function for a 'returned' position!");
  1067. assert(getAsValuePtr() == &getAssociatedValue() &&
  1068. "Associated value mismatch!");
  1069. return;
  1070. case IRP_CALL_SITE_RETURNED:
  1071. assert((CBContext == nullptr) &&
  1072. "'call site returned' position must not have CallBaseContext!");
  1073. assert((isa<CallBase>(getAsValuePtr())) &&
  1074. "Expected call base for 'call site returned' position!");
  1075. assert(getAsValuePtr() == &getAssociatedValue() &&
  1076. "Associated value mismatch!");
  1077. return;
  1078. case IRP_CALL_SITE:
  1079. assert((CBContext == nullptr) &&
  1080. "'call site function' position must not have CallBaseContext!");
  1081. assert((isa<CallBase>(getAsValuePtr())) &&
  1082. "Expected call base for 'call site function' position!");
  1083. assert(getAsValuePtr() == &getAssociatedValue() &&
  1084. "Associated value mismatch!");
  1085. return;
  1086. case IRP_FUNCTION:
  1087. assert(isa<Function>(getAsValuePtr()) &&
  1088. "Expected function for a 'function' position!");
  1089. assert(getAsValuePtr() == &getAssociatedValue() &&
  1090. "Associated value mismatch!");
  1091. return;
  1092. case IRP_ARGUMENT:
  1093. assert(isa<Argument>(getAsValuePtr()) &&
  1094. "Expected argument for a 'argument' position!");
  1095. assert(getAsValuePtr() == &getAssociatedValue() &&
  1096. "Associated value mismatch!");
  1097. return;
  1098. case IRP_CALL_SITE_ARGUMENT: {
  1099. assert((CBContext == nullptr) &&
  1100. "'call site argument' position must not have CallBaseContext!");
  1101. Use *U = getAsUsePtr();
  1102. (void)U; // Silence unused variable warning.
  1103. assert(U && "Expected use for a 'call site argument' position!");
  1104. assert(isa<CallBase>(U->getUser()) &&
  1105. "Expected call base user for a 'call site argument' position!");
  1106. assert(cast<CallBase>(U->getUser())->isArgOperand(U) &&
  1107. "Expected call base argument operand for a 'call site argument' "
  1108. "position");
  1109. assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) ==
  1110. unsigned(getCallSiteArgNo()) &&
  1111. "Argument number mismatch!");
  1112. assert(U->get() == &getAssociatedValue() && "Associated value mismatch!");
  1113. return;
  1114. }
  1115. }
  1116. #endif
  1117. }
  1118. std::optional<Constant *>
  1119. Attributor::getAssumedConstant(const IRPosition &IRP,
  1120. const AbstractAttribute &AA,
  1121. bool &UsedAssumedInformation) {
  1122. // First check all callbacks provided by outside AAs. If any of them returns
  1123. // a non-null value that is different from the associated value, or
  1124. // std::nullopt, we assume it's simplified.
  1125. for (auto &CB : SimplificationCallbacks.lookup(IRP)) {
  1126. std::optional<Value *> SimplifiedV = CB(IRP, &AA, UsedAssumedInformation);
  1127. if (!SimplifiedV)
  1128. return std::nullopt;
  1129. if (isa_and_nonnull<Constant>(*SimplifiedV))
  1130. return cast<Constant>(*SimplifiedV);
  1131. return nullptr;
  1132. }
  1133. if (auto *C = dyn_cast<Constant>(&IRP.getAssociatedValue()))
  1134. return C;
  1135. SmallVector<AA::ValueAndContext> Values;
  1136. if (getAssumedSimplifiedValues(IRP, &AA, Values,
  1137. AA::ValueScope::Interprocedural,
  1138. UsedAssumedInformation)) {
  1139. if (Values.empty())
  1140. return std::nullopt;
  1141. if (auto *C = dyn_cast_or_null<Constant>(
  1142. AAPotentialValues::getSingleValue(*this, AA, IRP, Values)))
  1143. return C;
  1144. }
  1145. return nullptr;
  1146. }
  1147. std::optional<Value *> Attributor::getAssumedSimplified(
  1148. const IRPosition &IRP, const AbstractAttribute *AA,
  1149. bool &UsedAssumedInformation, AA::ValueScope S) {
  1150. // First check all callbacks provided by outside AAs. If any of them returns
  1151. // a non-null value that is different from the associated value, or
  1152. // std::nullopt, we assume it's simplified.
  1153. for (auto &CB : SimplificationCallbacks.lookup(IRP))
  1154. return CB(IRP, AA, UsedAssumedInformation);
  1155. SmallVector<AA::ValueAndContext> Values;
  1156. if (!getAssumedSimplifiedValues(IRP, AA, Values, S, UsedAssumedInformation))
  1157. return &IRP.getAssociatedValue();
  1158. if (Values.empty())
  1159. return std::nullopt;
  1160. if (AA)
  1161. if (Value *V = AAPotentialValues::getSingleValue(*this, *AA, IRP, Values))
  1162. return V;
  1163. if (IRP.getPositionKind() == IRPosition::IRP_RETURNED ||
  1164. IRP.getPositionKind() == IRPosition::IRP_CALL_SITE_RETURNED)
  1165. return nullptr;
  1166. return &IRP.getAssociatedValue();
  1167. }
  1168. bool Attributor::getAssumedSimplifiedValues(
  1169. const IRPosition &IRP, const AbstractAttribute *AA,
  1170. SmallVectorImpl<AA::ValueAndContext> &Values, AA::ValueScope S,
  1171. bool &UsedAssumedInformation) {
  1172. // First check all callbacks provided by outside AAs. If any of them returns
  1173. // a non-null value that is different from the associated value, or
  1174. // std::nullopt, we assume it's simplified.
  1175. const auto &SimplificationCBs = SimplificationCallbacks.lookup(IRP);
  1176. for (const auto &CB : SimplificationCBs) {
  1177. std::optional<Value *> CBResult = CB(IRP, AA, UsedAssumedInformation);
  1178. if (!CBResult.has_value())
  1179. continue;
  1180. Value *V = *CBResult;
  1181. if (!V)
  1182. return false;
  1183. if ((S & AA::ValueScope::Interprocedural) ||
  1184. AA::isValidInScope(*V, IRP.getAnchorScope()))
  1185. Values.push_back(AA::ValueAndContext{*V, nullptr});
  1186. else
  1187. return false;
  1188. }
  1189. if (!SimplificationCBs.empty())
  1190. return true;
  1191. // If no high-level/outside simplification occurred, use AAPotentialValues.
  1192. const auto &PotentialValuesAA =
  1193. getOrCreateAAFor<AAPotentialValues>(IRP, AA, DepClassTy::OPTIONAL);
  1194. if (!PotentialValuesAA.getAssumedSimplifiedValues(*this, Values, S))
  1195. return false;
  1196. UsedAssumedInformation |= !PotentialValuesAA.isAtFixpoint();
  1197. return true;
  1198. }
  1199. std::optional<Value *> Attributor::translateArgumentToCallSiteContent(
  1200. std::optional<Value *> V, CallBase &CB, const AbstractAttribute &AA,
  1201. bool &UsedAssumedInformation) {
  1202. if (!V)
  1203. return V;
  1204. if (*V == nullptr || isa<Constant>(*V))
  1205. return V;
  1206. if (auto *Arg = dyn_cast<Argument>(*V))
  1207. if (CB.getCalledFunction() == Arg->getParent())
  1208. if (!Arg->hasPointeeInMemoryValueAttr())
  1209. return getAssumedSimplified(
  1210. IRPosition::callsite_argument(CB, Arg->getArgNo()), AA,
  1211. UsedAssumedInformation, AA::Intraprocedural);
  1212. return nullptr;
  1213. }
  1214. Attributor::~Attributor() {
  1215. // The abstract attributes are allocated via the BumpPtrAllocator Allocator,
  1216. // thus we cannot delete them. We can, and want to, destruct them though.
  1217. for (auto &It : AAMap) {
  1218. AbstractAttribute *AA = It.getSecond();
  1219. AA->~AbstractAttribute();
  1220. }
  1221. }
  1222. bool Attributor::isAssumedDead(const AbstractAttribute &AA,
  1223. const AAIsDead *FnLivenessAA,
  1224. bool &UsedAssumedInformation,
  1225. bool CheckBBLivenessOnly, DepClassTy DepClass) {
  1226. const IRPosition &IRP = AA.getIRPosition();
  1227. if (!Functions.count(IRP.getAnchorScope()))
  1228. return false;
  1229. return isAssumedDead(IRP, &AA, FnLivenessAA, UsedAssumedInformation,
  1230. CheckBBLivenessOnly, DepClass);
  1231. }
  1232. bool Attributor::isAssumedDead(const Use &U,
  1233. const AbstractAttribute *QueryingAA,
  1234. const AAIsDead *FnLivenessAA,
  1235. bool &UsedAssumedInformation,
  1236. bool CheckBBLivenessOnly, DepClassTy DepClass) {
  1237. Instruction *UserI = dyn_cast<Instruction>(U.getUser());
  1238. if (!UserI)
  1239. return isAssumedDead(IRPosition::value(*U.get()), QueryingAA, FnLivenessAA,
  1240. UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
  1241. if (auto *CB = dyn_cast<CallBase>(UserI)) {
  1242. // For call site argument uses we can check if the argument is
  1243. // unused/dead.
  1244. if (CB->isArgOperand(&U)) {
  1245. const IRPosition &CSArgPos =
  1246. IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
  1247. return isAssumedDead(CSArgPos, QueryingAA, FnLivenessAA,
  1248. UsedAssumedInformation, CheckBBLivenessOnly,
  1249. DepClass);
  1250. }
  1251. } else if (ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) {
  1252. const IRPosition &RetPos = IRPosition::returned(*RI->getFunction());
  1253. return isAssumedDead(RetPos, QueryingAA, FnLivenessAA,
  1254. UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
  1255. } else if (PHINode *PHI = dyn_cast<PHINode>(UserI)) {
  1256. BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
  1257. return isAssumedDead(*IncomingBB->getTerminator(), QueryingAA, FnLivenessAA,
  1258. UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
  1259. } else if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  1260. if (!CheckBBLivenessOnly && SI->getPointerOperand() != U.get()) {
  1261. const IRPosition IRP = IRPosition::inst(*SI);
  1262. const AAIsDead &IsDeadAA =
  1263. getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClassTy::NONE);
  1264. if (IsDeadAA.isRemovableStore()) {
  1265. if (QueryingAA)
  1266. recordDependence(IsDeadAA, *QueryingAA, DepClass);
  1267. if (!IsDeadAA.isKnown(AAIsDead::IS_REMOVABLE))
  1268. UsedAssumedInformation = true;
  1269. return true;
  1270. }
  1271. }
  1272. }
  1273. return isAssumedDead(IRPosition::inst(*UserI), QueryingAA, FnLivenessAA,
  1274. UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
  1275. }
  1276. bool Attributor::isAssumedDead(const Instruction &I,
  1277. const AbstractAttribute *QueryingAA,
  1278. const AAIsDead *FnLivenessAA,
  1279. bool &UsedAssumedInformation,
  1280. bool CheckBBLivenessOnly, DepClassTy DepClass,
  1281. bool CheckForDeadStore) {
  1282. const IRPosition::CallBaseContext *CBCtx =
  1283. QueryingAA ? QueryingAA->getCallBaseContext() : nullptr;
  1284. if (ManifestAddedBlocks.contains(I.getParent()))
  1285. return false;
  1286. const Function &F = *I.getFunction();
  1287. if (!FnLivenessAA || FnLivenessAA->getAnchorScope() != &F)
  1288. FnLivenessAA = &getOrCreateAAFor<AAIsDead>(IRPosition::function(F, CBCtx),
  1289. QueryingAA, DepClassTy::NONE);
  1290. // Don't use recursive reasoning.
  1291. if (QueryingAA == FnLivenessAA)
  1292. return false;
  1293. // If we have a context instruction and a liveness AA we use it.
  1294. if (CheckBBLivenessOnly ? FnLivenessAA->isAssumedDead(I.getParent())
  1295. : FnLivenessAA->isAssumedDead(&I)) {
  1296. if (QueryingAA)
  1297. recordDependence(*FnLivenessAA, *QueryingAA, DepClass);
  1298. if (!FnLivenessAA->isKnownDead(&I))
  1299. UsedAssumedInformation = true;
  1300. return true;
  1301. }
  1302. if (CheckBBLivenessOnly)
  1303. return false;
  1304. const IRPosition IRP = IRPosition::inst(I, CBCtx);
  1305. const AAIsDead &IsDeadAA =
  1306. getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClassTy::NONE);
  1307. // Don't use recursive reasoning.
  1308. if (QueryingAA == &IsDeadAA)
  1309. return false;
  1310. if (IsDeadAA.isAssumedDead()) {
  1311. if (QueryingAA)
  1312. recordDependence(IsDeadAA, *QueryingAA, DepClass);
  1313. if (!IsDeadAA.isKnownDead())
  1314. UsedAssumedInformation = true;
  1315. return true;
  1316. }
  1317. if (CheckForDeadStore && isa<StoreInst>(I) && IsDeadAA.isRemovableStore()) {
  1318. if (QueryingAA)
  1319. recordDependence(IsDeadAA, *QueryingAA, DepClass);
  1320. if (!IsDeadAA.isKnownDead())
  1321. UsedAssumedInformation = true;
  1322. return true;
  1323. }
  1324. return false;
  1325. }
  1326. bool Attributor::isAssumedDead(const IRPosition &IRP,
  1327. const AbstractAttribute *QueryingAA,
  1328. const AAIsDead *FnLivenessAA,
  1329. bool &UsedAssumedInformation,
  1330. bool CheckBBLivenessOnly, DepClassTy DepClass) {
  1331. // Don't check liveness for constants, e.g. functions, used as (floating)
  1332. // values since the context instruction and such is here meaningless.
  1333. if (IRP.getPositionKind() == IRPosition::IRP_FLOAT &&
  1334. isa<Constant>(IRP.getAssociatedValue())) {
  1335. return false;
  1336. }
  1337. Instruction *CtxI = IRP.getCtxI();
  1338. if (CtxI &&
  1339. isAssumedDead(*CtxI, QueryingAA, FnLivenessAA, UsedAssumedInformation,
  1340. /* CheckBBLivenessOnly */ true,
  1341. CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL))
  1342. return true;
  1343. if (CheckBBLivenessOnly)
  1344. return false;
  1345. // If we haven't succeeded we query the specific liveness info for the IRP.
  1346. const AAIsDead *IsDeadAA;
  1347. if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE)
  1348. IsDeadAA = &getOrCreateAAFor<AAIsDead>(
  1349. IRPosition::callsite_returned(cast<CallBase>(IRP.getAssociatedValue())),
  1350. QueryingAA, DepClassTy::NONE);
  1351. else
  1352. IsDeadAA = &getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClassTy::NONE);
  1353. // Don't use recursive reasoning.
  1354. if (QueryingAA == IsDeadAA)
  1355. return false;
  1356. if (IsDeadAA->isAssumedDead()) {
  1357. if (QueryingAA)
  1358. recordDependence(*IsDeadAA, *QueryingAA, DepClass);
  1359. if (!IsDeadAA->isKnownDead())
  1360. UsedAssumedInformation = true;
  1361. return true;
  1362. }
  1363. return false;
  1364. }
  1365. bool Attributor::isAssumedDead(const BasicBlock &BB,
  1366. const AbstractAttribute *QueryingAA,
  1367. const AAIsDead *FnLivenessAA,
  1368. DepClassTy DepClass) {
  1369. const Function &F = *BB.getParent();
  1370. if (!FnLivenessAA || FnLivenessAA->getAnchorScope() != &F)
  1371. FnLivenessAA = &getOrCreateAAFor<AAIsDead>(IRPosition::function(F),
  1372. QueryingAA, DepClassTy::NONE);
  1373. // Don't use recursive reasoning.
  1374. if (QueryingAA == FnLivenessAA)
  1375. return false;
  1376. if (FnLivenessAA->isAssumedDead(&BB)) {
  1377. if (QueryingAA)
  1378. recordDependence(*FnLivenessAA, *QueryingAA, DepClass);
  1379. return true;
  1380. }
  1381. return false;
  1382. }
  1383. bool Attributor::checkForAllUses(
  1384. function_ref<bool(const Use &, bool &)> Pred,
  1385. const AbstractAttribute &QueryingAA, const Value &V,
  1386. bool CheckBBLivenessOnly, DepClassTy LivenessDepClass,
  1387. bool IgnoreDroppableUses,
  1388. function_ref<bool(const Use &OldU, const Use &NewU)> EquivalentUseCB) {
  1389. // Check virtual uses first.
  1390. for (VirtualUseCallbackTy &CB : VirtualUseCallbacks.lookup(&V))
  1391. if (!CB(*this, &QueryingAA))
  1392. return false;
  1393. // Check the trivial case first as it catches void values.
  1394. if (V.use_empty())
  1395. return true;
  1396. const IRPosition &IRP = QueryingAA.getIRPosition();
  1397. SmallVector<const Use *, 16> Worklist;
  1398. SmallPtrSet<const Use *, 16> Visited;
  1399. auto AddUsers = [&](const Value &V, const Use *OldUse) {
  1400. for (const Use &UU : V.uses()) {
  1401. if (OldUse && EquivalentUseCB && !EquivalentUseCB(*OldUse, UU)) {
  1402. LLVM_DEBUG(dbgs() << "[Attributor] Potential copy was "
  1403. "rejected by the equivalence call back: "
  1404. << *UU << "!\n");
  1405. return false;
  1406. }
  1407. Worklist.push_back(&UU);
  1408. }
  1409. return true;
  1410. };
  1411. AddUsers(V, /* OldUse */ nullptr);
  1412. LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size()
  1413. << " initial uses to check\n");
  1414. const Function *ScopeFn = IRP.getAnchorScope();
  1415. const auto *LivenessAA =
  1416. ScopeFn ? &getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*ScopeFn),
  1417. DepClassTy::NONE)
  1418. : nullptr;
  1419. while (!Worklist.empty()) {
  1420. const Use *U = Worklist.pop_back_val();
  1421. if (isa<PHINode>(U->getUser()) && !Visited.insert(U).second)
  1422. continue;
  1423. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
  1424. if (auto *Fn = dyn_cast<Function>(U->getUser()))
  1425. dbgs() << "[Attributor] Check use: " << **U << " in " << Fn->getName()
  1426. << "\n";
  1427. else
  1428. dbgs() << "[Attributor] Check use: " << **U << " in " << *U->getUser()
  1429. << "\n";
  1430. });
  1431. bool UsedAssumedInformation = false;
  1432. if (isAssumedDead(*U, &QueryingAA, LivenessAA, UsedAssumedInformation,
  1433. CheckBBLivenessOnly, LivenessDepClass)) {
  1434. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
  1435. dbgs() << "[Attributor] Dead use, skip!\n");
  1436. continue;
  1437. }
  1438. if (IgnoreDroppableUses && U->getUser()->isDroppable()) {
  1439. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
  1440. dbgs() << "[Attributor] Droppable user, skip!\n");
  1441. continue;
  1442. }
  1443. if (auto *SI = dyn_cast<StoreInst>(U->getUser())) {
  1444. if (&SI->getOperandUse(0) == U) {
  1445. if (!Visited.insert(U).second)
  1446. continue;
  1447. SmallSetVector<Value *, 4> PotentialCopies;
  1448. if (AA::getPotentialCopiesOfStoredValue(
  1449. *this, *SI, PotentialCopies, QueryingAA, UsedAssumedInformation,
  1450. /* OnlyExact */ true)) {
  1451. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
  1452. dbgs()
  1453. << "[Attributor] Value is stored, continue with "
  1454. << PotentialCopies.size()
  1455. << " potential copies instead!\n");
  1456. for (Value *PotentialCopy : PotentialCopies)
  1457. if (!AddUsers(*PotentialCopy, U))
  1458. return false;
  1459. continue;
  1460. }
  1461. }
  1462. }
  1463. bool Follow = false;
  1464. if (!Pred(*U, Follow))
  1465. return false;
  1466. if (!Follow)
  1467. continue;
  1468. User &Usr = *U->getUser();
  1469. AddUsers(Usr, /* OldUse */ nullptr);
  1470. auto *RI = dyn_cast<ReturnInst>(&Usr);
  1471. if (!RI)
  1472. continue;
  1473. Function &F = *RI->getFunction();
  1474. auto CallSitePred = [&](AbstractCallSite ACS) {
  1475. return AddUsers(*ACS.getInstruction(), U);
  1476. };
  1477. if (!checkForAllCallSites(CallSitePred, F, /* RequireAllCallSites */ true,
  1478. &QueryingAA, UsedAssumedInformation)) {
  1479. LLVM_DEBUG(dbgs() << "[Attributor] Could not follow return instruction "
  1480. "to all call sites: "
  1481. << *RI << "\n");
  1482. return false;
  1483. }
  1484. }
  1485. return true;
  1486. }
  1487. bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
  1488. const AbstractAttribute &QueryingAA,
  1489. bool RequireAllCallSites,
  1490. bool &UsedAssumedInformation) {
  1491. // We can try to determine information from
  1492. // the call sites. However, this is only possible all call sites are known,
  1493. // hence the function has internal linkage.
  1494. const IRPosition &IRP = QueryingAA.getIRPosition();
  1495. const Function *AssociatedFunction = IRP.getAssociatedFunction();
  1496. if (!AssociatedFunction) {
  1497. LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP
  1498. << "\n");
  1499. return false;
  1500. }
  1501. return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites,
  1502. &QueryingAA, UsedAssumedInformation);
  1503. }
  1504. bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
  1505. const Function &Fn,
  1506. bool RequireAllCallSites,
  1507. const AbstractAttribute *QueryingAA,
  1508. bool &UsedAssumedInformation,
  1509. bool CheckPotentiallyDead) {
  1510. if (RequireAllCallSites && !Fn.hasLocalLinkage()) {
  1511. LLVM_DEBUG(
  1512. dbgs()
  1513. << "[Attributor] Function " << Fn.getName()
  1514. << " has no internal linkage, hence not all call sites are known\n");
  1515. return false;
  1516. }
  1517. // Check virtual uses first.
  1518. for (VirtualUseCallbackTy &CB : VirtualUseCallbacks.lookup(&Fn))
  1519. if (!CB(*this, QueryingAA))
  1520. return false;
  1521. SmallVector<const Use *, 8> Uses(make_pointer_range(Fn.uses()));
  1522. for (unsigned u = 0; u < Uses.size(); ++u) {
  1523. const Use &U = *Uses[u];
  1524. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
  1525. if (auto *Fn = dyn_cast<Function>(U))
  1526. dbgs() << "[Attributor] Check use: " << Fn->getName() << " in "
  1527. << *U.getUser() << "\n";
  1528. else
  1529. dbgs() << "[Attributor] Check use: " << *U << " in " << *U.getUser()
  1530. << "\n";
  1531. });
  1532. if (!CheckPotentiallyDead &&
  1533. isAssumedDead(U, QueryingAA, nullptr, UsedAssumedInformation,
  1534. /* CheckBBLivenessOnly */ true)) {
  1535. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
  1536. dbgs() << "[Attributor] Dead use, skip!\n");
  1537. continue;
  1538. }
  1539. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
  1540. if (CE->isCast() && CE->getType()->isPointerTy()) {
  1541. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
  1542. dbgs() << "[Attributor] Use, is constant cast expression, add "
  1543. << CE->getNumUses() << " uses of that expression instead!\n";
  1544. });
  1545. for (const Use &CEU : CE->uses())
  1546. Uses.push_back(&CEU);
  1547. continue;
  1548. }
  1549. }
  1550. AbstractCallSite ACS(&U);
  1551. if (!ACS) {
  1552. LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName()
  1553. << " has non call site use " << *U.get() << " in "
  1554. << *U.getUser() << "\n");
  1555. // BlockAddress users are allowed.
  1556. if (isa<BlockAddress>(U.getUser()))
  1557. continue;
  1558. return false;
  1559. }
  1560. const Use *EffectiveUse =
  1561. ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U;
  1562. if (!ACS.isCallee(EffectiveUse)) {
  1563. if (!RequireAllCallSites) {
  1564. LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
  1565. << " is not a call of " << Fn.getName()
  1566. << ", skip use\n");
  1567. continue;
  1568. }
  1569. LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
  1570. << " is an invalid use of " << Fn.getName() << "\n");
  1571. return false;
  1572. }
  1573. // Make sure the arguments that can be matched between the call site and the
  1574. // callee argee on their type. It is unlikely they do not and it doesn't
  1575. // make sense for all attributes to know/care about this.
  1576. assert(&Fn == ACS.getCalledFunction() && "Expected known callee");
  1577. unsigned MinArgsParams =
  1578. std::min(size_t(ACS.getNumArgOperands()), Fn.arg_size());
  1579. for (unsigned u = 0; u < MinArgsParams; ++u) {
  1580. Value *CSArgOp = ACS.getCallArgOperand(u);
  1581. if (CSArgOp && Fn.getArg(u)->getType() != CSArgOp->getType()) {
  1582. LLVM_DEBUG(
  1583. dbgs() << "[Attributor] Call site / callee argument type mismatch ["
  1584. << u << "@" << Fn.getName() << ": "
  1585. << *Fn.getArg(u)->getType() << " vs. "
  1586. << *ACS.getCallArgOperand(u)->getType() << "\n");
  1587. return false;
  1588. }
  1589. }
  1590. if (Pred(ACS))
  1591. continue;
  1592. LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for "
  1593. << *ACS.getInstruction() << "\n");
  1594. return false;
  1595. }
  1596. return true;
  1597. }
  1598. bool Attributor::shouldPropagateCallBaseContext(const IRPosition &IRP) {
  1599. // TODO: Maintain a cache of Values that are
  1600. // on the pathway from a Argument to a Instruction that would effect the
  1601. // liveness/return state etc.
  1602. return EnableCallSiteSpecific;
  1603. }
  1604. bool Attributor::checkForAllReturnedValuesAndReturnInsts(
  1605. function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred,
  1606. const AbstractAttribute &QueryingAA) {
  1607. const IRPosition &IRP = QueryingAA.getIRPosition();
  1608. // Since we need to provide return instructions we have to have an exact
  1609. // definition.
  1610. const Function *AssociatedFunction = IRP.getAssociatedFunction();
  1611. if (!AssociatedFunction)
  1612. return false;
  1613. // If this is a call site query we use the call site specific return values
  1614. // and liveness information.
  1615. // TODO: use the function scope once we have call site AAReturnedValues.
  1616. const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
  1617. const auto &AARetVal =
  1618. getAAFor<AAReturnedValues>(QueryingAA, QueryIRP, DepClassTy::REQUIRED);
  1619. if (!AARetVal.getState().isValidState())
  1620. return false;
  1621. return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred);
  1622. }
  1623. bool Attributor::checkForAllReturnedValues(
  1624. function_ref<bool(Value &)> Pred, const AbstractAttribute &QueryingAA) {
  1625. const IRPosition &IRP = QueryingAA.getIRPosition();
  1626. const Function *AssociatedFunction = IRP.getAssociatedFunction();
  1627. if (!AssociatedFunction)
  1628. return false;
  1629. // TODO: use the function scope once we have call site AAReturnedValues.
  1630. const IRPosition &QueryIRP = IRPosition::function(
  1631. *AssociatedFunction, QueryingAA.getCallBaseContext());
  1632. const auto &AARetVal =
  1633. getAAFor<AAReturnedValues>(QueryingAA, QueryIRP, DepClassTy::REQUIRED);
  1634. if (!AARetVal.getState().isValidState())
  1635. return false;
  1636. return AARetVal.checkForAllReturnedValuesAndReturnInsts(
  1637. [&](Value &RV, const SmallSetVector<ReturnInst *, 4> &) {
  1638. return Pred(RV);
  1639. });
  1640. }
  1641. static bool checkForAllInstructionsImpl(
  1642. Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap,
  1643. function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA,
  1644. const AAIsDead *LivenessAA, const ArrayRef<unsigned> &Opcodes,
  1645. bool &UsedAssumedInformation, bool CheckBBLivenessOnly = false,
  1646. bool CheckPotentiallyDead = false) {
  1647. for (unsigned Opcode : Opcodes) {
  1648. // Check if we have instructions with this opcode at all first.
  1649. auto *Insts = OpcodeInstMap.lookup(Opcode);
  1650. if (!Insts)
  1651. continue;
  1652. for (Instruction *I : *Insts) {
  1653. // Skip dead instructions.
  1654. if (A && !CheckPotentiallyDead &&
  1655. A->isAssumedDead(IRPosition::inst(*I), QueryingAA, LivenessAA,
  1656. UsedAssumedInformation, CheckBBLivenessOnly)) {
  1657. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
  1658. dbgs() << "[Attributor] Instruction " << *I
  1659. << " is potentially dead, skip!\n";);
  1660. continue;
  1661. }
  1662. if (!Pred(*I))
  1663. return false;
  1664. }
  1665. }
  1666. return true;
  1667. }
  1668. bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
  1669. const Function *Fn,
  1670. const AbstractAttribute &QueryingAA,
  1671. const ArrayRef<unsigned> &Opcodes,
  1672. bool &UsedAssumedInformation,
  1673. bool CheckBBLivenessOnly,
  1674. bool CheckPotentiallyDead) {
  1675. // Since we need to provide instructions we have to have an exact definition.
  1676. if (!Fn || Fn->isDeclaration())
  1677. return false;
  1678. // TODO: use the function scope once we have call site AAReturnedValues.
  1679. const IRPosition &QueryIRP = IRPosition::function(*Fn);
  1680. const auto *LivenessAA =
  1681. (CheckBBLivenessOnly || CheckPotentiallyDead)
  1682. ? nullptr
  1683. : &(getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE));
  1684. auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
  1685. if (!checkForAllInstructionsImpl(this, OpcodeInstMap, Pred, &QueryingAA,
  1686. LivenessAA, Opcodes, UsedAssumedInformation,
  1687. CheckBBLivenessOnly, CheckPotentiallyDead))
  1688. return false;
  1689. return true;
  1690. }
  1691. bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
  1692. const AbstractAttribute &QueryingAA,
  1693. const ArrayRef<unsigned> &Opcodes,
  1694. bool &UsedAssumedInformation,
  1695. bool CheckBBLivenessOnly,
  1696. bool CheckPotentiallyDead) {
  1697. const IRPosition &IRP = QueryingAA.getIRPosition();
  1698. const Function *AssociatedFunction = IRP.getAssociatedFunction();
  1699. return checkForAllInstructions(Pred, AssociatedFunction, QueryingAA, Opcodes,
  1700. UsedAssumedInformation, CheckBBLivenessOnly,
  1701. CheckPotentiallyDead);
  1702. }
  1703. bool Attributor::checkForAllReadWriteInstructions(
  1704. function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA,
  1705. bool &UsedAssumedInformation) {
  1706. const Function *AssociatedFunction =
  1707. QueryingAA.getIRPosition().getAssociatedFunction();
  1708. if (!AssociatedFunction)
  1709. return false;
  1710. // TODO: use the function scope once we have call site AAReturnedValues.
  1711. const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
  1712. const auto &LivenessAA =
  1713. getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE);
  1714. for (Instruction *I :
  1715. InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) {
  1716. // Skip dead instructions.
  1717. if (isAssumedDead(IRPosition::inst(*I), &QueryingAA, &LivenessAA,
  1718. UsedAssumedInformation))
  1719. continue;
  1720. if (!Pred(*I))
  1721. return false;
  1722. }
  1723. return true;
  1724. }
  1725. void Attributor::runTillFixpoint() {
  1726. TimeTraceScope TimeScope("Attributor::runTillFixpoint");
  1727. LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
  1728. << DG.SyntheticRoot.Deps.size()
  1729. << " abstract attributes.\n");
  1730. // Now that all abstract attributes are collected and initialized we start
  1731. // the abstract analysis.
  1732. unsigned IterationCounter = 1;
  1733. unsigned MaxIterations =
  1734. Configuration.MaxFixpointIterations.value_or(SetFixpointIterations);
  1735. SmallVector<AbstractAttribute *, 32> ChangedAAs;
  1736. SetVector<AbstractAttribute *> Worklist, InvalidAAs;
  1737. Worklist.insert(DG.SyntheticRoot.begin(), DG.SyntheticRoot.end());
  1738. do {
  1739. // Remember the size to determine new attributes.
  1740. size_t NumAAs = DG.SyntheticRoot.Deps.size();
  1741. LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
  1742. << ", Worklist size: " << Worklist.size() << "\n");
  1743. // For invalid AAs we can fix dependent AAs that have a required dependence,
  1744. // thereby folding long dependence chains in a single step without the need
  1745. // to run updates.
  1746. for (unsigned u = 0; u < InvalidAAs.size(); ++u) {
  1747. AbstractAttribute *InvalidAA = InvalidAAs[u];
  1748. // Check the dependences to fast track invalidation.
  1749. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
  1750. dbgs() << "[Attributor] InvalidAA: " << *InvalidAA
  1751. << " has " << InvalidAA->Deps.size()
  1752. << " required & optional dependences\n");
  1753. while (!InvalidAA->Deps.empty()) {
  1754. const auto &Dep = InvalidAA->Deps.back();
  1755. InvalidAA->Deps.pop_back();
  1756. AbstractAttribute *DepAA = cast<AbstractAttribute>(Dep.getPointer());
  1757. if (Dep.getInt() == unsigned(DepClassTy::OPTIONAL)) {
  1758. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
  1759. dbgs() << " - recompute: " << *DepAA);
  1760. Worklist.insert(DepAA);
  1761. continue;
  1762. }
  1763. DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, dbgs()
  1764. << " - invalidate: " << *DepAA);
  1765. DepAA->getState().indicatePessimisticFixpoint();
  1766. assert(DepAA->getState().isAtFixpoint() && "Expected fixpoint state!");
  1767. if (!DepAA->getState().isValidState())
  1768. InvalidAAs.insert(DepAA);
  1769. else
  1770. ChangedAAs.push_back(DepAA);
  1771. }
  1772. }
  1773. // Add all abstract attributes that are potentially dependent on one that
  1774. // changed to the work list.
  1775. for (AbstractAttribute *ChangedAA : ChangedAAs)
  1776. while (!ChangedAA->Deps.empty()) {
  1777. Worklist.insert(
  1778. cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer()));
  1779. ChangedAA->Deps.pop_back();
  1780. }
  1781. LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter
  1782. << ", Worklist+Dependent size: " << Worklist.size()
  1783. << "\n");
  1784. // Reset the changed and invalid set.
  1785. ChangedAAs.clear();
  1786. InvalidAAs.clear();
  1787. // Update all abstract attribute in the work list and record the ones that
  1788. // changed.
  1789. for (AbstractAttribute *AA : Worklist) {
  1790. const auto &AAState = AA->getState();
  1791. if (!AAState.isAtFixpoint())
  1792. if (updateAA(*AA) == ChangeStatus::CHANGED)
  1793. ChangedAAs.push_back(AA);
  1794. // Use the InvalidAAs vector to propagate invalid states fast transitively
  1795. // without requiring updates.
  1796. if (!AAState.isValidState())
  1797. InvalidAAs.insert(AA);
  1798. }
  1799. // Add attributes to the changed set if they have been created in the last
  1800. // iteration.
  1801. ChangedAAs.append(DG.SyntheticRoot.begin() + NumAAs,
  1802. DG.SyntheticRoot.end());
  1803. // Reset the work list and repopulate with the changed abstract attributes.
  1804. // Note that dependent ones are added above.
  1805. Worklist.clear();
  1806. Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
  1807. Worklist.insert(QueryAAsAwaitingUpdate.begin(),
  1808. QueryAAsAwaitingUpdate.end());
  1809. QueryAAsAwaitingUpdate.clear();
  1810. } while (!Worklist.empty() &&
  1811. (IterationCounter++ < MaxIterations || VerifyMaxFixpointIterations));
  1812. if (IterationCounter > MaxIterations && !Functions.empty()) {
  1813. auto Remark = [&](OptimizationRemarkMissed ORM) {
  1814. return ORM << "Attributor did not reach a fixpoint after "
  1815. << ore::NV("Iterations", MaxIterations) << " iterations.";
  1816. };
  1817. Function *F = Functions.front();
  1818. emitRemark<OptimizationRemarkMissed>(F, "FixedPoint", Remark);
  1819. }
  1820. LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
  1821. << IterationCounter << "/" << MaxIterations
  1822. << " iterations\n");
  1823. // Reset abstract arguments not settled in a sound fixpoint by now. This
  1824. // happens when we stopped the fixpoint iteration early. Note that only the
  1825. // ones marked as "changed" *and* the ones transitively depending on them
  1826. // need to be reverted to a pessimistic state. Others might not be in a
  1827. // fixpoint state but we can use the optimistic results for them anyway.
  1828. SmallPtrSet<AbstractAttribute *, 32> Visited;
  1829. for (unsigned u = 0; u < ChangedAAs.size(); u++) {
  1830. AbstractAttribute *ChangedAA = ChangedAAs[u];
  1831. if (!Visited.insert(ChangedAA).second)
  1832. continue;
  1833. AbstractState &State = ChangedAA->getState();
  1834. if (!State.isAtFixpoint()) {
  1835. State.indicatePessimisticFixpoint();
  1836. NumAttributesTimedOut++;
  1837. }
  1838. while (!ChangedAA->Deps.empty()) {
  1839. ChangedAAs.push_back(
  1840. cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer()));
  1841. ChangedAA->Deps.pop_back();
  1842. }
  1843. }
  1844. LLVM_DEBUG({
  1845. if (!Visited.empty())
  1846. dbgs() << "\n[Attributor] Finalized " << Visited.size()
  1847. << " abstract attributes.\n";
  1848. });
  1849. if (VerifyMaxFixpointIterations && IterationCounter != MaxIterations) {
  1850. errs() << "\n[Attributor] Fixpoint iteration done after: "
  1851. << IterationCounter << "/" << MaxIterations << " iterations\n";
  1852. llvm_unreachable("The fixpoint was not reached with exactly the number of "
  1853. "specified iterations!");
  1854. }
  1855. }
  1856. void Attributor::registerForUpdate(AbstractAttribute &AA) {
  1857. assert(AA.isQueryAA() &&
  1858. "Non-query AAs should not be required to register for updates!");
  1859. QueryAAsAwaitingUpdate.insert(&AA);
  1860. }
  1861. ChangeStatus Attributor::manifestAttributes() {
  1862. TimeTraceScope TimeScope("Attributor::manifestAttributes");
  1863. size_t NumFinalAAs = DG.SyntheticRoot.Deps.size();
  1864. unsigned NumManifested = 0;
  1865. unsigned NumAtFixpoint = 0;
  1866. ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
  1867. for (auto &DepAA : DG.SyntheticRoot.Deps) {
  1868. AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer());
  1869. AbstractState &State = AA->getState();
  1870. // If there is not already a fixpoint reached, we can now take the
  1871. // optimistic state. This is correct because we enforced a pessimistic one
  1872. // on abstract attributes that were transitively dependent on a changed one
  1873. // already above.
  1874. if (!State.isAtFixpoint())
  1875. State.indicateOptimisticFixpoint();
  1876. // We must not manifest Attributes that use Callbase info.
  1877. if (AA->hasCallBaseContext())
  1878. continue;
  1879. // If the state is invalid, we do not try to manifest it.
  1880. if (!State.isValidState())
  1881. continue;
  1882. if (AA->getCtxI() && !isRunOn(*AA->getAnchorScope()))
  1883. continue;
  1884. // Skip dead code.
  1885. bool UsedAssumedInformation = false;
  1886. if (isAssumedDead(*AA, nullptr, UsedAssumedInformation,
  1887. /* CheckBBLivenessOnly */ true))
  1888. continue;
  1889. // Check if the manifest debug counter that allows skipping manifestation of
  1890. // AAs
  1891. if (!DebugCounter::shouldExecute(ManifestDBGCounter))
  1892. continue;
  1893. // Manifest the state and record if we changed the IR.
  1894. ChangeStatus LocalChange = AA->manifest(*this);
  1895. if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
  1896. AA->trackStatistics();
  1897. LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA
  1898. << "\n");
  1899. ManifestChange = ManifestChange | LocalChange;
  1900. NumAtFixpoint++;
  1901. NumManifested += (LocalChange == ChangeStatus::CHANGED);
  1902. }
  1903. (void)NumManifested;
  1904. (void)NumAtFixpoint;
  1905. LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
  1906. << " arguments while " << NumAtFixpoint
  1907. << " were in a valid fixpoint state\n");
  1908. NumAttributesManifested += NumManifested;
  1909. NumAttributesValidFixpoint += NumAtFixpoint;
  1910. (void)NumFinalAAs;
  1911. if (NumFinalAAs != DG.SyntheticRoot.Deps.size()) {
  1912. for (unsigned u = NumFinalAAs; u < DG.SyntheticRoot.Deps.size(); ++u)
  1913. errs() << "Unexpected abstract attribute: "
  1914. << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer())
  1915. << " :: "
  1916. << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer())
  1917. ->getIRPosition()
  1918. .getAssociatedValue()
  1919. << "\n";
  1920. llvm_unreachable("Expected the final number of abstract attributes to "
  1921. "remain unchanged!");
  1922. }
  1923. return ManifestChange;
  1924. }
  1925. void Attributor::identifyDeadInternalFunctions() {
  1926. // Early exit if we don't intend to delete functions.
  1927. if (!Configuration.DeleteFns)
  1928. return;
  1929. // To avoid triggering an assertion in the lazy call graph we will not delete
  1930. // any internal library functions. We should modify the assertion though and
  1931. // allow internals to be deleted.
  1932. const auto *TLI =
  1933. isModulePass()
  1934. ? nullptr
  1935. : getInfoCache().getTargetLibraryInfoForFunction(*Functions.back());
  1936. LibFunc LF;
  1937. // Identify dead internal functions and delete them. This happens outside
  1938. // the other fixpoint analysis as we might treat potentially dead functions
  1939. // as live to lower the number of iterations. If they happen to be dead, the
  1940. // below fixpoint loop will identify and eliminate them.
  1941. SmallVector<Function *, 8> InternalFns;
  1942. for (Function *F : Functions)
  1943. if (F->hasLocalLinkage() && (isModulePass() || !TLI->getLibFunc(*F, LF)))
  1944. InternalFns.push_back(F);
  1945. SmallPtrSet<Function *, 8> LiveInternalFns;
  1946. bool FoundLiveInternal = true;
  1947. while (FoundLiveInternal) {
  1948. FoundLiveInternal = false;
  1949. for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) {
  1950. Function *F = InternalFns[u];
  1951. if (!F)
  1952. continue;
  1953. bool UsedAssumedInformation = false;
  1954. if (checkForAllCallSites(
  1955. [&](AbstractCallSite ACS) {
  1956. Function *Callee = ACS.getInstruction()->getFunction();
  1957. return ToBeDeletedFunctions.count(Callee) ||
  1958. (Functions.count(Callee) && Callee->hasLocalLinkage() &&
  1959. !LiveInternalFns.count(Callee));
  1960. },
  1961. *F, true, nullptr, UsedAssumedInformation)) {
  1962. continue;
  1963. }
  1964. LiveInternalFns.insert(F);
  1965. InternalFns[u] = nullptr;
  1966. FoundLiveInternal = true;
  1967. }
  1968. }
  1969. for (unsigned u = 0, e = InternalFns.size(); u < e; ++u)
  1970. if (Function *F = InternalFns[u])
  1971. ToBeDeletedFunctions.insert(F);
  1972. }
  1973. ChangeStatus Attributor::cleanupIR() {
  1974. TimeTraceScope TimeScope("Attributor::cleanupIR");
  1975. // Delete stuff at the end to avoid invalid references and a nice order.
  1976. LLVM_DEBUG(dbgs() << "\n[Attributor] Delete/replace at least "
  1977. << ToBeDeletedFunctions.size() << " functions and "
  1978. << ToBeDeletedBlocks.size() << " blocks and "
  1979. << ToBeDeletedInsts.size() << " instructions and "
  1980. << ToBeChangedValues.size() << " values and "
  1981. << ToBeChangedUses.size() << " uses. To insert "
  1982. << ToBeChangedToUnreachableInsts.size()
  1983. << " unreachables.\n"
  1984. << "Preserve manifest added " << ManifestAddedBlocks.size()
  1985. << " blocks\n");
  1986. SmallVector<WeakTrackingVH, 32> DeadInsts;
  1987. SmallVector<Instruction *, 32> TerminatorsToFold;
  1988. auto ReplaceUse = [&](Use *U, Value *NewV) {
  1989. Value *OldV = U->get();
  1990. // If we plan to replace NewV we need to update it at this point.
  1991. do {
  1992. const auto &Entry = ToBeChangedValues.lookup(NewV);
  1993. if (!get<0>(Entry))
  1994. break;
  1995. NewV = get<0>(Entry);
  1996. } while (true);
  1997. Instruction *I = dyn_cast<Instruction>(U->getUser());
  1998. assert((!I || isRunOn(*I->getFunction())) &&
  1999. "Cannot replace an instruction outside the current SCC!");
  2000. // Do not replace uses in returns if the value is a must-tail call we will
  2001. // not delete.
  2002. if (auto *RI = dyn_cast_or_null<ReturnInst>(I)) {
  2003. if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts()))
  2004. if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI))
  2005. return;
  2006. // If we rewrite a return and the new value is not an argument, strip the
  2007. // `returned` attribute as it is wrong now.
  2008. if (!isa<Argument>(NewV))
  2009. for (auto &Arg : RI->getFunction()->args())
  2010. Arg.removeAttr(Attribute::Returned);
  2011. }
  2012. LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser()
  2013. << " instead of " << *OldV << "\n");
  2014. U->set(NewV);
  2015. if (Instruction *I = dyn_cast<Instruction>(OldV)) {
  2016. CGModifiedFunctions.insert(I->getFunction());
  2017. if (!isa<PHINode>(I) && !ToBeDeletedInsts.count(I) &&
  2018. isInstructionTriviallyDead(I))
  2019. DeadInsts.push_back(I);
  2020. }
  2021. if (isa<UndefValue>(NewV) && isa<CallBase>(U->getUser())) {
  2022. auto *CB = cast<CallBase>(U->getUser());
  2023. if (CB->isArgOperand(U)) {
  2024. unsigned Idx = CB->getArgOperandNo(U);
  2025. CB->removeParamAttr(Idx, Attribute::NoUndef);
  2026. Function *Fn = CB->getCalledFunction();
  2027. if (Fn && Fn->arg_size() > Idx)
  2028. Fn->removeParamAttr(Idx, Attribute::NoUndef);
  2029. }
  2030. }
  2031. if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) {
  2032. Instruction *UserI = cast<Instruction>(U->getUser());
  2033. if (isa<UndefValue>(NewV)) {
  2034. ToBeChangedToUnreachableInsts.insert(UserI);
  2035. } else {
  2036. TerminatorsToFold.push_back(UserI);
  2037. }
  2038. }
  2039. };
  2040. for (auto &It : ToBeChangedUses) {
  2041. Use *U = It.first;
  2042. Value *NewV = It.second;
  2043. ReplaceUse(U, NewV);
  2044. }
  2045. SmallVector<Use *, 4> Uses;
  2046. for (auto &It : ToBeChangedValues) {
  2047. Value *OldV = It.first;
  2048. auto [NewV, Done] = It.second;
  2049. Uses.clear();
  2050. for (auto &U : OldV->uses())
  2051. if (Done || !U.getUser()->isDroppable())
  2052. Uses.push_back(&U);
  2053. for (Use *U : Uses) {
  2054. if (auto *I = dyn_cast<Instruction>(U->getUser()))
  2055. if (!isRunOn(*I->getFunction()))
  2056. continue;
  2057. ReplaceUse(U, NewV);
  2058. }
  2059. }
  2060. for (const auto &V : InvokeWithDeadSuccessor)
  2061. if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) {
  2062. assert(isRunOn(*II->getFunction()) &&
  2063. "Cannot replace an invoke outside the current SCC!");
  2064. bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind);
  2065. bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn);
  2066. bool Invoke2CallAllowed =
  2067. !AAIsDead::mayCatchAsynchronousExceptions(*II->getFunction());
  2068. assert((UnwindBBIsDead || NormalBBIsDead) &&
  2069. "Invoke does not have dead successors!");
  2070. BasicBlock *BB = II->getParent();
  2071. BasicBlock *NormalDestBB = II->getNormalDest();
  2072. if (UnwindBBIsDead) {
  2073. Instruction *NormalNextIP = &NormalDestBB->front();
  2074. if (Invoke2CallAllowed) {
  2075. changeToCall(II);
  2076. NormalNextIP = BB->getTerminator();
  2077. }
  2078. if (NormalBBIsDead)
  2079. ToBeChangedToUnreachableInsts.insert(NormalNextIP);
  2080. } else {
  2081. assert(NormalBBIsDead && "Broken invariant!");
  2082. if (!NormalDestBB->getUniquePredecessor())
  2083. NormalDestBB = SplitBlockPredecessors(NormalDestBB, {BB}, ".dead");
  2084. ToBeChangedToUnreachableInsts.insert(&NormalDestBB->front());
  2085. }
  2086. }
  2087. for (Instruction *I : TerminatorsToFold) {
  2088. assert(isRunOn(*I->getFunction()) &&
  2089. "Cannot replace a terminator outside the current SCC!");
  2090. CGModifiedFunctions.insert(I->getFunction());
  2091. ConstantFoldTerminator(I->getParent());
  2092. }
  2093. for (const auto &V : ToBeChangedToUnreachableInsts)
  2094. if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
  2095. LLVM_DEBUG(dbgs() << "[Attributor] Change to unreachable: " << *I
  2096. << "\n");
  2097. assert(isRunOn(*I->getFunction()) &&
  2098. "Cannot replace an instruction outside the current SCC!");
  2099. CGModifiedFunctions.insert(I->getFunction());
  2100. changeToUnreachable(I);
  2101. }
  2102. for (const auto &V : ToBeDeletedInsts) {
  2103. if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
  2104. if (auto *CB = dyn_cast<CallBase>(I)) {
  2105. assert((isa<IntrinsicInst>(CB) || isRunOn(*I->getFunction())) &&
  2106. "Cannot delete an instruction outside the current SCC!");
  2107. if (!isa<IntrinsicInst>(CB))
  2108. Configuration.CGUpdater.removeCallSite(*CB);
  2109. }
  2110. I->dropDroppableUses();
  2111. CGModifiedFunctions.insert(I->getFunction());
  2112. if (!I->getType()->isVoidTy())
  2113. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  2114. if (!isa<PHINode>(I) && isInstructionTriviallyDead(I))
  2115. DeadInsts.push_back(I);
  2116. else
  2117. I->eraseFromParent();
  2118. }
  2119. }
  2120. llvm::erase_if(DeadInsts, [&](WeakTrackingVH I) { return !I; });
  2121. LLVM_DEBUG({
  2122. dbgs() << "[Attributor] DeadInsts size: " << DeadInsts.size() << "\n";
  2123. for (auto &I : DeadInsts)
  2124. if (I)
  2125. dbgs() << " - " << *I << "\n";
  2126. });
  2127. RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
  2128. if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
  2129. SmallVector<BasicBlock *, 8> ToBeDeletedBBs;
  2130. ToBeDeletedBBs.reserve(NumDeadBlocks);
  2131. for (BasicBlock *BB : ToBeDeletedBlocks) {
  2132. assert(isRunOn(*BB->getParent()) &&
  2133. "Cannot delete a block outside the current SCC!");
  2134. CGModifiedFunctions.insert(BB->getParent());
  2135. // Do not delete BBs added during manifests of AAs.
  2136. if (ManifestAddedBlocks.contains(BB))
  2137. continue;
  2138. ToBeDeletedBBs.push_back(BB);
  2139. }
  2140. // Actually we do not delete the blocks but squash them into a single
  2141. // unreachable but untangling branches that jump here is something we need
  2142. // to do in a more generic way.
  2143. detachDeadBlocks(ToBeDeletedBBs, nullptr);
  2144. }
  2145. identifyDeadInternalFunctions();
  2146. // Rewrite the functions as requested during manifest.
  2147. ChangeStatus ManifestChange = rewriteFunctionSignatures(CGModifiedFunctions);
  2148. for (Function *Fn : CGModifiedFunctions)
  2149. if (!ToBeDeletedFunctions.count(Fn) && Functions.count(Fn))
  2150. Configuration.CGUpdater.reanalyzeFunction(*Fn);
  2151. for (Function *Fn : ToBeDeletedFunctions) {
  2152. if (!Functions.count(Fn))
  2153. continue;
  2154. Configuration.CGUpdater.removeFunction(*Fn);
  2155. }
  2156. if (!ToBeChangedUses.empty())
  2157. ManifestChange = ChangeStatus::CHANGED;
  2158. if (!ToBeChangedToUnreachableInsts.empty())
  2159. ManifestChange = ChangeStatus::CHANGED;
  2160. if (!ToBeDeletedFunctions.empty())
  2161. ManifestChange = ChangeStatus::CHANGED;
  2162. if (!ToBeDeletedBlocks.empty())
  2163. ManifestChange = ChangeStatus::CHANGED;
  2164. if (!ToBeDeletedInsts.empty())
  2165. ManifestChange = ChangeStatus::CHANGED;
  2166. if (!InvokeWithDeadSuccessor.empty())
  2167. ManifestChange = ChangeStatus::CHANGED;
  2168. if (!DeadInsts.empty())
  2169. ManifestChange = ChangeStatus::CHANGED;
  2170. NumFnDeleted += ToBeDeletedFunctions.size();
  2171. LLVM_DEBUG(dbgs() << "[Attributor] Deleted " << ToBeDeletedFunctions.size()
  2172. << " functions after manifest.\n");
  2173. #ifdef EXPENSIVE_CHECKS
  2174. for (Function *F : Functions) {
  2175. if (ToBeDeletedFunctions.count(F))
  2176. continue;
  2177. assert(!verifyFunction(*F, &errs()) && "Module verification failed!");
  2178. }
  2179. #endif
  2180. return ManifestChange;
  2181. }
  2182. ChangeStatus Attributor::run() {
  2183. TimeTraceScope TimeScope("Attributor::run");
  2184. AttributorCallGraph ACallGraph(*this);
  2185. if (PrintCallGraph)
  2186. ACallGraph.populateAll();
  2187. Phase = AttributorPhase::UPDATE;
  2188. runTillFixpoint();
  2189. // dump graphs on demand
  2190. if (DumpDepGraph)
  2191. DG.dumpGraph();
  2192. if (ViewDepGraph)
  2193. DG.viewGraph();
  2194. if (PrintDependencies)
  2195. DG.print();
  2196. Phase = AttributorPhase::MANIFEST;
  2197. ChangeStatus ManifestChange = manifestAttributes();
  2198. Phase = AttributorPhase::CLEANUP;
  2199. ChangeStatus CleanupChange = cleanupIR();
  2200. if (PrintCallGraph)
  2201. ACallGraph.print();
  2202. return ManifestChange | CleanupChange;
  2203. }
  2204. ChangeStatus Attributor::updateAA(AbstractAttribute &AA) {
  2205. TimeTraceScope TimeScope(
  2206. AA.getName() + std::to_string(AA.getIRPosition().getPositionKind()) +
  2207. "::updateAA");
  2208. assert(Phase == AttributorPhase::UPDATE &&
  2209. "We can update AA only in the update stage!");
  2210. // Use a new dependence vector for this update.
  2211. DependenceVector DV;
  2212. DependenceStack.push_back(&DV);
  2213. auto &AAState = AA.getState();
  2214. ChangeStatus CS = ChangeStatus::UNCHANGED;
  2215. bool UsedAssumedInformation = false;
  2216. if (!isAssumedDead(AA, nullptr, UsedAssumedInformation,
  2217. /* CheckBBLivenessOnly */ true))
  2218. CS = AA.update(*this);
  2219. if (!AA.isQueryAA() && DV.empty() && !AA.getState().isAtFixpoint()) {
  2220. // If the AA did not rely on outside information but changed, we run it
  2221. // again to see if it found a fixpoint. Most AAs do but we don't require
  2222. // them to. Hence, it might take the AA multiple iterations to get to a
  2223. // fixpoint even if it does not rely on outside information, which is fine.
  2224. ChangeStatus RerunCS = ChangeStatus::UNCHANGED;
  2225. if (CS == ChangeStatus::CHANGED)
  2226. RerunCS = AA.update(*this);
  2227. // If the attribute did not change during the run or rerun, and it still did
  2228. // not query any non-fix information, the state will not change and we can
  2229. // indicate that right at this point.
  2230. if (RerunCS == ChangeStatus::UNCHANGED && !AA.isQueryAA() && DV.empty())
  2231. AAState.indicateOptimisticFixpoint();
  2232. }
  2233. if (!AAState.isAtFixpoint())
  2234. rememberDependences();
  2235. // Verify the stack was used properly, that is we pop the dependence vector we
  2236. // put there earlier.
  2237. DependenceVector *PoppedDV = DependenceStack.pop_back_val();
  2238. (void)PoppedDV;
  2239. assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!");
  2240. return CS;
  2241. }
  2242. void Attributor::createShallowWrapper(Function &F) {
  2243. assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!");
  2244. Module &M = *F.getParent();
  2245. LLVMContext &Ctx = M.getContext();
  2246. FunctionType *FnTy = F.getFunctionType();
  2247. Function *Wrapper =
  2248. Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), F.getName());
  2249. F.setName(""); // set the inside function anonymous
  2250. M.getFunctionList().insert(F.getIterator(), Wrapper);
  2251. F.setLinkage(GlobalValue::InternalLinkage);
  2252. F.replaceAllUsesWith(Wrapper);
  2253. assert(F.use_empty() && "Uses remained after wrapper was created!");
  2254. // Move the COMDAT section to the wrapper.
  2255. // TODO: Check if we need to keep it for F as well.
  2256. Wrapper->setComdat(F.getComdat());
  2257. F.setComdat(nullptr);
  2258. // Copy all metadata and attributes but keep them on F as well.
  2259. SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
  2260. F.getAllMetadata(MDs);
  2261. for (auto MDIt : MDs)
  2262. Wrapper->addMetadata(MDIt.first, *MDIt.second);
  2263. Wrapper->setAttributes(F.getAttributes());
  2264. // Create the call in the wrapper.
  2265. BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Wrapper);
  2266. SmallVector<Value *, 8> Args;
  2267. Argument *FArgIt = F.arg_begin();
  2268. for (Argument &Arg : Wrapper->args()) {
  2269. Args.push_back(&Arg);
  2270. Arg.setName((FArgIt++)->getName());
  2271. }
  2272. CallInst *CI = CallInst::Create(&F, Args, "", EntryBB);
  2273. CI->setTailCall(true);
  2274. CI->addFnAttr(Attribute::NoInline);
  2275. ReturnInst::Create(Ctx, CI->getType()->isVoidTy() ? nullptr : CI, EntryBB);
  2276. NumFnShallowWrappersCreated++;
  2277. }
  2278. bool Attributor::isInternalizable(Function &F) {
  2279. if (F.isDeclaration() || F.hasLocalLinkage() ||
  2280. GlobalValue::isInterposableLinkage(F.getLinkage()))
  2281. return false;
  2282. return true;
  2283. }
  2284. Function *Attributor::internalizeFunction(Function &F, bool Force) {
  2285. if (!AllowDeepWrapper && !Force)
  2286. return nullptr;
  2287. if (!isInternalizable(F))
  2288. return nullptr;
  2289. SmallPtrSet<Function *, 2> FnSet = {&F};
  2290. DenseMap<Function *, Function *> InternalizedFns;
  2291. internalizeFunctions(FnSet, InternalizedFns);
  2292. return InternalizedFns[&F];
  2293. }
  2294. bool Attributor::internalizeFunctions(SmallPtrSetImpl<Function *> &FnSet,
  2295. DenseMap<Function *, Function *> &FnMap) {
  2296. for (Function *F : FnSet)
  2297. if (!Attributor::isInternalizable(*F))
  2298. return false;
  2299. FnMap.clear();
  2300. // Generate the internalized version of each function.
  2301. for (Function *F : FnSet) {
  2302. Module &M = *F->getParent();
  2303. FunctionType *FnTy = F->getFunctionType();
  2304. // Create a copy of the current function
  2305. Function *Copied =
  2306. Function::Create(FnTy, F->getLinkage(), F->getAddressSpace(),
  2307. F->getName() + ".internalized");
  2308. ValueToValueMapTy VMap;
  2309. auto *NewFArgIt = Copied->arg_begin();
  2310. for (auto &Arg : F->args()) {
  2311. auto ArgName = Arg.getName();
  2312. NewFArgIt->setName(ArgName);
  2313. VMap[&Arg] = &(*NewFArgIt++);
  2314. }
  2315. SmallVector<ReturnInst *, 8> Returns;
  2316. // Copy the body of the original function to the new one
  2317. CloneFunctionInto(Copied, F, VMap,
  2318. CloneFunctionChangeType::LocalChangesOnly, Returns);
  2319. // Set the linakage and visibility late as CloneFunctionInto has some
  2320. // implicit requirements.
  2321. Copied->setVisibility(GlobalValue::DefaultVisibility);
  2322. Copied->setLinkage(GlobalValue::PrivateLinkage);
  2323. // Copy metadata
  2324. SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
  2325. F->getAllMetadata(MDs);
  2326. for (auto MDIt : MDs)
  2327. if (!Copied->hasMetadata())
  2328. Copied->addMetadata(MDIt.first, *MDIt.second);
  2329. M.getFunctionList().insert(F->getIterator(), Copied);
  2330. Copied->setDSOLocal(true);
  2331. FnMap[F] = Copied;
  2332. }
  2333. // Replace all uses of the old function with the new internalized function
  2334. // unless the caller is a function that was just internalized.
  2335. for (Function *F : FnSet) {
  2336. auto &InternalizedFn = FnMap[F];
  2337. auto IsNotInternalized = [&](Use &U) -> bool {
  2338. if (auto *CB = dyn_cast<CallBase>(U.getUser()))
  2339. return !FnMap.lookup(CB->getCaller());
  2340. return false;
  2341. };
  2342. F->replaceUsesWithIf(InternalizedFn, IsNotInternalized);
  2343. }
  2344. return true;
  2345. }
  2346. bool Attributor::isValidFunctionSignatureRewrite(
  2347. Argument &Arg, ArrayRef<Type *> ReplacementTypes) {
  2348. if (!Configuration.RewriteSignatures)
  2349. return false;
  2350. Function *Fn = Arg.getParent();
  2351. auto CallSiteCanBeChanged = [Fn](AbstractCallSite ACS) {
  2352. // Forbid the call site to cast the function return type. If we need to
  2353. // rewrite these functions we need to re-create a cast for the new call site
  2354. // (if the old had uses).
  2355. if (!ACS.getCalledFunction() ||
  2356. ACS.getInstruction()->getType() !=
  2357. ACS.getCalledFunction()->getReturnType())
  2358. return false;
  2359. if (ACS.getCalledOperand()->getType() != Fn->getType())
  2360. return false;
  2361. // Forbid must-tail calls for now.
  2362. return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall();
  2363. };
  2364. // Avoid var-arg functions for now.
  2365. if (Fn->isVarArg()) {
  2366. LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n");
  2367. return false;
  2368. }
  2369. // Avoid functions with complicated argument passing semantics.
  2370. AttributeList FnAttributeList = Fn->getAttributes();
  2371. if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) ||
  2372. FnAttributeList.hasAttrSomewhere(Attribute::StructRet) ||
  2373. FnAttributeList.hasAttrSomewhere(Attribute::InAlloca) ||
  2374. FnAttributeList.hasAttrSomewhere(Attribute::Preallocated)) {
  2375. LLVM_DEBUG(
  2376. dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n");
  2377. return false;
  2378. }
  2379. // Avoid callbacks for now.
  2380. bool UsedAssumedInformation = false;
  2381. if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn, true, nullptr,
  2382. UsedAssumedInformation)) {
  2383. LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n");
  2384. return false;
  2385. }
  2386. auto InstPred = [](Instruction &I) {
  2387. if (auto *CI = dyn_cast<CallInst>(&I))
  2388. return !CI->isMustTailCall();
  2389. return true;
  2390. };
  2391. // Forbid must-tail calls for now.
  2392. // TODO:
  2393. auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
  2394. if (!checkForAllInstructionsImpl(nullptr, OpcodeInstMap, InstPred, nullptr,
  2395. nullptr, {Instruction::Call},
  2396. UsedAssumedInformation)) {
  2397. LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n");
  2398. return false;
  2399. }
  2400. return true;
  2401. }
  2402. bool Attributor::registerFunctionSignatureRewrite(
  2403. Argument &Arg, ArrayRef<Type *> ReplacementTypes,
  2404. ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB,
  2405. ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) {
  2406. LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
  2407. << Arg.getParent()->getName() << " with "
  2408. << ReplacementTypes.size() << " replacements\n");
  2409. assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) &&
  2410. "Cannot register an invalid rewrite");
  2411. Function *Fn = Arg.getParent();
  2412. SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
  2413. ArgumentReplacementMap[Fn];
  2414. if (ARIs.empty())
  2415. ARIs.resize(Fn->arg_size());
  2416. // If we have a replacement already with less than or equal new arguments,
  2417. // ignore this request.
  2418. std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()];
  2419. if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) {
  2420. LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n");
  2421. return false;
  2422. }
  2423. // If we have a replacement already but we like the new one better, delete
  2424. // the old.
  2425. ARI.reset();
  2426. LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
  2427. << Arg.getParent()->getName() << " with "
  2428. << ReplacementTypes.size() << " replacements\n");
  2429. // Remember the replacement.
  2430. ARI.reset(new ArgumentReplacementInfo(*this, Arg, ReplacementTypes,
  2431. std::move(CalleeRepairCB),
  2432. std::move(ACSRepairCB)));
  2433. return true;
  2434. }
  2435. bool Attributor::shouldSeedAttribute(AbstractAttribute &AA) {
  2436. bool Result = true;
  2437. #ifndef NDEBUG
  2438. if (SeedAllowList.size() != 0)
  2439. Result = llvm::is_contained(SeedAllowList, AA.getName());
  2440. Function *Fn = AA.getAnchorScope();
  2441. if (FunctionSeedAllowList.size() != 0 && Fn)
  2442. Result &= llvm::is_contained(FunctionSeedAllowList, Fn->getName());
  2443. #endif
  2444. return Result;
  2445. }
  2446. ChangeStatus Attributor::rewriteFunctionSignatures(
  2447. SmallSetVector<Function *, 8> &ModifiedFns) {
  2448. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  2449. for (auto &It : ArgumentReplacementMap) {
  2450. Function *OldFn = It.getFirst();
  2451. // Deleted functions do not require rewrites.
  2452. if (!Functions.count(OldFn) || ToBeDeletedFunctions.count(OldFn))
  2453. continue;
  2454. const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
  2455. It.getSecond();
  2456. assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!");
  2457. SmallVector<Type *, 16> NewArgumentTypes;
  2458. SmallVector<AttributeSet, 16> NewArgumentAttributes;
  2459. // Collect replacement argument types and copy over existing attributes.
  2460. AttributeList OldFnAttributeList = OldFn->getAttributes();
  2461. for (Argument &Arg : OldFn->args()) {
  2462. if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
  2463. ARIs[Arg.getArgNo()]) {
  2464. NewArgumentTypes.append(ARI->ReplacementTypes.begin(),
  2465. ARI->ReplacementTypes.end());
  2466. NewArgumentAttributes.append(ARI->getNumReplacementArgs(),
  2467. AttributeSet());
  2468. } else {
  2469. NewArgumentTypes.push_back(Arg.getType());
  2470. NewArgumentAttributes.push_back(
  2471. OldFnAttributeList.getParamAttrs(Arg.getArgNo()));
  2472. }
  2473. }
  2474. uint64_t LargestVectorWidth = 0;
  2475. for (auto *I : NewArgumentTypes)
  2476. if (auto *VT = dyn_cast<llvm::VectorType>(I))
  2477. LargestVectorWidth =
  2478. std::max(LargestVectorWidth,
  2479. VT->getPrimitiveSizeInBits().getKnownMinValue());
  2480. FunctionType *OldFnTy = OldFn->getFunctionType();
  2481. Type *RetTy = OldFnTy->getReturnType();
  2482. // Construct the new function type using the new arguments types.
  2483. FunctionType *NewFnTy =
  2484. FunctionType::get(RetTy, NewArgumentTypes, OldFnTy->isVarArg());
  2485. LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName()
  2486. << "' from " << *OldFn->getFunctionType() << " to "
  2487. << *NewFnTy << "\n");
  2488. // Create the new function body and insert it into the module.
  2489. Function *NewFn = Function::Create(NewFnTy, OldFn->getLinkage(),
  2490. OldFn->getAddressSpace(), "");
  2491. Functions.insert(NewFn);
  2492. OldFn->getParent()->getFunctionList().insert(OldFn->getIterator(), NewFn);
  2493. NewFn->takeName(OldFn);
  2494. NewFn->copyAttributesFrom(OldFn);
  2495. // Patch the pointer to LLVM function in debug info descriptor.
  2496. NewFn->setSubprogram(OldFn->getSubprogram());
  2497. OldFn->setSubprogram(nullptr);
  2498. // Recompute the parameter attributes list based on the new arguments for
  2499. // the function.
  2500. LLVMContext &Ctx = OldFn->getContext();
  2501. NewFn->setAttributes(AttributeList::get(
  2502. Ctx, OldFnAttributeList.getFnAttrs(), OldFnAttributeList.getRetAttrs(),
  2503. NewArgumentAttributes));
  2504. AttributeFuncs::updateMinLegalVectorWidthAttr(*NewFn, LargestVectorWidth);
  2505. // Since we have now created the new function, splice the body of the old
  2506. // function right into the new function, leaving the old rotting hulk of the
  2507. // function empty.
  2508. NewFn->splice(NewFn->begin(), OldFn);
  2509. // Fixup block addresses to reference new function.
  2510. SmallVector<BlockAddress *, 8u> BlockAddresses;
  2511. for (User *U : OldFn->users())
  2512. if (auto *BA = dyn_cast<BlockAddress>(U))
  2513. BlockAddresses.push_back(BA);
  2514. for (auto *BA : BlockAddresses)
  2515. BA->replaceAllUsesWith(BlockAddress::get(NewFn, BA->getBasicBlock()));
  2516. // Set of all "call-like" instructions that invoke the old function mapped
  2517. // to their new replacements.
  2518. SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs;
  2519. // Callback to create a new "call-like" instruction for a given one.
  2520. auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) {
  2521. CallBase *OldCB = cast<CallBase>(ACS.getInstruction());
  2522. const AttributeList &OldCallAttributeList = OldCB->getAttributes();
  2523. // Collect the new argument operands for the replacement call site.
  2524. SmallVector<Value *, 16> NewArgOperands;
  2525. SmallVector<AttributeSet, 16> NewArgOperandAttributes;
  2526. for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) {
  2527. unsigned NewFirstArgNum = NewArgOperands.size();
  2528. (void)NewFirstArgNum; // only used inside assert.
  2529. if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
  2530. ARIs[OldArgNum]) {
  2531. if (ARI->ACSRepairCB)
  2532. ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
  2533. assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
  2534. NewArgOperands.size() &&
  2535. "ACS repair callback did not provide as many operand as new "
  2536. "types were registered!");
  2537. // TODO: Exose the attribute set to the ACS repair callback
  2538. NewArgOperandAttributes.append(ARI->ReplacementTypes.size(),
  2539. AttributeSet());
  2540. } else {
  2541. NewArgOperands.push_back(ACS.getCallArgOperand(OldArgNum));
  2542. NewArgOperandAttributes.push_back(
  2543. OldCallAttributeList.getParamAttrs(OldArgNum));
  2544. }
  2545. }
  2546. assert(NewArgOperands.size() == NewArgOperandAttributes.size() &&
  2547. "Mismatch # argument operands vs. # argument operand attributes!");
  2548. assert(NewArgOperands.size() == NewFn->arg_size() &&
  2549. "Mismatch # argument operands vs. # function arguments!");
  2550. SmallVector<OperandBundleDef, 4> OperandBundleDefs;
  2551. OldCB->getOperandBundlesAsDefs(OperandBundleDefs);
  2552. // Create a new call or invoke instruction to replace the old one.
  2553. CallBase *NewCB;
  2554. if (InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) {
  2555. NewCB =
  2556. InvokeInst::Create(NewFn, II->getNormalDest(), II->getUnwindDest(),
  2557. NewArgOperands, OperandBundleDefs, "", OldCB);
  2558. } else {
  2559. auto *NewCI = CallInst::Create(NewFn, NewArgOperands, OperandBundleDefs,
  2560. "", OldCB);
  2561. NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind());
  2562. NewCB = NewCI;
  2563. }
  2564. // Copy over various properties and the new attributes.
  2565. NewCB->copyMetadata(*OldCB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
  2566. NewCB->setCallingConv(OldCB->getCallingConv());
  2567. NewCB->takeName(OldCB);
  2568. NewCB->setAttributes(AttributeList::get(
  2569. Ctx, OldCallAttributeList.getFnAttrs(),
  2570. OldCallAttributeList.getRetAttrs(), NewArgOperandAttributes));
  2571. AttributeFuncs::updateMinLegalVectorWidthAttr(*NewCB->getCaller(),
  2572. LargestVectorWidth);
  2573. CallSitePairs.push_back({OldCB, NewCB});
  2574. return true;
  2575. };
  2576. // Use the CallSiteReplacementCreator to create replacement call sites.
  2577. bool UsedAssumedInformation = false;
  2578. bool Success = checkForAllCallSites(CallSiteReplacementCreator, *OldFn,
  2579. true, nullptr, UsedAssumedInformation,
  2580. /* CheckPotentiallyDead */ true);
  2581. (void)Success;
  2582. assert(Success && "Assumed call site replacement to succeed!");
  2583. // Rewire the arguments.
  2584. Argument *OldFnArgIt = OldFn->arg_begin();
  2585. Argument *NewFnArgIt = NewFn->arg_begin();
  2586. for (unsigned OldArgNum = 0; OldArgNum < ARIs.size();
  2587. ++OldArgNum, ++OldFnArgIt) {
  2588. if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
  2589. ARIs[OldArgNum]) {
  2590. if (ARI->CalleeRepairCB)
  2591. ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
  2592. if (ARI->ReplacementTypes.empty())
  2593. OldFnArgIt->replaceAllUsesWith(
  2594. PoisonValue::get(OldFnArgIt->getType()));
  2595. NewFnArgIt += ARI->ReplacementTypes.size();
  2596. } else {
  2597. NewFnArgIt->takeName(&*OldFnArgIt);
  2598. OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt);
  2599. ++NewFnArgIt;
  2600. }
  2601. }
  2602. // Eliminate the instructions *after* we visited all of them.
  2603. for (auto &CallSitePair : CallSitePairs) {
  2604. CallBase &OldCB = *CallSitePair.first;
  2605. CallBase &NewCB = *CallSitePair.second;
  2606. assert(OldCB.getType() == NewCB.getType() &&
  2607. "Cannot handle call sites with different types!");
  2608. ModifiedFns.insert(OldCB.getFunction());
  2609. Configuration.CGUpdater.replaceCallSite(OldCB, NewCB);
  2610. OldCB.replaceAllUsesWith(&NewCB);
  2611. OldCB.eraseFromParent();
  2612. }
  2613. // Replace the function in the call graph (if any).
  2614. Configuration.CGUpdater.replaceFunctionWith(*OldFn, *NewFn);
  2615. // If the old function was modified and needed to be reanalyzed, the new one
  2616. // does now.
  2617. if (ModifiedFns.remove(OldFn))
  2618. ModifiedFns.insert(NewFn);
  2619. Changed = ChangeStatus::CHANGED;
  2620. }
  2621. return Changed;
  2622. }
  2623. void InformationCache::initializeInformationCache(const Function &CF,
  2624. FunctionInfo &FI) {
  2625. // As we do not modify the function here we can remove the const
  2626. // withouth breaking implicit assumptions. At the end of the day, we could
  2627. // initialize the cache eagerly which would look the same to the users.
  2628. Function &F = const_cast<Function &>(CF);
  2629. // Walk all instructions to find interesting instructions that might be
  2630. // queried by abstract attributes during their initialization or update.
  2631. // This has to happen before we create attributes.
  2632. DenseMap<const Value *, std::optional<short>> AssumeUsesMap;
  2633. // Add \p V to the assume uses map which track the number of uses outside of
  2634. // "visited" assumes. If no outside uses are left the value is added to the
  2635. // assume only use vector.
  2636. auto AddToAssumeUsesMap = [&](const Value &V) -> void {
  2637. SmallVector<const Instruction *> Worklist;
  2638. if (auto *I = dyn_cast<Instruction>(&V))
  2639. Worklist.push_back(I);
  2640. while (!Worklist.empty()) {
  2641. const Instruction *I = Worklist.pop_back_val();
  2642. std::optional<short> &NumUses = AssumeUsesMap[I];
  2643. if (!NumUses)
  2644. NumUses = I->getNumUses();
  2645. NumUses = *NumUses - /* this assume */ 1;
  2646. if (*NumUses != 0)
  2647. continue;
  2648. AssumeOnlyValues.insert(I);
  2649. for (const Value *Op : I->operands())
  2650. if (auto *OpI = dyn_cast<Instruction>(Op))
  2651. Worklist.push_back(OpI);
  2652. }
  2653. };
  2654. for (Instruction &I : instructions(&F)) {
  2655. bool IsInterestingOpcode = false;
  2656. // To allow easy access to all instructions in a function with a given
  2657. // opcode we store them in the InfoCache. As not all opcodes are interesting
  2658. // to concrete attributes we only cache the ones that are as identified in
  2659. // the following switch.
  2660. // Note: There are no concrete attributes now so this is initially empty.
  2661. switch (I.getOpcode()) {
  2662. default:
  2663. assert(!isa<CallBase>(&I) &&
  2664. "New call base instruction type needs to be known in the "
  2665. "Attributor.");
  2666. break;
  2667. case Instruction::Call:
  2668. // Calls are interesting on their own, additionally:
  2669. // For `llvm.assume` calls we also fill the KnowledgeMap as we find them.
  2670. // For `must-tail` calls we remember the caller and callee.
  2671. if (auto *Assume = dyn_cast<AssumeInst>(&I)) {
  2672. AssumeOnlyValues.insert(Assume);
  2673. fillMapFromAssume(*Assume, KnowledgeMap);
  2674. AddToAssumeUsesMap(*Assume->getArgOperand(0));
  2675. } else if (cast<CallInst>(I).isMustTailCall()) {
  2676. FI.ContainsMustTailCall = true;
  2677. if (const Function *Callee = cast<CallInst>(I).getCalledFunction())
  2678. getFunctionInfo(*Callee).CalledViaMustTail = true;
  2679. }
  2680. [[fallthrough]];
  2681. case Instruction::CallBr:
  2682. case Instruction::Invoke:
  2683. case Instruction::CleanupRet:
  2684. case Instruction::CatchSwitch:
  2685. case Instruction::AtomicRMW:
  2686. case Instruction::AtomicCmpXchg:
  2687. case Instruction::Br:
  2688. case Instruction::Resume:
  2689. case Instruction::Ret:
  2690. case Instruction::Load:
  2691. // The alignment of a pointer is interesting for loads.
  2692. case Instruction::Store:
  2693. // The alignment of a pointer is interesting for stores.
  2694. case Instruction::Alloca:
  2695. case Instruction::AddrSpaceCast:
  2696. IsInterestingOpcode = true;
  2697. }
  2698. if (IsInterestingOpcode) {
  2699. auto *&Insts = FI.OpcodeInstMap[I.getOpcode()];
  2700. if (!Insts)
  2701. Insts = new (Allocator) InstructionVectorTy();
  2702. Insts->push_back(&I);
  2703. }
  2704. if (I.mayReadOrWriteMemory())
  2705. FI.RWInsts.push_back(&I);
  2706. }
  2707. if (F.hasFnAttribute(Attribute::AlwaysInline) &&
  2708. isInlineViable(F).isSuccess())
  2709. InlineableFunctions.insert(&F);
  2710. }
  2711. AAResults *InformationCache::getAAResultsForFunction(const Function &F) {
  2712. return AG.getAnalysis<AAManager>(F);
  2713. }
  2714. InformationCache::FunctionInfo::~FunctionInfo() {
  2715. // The instruction vectors are allocated using a BumpPtrAllocator, we need to
  2716. // manually destroy them.
  2717. for (auto &It : OpcodeInstMap)
  2718. It.getSecond()->~InstructionVectorTy();
  2719. }
  2720. void Attributor::recordDependence(const AbstractAttribute &FromAA,
  2721. const AbstractAttribute &ToAA,
  2722. DepClassTy DepClass) {
  2723. if (DepClass == DepClassTy::NONE)
  2724. return;
  2725. // If we are outside of an update, thus before the actual fixpoint iteration
  2726. // started (= when we create AAs), we do not track dependences because we will
  2727. // put all AAs into the initial worklist anyway.
  2728. if (DependenceStack.empty())
  2729. return;
  2730. if (FromAA.getState().isAtFixpoint())
  2731. return;
  2732. DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass});
  2733. }
  2734. void Attributor::rememberDependences() {
  2735. assert(!DependenceStack.empty() && "No dependences to remember!");
  2736. for (DepInfo &DI : *DependenceStack.back()) {
  2737. assert((DI.DepClass == DepClassTy::REQUIRED ||
  2738. DI.DepClass == DepClassTy::OPTIONAL) &&
  2739. "Expected required or optional dependence (1 bit)!");
  2740. auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps;
  2741. DepAAs.push_back(AbstractAttribute::DepTy(
  2742. const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass)));
  2743. }
  2744. }
  2745. void Attributor::identifyDefaultAbstractAttributes(Function &F) {
  2746. if (!VisitedFunctions.insert(&F).second)
  2747. return;
  2748. if (F.isDeclaration())
  2749. return;
  2750. // In non-module runs we need to look at the call sites of a function to
  2751. // determine if it is part of a must-tail call edge. This will influence what
  2752. // attributes we can derive.
  2753. InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F);
  2754. if (!isModulePass() && !FI.CalledViaMustTail) {
  2755. for (const Use &U : F.uses())
  2756. if (const auto *CB = dyn_cast<CallBase>(U.getUser()))
  2757. if (CB->isCallee(&U) && CB->isMustTailCall())
  2758. FI.CalledViaMustTail = true;
  2759. }
  2760. IRPosition FPos = IRPosition::function(F);
  2761. // Check for dead BasicBlocks in every function.
  2762. // We need dead instruction detection because we do not want to deal with
  2763. // broken IR in which SSA rules do not apply.
  2764. getOrCreateAAFor<AAIsDead>(FPos);
  2765. // Every function might be "will-return".
  2766. getOrCreateAAFor<AAWillReturn>(FPos);
  2767. // Every function might contain instructions that cause "undefined behavior".
  2768. getOrCreateAAFor<AAUndefinedBehavior>(FPos);
  2769. // Every function can be nounwind.
  2770. getOrCreateAAFor<AANoUnwind>(FPos);
  2771. // Every function might be marked "nosync"
  2772. getOrCreateAAFor<AANoSync>(FPos);
  2773. // Every function might be "no-free".
  2774. getOrCreateAAFor<AANoFree>(FPos);
  2775. // Every function might be "no-return".
  2776. getOrCreateAAFor<AANoReturn>(FPos);
  2777. // Every function might be "no-recurse".
  2778. getOrCreateAAFor<AANoRecurse>(FPos);
  2779. // Every function might be "readnone/readonly/writeonly/...".
  2780. getOrCreateAAFor<AAMemoryBehavior>(FPos);
  2781. // Every function can be "readnone/argmemonly/inaccessiblememonly/...".
  2782. getOrCreateAAFor<AAMemoryLocation>(FPos);
  2783. // Every function can track active assumptions.
  2784. getOrCreateAAFor<AAAssumptionInfo>(FPos);
  2785. // Every function might be applicable for Heap-To-Stack conversion.
  2786. if (EnableHeapToStack)
  2787. getOrCreateAAFor<AAHeapToStack>(FPos);
  2788. // Return attributes are only appropriate if the return type is non void.
  2789. Type *ReturnType = F.getReturnType();
  2790. if (!ReturnType->isVoidTy()) {
  2791. // Argument attribute "returned" --- Create only one per function even
  2792. // though it is an argument attribute.
  2793. getOrCreateAAFor<AAReturnedValues>(FPos);
  2794. IRPosition RetPos = IRPosition::returned(F);
  2795. // Every returned value might be dead.
  2796. getOrCreateAAFor<AAIsDead>(RetPos);
  2797. // Every function might be simplified.
  2798. bool UsedAssumedInformation = false;
  2799. getAssumedSimplified(RetPos, nullptr, UsedAssumedInformation,
  2800. AA::Intraprocedural);
  2801. // Every returned value might be marked noundef.
  2802. getOrCreateAAFor<AANoUndef>(RetPos);
  2803. if (ReturnType->isPointerTy()) {
  2804. // Every function with pointer return type might be marked align.
  2805. getOrCreateAAFor<AAAlign>(RetPos);
  2806. // Every function with pointer return type might be marked nonnull.
  2807. getOrCreateAAFor<AANonNull>(RetPos);
  2808. // Every function with pointer return type might be marked noalias.
  2809. getOrCreateAAFor<AANoAlias>(RetPos);
  2810. // Every function with pointer return type might be marked
  2811. // dereferenceable.
  2812. getOrCreateAAFor<AADereferenceable>(RetPos);
  2813. }
  2814. }
  2815. for (Argument &Arg : F.args()) {
  2816. IRPosition ArgPos = IRPosition::argument(Arg);
  2817. // Every argument might be simplified. We have to go through the Attributor
  2818. // interface though as outside AAs can register custom simplification
  2819. // callbacks.
  2820. bool UsedAssumedInformation = false;
  2821. getAssumedSimplified(ArgPos, /* AA */ nullptr, UsedAssumedInformation,
  2822. AA::Intraprocedural);
  2823. // Every argument might be dead.
  2824. getOrCreateAAFor<AAIsDead>(ArgPos);
  2825. // Every argument might be marked noundef.
  2826. getOrCreateAAFor<AANoUndef>(ArgPos);
  2827. if (Arg.getType()->isPointerTy()) {
  2828. // Every argument with pointer type might be marked nonnull.
  2829. getOrCreateAAFor<AANonNull>(ArgPos);
  2830. // Every argument with pointer type might be marked noalias.
  2831. getOrCreateAAFor<AANoAlias>(ArgPos);
  2832. // Every argument with pointer type might be marked dereferenceable.
  2833. getOrCreateAAFor<AADereferenceable>(ArgPos);
  2834. // Every argument with pointer type might be marked align.
  2835. getOrCreateAAFor<AAAlign>(ArgPos);
  2836. // Every argument with pointer type might be marked nocapture.
  2837. getOrCreateAAFor<AANoCapture>(ArgPos);
  2838. // Every argument with pointer type might be marked
  2839. // "readnone/readonly/writeonly/..."
  2840. getOrCreateAAFor<AAMemoryBehavior>(ArgPos);
  2841. // Every argument with pointer type might be marked nofree.
  2842. getOrCreateAAFor<AANoFree>(ArgPos);
  2843. // Every argument with pointer type might be privatizable (or promotable)
  2844. getOrCreateAAFor<AAPrivatizablePtr>(ArgPos);
  2845. }
  2846. }
  2847. auto CallSitePred = [&](Instruction &I) -> bool {
  2848. auto &CB = cast<CallBase>(I);
  2849. IRPosition CBInstPos = IRPosition::inst(CB);
  2850. IRPosition CBFnPos = IRPosition::callsite_function(CB);
  2851. // Call sites might be dead if they do not have side effects and no live
  2852. // users. The return value might be dead if there are no live users.
  2853. getOrCreateAAFor<AAIsDead>(CBInstPos);
  2854. Function *Callee = CB.getCalledFunction();
  2855. // TODO: Even if the callee is not known now we might be able to simplify
  2856. // the call/callee.
  2857. if (!Callee)
  2858. return true;
  2859. // Every call site can track active assumptions.
  2860. getOrCreateAAFor<AAAssumptionInfo>(CBFnPos);
  2861. // Skip declarations except if annotations on their call sites were
  2862. // explicitly requested.
  2863. if (!AnnotateDeclarationCallSites && Callee->isDeclaration() &&
  2864. !Callee->hasMetadata(LLVMContext::MD_callback))
  2865. return true;
  2866. if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) {
  2867. IRPosition CBRetPos = IRPosition::callsite_returned(CB);
  2868. bool UsedAssumedInformation = false;
  2869. getAssumedSimplified(CBRetPos, nullptr, UsedAssumedInformation,
  2870. AA::Intraprocedural);
  2871. }
  2872. for (int I = 0, E = CB.arg_size(); I < E; ++I) {
  2873. IRPosition CBArgPos = IRPosition::callsite_argument(CB, I);
  2874. // Every call site argument might be dead.
  2875. getOrCreateAAFor<AAIsDead>(CBArgPos);
  2876. // Call site argument might be simplified. We have to go through the
  2877. // Attributor interface though as outside AAs can register custom
  2878. // simplification callbacks.
  2879. bool UsedAssumedInformation = false;
  2880. getAssumedSimplified(CBArgPos, /* AA */ nullptr, UsedAssumedInformation,
  2881. AA::Intraprocedural);
  2882. // Every call site argument might be marked "noundef".
  2883. getOrCreateAAFor<AANoUndef>(CBArgPos);
  2884. if (!CB.getArgOperand(I)->getType()->isPointerTy())
  2885. continue;
  2886. // Call site argument attribute "non-null".
  2887. getOrCreateAAFor<AANonNull>(CBArgPos);
  2888. // Call site argument attribute "nocapture".
  2889. getOrCreateAAFor<AANoCapture>(CBArgPos);
  2890. // Call site argument attribute "no-alias".
  2891. getOrCreateAAFor<AANoAlias>(CBArgPos);
  2892. // Call site argument attribute "dereferenceable".
  2893. getOrCreateAAFor<AADereferenceable>(CBArgPos);
  2894. // Call site argument attribute "align".
  2895. getOrCreateAAFor<AAAlign>(CBArgPos);
  2896. // Call site argument attribute
  2897. // "readnone/readonly/writeonly/..."
  2898. getOrCreateAAFor<AAMemoryBehavior>(CBArgPos);
  2899. // Call site argument attribute "nofree".
  2900. getOrCreateAAFor<AANoFree>(CBArgPos);
  2901. }
  2902. return true;
  2903. };
  2904. auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
  2905. bool Success;
  2906. bool UsedAssumedInformation = false;
  2907. Success = checkForAllInstructionsImpl(
  2908. nullptr, OpcodeInstMap, CallSitePred, nullptr, nullptr,
  2909. {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
  2910. (unsigned)Instruction::Call},
  2911. UsedAssumedInformation);
  2912. (void)Success;
  2913. assert(Success && "Expected the check call to be successful!");
  2914. auto LoadStorePred = [&](Instruction &I) -> bool {
  2915. if (isa<LoadInst>(I)) {
  2916. getOrCreateAAFor<AAAlign>(
  2917. IRPosition::value(*cast<LoadInst>(I).getPointerOperand()));
  2918. if (SimplifyAllLoads)
  2919. getAssumedSimplified(IRPosition::value(I), nullptr,
  2920. UsedAssumedInformation, AA::Intraprocedural);
  2921. } else {
  2922. auto &SI = cast<StoreInst>(I);
  2923. getOrCreateAAFor<AAIsDead>(IRPosition::inst(I));
  2924. getAssumedSimplified(IRPosition::value(*SI.getValueOperand()), nullptr,
  2925. UsedAssumedInformation, AA::Intraprocedural);
  2926. getOrCreateAAFor<AAAlign>(IRPosition::value(*SI.getPointerOperand()));
  2927. }
  2928. return true;
  2929. };
  2930. Success = checkForAllInstructionsImpl(
  2931. nullptr, OpcodeInstMap, LoadStorePred, nullptr, nullptr,
  2932. {(unsigned)Instruction::Load, (unsigned)Instruction::Store},
  2933. UsedAssumedInformation);
  2934. (void)Success;
  2935. assert(Success && "Expected the check call to be successful!");
  2936. }
  2937. /// Helpers to ease debugging through output streams and print calls.
  2938. ///
  2939. ///{
  2940. raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
  2941. return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
  2942. }
  2943. raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) {
  2944. switch (AP) {
  2945. case IRPosition::IRP_INVALID:
  2946. return OS << "inv";
  2947. case IRPosition::IRP_FLOAT:
  2948. return OS << "flt";
  2949. case IRPosition::IRP_RETURNED:
  2950. return OS << "fn_ret";
  2951. case IRPosition::IRP_CALL_SITE_RETURNED:
  2952. return OS << "cs_ret";
  2953. case IRPosition::IRP_FUNCTION:
  2954. return OS << "fn";
  2955. case IRPosition::IRP_CALL_SITE:
  2956. return OS << "cs";
  2957. case IRPosition::IRP_ARGUMENT:
  2958. return OS << "arg";
  2959. case IRPosition::IRP_CALL_SITE_ARGUMENT:
  2960. return OS << "cs_arg";
  2961. }
  2962. llvm_unreachable("Unknown attribute position!");
  2963. }
  2964. raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) {
  2965. const Value &AV = Pos.getAssociatedValue();
  2966. OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " ["
  2967. << Pos.getAnchorValue().getName() << "@" << Pos.getCallSiteArgNo() << "]";
  2968. if (Pos.hasCallBaseContext())
  2969. OS << "[cb_context:" << *Pos.getCallBaseContext() << "]";
  2970. return OS << "}";
  2971. }
  2972. raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) {
  2973. OS << "range-state(" << S.getBitWidth() << ")<";
  2974. S.getKnown().print(OS);
  2975. OS << " / ";
  2976. S.getAssumed().print(OS);
  2977. OS << ">";
  2978. return OS << static_cast<const AbstractState &>(S);
  2979. }
  2980. raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
  2981. return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
  2982. }
  2983. raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
  2984. AA.print(OS);
  2985. return OS;
  2986. }
  2987. raw_ostream &llvm::operator<<(raw_ostream &OS,
  2988. const PotentialConstantIntValuesState &S) {
  2989. OS << "set-state(< {";
  2990. if (!S.isValidState())
  2991. OS << "full-set";
  2992. else {
  2993. for (const auto &It : S.getAssumedSet())
  2994. OS << It << ", ";
  2995. if (S.undefIsContained())
  2996. OS << "undef ";
  2997. }
  2998. OS << "} >)";
  2999. return OS;
  3000. }
  3001. raw_ostream &llvm::operator<<(raw_ostream &OS,
  3002. const PotentialLLVMValuesState &S) {
  3003. OS << "set-state(< {";
  3004. if (!S.isValidState())
  3005. OS << "full-set";
  3006. else {
  3007. for (const auto &It : S.getAssumedSet()) {
  3008. if (auto *F = dyn_cast<Function>(It.first.getValue()))
  3009. OS << "@" << F->getName() << "[" << int(It.second) << "], ";
  3010. else
  3011. OS << *It.first.getValue() << "[" << int(It.second) << "], ";
  3012. }
  3013. if (S.undefIsContained())
  3014. OS << "undef ";
  3015. }
  3016. OS << "} >)";
  3017. return OS;
  3018. }
  3019. void AbstractAttribute::print(raw_ostream &OS) const {
  3020. OS << "[";
  3021. OS << getName();
  3022. OS << "] for CtxI ";
  3023. if (auto *I = getCtxI()) {
  3024. OS << "'";
  3025. I->print(OS);
  3026. OS << "'";
  3027. } else
  3028. OS << "<<null inst>>";
  3029. OS << " at position " << getIRPosition() << " with state " << getAsStr()
  3030. << '\n';
  3031. }
  3032. void AbstractAttribute::printWithDeps(raw_ostream &OS) const {
  3033. print(OS);
  3034. for (const auto &DepAA : Deps) {
  3035. auto *AA = DepAA.getPointer();
  3036. OS << " updates ";
  3037. AA->print(OS);
  3038. }
  3039. OS << '\n';
  3040. }
  3041. raw_ostream &llvm::operator<<(raw_ostream &OS,
  3042. const AAPointerInfo::Access &Acc) {
  3043. OS << " [" << Acc.getKind() << "] " << *Acc.getRemoteInst();
  3044. if (Acc.getLocalInst() != Acc.getRemoteInst())
  3045. OS << " via " << *Acc.getLocalInst();
  3046. if (Acc.getContent()) {
  3047. if (*Acc.getContent())
  3048. OS << " [" << **Acc.getContent() << "]";
  3049. else
  3050. OS << " [ <unknown> ]";
  3051. }
  3052. return OS;
  3053. }
  3054. ///}
  3055. /// ----------------------------------------------------------------------------
  3056. /// Pass (Manager) Boilerplate
  3057. /// ----------------------------------------------------------------------------
  3058. static bool runAttributorOnFunctions(InformationCache &InfoCache,
  3059. SetVector<Function *> &Functions,
  3060. AnalysisGetter &AG,
  3061. CallGraphUpdater &CGUpdater,
  3062. bool DeleteFns, bool IsModulePass) {
  3063. if (Functions.empty())
  3064. return false;
  3065. LLVM_DEBUG({
  3066. dbgs() << "[Attributor] Run on module with " << Functions.size()
  3067. << " functions:\n";
  3068. for (Function *Fn : Functions)
  3069. dbgs() << " - " << Fn->getName() << "\n";
  3070. });
  3071. // Create an Attributor and initially empty information cache that is filled
  3072. // while we identify default attribute opportunities.
  3073. AttributorConfig AC(CGUpdater);
  3074. AC.IsModulePass = IsModulePass;
  3075. AC.DeleteFns = DeleteFns;
  3076. Attributor A(Functions, InfoCache, AC);
  3077. // Create shallow wrappers for all functions that are not IPO amendable
  3078. if (AllowShallowWrappers)
  3079. for (Function *F : Functions)
  3080. if (!A.isFunctionIPOAmendable(*F))
  3081. Attributor::createShallowWrapper(*F);
  3082. // Internalize non-exact functions
  3083. // TODO: for now we eagerly internalize functions without calculating the
  3084. // cost, we need a cost interface to determine whether internalizing
  3085. // a function is "beneficial"
  3086. if (AllowDeepWrapper) {
  3087. unsigned FunSize = Functions.size();
  3088. for (unsigned u = 0; u < FunSize; u++) {
  3089. Function *F = Functions[u];
  3090. if (!F->isDeclaration() && !F->isDefinitionExact() && F->getNumUses() &&
  3091. !GlobalValue::isInterposableLinkage(F->getLinkage())) {
  3092. Function *NewF = Attributor::internalizeFunction(*F);
  3093. assert(NewF && "Could not internalize function.");
  3094. Functions.insert(NewF);
  3095. // Update call graph
  3096. CGUpdater.replaceFunctionWith(*F, *NewF);
  3097. for (const Use &U : NewF->uses())
  3098. if (CallBase *CB = dyn_cast<CallBase>(U.getUser())) {
  3099. auto *CallerF = CB->getCaller();
  3100. CGUpdater.reanalyzeFunction(*CallerF);
  3101. }
  3102. }
  3103. }
  3104. }
  3105. for (Function *F : Functions) {
  3106. if (F->hasExactDefinition())
  3107. NumFnWithExactDefinition++;
  3108. else
  3109. NumFnWithoutExactDefinition++;
  3110. // We look at internal functions only on-demand but if any use is not a
  3111. // direct call or outside the current set of analyzed functions, we have
  3112. // to do it eagerly.
  3113. if (F->hasLocalLinkage()) {
  3114. if (llvm::all_of(F->uses(), [&Functions](const Use &U) {
  3115. const auto *CB = dyn_cast<CallBase>(U.getUser());
  3116. return CB && CB->isCallee(&U) &&
  3117. Functions.count(const_cast<Function *>(CB->getCaller()));
  3118. }))
  3119. continue;
  3120. }
  3121. // Populate the Attributor with abstract attribute opportunities in the
  3122. // function and the information cache with IR information.
  3123. A.identifyDefaultAbstractAttributes(*F);
  3124. }
  3125. ChangeStatus Changed = A.run();
  3126. LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
  3127. << " functions, result: " << Changed << ".\n");
  3128. return Changed == ChangeStatus::CHANGED;
  3129. }
  3130. void AADepGraph::viewGraph() { llvm::ViewGraph(this, "Dependency Graph"); }
  3131. void AADepGraph::dumpGraph() {
  3132. static std::atomic<int> CallTimes;
  3133. std::string Prefix;
  3134. if (!DepGraphDotFileNamePrefix.empty())
  3135. Prefix = DepGraphDotFileNamePrefix;
  3136. else
  3137. Prefix = "dep_graph";
  3138. std::string Filename =
  3139. Prefix + "_" + std::to_string(CallTimes.load()) + ".dot";
  3140. outs() << "Dependency graph dump to " << Filename << ".\n";
  3141. std::error_code EC;
  3142. raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF);
  3143. if (!EC)
  3144. llvm::WriteGraph(File, this);
  3145. CallTimes++;
  3146. }
  3147. void AADepGraph::print() {
  3148. for (auto DepAA : SyntheticRoot.Deps)
  3149. cast<AbstractAttribute>(DepAA.getPointer())->printWithDeps(outs());
  3150. }
  3151. PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
  3152. FunctionAnalysisManager &FAM =
  3153. AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  3154. AnalysisGetter AG(FAM);
  3155. SetVector<Function *> Functions;
  3156. for (Function &F : M)
  3157. Functions.insert(&F);
  3158. CallGraphUpdater CGUpdater;
  3159. BumpPtrAllocator Allocator;
  3160. InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
  3161. if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
  3162. /* DeleteFns */ true, /* IsModulePass */ true)) {
  3163. // FIXME: Think about passes we will preserve and add them here.
  3164. return PreservedAnalyses::none();
  3165. }
  3166. return PreservedAnalyses::all();
  3167. }
  3168. PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C,
  3169. CGSCCAnalysisManager &AM,
  3170. LazyCallGraph &CG,
  3171. CGSCCUpdateResult &UR) {
  3172. FunctionAnalysisManager &FAM =
  3173. AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
  3174. AnalysisGetter AG(FAM);
  3175. SetVector<Function *> Functions;
  3176. for (LazyCallGraph::Node &N : C)
  3177. Functions.insert(&N.getFunction());
  3178. if (Functions.empty())
  3179. return PreservedAnalyses::all();
  3180. Module &M = *Functions.back()->getParent();
  3181. CallGraphUpdater CGUpdater;
  3182. CGUpdater.initialize(CG, C, AM, UR);
  3183. BumpPtrAllocator Allocator;
  3184. InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
  3185. if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
  3186. /* DeleteFns */ false,
  3187. /* IsModulePass */ false)) {
  3188. // FIXME: Think about passes we will preserve and add them here.
  3189. PreservedAnalyses PA;
  3190. PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
  3191. return PA;
  3192. }
  3193. return PreservedAnalyses::all();
  3194. }
  3195. namespace llvm {
  3196. template <> struct GraphTraits<AADepGraphNode *> {
  3197. using NodeRef = AADepGraphNode *;
  3198. using DepTy = PointerIntPair<AADepGraphNode *, 1>;
  3199. using EdgeRef = PointerIntPair<AADepGraphNode *, 1>;
  3200. static NodeRef getEntryNode(AADepGraphNode *DGN) { return DGN; }
  3201. static NodeRef DepGetVal(DepTy &DT) { return DT.getPointer(); }
  3202. using ChildIteratorType =
  3203. mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>;
  3204. using ChildEdgeIteratorType = TinyPtrVector<DepTy>::iterator;
  3205. static ChildIteratorType child_begin(NodeRef N) { return N->child_begin(); }
  3206. static ChildIteratorType child_end(NodeRef N) { return N->child_end(); }
  3207. };
  3208. template <>
  3209. struct GraphTraits<AADepGraph *> : public GraphTraits<AADepGraphNode *> {
  3210. static NodeRef getEntryNode(AADepGraph *DG) { return DG->GetEntryNode(); }
  3211. using nodes_iterator =
  3212. mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>;
  3213. static nodes_iterator nodes_begin(AADepGraph *DG) { return DG->begin(); }
  3214. static nodes_iterator nodes_end(AADepGraph *DG) { return DG->end(); }
  3215. };
  3216. template <> struct DOTGraphTraits<AADepGraph *> : public DefaultDOTGraphTraits {
  3217. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  3218. static std::string getNodeLabel(const AADepGraphNode *Node,
  3219. const AADepGraph *DG) {
  3220. std::string AAString;
  3221. raw_string_ostream O(AAString);
  3222. Node->print(O);
  3223. return AAString;
  3224. }
  3225. };
  3226. } // end namespace llvm
  3227. namespace {
  3228. struct AttributorLegacyPass : public ModulePass {
  3229. static char ID;
  3230. AttributorLegacyPass() : ModulePass(ID) {
  3231. initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry());
  3232. }
  3233. bool runOnModule(Module &M) override {
  3234. if (skipModule(M))
  3235. return false;
  3236. AnalysisGetter AG;
  3237. SetVector<Function *> Functions;
  3238. for (Function &F : M)
  3239. Functions.insert(&F);
  3240. CallGraphUpdater CGUpdater;
  3241. BumpPtrAllocator Allocator;
  3242. InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
  3243. return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
  3244. /* DeleteFns*/ true,
  3245. /* IsModulePass */ true);
  3246. }
  3247. void getAnalysisUsage(AnalysisUsage &AU) const override {
  3248. // FIXME: Think about passes we will preserve and add them here.
  3249. AU.addRequired<TargetLibraryInfoWrapperPass>();
  3250. }
  3251. };
  3252. struct AttributorCGSCCLegacyPass : public CallGraphSCCPass {
  3253. static char ID;
  3254. AttributorCGSCCLegacyPass() : CallGraphSCCPass(ID) {
  3255. initializeAttributorCGSCCLegacyPassPass(*PassRegistry::getPassRegistry());
  3256. }
  3257. bool runOnSCC(CallGraphSCC &SCC) override {
  3258. if (skipSCC(SCC))
  3259. return false;
  3260. SetVector<Function *> Functions;
  3261. for (CallGraphNode *CGN : SCC)
  3262. if (Function *Fn = CGN->getFunction())
  3263. if (!Fn->isDeclaration())
  3264. Functions.insert(Fn);
  3265. if (Functions.empty())
  3266. return false;
  3267. AnalysisGetter AG;
  3268. CallGraph &CG = const_cast<CallGraph &>(SCC.getCallGraph());
  3269. CallGraphUpdater CGUpdater;
  3270. CGUpdater.initialize(CG, SCC);
  3271. Module &M = *Functions.back()->getParent();
  3272. BumpPtrAllocator Allocator;
  3273. InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
  3274. return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
  3275. /* DeleteFns */ false,
  3276. /* IsModulePass */ false);
  3277. }
  3278. void getAnalysisUsage(AnalysisUsage &AU) const override {
  3279. // FIXME: Think about passes we will preserve and add them here.
  3280. AU.addRequired<TargetLibraryInfoWrapperPass>();
  3281. CallGraphSCCPass::getAnalysisUsage(AU);
  3282. }
  3283. };
  3284. } // end anonymous namespace
  3285. Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); }
  3286. Pass *llvm::createAttributorCGSCCLegacyPass() {
  3287. return new AttributorCGSCCLegacyPass();
  3288. }
  3289. char AttributorLegacyPass::ID = 0;
  3290. char AttributorCGSCCLegacyPass::ID = 0;
  3291. INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor",
  3292. "Deduce and propagate attributes", false, false)
  3293. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  3294. INITIALIZE_PASS_END(AttributorLegacyPass, "attributor",
  3295. "Deduce and propagate attributes", false, false)
  3296. INITIALIZE_PASS_BEGIN(AttributorCGSCCLegacyPass, "attributor-cgscc",
  3297. "Deduce and propagate attributes (CGSCC pass)", false,
  3298. false)
  3299. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  3300. INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
  3301. INITIALIZE_PASS_END(AttributorCGSCCLegacyPass, "attributor-cgscc",
  3302. "Deduce and propagate attributes (CGSCC pass)", false,
  3303. false)