RewriteStatepointsForGC.cpp 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136
  1. //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
  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. // Rewrite call/invoke instructions so as to make potential relocations
  10. // performed by the garbage collector explicit in the IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/DenseSet.h"
  17. #include "llvm/ADT/MapVector.h"
  18. #include "llvm/ADT/None.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SetVector.h"
  22. #include "llvm/ADT/SmallSet.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/ADT/iterator_range.h"
  26. #include "llvm/Analysis/DomTreeUpdater.h"
  27. #include "llvm/Analysis/TargetLibraryInfo.h"
  28. #include "llvm/Analysis/TargetTransformInfo.h"
  29. #include "llvm/IR/Argument.h"
  30. #include "llvm/IR/Attributes.h"
  31. #include "llvm/IR/BasicBlock.h"
  32. #include "llvm/IR/CallingConv.h"
  33. #include "llvm/IR/Constant.h"
  34. #include "llvm/IR/Constants.h"
  35. #include "llvm/IR/DataLayout.h"
  36. #include "llvm/IR/DerivedTypes.h"
  37. #include "llvm/IR/Dominators.h"
  38. #include "llvm/IR/Function.h"
  39. #include "llvm/IR/IRBuilder.h"
  40. #include "llvm/IR/InstIterator.h"
  41. #include "llvm/IR/InstrTypes.h"
  42. #include "llvm/IR/Instruction.h"
  43. #include "llvm/IR/Instructions.h"
  44. #include "llvm/IR/IntrinsicInst.h"
  45. #include "llvm/IR/Intrinsics.h"
  46. #include "llvm/IR/LLVMContext.h"
  47. #include "llvm/IR/MDBuilder.h"
  48. #include "llvm/IR/Metadata.h"
  49. #include "llvm/IR/Module.h"
  50. #include "llvm/IR/Statepoint.h"
  51. #include "llvm/IR/Type.h"
  52. #include "llvm/IR/User.h"
  53. #include "llvm/IR/Value.h"
  54. #include "llvm/IR/ValueHandle.h"
  55. #include "llvm/InitializePasses.h"
  56. #include "llvm/Pass.h"
  57. #include "llvm/Support/Casting.h"
  58. #include "llvm/Support/CommandLine.h"
  59. #include "llvm/Support/Compiler.h"
  60. #include "llvm/Support/Debug.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Support/raw_ostream.h"
  63. #include "llvm/Transforms/Scalar.h"
  64. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  65. #include "llvm/Transforms/Utils/Local.h"
  66. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  67. #include <algorithm>
  68. #include <cassert>
  69. #include <cstddef>
  70. #include <cstdint>
  71. #include <iterator>
  72. #include <set>
  73. #include <string>
  74. #include <utility>
  75. #include <vector>
  76. #define DEBUG_TYPE "rewrite-statepoints-for-gc"
  77. using namespace llvm;
  78. // Print the liveset found at the insert location
  79. static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
  80. cl::init(false));
  81. static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
  82. cl::init(false));
  83. // Print out the base pointers for debugging
  84. static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
  85. cl::init(false));
  86. // Cost threshold measuring when it is profitable to rematerialize value instead
  87. // of relocating it
  88. static cl::opt<unsigned>
  89. RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
  90. cl::init(6));
  91. #ifdef EXPENSIVE_CHECKS
  92. static bool ClobberNonLive = true;
  93. #else
  94. static bool ClobberNonLive = false;
  95. #endif
  96. static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
  97. cl::location(ClobberNonLive),
  98. cl::Hidden);
  99. static cl::opt<bool>
  100. AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
  101. cl::Hidden, cl::init(true));
  102. /// The IR fed into RewriteStatepointsForGC may have had attributes and
  103. /// metadata implying dereferenceability that are no longer valid/correct after
  104. /// RewriteStatepointsForGC has run. This is because semantically, after
  105. /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
  106. /// heap. stripNonValidData (conservatively) restores
  107. /// correctness by erasing all attributes in the module that externally imply
  108. /// dereferenceability. Similar reasoning also applies to the noalias
  109. /// attributes and metadata. gc.statepoint can touch the entire heap including
  110. /// noalias objects.
  111. /// Apart from attributes and metadata, we also remove instructions that imply
  112. /// constant physical memory: llvm.invariant.start.
  113. static void stripNonValidData(Module &M);
  114. static bool shouldRewriteStatepointsIn(Function &F);
  115. PreservedAnalyses RewriteStatepointsForGC::run(Module &M,
  116. ModuleAnalysisManager &AM) {
  117. bool Changed = false;
  118. auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  119. for (Function &F : M) {
  120. // Nothing to do for declarations.
  121. if (F.isDeclaration() || F.empty())
  122. continue;
  123. // Policy choice says not to rewrite - the most common reason is that we're
  124. // compiling code without a GCStrategy.
  125. if (!shouldRewriteStatepointsIn(F))
  126. continue;
  127. auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
  128. auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
  129. auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
  130. Changed |= runOnFunction(F, DT, TTI, TLI);
  131. }
  132. if (!Changed)
  133. return PreservedAnalyses::all();
  134. // stripNonValidData asserts that shouldRewriteStatepointsIn
  135. // returns true for at least one function in the module. Since at least
  136. // one function changed, we know that the precondition is satisfied.
  137. stripNonValidData(M);
  138. PreservedAnalyses PA;
  139. PA.preserve<TargetIRAnalysis>();
  140. PA.preserve<TargetLibraryAnalysis>();
  141. return PA;
  142. }
  143. namespace {
  144. class RewriteStatepointsForGCLegacyPass : public ModulePass {
  145. RewriteStatepointsForGC Impl;
  146. public:
  147. static char ID; // Pass identification, replacement for typeid
  148. RewriteStatepointsForGCLegacyPass() : ModulePass(ID), Impl() {
  149. initializeRewriteStatepointsForGCLegacyPassPass(
  150. *PassRegistry::getPassRegistry());
  151. }
  152. bool runOnModule(Module &M) override {
  153. bool Changed = false;
  154. for (Function &F : M) {
  155. // Nothing to do for declarations.
  156. if (F.isDeclaration() || F.empty())
  157. continue;
  158. // Policy choice says not to rewrite - the most common reason is that
  159. // we're compiling code without a GCStrategy.
  160. if (!shouldRewriteStatepointsIn(F))
  161. continue;
  162. TargetTransformInfo &TTI =
  163. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  164. const TargetLibraryInfo &TLI =
  165. getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  166. auto &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
  167. Changed |= Impl.runOnFunction(F, DT, TTI, TLI);
  168. }
  169. if (!Changed)
  170. return false;
  171. // stripNonValidData asserts that shouldRewriteStatepointsIn
  172. // returns true for at least one function in the module. Since at least
  173. // one function changed, we know that the precondition is satisfied.
  174. stripNonValidData(M);
  175. return true;
  176. }
  177. void getAnalysisUsage(AnalysisUsage &AU) const override {
  178. // We add and rewrite a bunch of instructions, but don't really do much
  179. // else. We could in theory preserve a lot more analyses here.
  180. AU.addRequired<DominatorTreeWrapperPass>();
  181. AU.addRequired<TargetTransformInfoWrapperPass>();
  182. AU.addRequired<TargetLibraryInfoWrapperPass>();
  183. }
  184. };
  185. } // end anonymous namespace
  186. char RewriteStatepointsForGCLegacyPass::ID = 0;
  187. ModulePass *llvm::createRewriteStatepointsForGCLegacyPass() {
  188. return new RewriteStatepointsForGCLegacyPass();
  189. }
  190. INITIALIZE_PASS_BEGIN(RewriteStatepointsForGCLegacyPass,
  191. "rewrite-statepoints-for-gc",
  192. "Make relocations explicit at statepoints", false, false)
  193. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  194. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  195. INITIALIZE_PASS_END(RewriteStatepointsForGCLegacyPass,
  196. "rewrite-statepoints-for-gc",
  197. "Make relocations explicit at statepoints", false, false)
  198. namespace {
  199. struct GCPtrLivenessData {
  200. /// Values defined in this block.
  201. MapVector<BasicBlock *, SetVector<Value *>> KillSet;
  202. /// Values used in this block (and thus live); does not included values
  203. /// killed within this block.
  204. MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
  205. /// Values live into this basic block (i.e. used by any
  206. /// instruction in this basic block or ones reachable from here)
  207. MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
  208. /// Values live out of this basic block (i.e. live into
  209. /// any successor block)
  210. MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
  211. };
  212. // The type of the internal cache used inside the findBasePointers family
  213. // of functions. From the callers perspective, this is an opaque type and
  214. // should not be inspected.
  215. //
  216. // In the actual implementation this caches two relations:
  217. // - The base relation itself (i.e. this pointer is based on that one)
  218. // - The base defining value relation (i.e. before base_phi insertion)
  219. // Generally, after the execution of a full findBasePointer call, only the
  220. // base relation will remain. Internally, we add a mixture of the two
  221. // types, then update all the second type to the first type
  222. using DefiningValueMapTy = MapVector<Value *, Value *>;
  223. using PointerToBaseTy = MapVector<Value *, Value *>;
  224. using StatepointLiveSetTy = SetVector<Value *>;
  225. using RematerializedValueMapTy =
  226. MapVector<AssertingVH<Instruction>, AssertingVH<Value>>;
  227. struct PartiallyConstructedSafepointRecord {
  228. /// The set of values known to be live across this safepoint
  229. StatepointLiveSetTy LiveSet;
  230. /// The *new* gc.statepoint instruction itself. This produces the token
  231. /// that normal path gc.relocates and the gc.result are tied to.
  232. GCStatepointInst *StatepointToken;
  233. /// Instruction to which exceptional gc relocates are attached
  234. /// Makes it easier to iterate through them during relocationViaAlloca.
  235. Instruction *UnwindToken;
  236. /// Record live values we are rematerialized instead of relocating.
  237. /// They are not included into 'LiveSet' field.
  238. /// Maps rematerialized copy to it's original value.
  239. RematerializedValueMapTy RematerializedValues;
  240. };
  241. } // end anonymous namespace
  242. static ArrayRef<Use> GetDeoptBundleOperands(const CallBase *Call) {
  243. Optional<OperandBundleUse> DeoptBundle =
  244. Call->getOperandBundle(LLVMContext::OB_deopt);
  245. if (!DeoptBundle.hasValue()) {
  246. assert(AllowStatepointWithNoDeoptInfo &&
  247. "Found non-leaf call without deopt info!");
  248. return None;
  249. }
  250. return DeoptBundle.getValue().Inputs;
  251. }
  252. /// Compute the live-in set for every basic block in the function
  253. static void computeLiveInValues(DominatorTree &DT, Function &F,
  254. GCPtrLivenessData &Data);
  255. /// Given results from the dataflow liveness computation, find the set of live
  256. /// Values at a particular instruction.
  257. static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
  258. StatepointLiveSetTy &out);
  259. // TODO: Once we can get to the GCStrategy, this becomes
  260. // Optional<bool> isGCManagedPointer(const Type *Ty) const override {
  261. static bool isGCPointerType(Type *T) {
  262. if (auto *PT = dyn_cast<PointerType>(T))
  263. // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
  264. // GC managed heap. We know that a pointer into this heap needs to be
  265. // updated and that no other pointer does.
  266. return PT->getAddressSpace() == 1;
  267. return false;
  268. }
  269. // Return true if this type is one which a) is a gc pointer or contains a GC
  270. // pointer and b) is of a type this code expects to encounter as a live value.
  271. // (The insertion code will assert that a type which matches (a) and not (b)
  272. // is not encountered.)
  273. static bool isHandledGCPointerType(Type *T) {
  274. // We fully support gc pointers
  275. if (isGCPointerType(T))
  276. return true;
  277. // We partially support vectors of gc pointers. The code will assert if it
  278. // can't handle something.
  279. if (auto VT = dyn_cast<VectorType>(T))
  280. if (isGCPointerType(VT->getElementType()))
  281. return true;
  282. return false;
  283. }
  284. #ifndef NDEBUG
  285. /// Returns true if this type contains a gc pointer whether we know how to
  286. /// handle that type or not.
  287. static bool containsGCPtrType(Type *Ty) {
  288. if (isGCPointerType(Ty))
  289. return true;
  290. if (VectorType *VT = dyn_cast<VectorType>(Ty))
  291. return isGCPointerType(VT->getScalarType());
  292. if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
  293. return containsGCPtrType(AT->getElementType());
  294. if (StructType *ST = dyn_cast<StructType>(Ty))
  295. return llvm::any_of(ST->elements(), containsGCPtrType);
  296. return false;
  297. }
  298. // Returns true if this is a type which a) is a gc pointer or contains a GC
  299. // pointer and b) is of a type which the code doesn't expect (i.e. first class
  300. // aggregates). Used to trip assertions.
  301. static bool isUnhandledGCPointerType(Type *Ty) {
  302. return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
  303. }
  304. #endif
  305. // Return the name of the value suffixed with the provided value, or if the
  306. // value didn't have a name, the default value specified.
  307. static std::string suffixed_name_or(Value *V, StringRef Suffix,
  308. StringRef DefaultName) {
  309. return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
  310. }
  311. // Conservatively identifies any definitions which might be live at the
  312. // given instruction. The analysis is performed immediately before the
  313. // given instruction. Values defined by that instruction are not considered
  314. // live. Values used by that instruction are considered live.
  315. static void analyzeParsePointLiveness(
  316. DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, CallBase *Call,
  317. PartiallyConstructedSafepointRecord &Result) {
  318. StatepointLiveSetTy LiveSet;
  319. findLiveSetAtInst(Call, OriginalLivenessData, LiveSet);
  320. if (PrintLiveSet) {
  321. dbgs() << "Live Variables:\n";
  322. for (Value *V : LiveSet)
  323. dbgs() << " " << V->getName() << " " << *V << "\n";
  324. }
  325. if (PrintLiveSetSize) {
  326. dbgs() << "Safepoint For: " << Call->getCalledOperand()->getName() << "\n";
  327. dbgs() << "Number live values: " << LiveSet.size() << "\n";
  328. }
  329. Result.LiveSet = LiveSet;
  330. }
  331. // Returns true is V is a knownBaseResult.
  332. static bool isKnownBaseResult(Value *V);
  333. // Returns true if V is a BaseResult that already exists in the IR, i.e. it is
  334. // not created by the findBasePointers algorithm.
  335. static bool isOriginalBaseResult(Value *V);
  336. namespace {
  337. /// A single base defining value - An immediate base defining value for an
  338. /// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
  339. /// For instructions which have multiple pointer [vector] inputs or that
  340. /// transition between vector and scalar types, there is no immediate base
  341. /// defining value. The 'base defining value' for 'Def' is the transitive
  342. /// closure of this relation stopping at the first instruction which has no
  343. /// immediate base defining value. The b.d.v. might itself be a base pointer,
  344. /// but it can also be an arbitrary derived pointer.
  345. struct BaseDefiningValueResult {
  346. /// Contains the value which is the base defining value.
  347. Value * const BDV;
  348. /// True if the base defining value is also known to be an actual base
  349. /// pointer.
  350. const bool IsKnownBase;
  351. BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
  352. : BDV(BDV), IsKnownBase(IsKnownBase) {
  353. #ifndef NDEBUG
  354. // Check consistency between new and old means of checking whether a BDV is
  355. // a base.
  356. bool MustBeBase = isKnownBaseResult(BDV);
  357. assert(!MustBeBase || MustBeBase == IsKnownBase);
  358. #endif
  359. }
  360. };
  361. } // end anonymous namespace
  362. static BaseDefiningValueResult findBaseDefiningValue(Value *I);
  363. /// Return a base defining value for the 'Index' element of the given vector
  364. /// instruction 'I'. If Index is null, returns a BDV for the entire vector
  365. /// 'I'. As an optimization, this method will try to determine when the
  366. /// element is known to already be a base pointer. If this can be established,
  367. /// the second value in the returned pair will be true. Note that either a
  368. /// vector or a pointer typed value can be returned. For the former, the
  369. /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
  370. /// If the later, the return pointer is a BDV (or possibly a base) for the
  371. /// particular element in 'I'.
  372. static BaseDefiningValueResult
  373. findBaseDefiningValueOfVector(Value *I) {
  374. // Each case parallels findBaseDefiningValue below, see that code for
  375. // detailed motivation.
  376. if (isa<Argument>(I))
  377. // An incoming argument to the function is a base pointer
  378. return BaseDefiningValueResult(I, true);
  379. if (isa<Constant>(I))
  380. // Base of constant vector consists only of constant null pointers.
  381. // For reasoning see similar case inside 'findBaseDefiningValue' function.
  382. return BaseDefiningValueResult(ConstantAggregateZero::get(I->getType()),
  383. true);
  384. if (isa<LoadInst>(I))
  385. return BaseDefiningValueResult(I, true);
  386. if (isa<InsertElementInst>(I))
  387. // We don't know whether this vector contains entirely base pointers or
  388. // not. To be conservatively correct, we treat it as a BDV and will
  389. // duplicate code as needed to construct a parallel vector of bases.
  390. return BaseDefiningValueResult(I, false);
  391. if (isa<ShuffleVectorInst>(I))
  392. // We don't know whether this vector contains entirely base pointers or
  393. // not. To be conservatively correct, we treat it as a BDV and will
  394. // duplicate code as needed to construct a parallel vector of bases.
  395. // TODO: There a number of local optimizations which could be applied here
  396. // for particular sufflevector patterns.
  397. return BaseDefiningValueResult(I, false);
  398. // The behavior of getelementptr instructions is the same for vector and
  399. // non-vector data types.
  400. if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
  401. return findBaseDefiningValue(GEP->getPointerOperand());
  402. // If the pointer comes through a bitcast of a vector of pointers to
  403. // a vector of another type of pointer, then look through the bitcast
  404. if (auto *BC = dyn_cast<BitCastInst>(I))
  405. return findBaseDefiningValue(BC->getOperand(0));
  406. // We assume that functions in the source language only return base
  407. // pointers. This should probably be generalized via attributes to support
  408. // both source language and internal functions.
  409. if (isa<CallInst>(I) || isa<InvokeInst>(I))
  410. return BaseDefiningValueResult(I, true);
  411. // A PHI or Select is a base defining value. The outer findBasePointer
  412. // algorithm is responsible for constructing a base value for this BDV.
  413. assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
  414. "unknown vector instruction - no base found for vector element");
  415. return BaseDefiningValueResult(I, false);
  416. }
  417. /// Helper function for findBasePointer - Will return a value which either a)
  418. /// defines the base pointer for the input, b) blocks the simple search
  419. /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
  420. /// from pointer to vector type or back.
  421. static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
  422. assert(I->getType()->isPtrOrPtrVectorTy() &&
  423. "Illegal to ask for the base pointer of a non-pointer type");
  424. if (I->getType()->isVectorTy())
  425. return findBaseDefiningValueOfVector(I);
  426. if (isa<Argument>(I))
  427. // An incoming argument to the function is a base pointer
  428. // We should have never reached here if this argument isn't an gc value
  429. return BaseDefiningValueResult(I, true);
  430. if (isa<Constant>(I)) {
  431. // We assume that objects with a constant base (e.g. a global) can't move
  432. // and don't need to be reported to the collector because they are always
  433. // live. Besides global references, all kinds of constants (e.g. undef,
  434. // constant expressions, null pointers) can be introduced by the inliner or
  435. // the optimizer, especially on dynamically dead paths.
  436. // Here we treat all of them as having single null base. By doing this we
  437. // trying to avoid problems reporting various conflicts in a form of
  438. // "phi (const1, const2)" or "phi (const, regular gc ptr)".
  439. // See constant.ll file for relevant test cases.
  440. return BaseDefiningValueResult(
  441. ConstantPointerNull::get(cast<PointerType>(I->getType())), true);
  442. }
  443. // inttoptrs in an integral address space are currently ill-defined. We
  444. // treat them as defining base pointers here for consistency with the
  445. // constant rule above and because we don't really have a better semantic
  446. // to give them. Note that the optimizer is always free to insert undefined
  447. // behavior on dynamically dead paths as well.
  448. if (isa<IntToPtrInst>(I))
  449. return BaseDefiningValueResult(I, true);
  450. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  451. Value *Def = CI->stripPointerCasts();
  452. // If stripping pointer casts changes the address space there is an
  453. // addrspacecast in between.
  454. assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
  455. cast<PointerType>(CI->getType())->getAddressSpace() &&
  456. "unsupported addrspacecast");
  457. // If we find a cast instruction here, it means we've found a cast which is
  458. // not simply a pointer cast (i.e. an inttoptr). We don't know how to
  459. // handle int->ptr conversion.
  460. assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
  461. return findBaseDefiningValue(Def);
  462. }
  463. if (isa<LoadInst>(I))
  464. // The value loaded is an gc base itself
  465. return BaseDefiningValueResult(I, true);
  466. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
  467. // The base of this GEP is the base
  468. return findBaseDefiningValue(GEP->getPointerOperand());
  469. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  470. switch (II->getIntrinsicID()) {
  471. default:
  472. // fall through to general call handling
  473. break;
  474. case Intrinsic::experimental_gc_statepoint:
  475. llvm_unreachable("statepoints don't produce pointers");
  476. case Intrinsic::experimental_gc_relocate:
  477. // Rerunning safepoint insertion after safepoints are already
  478. // inserted is not supported. It could probably be made to work,
  479. // but why are you doing this? There's no good reason.
  480. llvm_unreachable("repeat safepoint insertion is not supported");
  481. case Intrinsic::gcroot:
  482. // Currently, this mechanism hasn't been extended to work with gcroot.
  483. // There's no reason it couldn't be, but I haven't thought about the
  484. // implications much.
  485. llvm_unreachable(
  486. "interaction with the gcroot mechanism is not supported");
  487. case Intrinsic::experimental_gc_get_pointer_base:
  488. return findBaseDefiningValue(II->getOperand(0));
  489. }
  490. }
  491. // We assume that functions in the source language only return base
  492. // pointers. This should probably be generalized via attributes to support
  493. // both source language and internal functions.
  494. if (isa<CallInst>(I) || isa<InvokeInst>(I))
  495. return BaseDefiningValueResult(I, true);
  496. // TODO: I have absolutely no idea how to implement this part yet. It's not
  497. // necessarily hard, I just haven't really looked at it yet.
  498. assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
  499. if (isa<AtomicCmpXchgInst>(I))
  500. // A CAS is effectively a atomic store and load combined under a
  501. // predicate. From the perspective of base pointers, we just treat it
  502. // like a load.
  503. return BaseDefiningValueResult(I, true);
  504. assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
  505. "binary ops which don't apply to pointers");
  506. // The aggregate ops. Aggregates can either be in the heap or on the
  507. // stack, but in either case, this is simply a field load. As a result,
  508. // this is a defining definition of the base just like a load is.
  509. if (isa<ExtractValueInst>(I))
  510. return BaseDefiningValueResult(I, true);
  511. // We should never see an insert vector since that would require we be
  512. // tracing back a struct value not a pointer value.
  513. assert(!isa<InsertValueInst>(I) &&
  514. "Base pointer for a struct is meaningless");
  515. // This value might have been generated by findBasePointer() called when
  516. // substituting gc.get.pointer.base() intrinsic.
  517. bool IsKnownBase =
  518. isa<Instruction>(I) && cast<Instruction>(I)->getMetadata("is_base_value");
  519. // An extractelement produces a base result exactly when it's input does.
  520. // We may need to insert a parallel instruction to extract the appropriate
  521. // element out of the base vector corresponding to the input. Given this,
  522. // it's analogous to the phi and select case even though it's not a merge.
  523. if (isa<ExtractElementInst>(I))
  524. // Note: There a lot of obvious peephole cases here. This are deliberately
  525. // handled after the main base pointer inference algorithm to make writing
  526. // test cases to exercise that code easier.
  527. return BaseDefiningValueResult(I, IsKnownBase);
  528. // The last two cases here don't return a base pointer. Instead, they
  529. // return a value which dynamically selects from among several base
  530. // derived pointers (each with it's own base potentially). It's the job of
  531. // the caller to resolve these.
  532. assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
  533. "missing instruction case in findBaseDefiningValing");
  534. return BaseDefiningValueResult(I, IsKnownBase);
  535. }
  536. /// Returns the base defining value for this value.
  537. static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
  538. Value *&Cached = Cache[I];
  539. if (!Cached) {
  540. Cached = findBaseDefiningValue(I).BDV;
  541. LLVM_DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
  542. << Cached->getName() << "\n");
  543. }
  544. assert(Cache[I] != nullptr);
  545. return Cached;
  546. }
  547. /// Return a base pointer for this value if known. Otherwise, return it's
  548. /// base defining value.
  549. static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
  550. Value *Def = findBaseDefiningValueCached(I, Cache);
  551. auto Found = Cache.find(Def);
  552. if (Found != Cache.end()) {
  553. // Either a base-of relation, or a self reference. Caller must check.
  554. return Found->second;
  555. }
  556. // Only a BDV available
  557. return Def;
  558. }
  559. /// This value is a base pointer that is not generated by RS4GC, i.e. it already
  560. /// exists in the code.
  561. static bool isOriginalBaseResult(Value *V) {
  562. // no recursion possible
  563. return !isa<PHINode>(V) && !isa<SelectInst>(V) &&
  564. !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
  565. !isa<ShuffleVectorInst>(V);
  566. }
  567. /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
  568. /// is it known to be a base pointer? Or do we need to continue searching.
  569. static bool isKnownBaseResult(Value *V) {
  570. if (isOriginalBaseResult(V))
  571. return true;
  572. if (isa<Instruction>(V) &&
  573. cast<Instruction>(V)->getMetadata("is_base_value")) {
  574. // This is a previously inserted base phi or select. We know
  575. // that this is a base value.
  576. return true;
  577. }
  578. // We need to keep searching
  579. return false;
  580. }
  581. // Returns true if First and Second values are both scalar or both vector.
  582. static bool areBothVectorOrScalar(Value *First, Value *Second) {
  583. return isa<VectorType>(First->getType()) ==
  584. isa<VectorType>(Second->getType());
  585. }
  586. namespace {
  587. /// Models the state of a single base defining value in the findBasePointer
  588. /// algorithm for determining where a new instruction is needed to propagate
  589. /// the base of this BDV.
  590. class BDVState {
  591. public:
  592. enum StatusTy {
  593. // Starting state of lattice
  594. Unknown,
  595. // Some specific base value -- does *not* mean that instruction
  596. // propagates the base of the object
  597. // ex: gep %arg, 16 -> %arg is the base value
  598. Base,
  599. // Need to insert a node to represent a merge.
  600. Conflict
  601. };
  602. BDVState() {
  603. llvm_unreachable("missing state in map");
  604. }
  605. explicit BDVState(Value *OriginalValue)
  606. : OriginalValue(OriginalValue) {}
  607. explicit BDVState(Value *OriginalValue, StatusTy Status, Value *BaseValue = nullptr)
  608. : OriginalValue(OriginalValue), Status(Status), BaseValue(BaseValue) {
  609. assert(Status != Base || BaseValue);
  610. }
  611. StatusTy getStatus() const { return Status; }
  612. Value *getOriginalValue() const { return OriginalValue; }
  613. Value *getBaseValue() const { return BaseValue; }
  614. bool isBase() const { return getStatus() == Base; }
  615. bool isUnknown() const { return getStatus() == Unknown; }
  616. bool isConflict() const { return getStatus() == Conflict; }
  617. // Values of type BDVState form a lattice, and this function implements the
  618. // meet
  619. // operation.
  620. void meet(const BDVState &Other) {
  621. auto markConflict = [&]() {
  622. Status = BDVState::Conflict;
  623. BaseValue = nullptr;
  624. };
  625. // Conflict is a final state.
  626. if (isConflict())
  627. return;
  628. // if we are not known - just take other state.
  629. if (isUnknown()) {
  630. Status = Other.getStatus();
  631. BaseValue = Other.getBaseValue();
  632. return;
  633. }
  634. // We are base.
  635. assert(isBase() && "Unknown state");
  636. // If other is unknown - just keep our state.
  637. if (Other.isUnknown())
  638. return;
  639. // If other is conflict - it is a final state.
  640. if (Other.isConflict())
  641. return markConflict();
  642. // Other is base as well.
  643. assert(Other.isBase() && "Unknown state");
  644. // If bases are different - Conflict.
  645. if (getBaseValue() != Other.getBaseValue())
  646. return markConflict();
  647. // We are identical, do nothing.
  648. }
  649. bool operator==(const BDVState &Other) const {
  650. return OriginalValue == Other.OriginalValue && BaseValue == Other.BaseValue &&
  651. Status == Other.Status;
  652. }
  653. bool operator!=(const BDVState &other) const { return !(*this == other); }
  654. LLVM_DUMP_METHOD
  655. void dump() const {
  656. print(dbgs());
  657. dbgs() << '\n';
  658. }
  659. void print(raw_ostream &OS) const {
  660. switch (getStatus()) {
  661. case Unknown:
  662. OS << "U";
  663. break;
  664. case Base:
  665. OS << "B";
  666. break;
  667. case Conflict:
  668. OS << "C";
  669. break;
  670. }
  671. OS << " (base " << getBaseValue() << " - "
  672. << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << ")"
  673. << " for " << OriginalValue->getName() << ":";
  674. }
  675. private:
  676. AssertingVH<Value> OriginalValue; // instruction this state corresponds to
  677. StatusTy Status = Unknown;
  678. AssertingVH<Value> BaseValue = nullptr; // Non-null only if Status == Base.
  679. };
  680. } // end anonymous namespace
  681. #ifndef NDEBUG
  682. static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
  683. State.print(OS);
  684. return OS;
  685. }
  686. #endif
  687. /// For a given value or instruction, figure out what base ptr its derived from.
  688. /// For gc objects, this is simply itself. On success, returns a value which is
  689. /// the base pointer. (This is reliable and can be used for relocation.) On
  690. /// failure, returns nullptr.
  691. static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache) {
  692. Value *Def = findBaseOrBDV(I, Cache);
  693. if (isKnownBaseResult(Def) && areBothVectorOrScalar(Def, I))
  694. return Def;
  695. // Here's the rough algorithm:
  696. // - For every SSA value, construct a mapping to either an actual base
  697. // pointer or a PHI which obscures the base pointer.
  698. // - Construct a mapping from PHI to unknown TOP state. Use an
  699. // optimistic algorithm to propagate base pointer information. Lattice
  700. // looks like:
  701. // UNKNOWN
  702. // b1 b2 b3 b4
  703. // CONFLICT
  704. // When algorithm terminates, all PHIs will either have a single concrete
  705. // base or be in a conflict state.
  706. // - For every conflict, insert a dummy PHI node without arguments. Add
  707. // these to the base[Instruction] = BasePtr mapping. For every
  708. // non-conflict, add the actual base.
  709. // - For every conflict, add arguments for the base[a] of each input
  710. // arguments.
  711. //
  712. // Note: A simpler form of this would be to add the conflict form of all
  713. // PHIs without running the optimistic algorithm. This would be
  714. // analogous to pessimistic data flow and would likely lead to an
  715. // overall worse solution.
  716. #ifndef NDEBUG
  717. auto isExpectedBDVType = [](Value *BDV) {
  718. return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
  719. isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
  720. isa<ShuffleVectorInst>(BDV);
  721. };
  722. #endif
  723. // Once populated, will contain a mapping from each potentially non-base BDV
  724. // to a lattice value (described above) which corresponds to that BDV.
  725. // We use the order of insertion (DFS over the def/use graph) to provide a
  726. // stable deterministic ordering for visiting DenseMaps (which are unordered)
  727. // below. This is important for deterministic compilation.
  728. MapVector<Value *, BDVState> States;
  729. #ifndef NDEBUG
  730. auto VerifyStates = [&]() {
  731. for (auto &Entry : States) {
  732. assert(Entry.first == Entry.second.getOriginalValue());
  733. }
  734. };
  735. #endif
  736. auto visitBDVOperands = [](Value *BDV, std::function<void (Value*)> F) {
  737. if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
  738. for (Value *InVal : PN->incoming_values())
  739. F(InVal);
  740. } else if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
  741. F(SI->getTrueValue());
  742. F(SI->getFalseValue());
  743. } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
  744. F(EE->getVectorOperand());
  745. } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)) {
  746. F(IE->getOperand(0));
  747. F(IE->getOperand(1));
  748. } else if (auto *SV = dyn_cast<ShuffleVectorInst>(BDV)) {
  749. // For a canonical broadcast, ignore the undef argument
  750. // (without this, we insert a parallel base shuffle for every broadcast)
  751. F(SV->getOperand(0));
  752. if (!SV->isZeroEltSplat())
  753. F(SV->getOperand(1));
  754. } else {
  755. llvm_unreachable("unexpected BDV type");
  756. }
  757. };
  758. // Recursively fill in all base defining values reachable from the initial
  759. // one for which we don't already know a definite base value for
  760. /* scope */ {
  761. SmallVector<Value*, 16> Worklist;
  762. Worklist.push_back(Def);
  763. States.insert({Def, BDVState(Def)});
  764. while (!Worklist.empty()) {
  765. Value *Current = Worklist.pop_back_val();
  766. assert(!isOriginalBaseResult(Current) && "why did it get added?");
  767. auto visitIncomingValue = [&](Value *InVal) {
  768. Value *Base = findBaseOrBDV(InVal, Cache);
  769. if (isKnownBaseResult(Base) && areBothVectorOrScalar(Base, InVal))
  770. // Known bases won't need new instructions introduced and can be
  771. // ignored safely. However, this can only be done when InVal and Base
  772. // are both scalar or both vector. Otherwise, we need to find a
  773. // correct BDV for InVal, by creating an entry in the lattice
  774. // (States).
  775. return;
  776. assert(isExpectedBDVType(Base) && "the only non-base values "
  777. "we see should be base defining values");
  778. if (States.insert(std::make_pair(Base, BDVState(Base))).second)
  779. Worklist.push_back(Base);
  780. };
  781. visitBDVOperands(Current, visitIncomingValue);
  782. }
  783. }
  784. #ifndef NDEBUG
  785. VerifyStates();
  786. LLVM_DEBUG(dbgs() << "States after initialization:\n");
  787. for (const auto &Pair : States) {
  788. LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
  789. }
  790. #endif
  791. // Iterate forward through the value graph pruning any node from the state
  792. // list where all of the inputs are base pointers. The purpose of this is to
  793. // reuse existing values when the derived pointer we were asked to materialize
  794. // a base pointer for happens to be a base pointer itself. (Or a sub-graph
  795. // feeding it does.)
  796. SmallVector<Value *> ToRemove;
  797. do {
  798. ToRemove.clear();
  799. for (auto Pair : States) {
  800. Value *BDV = Pair.first;
  801. auto canPruneInput = [&](Value *V) {
  802. Value *BDV = findBaseOrBDV(V, Cache);
  803. if (V->stripPointerCasts() != BDV)
  804. return false;
  805. // The assumption is that anything not in the state list is
  806. // propagates a base pointer.
  807. return States.count(BDV) == 0;
  808. };
  809. bool CanPrune = true;
  810. visitBDVOperands(BDV, [&](Value *Op) {
  811. CanPrune = CanPrune && canPruneInput(Op);
  812. });
  813. if (CanPrune)
  814. ToRemove.push_back(BDV);
  815. }
  816. for (Value *V : ToRemove) {
  817. States.erase(V);
  818. // Cache the fact V is it's own base for later usage.
  819. Cache[V] = V;
  820. }
  821. } while (!ToRemove.empty());
  822. // Did we manage to prove that Def itself must be a base pointer?
  823. if (!States.count(Def))
  824. return Def;
  825. // Return a phi state for a base defining value. We'll generate a new
  826. // base state for known bases and expect to find a cached state otherwise.
  827. auto GetStateForBDV = [&](Value *BaseValue, Value *Input) {
  828. auto I = States.find(BaseValue);
  829. if (I != States.end())
  830. return I->second;
  831. assert(areBothVectorOrScalar(BaseValue, Input));
  832. return BDVState(BaseValue, BDVState::Base, BaseValue);
  833. };
  834. bool Progress = true;
  835. while (Progress) {
  836. #ifndef NDEBUG
  837. const size_t OldSize = States.size();
  838. #endif
  839. Progress = false;
  840. // We're only changing values in this loop, thus safe to keep iterators.
  841. // Since this is computing a fixed point, the order of visit does not
  842. // effect the result. TODO: We could use a worklist here and make this run
  843. // much faster.
  844. for (auto Pair : States) {
  845. Value *BDV = Pair.first;
  846. // Only values that do not have known bases or those that have differing
  847. // type (scalar versus vector) from a possible known base should be in the
  848. // lattice.
  849. assert((!isKnownBaseResult(BDV) ||
  850. !areBothVectorOrScalar(BDV, Pair.second.getBaseValue())) &&
  851. "why did it get added?");
  852. BDVState NewState(BDV);
  853. visitBDVOperands(BDV, [&](Value *Op) {
  854. Value *BDV = findBaseOrBDV(Op, Cache);
  855. auto OpState = GetStateForBDV(BDV, Op);
  856. NewState.meet(OpState);
  857. });
  858. BDVState OldState = States[BDV];
  859. if (OldState != NewState) {
  860. Progress = true;
  861. States[BDV] = NewState;
  862. }
  863. }
  864. assert(OldSize == States.size() &&
  865. "fixed point shouldn't be adding any new nodes to state");
  866. }
  867. #ifndef NDEBUG
  868. VerifyStates();
  869. LLVM_DEBUG(dbgs() << "States after meet iteration:\n");
  870. for (const auto &Pair : States) {
  871. LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
  872. }
  873. #endif
  874. // Handle all instructions that have a vector BDV, but the instruction itself
  875. // is of scalar type.
  876. for (auto Pair : States) {
  877. Instruction *I = cast<Instruction>(Pair.first);
  878. BDVState State = Pair.second;
  879. auto *BaseValue = State.getBaseValue();
  880. // Only values that do not have known bases or those that have differing
  881. // type (scalar versus vector) from a possible known base should be in the
  882. // lattice.
  883. assert((!isKnownBaseResult(I) || !areBothVectorOrScalar(I, BaseValue)) &&
  884. "why did it get added?");
  885. assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
  886. if (!State.isBase() || !isa<VectorType>(BaseValue->getType()))
  887. continue;
  888. // extractelement instructions are a bit special in that we may need to
  889. // insert an extract even when we know an exact base for the instruction.
  890. // The problem is that we need to convert from a vector base to a scalar
  891. // base for the particular indice we're interested in.
  892. if (isa<ExtractElementInst>(I)) {
  893. auto *EE = cast<ExtractElementInst>(I);
  894. // TODO: In many cases, the new instruction is just EE itself. We should
  895. // exploit this, but can't do it here since it would break the invariant
  896. // about the BDV not being known to be a base.
  897. auto *BaseInst = ExtractElementInst::Create(
  898. State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
  899. BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
  900. States[I] = BDVState(I, BDVState::Base, BaseInst);
  901. } else if (!isa<VectorType>(I->getType())) {
  902. // We need to handle cases that have a vector base but the instruction is
  903. // a scalar type (these could be phis or selects or any instruction that
  904. // are of scalar type, but the base can be a vector type). We
  905. // conservatively set this as conflict. Setting the base value for these
  906. // conflicts is handled in the next loop which traverses States.
  907. States[I] = BDVState(I, BDVState::Conflict);
  908. }
  909. }
  910. #ifndef NDEBUG
  911. VerifyStates();
  912. #endif
  913. // Insert Phis for all conflicts
  914. // TODO: adjust naming patterns to avoid this order of iteration dependency
  915. for (auto Pair : States) {
  916. Instruction *I = cast<Instruction>(Pair.first);
  917. BDVState State = Pair.second;
  918. // Only values that do not have known bases or those that have differing
  919. // type (scalar versus vector) from a possible known base should be in the
  920. // lattice.
  921. assert((!isKnownBaseResult(I) || !areBothVectorOrScalar(I, State.getBaseValue())) &&
  922. "why did it get added?");
  923. assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
  924. // Since we're joining a vector and scalar base, they can never be the
  925. // same. As a result, we should always see insert element having reached
  926. // the conflict state.
  927. assert(!isa<InsertElementInst>(I) || State.isConflict());
  928. if (!State.isConflict())
  929. continue;
  930. auto getMangledName = [](Instruction *I) -> std::string {
  931. if (isa<PHINode>(I)) {
  932. return suffixed_name_or(I, ".base", "base_phi");
  933. } else if (isa<SelectInst>(I)) {
  934. return suffixed_name_or(I, ".base", "base_select");
  935. } else if (isa<ExtractElementInst>(I)) {
  936. return suffixed_name_or(I, ".base", "base_ee");
  937. } else if (isa<InsertElementInst>(I)) {
  938. return suffixed_name_or(I, ".base", "base_ie");
  939. } else {
  940. return suffixed_name_or(I, ".base", "base_sv");
  941. }
  942. };
  943. Instruction *BaseInst = I->clone();
  944. BaseInst->insertBefore(I);
  945. BaseInst->setName(getMangledName(I));
  946. // Add metadata marking this as a base value
  947. BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
  948. States[I] = BDVState(I, BDVState::Conflict, BaseInst);
  949. }
  950. #ifndef NDEBUG
  951. VerifyStates();
  952. #endif
  953. // Returns a instruction which produces the base pointer for a given
  954. // instruction. The instruction is assumed to be an input to one of the BDVs
  955. // seen in the inference algorithm above. As such, we must either already
  956. // know it's base defining value is a base, or have inserted a new
  957. // instruction to propagate the base of it's BDV and have entered that newly
  958. // introduced instruction into the state table. In either case, we are
  959. // assured to be able to determine an instruction which produces it's base
  960. // pointer.
  961. auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
  962. Value *BDV = findBaseOrBDV(Input, Cache);
  963. Value *Base = nullptr;
  964. if (!States.count(BDV)) {
  965. assert(areBothVectorOrScalar(BDV, Input));
  966. Base = BDV;
  967. } else {
  968. // Either conflict or base.
  969. assert(States.count(BDV));
  970. Base = States[BDV].getBaseValue();
  971. }
  972. assert(Base && "Can't be null");
  973. // The cast is needed since base traversal may strip away bitcasts
  974. if (Base->getType() != Input->getType() && InsertPt)
  975. Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
  976. return Base;
  977. };
  978. // Fixup all the inputs of the new PHIs. Visit order needs to be
  979. // deterministic and predictable because we're naming newly created
  980. // instructions.
  981. for (auto Pair : States) {
  982. Instruction *BDV = cast<Instruction>(Pair.first);
  983. BDVState State = Pair.second;
  984. // Only values that do not have known bases or those that have differing
  985. // type (scalar versus vector) from a possible known base should be in the
  986. // lattice.
  987. assert((!isKnownBaseResult(BDV) ||
  988. !areBothVectorOrScalar(BDV, State.getBaseValue())) &&
  989. "why did it get added?");
  990. assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
  991. if (!State.isConflict())
  992. continue;
  993. if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
  994. PHINode *PN = cast<PHINode>(BDV);
  995. const unsigned NumPHIValues = PN->getNumIncomingValues();
  996. // The IR verifier requires phi nodes with multiple entries from the
  997. // same basic block to have the same incoming value for each of those
  998. // entries. Since we're inserting bitcasts in the loop, make sure we
  999. // do so at least once per incoming block.
  1000. DenseMap<BasicBlock *, Value*> BlockToValue;
  1001. for (unsigned i = 0; i < NumPHIValues; i++) {
  1002. Value *InVal = PN->getIncomingValue(i);
  1003. BasicBlock *InBB = PN->getIncomingBlock(i);
  1004. if (!BlockToValue.count(InBB))
  1005. BlockToValue[InBB] = getBaseForInput(InVal, InBB->getTerminator());
  1006. else {
  1007. #ifndef NDEBUG
  1008. Value *OldBase = BlockToValue[InBB];
  1009. Value *Base = getBaseForInput(InVal, nullptr);
  1010. // In essence this assert states: the only way two values
  1011. // incoming from the same basic block may be different is by
  1012. // being different bitcasts of the same value. A cleanup
  1013. // that remains TODO is changing findBaseOrBDV to return an
  1014. // llvm::Value of the correct type (and still remain pure).
  1015. // This will remove the need to add bitcasts.
  1016. assert(Base->stripPointerCasts() == OldBase->stripPointerCasts() &&
  1017. "findBaseOrBDV should be pure!");
  1018. #endif
  1019. }
  1020. Value *Base = BlockToValue[InBB];
  1021. BasePHI->setIncomingValue(i, Base);
  1022. }
  1023. } else if (SelectInst *BaseSI =
  1024. dyn_cast<SelectInst>(State.getBaseValue())) {
  1025. SelectInst *SI = cast<SelectInst>(BDV);
  1026. // Find the instruction which produces the base for each input.
  1027. // We may need to insert a bitcast.
  1028. BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
  1029. BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
  1030. } else if (auto *BaseEE =
  1031. dyn_cast<ExtractElementInst>(State.getBaseValue())) {
  1032. Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
  1033. // Find the instruction which produces the base for each input. We may
  1034. // need to insert a bitcast.
  1035. BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
  1036. } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
  1037. auto *BdvIE = cast<InsertElementInst>(BDV);
  1038. auto UpdateOperand = [&](int OperandIdx) {
  1039. Value *InVal = BdvIE->getOperand(OperandIdx);
  1040. Value *Base = getBaseForInput(InVal, BaseIE);
  1041. BaseIE->setOperand(OperandIdx, Base);
  1042. };
  1043. UpdateOperand(0); // vector operand
  1044. UpdateOperand(1); // scalar operand
  1045. } else {
  1046. auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
  1047. auto *BdvSV = cast<ShuffleVectorInst>(BDV);
  1048. auto UpdateOperand = [&](int OperandIdx) {
  1049. Value *InVal = BdvSV->getOperand(OperandIdx);
  1050. Value *Base = getBaseForInput(InVal, BaseSV);
  1051. BaseSV->setOperand(OperandIdx, Base);
  1052. };
  1053. UpdateOperand(0); // vector operand
  1054. if (!BdvSV->isZeroEltSplat())
  1055. UpdateOperand(1); // vector operand
  1056. else {
  1057. // Never read, so just use undef
  1058. Value *InVal = BdvSV->getOperand(1);
  1059. BaseSV->setOperand(1, UndefValue::get(InVal->getType()));
  1060. }
  1061. }
  1062. }
  1063. #ifndef NDEBUG
  1064. VerifyStates();
  1065. #endif
  1066. // Cache all of our results so we can cheaply reuse them
  1067. // NOTE: This is actually two caches: one of the base defining value
  1068. // relation and one of the base pointer relation! FIXME
  1069. for (auto Pair : States) {
  1070. auto *BDV = Pair.first;
  1071. Value *Base = Pair.second.getBaseValue();
  1072. assert(BDV && Base);
  1073. // Only values that do not have known bases or those that have differing
  1074. // type (scalar versus vector) from a possible known base should be in the
  1075. // lattice.
  1076. assert((!isKnownBaseResult(BDV) || !areBothVectorOrScalar(BDV, Base)) &&
  1077. "why did it get added?");
  1078. LLVM_DEBUG(
  1079. dbgs() << "Updating base value cache"
  1080. << " for: " << BDV->getName() << " from: "
  1081. << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
  1082. << " to: " << Base->getName() << "\n");
  1083. Cache[BDV] = Base;
  1084. }
  1085. assert(Cache.count(Def));
  1086. return Cache[Def];
  1087. }
  1088. // For a set of live pointers (base and/or derived), identify the base
  1089. // pointer of the object which they are derived from. This routine will
  1090. // mutate the IR graph as needed to make the 'base' pointer live at the
  1091. // definition site of 'derived'. This ensures that any use of 'derived' can
  1092. // also use 'base'. This may involve the insertion of a number of
  1093. // additional PHI nodes.
  1094. //
  1095. // preconditions: live is a set of pointer type Values
  1096. //
  1097. // side effects: may insert PHI nodes into the existing CFG, will preserve
  1098. // CFG, will not remove or mutate any existing nodes
  1099. //
  1100. // post condition: PointerToBase contains one (derived, base) pair for every
  1101. // pointer in live. Note that derived can be equal to base if the original
  1102. // pointer was a base pointer.
  1103. static void findBasePointers(const StatepointLiveSetTy &live,
  1104. PointerToBaseTy &PointerToBase, DominatorTree *DT,
  1105. DefiningValueMapTy &DVCache) {
  1106. for (Value *ptr : live) {
  1107. Value *base = findBasePointer(ptr, DVCache);
  1108. assert(base && "failed to find base pointer");
  1109. PointerToBase[ptr] = base;
  1110. assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
  1111. DT->dominates(cast<Instruction>(base)->getParent(),
  1112. cast<Instruction>(ptr)->getParent())) &&
  1113. "The base we found better dominate the derived pointer");
  1114. }
  1115. }
  1116. /// Find the required based pointers (and adjust the live set) for the given
  1117. /// parse point.
  1118. static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
  1119. CallBase *Call,
  1120. PartiallyConstructedSafepointRecord &result,
  1121. PointerToBaseTy &PointerToBase) {
  1122. StatepointLiveSetTy PotentiallyDerivedPointers = result.LiveSet;
  1123. // We assume that all pointers passed to deopt are base pointers; as an
  1124. // optimization, we can use this to avoid seperately materializing the base
  1125. // pointer graph. This is only relevant since we're very conservative about
  1126. // generating new conflict nodes during base pointer insertion. If we were
  1127. // smarter there, this would be irrelevant.
  1128. if (auto Opt = Call->getOperandBundle(LLVMContext::OB_deopt))
  1129. for (Value *V : Opt->Inputs) {
  1130. if (!PotentiallyDerivedPointers.count(V))
  1131. continue;
  1132. PotentiallyDerivedPointers.remove(V);
  1133. PointerToBase[V] = V;
  1134. }
  1135. findBasePointers(PotentiallyDerivedPointers, PointerToBase, &DT, DVCache);
  1136. }
  1137. /// Given an updated version of the dataflow liveness results, update the
  1138. /// liveset and base pointer maps for the call site CS.
  1139. static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
  1140. CallBase *Call,
  1141. PartiallyConstructedSafepointRecord &result,
  1142. PointerToBaseTy &PointerToBase);
  1143. static void recomputeLiveInValues(
  1144. Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
  1145. MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,
  1146. PointerToBaseTy &PointerToBase) {
  1147. // TODO-PERF: reuse the original liveness, then simply run the dataflow
  1148. // again. The old values are still live and will help it stabilize quickly.
  1149. GCPtrLivenessData RevisedLivenessData;
  1150. computeLiveInValues(DT, F, RevisedLivenessData);
  1151. for (size_t i = 0; i < records.size(); i++) {
  1152. struct PartiallyConstructedSafepointRecord &info = records[i];
  1153. recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info,
  1154. PointerToBase);
  1155. }
  1156. }
  1157. // When inserting gc.relocate and gc.result calls, we need to ensure there are
  1158. // no uses of the original value / return value between the gc.statepoint and
  1159. // the gc.relocate / gc.result call. One case which can arise is a phi node
  1160. // starting one of the successor blocks. We also need to be able to insert the
  1161. // gc.relocates only on the path which goes through the statepoint. We might
  1162. // need to split an edge to make this possible.
  1163. static BasicBlock *
  1164. normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
  1165. DominatorTree &DT) {
  1166. BasicBlock *Ret = BB;
  1167. if (!BB->getUniquePredecessor())
  1168. Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
  1169. // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
  1170. // from it
  1171. FoldSingleEntryPHINodes(Ret);
  1172. assert(!isa<PHINode>(Ret->begin()) &&
  1173. "All PHI nodes should have been removed!");
  1174. // At this point, we can safely insert a gc.relocate or gc.result as the first
  1175. // instruction in Ret if needed.
  1176. return Ret;
  1177. }
  1178. // List of all function attributes which must be stripped when lowering from
  1179. // abstract machine model to physical machine model. Essentially, these are
  1180. // all the effects a safepoint might have which we ignored in the abstract
  1181. // machine model for purposes of optimization. We have to strip these on
  1182. // both function declarations and call sites.
  1183. static constexpr Attribute::AttrKind FnAttrsToStrip[] =
  1184. {Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly,
  1185. Attribute::ArgMemOnly, Attribute::InaccessibleMemOnly,
  1186. Attribute::InaccessibleMemOrArgMemOnly,
  1187. Attribute::NoSync, Attribute::NoFree};
  1188. // Create new attribute set containing only attributes which can be transferred
  1189. // from original call to the safepoint.
  1190. static AttributeList legalizeCallAttributes(LLVMContext &Ctx,
  1191. AttributeList AL) {
  1192. if (AL.isEmpty())
  1193. return AL;
  1194. // Remove the readonly, readnone, and statepoint function attributes.
  1195. AttrBuilder FnAttrs(Ctx, AL.getFnAttrs());
  1196. for (auto Attr : FnAttrsToStrip)
  1197. FnAttrs.removeAttribute(Attr);
  1198. for (Attribute A : AL.getFnAttrs()) {
  1199. if (isStatepointDirectiveAttr(A))
  1200. FnAttrs.removeAttribute(A);
  1201. }
  1202. // Just skip parameter and return attributes for now
  1203. return AttributeList::get(Ctx, AttributeList::FunctionIndex,
  1204. AttributeSet::get(Ctx, FnAttrs));
  1205. }
  1206. /// Helper function to place all gc relocates necessary for the given
  1207. /// statepoint.
  1208. /// Inputs:
  1209. /// liveVariables - list of variables to be relocated.
  1210. /// basePtrs - base pointers.
  1211. /// statepointToken - statepoint instruction to which relocates should be
  1212. /// bound.
  1213. /// Builder - Llvm IR builder to be used to construct new calls.
  1214. static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
  1215. ArrayRef<Value *> BasePtrs,
  1216. Instruction *StatepointToken,
  1217. IRBuilder<> &Builder) {
  1218. if (LiveVariables.empty())
  1219. return;
  1220. auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
  1221. auto ValIt = llvm::find(LiveVec, Val);
  1222. assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
  1223. size_t Index = std::distance(LiveVec.begin(), ValIt);
  1224. assert(Index < LiveVec.size() && "Bug in std::find?");
  1225. return Index;
  1226. };
  1227. Module *M = StatepointToken->getModule();
  1228. // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
  1229. // element type is i8 addrspace(1)*). We originally generated unique
  1230. // declarations for each pointer type, but this proved problematic because
  1231. // the intrinsic mangling code is incomplete and fragile. Since we're moving
  1232. // towards a single unified pointer type anyways, we can just cast everything
  1233. // to an i8* of the right address space. A bitcast is added later to convert
  1234. // gc_relocate to the actual value's type.
  1235. auto getGCRelocateDecl = [&] (Type *Ty) {
  1236. assert(isHandledGCPointerType(Ty));
  1237. auto AS = Ty->getScalarType()->getPointerAddressSpace();
  1238. Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
  1239. if (auto *VT = dyn_cast<VectorType>(Ty))
  1240. NewTy = FixedVectorType::get(NewTy,
  1241. cast<FixedVectorType>(VT)->getNumElements());
  1242. return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
  1243. {NewTy});
  1244. };
  1245. // Lazily populated map from input types to the canonicalized form mentioned
  1246. // in the comment above. This should probably be cached somewhere more
  1247. // broadly.
  1248. DenseMap<Type *, Function *> TypeToDeclMap;
  1249. for (unsigned i = 0; i < LiveVariables.size(); i++) {
  1250. // Generate the gc.relocate call and save the result
  1251. Value *BaseIdx = Builder.getInt32(FindIndex(LiveVariables, BasePtrs[i]));
  1252. Value *LiveIdx = Builder.getInt32(i);
  1253. Type *Ty = LiveVariables[i]->getType();
  1254. if (!TypeToDeclMap.count(Ty))
  1255. TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
  1256. Function *GCRelocateDecl = TypeToDeclMap[Ty];
  1257. // only specify a debug name if we can give a useful one
  1258. CallInst *Reloc = Builder.CreateCall(
  1259. GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
  1260. suffixed_name_or(LiveVariables[i], ".relocated", ""));
  1261. // Trick CodeGen into thinking there are lots of free registers at this
  1262. // fake call.
  1263. Reloc->setCallingConv(CallingConv::Cold);
  1264. }
  1265. }
  1266. namespace {
  1267. /// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
  1268. /// avoids having to worry about keeping around dangling pointers to Values.
  1269. class DeferredReplacement {
  1270. AssertingVH<Instruction> Old;
  1271. AssertingVH<Instruction> New;
  1272. bool IsDeoptimize = false;
  1273. DeferredReplacement() = default;
  1274. public:
  1275. static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
  1276. assert(Old != New && Old && New &&
  1277. "Cannot RAUW equal values or to / from null!");
  1278. DeferredReplacement D;
  1279. D.Old = Old;
  1280. D.New = New;
  1281. return D;
  1282. }
  1283. static DeferredReplacement createDelete(Instruction *ToErase) {
  1284. DeferredReplacement D;
  1285. D.Old = ToErase;
  1286. return D;
  1287. }
  1288. static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
  1289. #ifndef NDEBUG
  1290. auto *F = cast<CallInst>(Old)->getCalledFunction();
  1291. assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
  1292. "Only way to construct a deoptimize deferred replacement");
  1293. #endif
  1294. DeferredReplacement D;
  1295. D.Old = Old;
  1296. D.IsDeoptimize = true;
  1297. return D;
  1298. }
  1299. /// Does the task represented by this instance.
  1300. void doReplacement() {
  1301. Instruction *OldI = Old;
  1302. Instruction *NewI = New;
  1303. assert(OldI != NewI && "Disallowed at construction?!");
  1304. assert((!IsDeoptimize || !New) &&
  1305. "Deoptimize intrinsics are not replaced!");
  1306. Old = nullptr;
  1307. New = nullptr;
  1308. if (NewI)
  1309. OldI->replaceAllUsesWith(NewI);
  1310. if (IsDeoptimize) {
  1311. // Note: we've inserted instructions, so the call to llvm.deoptimize may
  1312. // not necessarily be followed by the matching return.
  1313. auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
  1314. new UnreachableInst(RI->getContext(), RI);
  1315. RI->eraseFromParent();
  1316. }
  1317. OldI->eraseFromParent();
  1318. }
  1319. };
  1320. } // end anonymous namespace
  1321. static StringRef getDeoptLowering(CallBase *Call) {
  1322. const char *DeoptLowering = "deopt-lowering";
  1323. if (Call->hasFnAttr(DeoptLowering)) {
  1324. // FIXME: Calls have a *really* confusing interface around attributes
  1325. // with values.
  1326. const AttributeList &CSAS = Call->getAttributes();
  1327. if (CSAS.hasFnAttr(DeoptLowering))
  1328. return CSAS.getFnAttr(DeoptLowering).getValueAsString();
  1329. Function *F = Call->getCalledFunction();
  1330. assert(F && F->hasFnAttribute(DeoptLowering));
  1331. return F->getFnAttribute(DeoptLowering).getValueAsString();
  1332. }
  1333. return "live-through";
  1334. }
  1335. static void
  1336. makeStatepointExplicitImpl(CallBase *Call, /* to replace */
  1337. const SmallVectorImpl<Value *> &BasePtrs,
  1338. const SmallVectorImpl<Value *> &LiveVariables,
  1339. PartiallyConstructedSafepointRecord &Result,
  1340. std::vector<DeferredReplacement> &Replacements,
  1341. const PointerToBaseTy &PointerToBase) {
  1342. assert(BasePtrs.size() == LiveVariables.size());
  1343. // Then go ahead and use the builder do actually do the inserts. We insert
  1344. // immediately before the previous instruction under the assumption that all
  1345. // arguments will be available here. We can't insert afterwards since we may
  1346. // be replacing a terminator.
  1347. IRBuilder<> Builder(Call);
  1348. ArrayRef<Value *> GCArgs(LiveVariables);
  1349. uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
  1350. uint32_t NumPatchBytes = 0;
  1351. uint32_t Flags = uint32_t(StatepointFlags::None);
  1352. SmallVector<Value *, 8> CallArgs(Call->args());
  1353. Optional<ArrayRef<Use>> DeoptArgs;
  1354. if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_deopt))
  1355. DeoptArgs = Bundle->Inputs;
  1356. Optional<ArrayRef<Use>> TransitionArgs;
  1357. if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_gc_transition)) {
  1358. TransitionArgs = Bundle->Inputs;
  1359. // TODO: This flag no longer serves a purpose and can be removed later
  1360. Flags |= uint32_t(StatepointFlags::GCTransition);
  1361. }
  1362. // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
  1363. // with a return value, we lower then as never returning calls to
  1364. // __llvm_deoptimize that are followed by unreachable to get better codegen.
  1365. bool IsDeoptimize = false;
  1366. StatepointDirectives SD =
  1367. parseStatepointDirectivesFromAttrs(Call->getAttributes());
  1368. if (SD.NumPatchBytes)
  1369. NumPatchBytes = *SD.NumPatchBytes;
  1370. if (SD.StatepointID)
  1371. StatepointID = *SD.StatepointID;
  1372. // Pass through the requested lowering if any. The default is live-through.
  1373. StringRef DeoptLowering = getDeoptLowering(Call);
  1374. if (DeoptLowering.equals("live-in"))
  1375. Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
  1376. else {
  1377. assert(DeoptLowering.equals("live-through") && "Unsupported value!");
  1378. }
  1379. Value *CallTarget = Call->getCalledOperand();
  1380. if (Function *F = dyn_cast<Function>(CallTarget)) {
  1381. auto IID = F->getIntrinsicID();
  1382. if (IID == Intrinsic::experimental_deoptimize) {
  1383. // Calls to llvm.experimental.deoptimize are lowered to calls to the
  1384. // __llvm_deoptimize symbol. We want to resolve this now, since the
  1385. // verifier does not allow taking the address of an intrinsic function.
  1386. SmallVector<Type *, 8> DomainTy;
  1387. for (Value *Arg : CallArgs)
  1388. DomainTy.push_back(Arg->getType());
  1389. auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
  1390. /* isVarArg = */ false);
  1391. // Note: CallTarget can be a bitcast instruction of a symbol if there are
  1392. // calls to @llvm.experimental.deoptimize with different argument types in
  1393. // the same module. This is fine -- we assume the frontend knew what it
  1394. // was doing when generating this kind of IR.
  1395. CallTarget = F->getParent()
  1396. ->getOrInsertFunction("__llvm_deoptimize", FTy)
  1397. .getCallee();
  1398. IsDeoptimize = true;
  1399. } else if (IID == Intrinsic::memcpy_element_unordered_atomic ||
  1400. IID == Intrinsic::memmove_element_unordered_atomic) {
  1401. // Unordered atomic memcpy and memmove intrinsics which are not explicitly
  1402. // marked as "gc-leaf-function" should be lowered in a GC parseable way.
  1403. // Specifically, these calls should be lowered to the
  1404. // __llvm_{memcpy|memmove}_element_unordered_atomic_safepoint symbols.
  1405. // Similarly to __llvm_deoptimize we want to resolve this now, since the
  1406. // verifier does not allow taking the address of an intrinsic function.
  1407. //
  1408. // Moreover we need to shuffle the arguments for the call in order to
  1409. // accommodate GC. The underlying source and destination objects might be
  1410. // relocated during copy operation should the GC occur. To relocate the
  1411. // derived source and destination pointers the implementation of the
  1412. // intrinsic should know the corresponding base pointers.
  1413. //
  1414. // To make the base pointers available pass them explicitly as arguments:
  1415. // memcpy(dest_derived, source_derived, ...) =>
  1416. // memcpy(dest_base, dest_offset, source_base, source_offset, ...)
  1417. auto &Context = Call->getContext();
  1418. auto &DL = Call->getModule()->getDataLayout();
  1419. auto GetBaseAndOffset = [&](Value *Derived) {
  1420. assert(PointerToBase.count(Derived));
  1421. unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
  1422. unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
  1423. Value *Base = PointerToBase.find(Derived)->second;
  1424. Value *Base_int = Builder.CreatePtrToInt(
  1425. Base, Type::getIntNTy(Context, IntPtrSize));
  1426. Value *Derived_int = Builder.CreatePtrToInt(
  1427. Derived, Type::getIntNTy(Context, IntPtrSize));
  1428. return std::make_pair(Base, Builder.CreateSub(Derived_int, Base_int));
  1429. };
  1430. auto *Dest = CallArgs[0];
  1431. Value *DestBase, *DestOffset;
  1432. std::tie(DestBase, DestOffset) = GetBaseAndOffset(Dest);
  1433. auto *Source = CallArgs[1];
  1434. Value *SourceBase, *SourceOffset;
  1435. std::tie(SourceBase, SourceOffset) = GetBaseAndOffset(Source);
  1436. auto *LengthInBytes = CallArgs[2];
  1437. auto *ElementSizeCI = cast<ConstantInt>(CallArgs[3]);
  1438. CallArgs.clear();
  1439. CallArgs.push_back(DestBase);
  1440. CallArgs.push_back(DestOffset);
  1441. CallArgs.push_back(SourceBase);
  1442. CallArgs.push_back(SourceOffset);
  1443. CallArgs.push_back(LengthInBytes);
  1444. SmallVector<Type *, 8> DomainTy;
  1445. for (Value *Arg : CallArgs)
  1446. DomainTy.push_back(Arg->getType());
  1447. auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
  1448. /* isVarArg = */ false);
  1449. auto GetFunctionName = [](Intrinsic::ID IID, ConstantInt *ElementSizeCI) {
  1450. uint64_t ElementSize = ElementSizeCI->getZExtValue();
  1451. if (IID == Intrinsic::memcpy_element_unordered_atomic) {
  1452. switch (ElementSize) {
  1453. case 1:
  1454. return "__llvm_memcpy_element_unordered_atomic_safepoint_1";
  1455. case 2:
  1456. return "__llvm_memcpy_element_unordered_atomic_safepoint_2";
  1457. case 4:
  1458. return "__llvm_memcpy_element_unordered_atomic_safepoint_4";
  1459. case 8:
  1460. return "__llvm_memcpy_element_unordered_atomic_safepoint_8";
  1461. case 16:
  1462. return "__llvm_memcpy_element_unordered_atomic_safepoint_16";
  1463. default:
  1464. llvm_unreachable("unexpected element size!");
  1465. }
  1466. }
  1467. assert(IID == Intrinsic::memmove_element_unordered_atomic);
  1468. switch (ElementSize) {
  1469. case 1:
  1470. return "__llvm_memmove_element_unordered_atomic_safepoint_1";
  1471. case 2:
  1472. return "__llvm_memmove_element_unordered_atomic_safepoint_2";
  1473. case 4:
  1474. return "__llvm_memmove_element_unordered_atomic_safepoint_4";
  1475. case 8:
  1476. return "__llvm_memmove_element_unordered_atomic_safepoint_8";
  1477. case 16:
  1478. return "__llvm_memmove_element_unordered_atomic_safepoint_16";
  1479. default:
  1480. llvm_unreachable("unexpected element size!");
  1481. }
  1482. };
  1483. CallTarget =
  1484. F->getParent()
  1485. ->getOrInsertFunction(GetFunctionName(IID, ElementSizeCI), FTy)
  1486. .getCallee();
  1487. }
  1488. }
  1489. // Create the statepoint given all the arguments
  1490. GCStatepointInst *Token = nullptr;
  1491. if (auto *CI = dyn_cast<CallInst>(Call)) {
  1492. CallInst *SPCall = Builder.CreateGCStatepointCall(
  1493. StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
  1494. TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
  1495. SPCall->setTailCallKind(CI->getTailCallKind());
  1496. SPCall->setCallingConv(CI->getCallingConv());
  1497. // Currently we will fail on parameter attributes and on certain
  1498. // function attributes. In case if we can handle this set of attributes -
  1499. // set up function attrs directly on statepoint and return attrs later for
  1500. // gc_result intrinsic.
  1501. SPCall->setAttributes(
  1502. legalizeCallAttributes(CI->getContext(), CI->getAttributes()));
  1503. Token = cast<GCStatepointInst>(SPCall);
  1504. // Put the following gc_result and gc_relocate calls immediately after the
  1505. // the old call (which we're about to delete)
  1506. assert(CI->getNextNode() && "Not a terminator, must have next!");
  1507. Builder.SetInsertPoint(CI->getNextNode());
  1508. Builder.SetCurrentDebugLocation(CI->getNextNode()->getDebugLoc());
  1509. } else {
  1510. auto *II = cast<InvokeInst>(Call);
  1511. // Insert the new invoke into the old block. We'll remove the old one in a
  1512. // moment at which point this will become the new terminator for the
  1513. // original block.
  1514. InvokeInst *SPInvoke = Builder.CreateGCStatepointInvoke(
  1515. StatepointID, NumPatchBytes, CallTarget, II->getNormalDest(),
  1516. II->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs, GCArgs,
  1517. "statepoint_token");
  1518. SPInvoke->setCallingConv(II->getCallingConv());
  1519. // Currently we will fail on parameter attributes and on certain
  1520. // function attributes. In case if we can handle this set of attributes -
  1521. // set up function attrs directly on statepoint and return attrs later for
  1522. // gc_result intrinsic.
  1523. SPInvoke->setAttributes(
  1524. legalizeCallAttributes(II->getContext(), II->getAttributes()));
  1525. Token = cast<GCStatepointInst>(SPInvoke);
  1526. // Generate gc relocates in exceptional path
  1527. BasicBlock *UnwindBlock = II->getUnwindDest();
  1528. assert(!isa<PHINode>(UnwindBlock->begin()) &&
  1529. UnwindBlock->getUniquePredecessor() &&
  1530. "can't safely insert in this block!");
  1531. Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
  1532. Builder.SetCurrentDebugLocation(II->getDebugLoc());
  1533. // Attach exceptional gc relocates to the landingpad.
  1534. Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
  1535. Result.UnwindToken = ExceptionalToken;
  1536. CreateGCRelocates(LiveVariables, BasePtrs, ExceptionalToken, Builder);
  1537. // Generate gc relocates and returns for normal block
  1538. BasicBlock *NormalDest = II->getNormalDest();
  1539. assert(!isa<PHINode>(NormalDest->begin()) &&
  1540. NormalDest->getUniquePredecessor() &&
  1541. "can't safely insert in this block!");
  1542. Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
  1543. // gc relocates will be generated later as if it were regular call
  1544. // statepoint
  1545. }
  1546. assert(Token && "Should be set in one of the above branches!");
  1547. if (IsDeoptimize) {
  1548. // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
  1549. // transform the tail-call like structure to a call to a void function
  1550. // followed by unreachable to get better codegen.
  1551. Replacements.push_back(
  1552. DeferredReplacement::createDeoptimizeReplacement(Call));
  1553. } else {
  1554. Token->setName("statepoint_token");
  1555. if (!Call->getType()->isVoidTy() && !Call->use_empty()) {
  1556. StringRef Name = Call->hasName() ? Call->getName() : "";
  1557. CallInst *GCResult = Builder.CreateGCResult(Token, Call->getType(), Name);
  1558. GCResult->setAttributes(
  1559. AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
  1560. Call->getAttributes().getRetAttrs()));
  1561. // We cannot RAUW or delete CS.getInstruction() because it could be in the
  1562. // live set of some other safepoint, in which case that safepoint's
  1563. // PartiallyConstructedSafepointRecord will hold a raw pointer to this
  1564. // llvm::Instruction. Instead, we defer the replacement and deletion to
  1565. // after the live sets have been made explicit in the IR, and we no longer
  1566. // have raw pointers to worry about.
  1567. Replacements.emplace_back(
  1568. DeferredReplacement::createRAUW(Call, GCResult));
  1569. } else {
  1570. Replacements.emplace_back(DeferredReplacement::createDelete(Call));
  1571. }
  1572. }
  1573. Result.StatepointToken = Token;
  1574. // Second, create a gc.relocate for every live variable
  1575. CreateGCRelocates(LiveVariables, BasePtrs, Token, Builder);
  1576. }
  1577. // Replace an existing gc.statepoint with a new one and a set of gc.relocates
  1578. // which make the relocations happening at this safepoint explicit.
  1579. //
  1580. // WARNING: Does not do any fixup to adjust users of the original live
  1581. // values. That's the callers responsibility.
  1582. static void
  1583. makeStatepointExplicit(DominatorTree &DT, CallBase *Call,
  1584. PartiallyConstructedSafepointRecord &Result,
  1585. std::vector<DeferredReplacement> &Replacements,
  1586. const PointerToBaseTy &PointerToBase) {
  1587. const auto &LiveSet = Result.LiveSet;
  1588. // Convert to vector for efficient cross referencing.
  1589. SmallVector<Value *, 64> BaseVec, LiveVec;
  1590. LiveVec.reserve(LiveSet.size());
  1591. BaseVec.reserve(LiveSet.size());
  1592. for (Value *L : LiveSet) {
  1593. LiveVec.push_back(L);
  1594. assert(PointerToBase.count(L));
  1595. Value *Base = PointerToBase.find(L)->second;
  1596. BaseVec.push_back(Base);
  1597. }
  1598. assert(LiveVec.size() == BaseVec.size());
  1599. // Do the actual rewriting and delete the old statepoint
  1600. makeStatepointExplicitImpl(Call, BaseVec, LiveVec, Result, Replacements,
  1601. PointerToBase);
  1602. }
  1603. // Helper function for the relocationViaAlloca.
  1604. //
  1605. // It receives iterator to the statepoint gc relocates and emits a store to the
  1606. // assigned location (via allocaMap) for the each one of them. It adds the
  1607. // visited values into the visitedLiveValues set, which we will later use them
  1608. // for validation checking.
  1609. static void
  1610. insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
  1611. DenseMap<Value *, AllocaInst *> &AllocaMap,
  1612. DenseSet<Value *> &VisitedLiveValues) {
  1613. for (User *U : GCRelocs) {
  1614. GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
  1615. if (!Relocate)
  1616. continue;
  1617. Value *OriginalValue = Relocate->getDerivedPtr();
  1618. assert(AllocaMap.count(OriginalValue));
  1619. Value *Alloca = AllocaMap[OriginalValue];
  1620. // Emit store into the related alloca
  1621. // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
  1622. // the correct type according to alloca.
  1623. assert(Relocate->getNextNode() &&
  1624. "Should always have one since it's not a terminator");
  1625. IRBuilder<> Builder(Relocate->getNextNode());
  1626. Value *CastedRelocatedValue =
  1627. Builder.CreateBitCast(Relocate,
  1628. cast<AllocaInst>(Alloca)->getAllocatedType(),
  1629. suffixed_name_or(Relocate, ".casted", ""));
  1630. new StoreInst(CastedRelocatedValue, Alloca,
  1631. cast<Instruction>(CastedRelocatedValue)->getNextNode());
  1632. #ifndef NDEBUG
  1633. VisitedLiveValues.insert(OriginalValue);
  1634. #endif
  1635. }
  1636. }
  1637. // Helper function for the "relocationViaAlloca". Similar to the
  1638. // "insertRelocationStores" but works for rematerialized values.
  1639. static void insertRematerializationStores(
  1640. const RematerializedValueMapTy &RematerializedValues,
  1641. DenseMap<Value *, AllocaInst *> &AllocaMap,
  1642. DenseSet<Value *> &VisitedLiveValues) {
  1643. for (auto RematerializedValuePair: RematerializedValues) {
  1644. Instruction *RematerializedValue = RematerializedValuePair.first;
  1645. Value *OriginalValue = RematerializedValuePair.second;
  1646. assert(AllocaMap.count(OriginalValue) &&
  1647. "Can not find alloca for rematerialized value");
  1648. Value *Alloca = AllocaMap[OriginalValue];
  1649. new StoreInst(RematerializedValue, Alloca,
  1650. RematerializedValue->getNextNode());
  1651. #ifndef NDEBUG
  1652. VisitedLiveValues.insert(OriginalValue);
  1653. #endif
  1654. }
  1655. }
  1656. /// Do all the relocation update via allocas and mem2reg
  1657. static void relocationViaAlloca(
  1658. Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
  1659. ArrayRef<PartiallyConstructedSafepointRecord> Records) {
  1660. #ifndef NDEBUG
  1661. // record initial number of (static) allocas; we'll check we have the same
  1662. // number when we get done.
  1663. int InitialAllocaNum = 0;
  1664. for (Instruction &I : F.getEntryBlock())
  1665. if (isa<AllocaInst>(I))
  1666. InitialAllocaNum++;
  1667. #endif
  1668. // TODO-PERF: change data structures, reserve
  1669. DenseMap<Value *, AllocaInst *> AllocaMap;
  1670. SmallVector<AllocaInst *, 200> PromotableAllocas;
  1671. // Used later to chack that we have enough allocas to store all values
  1672. std::size_t NumRematerializedValues = 0;
  1673. PromotableAllocas.reserve(Live.size());
  1674. // Emit alloca for "LiveValue" and record it in "allocaMap" and
  1675. // "PromotableAllocas"
  1676. const DataLayout &DL = F.getParent()->getDataLayout();
  1677. auto emitAllocaFor = [&](Value *LiveValue) {
  1678. AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
  1679. DL.getAllocaAddrSpace(), "",
  1680. F.getEntryBlock().getFirstNonPHI());
  1681. AllocaMap[LiveValue] = Alloca;
  1682. PromotableAllocas.push_back(Alloca);
  1683. };
  1684. // Emit alloca for each live gc pointer
  1685. for (Value *V : Live)
  1686. emitAllocaFor(V);
  1687. // Emit allocas for rematerialized values
  1688. for (const auto &Info : Records)
  1689. for (auto RematerializedValuePair : Info.RematerializedValues) {
  1690. Value *OriginalValue = RematerializedValuePair.second;
  1691. if (AllocaMap.count(OriginalValue) != 0)
  1692. continue;
  1693. emitAllocaFor(OriginalValue);
  1694. ++NumRematerializedValues;
  1695. }
  1696. // The next two loops are part of the same conceptual operation. We need to
  1697. // insert a store to the alloca after the original def and at each
  1698. // redefinition. We need to insert a load before each use. These are split
  1699. // into distinct loops for performance reasons.
  1700. // Update gc pointer after each statepoint: either store a relocated value or
  1701. // null (if no relocated value was found for this gc pointer and it is not a
  1702. // gc_result). This must happen before we update the statepoint with load of
  1703. // alloca otherwise we lose the link between statepoint and old def.
  1704. for (const auto &Info : Records) {
  1705. Value *Statepoint = Info.StatepointToken;
  1706. // This will be used for consistency check
  1707. DenseSet<Value *> VisitedLiveValues;
  1708. // Insert stores for normal statepoint gc relocates
  1709. insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
  1710. // In case if it was invoke statepoint
  1711. // we will insert stores for exceptional path gc relocates.
  1712. if (isa<InvokeInst>(Statepoint)) {
  1713. insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
  1714. VisitedLiveValues);
  1715. }
  1716. // Do similar thing with rematerialized values
  1717. insertRematerializationStores(Info.RematerializedValues, AllocaMap,
  1718. VisitedLiveValues);
  1719. if (ClobberNonLive) {
  1720. // As a debugging aid, pretend that an unrelocated pointer becomes null at
  1721. // the gc.statepoint. This will turn some subtle GC problems into
  1722. // slightly easier to debug SEGVs. Note that on large IR files with
  1723. // lots of gc.statepoints this is extremely costly both memory and time
  1724. // wise.
  1725. SmallVector<AllocaInst *, 64> ToClobber;
  1726. for (auto Pair : AllocaMap) {
  1727. Value *Def = Pair.first;
  1728. AllocaInst *Alloca = Pair.second;
  1729. // This value was relocated
  1730. if (VisitedLiveValues.count(Def)) {
  1731. continue;
  1732. }
  1733. ToClobber.push_back(Alloca);
  1734. }
  1735. auto InsertClobbersAt = [&](Instruction *IP) {
  1736. for (auto *AI : ToClobber) {
  1737. auto PT = cast<PointerType>(AI->getAllocatedType());
  1738. Constant *CPN = ConstantPointerNull::get(PT);
  1739. new StoreInst(CPN, AI, IP);
  1740. }
  1741. };
  1742. // Insert the clobbering stores. These may get intermixed with the
  1743. // gc.results and gc.relocates, but that's fine.
  1744. if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
  1745. InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
  1746. InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
  1747. } else {
  1748. InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
  1749. }
  1750. }
  1751. }
  1752. // Update use with load allocas and add store for gc_relocated.
  1753. for (auto Pair : AllocaMap) {
  1754. Value *Def = Pair.first;
  1755. AllocaInst *Alloca = Pair.second;
  1756. // We pre-record the uses of allocas so that we dont have to worry about
  1757. // later update that changes the user information..
  1758. SmallVector<Instruction *, 20> Uses;
  1759. // PERF: trade a linear scan for repeated reallocation
  1760. Uses.reserve(Def->getNumUses());
  1761. for (User *U : Def->users()) {
  1762. if (!isa<ConstantExpr>(U)) {
  1763. // If the def has a ConstantExpr use, then the def is either a
  1764. // ConstantExpr use itself or null. In either case
  1765. // (recursively in the first, directly in the second), the oop
  1766. // it is ultimately dependent on is null and this particular
  1767. // use does not need to be fixed up.
  1768. Uses.push_back(cast<Instruction>(U));
  1769. }
  1770. }
  1771. llvm::sort(Uses);
  1772. auto Last = std::unique(Uses.begin(), Uses.end());
  1773. Uses.erase(Last, Uses.end());
  1774. for (Instruction *Use : Uses) {
  1775. if (isa<PHINode>(Use)) {
  1776. PHINode *Phi = cast<PHINode>(Use);
  1777. for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
  1778. if (Def == Phi->getIncomingValue(i)) {
  1779. LoadInst *Load =
  1780. new LoadInst(Alloca->getAllocatedType(), Alloca, "",
  1781. Phi->getIncomingBlock(i)->getTerminator());
  1782. Phi->setIncomingValue(i, Load);
  1783. }
  1784. }
  1785. } else {
  1786. LoadInst *Load =
  1787. new LoadInst(Alloca->getAllocatedType(), Alloca, "", Use);
  1788. Use->replaceUsesOfWith(Def, Load);
  1789. }
  1790. }
  1791. // Emit store for the initial gc value. Store must be inserted after load,
  1792. // otherwise store will be in alloca's use list and an extra load will be
  1793. // inserted before it.
  1794. StoreInst *Store = new StoreInst(Def, Alloca, /*volatile*/ false,
  1795. DL.getABITypeAlign(Def->getType()));
  1796. if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
  1797. if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
  1798. // InvokeInst is a terminator so the store need to be inserted into its
  1799. // normal destination block.
  1800. BasicBlock *NormalDest = Invoke->getNormalDest();
  1801. Store->insertBefore(NormalDest->getFirstNonPHI());
  1802. } else {
  1803. assert(!Inst->isTerminator() &&
  1804. "The only terminator that can produce a value is "
  1805. "InvokeInst which is handled above.");
  1806. Store->insertAfter(Inst);
  1807. }
  1808. } else {
  1809. assert(isa<Argument>(Def));
  1810. Store->insertAfter(cast<Instruction>(Alloca));
  1811. }
  1812. }
  1813. assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
  1814. "we must have the same allocas with lives");
  1815. if (!PromotableAllocas.empty()) {
  1816. // Apply mem2reg to promote alloca to SSA
  1817. PromoteMemToReg(PromotableAllocas, DT);
  1818. }
  1819. #ifndef NDEBUG
  1820. for (auto &I : F.getEntryBlock())
  1821. if (isa<AllocaInst>(I))
  1822. InitialAllocaNum--;
  1823. assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
  1824. #endif
  1825. }
  1826. /// Implement a unique function which doesn't require we sort the input
  1827. /// vector. Doing so has the effect of changing the output of a couple of
  1828. /// tests in ways which make them less useful in testing fused safepoints.
  1829. template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
  1830. SmallSet<T, 8> Seen;
  1831. erase_if(Vec, [&](const T &V) { return !Seen.insert(V).second; });
  1832. }
  1833. /// Insert holders so that each Value is obviously live through the entire
  1834. /// lifetime of the call.
  1835. static void insertUseHolderAfter(CallBase *Call, const ArrayRef<Value *> Values,
  1836. SmallVectorImpl<CallInst *> &Holders) {
  1837. if (Values.empty())
  1838. // No values to hold live, might as well not insert the empty holder
  1839. return;
  1840. Module *M = Call->getModule();
  1841. // Use a dummy vararg function to actually hold the values live
  1842. FunctionCallee Func = M->getOrInsertFunction(
  1843. "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true));
  1844. if (isa<CallInst>(Call)) {
  1845. // For call safepoints insert dummy calls right after safepoint
  1846. Holders.push_back(
  1847. CallInst::Create(Func, Values, "", &*++Call->getIterator()));
  1848. return;
  1849. }
  1850. // For invoke safepooints insert dummy calls both in normal and
  1851. // exceptional destination blocks
  1852. auto *II = cast<InvokeInst>(Call);
  1853. Holders.push_back(CallInst::Create(
  1854. Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
  1855. Holders.push_back(CallInst::Create(
  1856. Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
  1857. }
  1858. static void findLiveReferences(
  1859. Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
  1860. MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
  1861. GCPtrLivenessData OriginalLivenessData;
  1862. computeLiveInValues(DT, F, OriginalLivenessData);
  1863. for (size_t i = 0; i < records.size(); i++) {
  1864. struct PartiallyConstructedSafepointRecord &info = records[i];
  1865. analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
  1866. }
  1867. }
  1868. // Helper function for the "rematerializeLiveValues". It walks use chain
  1869. // starting from the "CurrentValue" until it reaches the root of the chain, i.e.
  1870. // the base or a value it cannot process. Only "simple" values are processed
  1871. // (currently it is GEP's and casts). The returned root is examined by the
  1872. // callers of findRematerializableChainToBasePointer. Fills "ChainToBase" array
  1873. // with all visited values.
  1874. static Value* findRematerializableChainToBasePointer(
  1875. SmallVectorImpl<Instruction*> &ChainToBase,
  1876. Value *CurrentValue) {
  1877. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
  1878. ChainToBase.push_back(GEP);
  1879. return findRematerializableChainToBasePointer(ChainToBase,
  1880. GEP->getPointerOperand());
  1881. }
  1882. if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
  1883. if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
  1884. return CI;
  1885. ChainToBase.push_back(CI);
  1886. return findRematerializableChainToBasePointer(ChainToBase,
  1887. CI->getOperand(0));
  1888. }
  1889. // We have reached the root of the chain, which is either equal to the base or
  1890. // is the first unsupported value along the use chain.
  1891. return CurrentValue;
  1892. }
  1893. // Helper function for the "rematerializeLiveValues". Compute cost of the use
  1894. // chain we are going to rematerialize.
  1895. static InstructionCost
  1896. chainToBasePointerCost(SmallVectorImpl<Instruction *> &Chain,
  1897. TargetTransformInfo &TTI) {
  1898. InstructionCost Cost = 0;
  1899. for (Instruction *Instr : Chain) {
  1900. if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
  1901. assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
  1902. "non noop cast is found during rematerialization");
  1903. Type *SrcTy = CI->getOperand(0)->getType();
  1904. Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy,
  1905. TTI::getCastContextHint(CI),
  1906. TargetTransformInfo::TCK_SizeAndLatency, CI);
  1907. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
  1908. // Cost of the address calculation
  1909. Type *ValTy = GEP->getSourceElementType();
  1910. Cost += TTI.getAddressComputationCost(ValTy);
  1911. // And cost of the GEP itself
  1912. // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
  1913. // allowed for the external usage)
  1914. if (!GEP->hasAllConstantIndices())
  1915. Cost += 2;
  1916. } else {
  1917. llvm_unreachable("unsupported instruction type during rematerialization");
  1918. }
  1919. }
  1920. return Cost;
  1921. }
  1922. static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
  1923. unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
  1924. if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
  1925. OrigRootPhi.getParent() != AlternateRootPhi.getParent())
  1926. return false;
  1927. // Map of incoming values and their corresponding basic blocks of
  1928. // OrigRootPhi.
  1929. SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
  1930. for (unsigned i = 0; i < PhiNum; i++)
  1931. CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
  1932. OrigRootPhi.getIncomingBlock(i);
  1933. // Both current and base PHIs should have same incoming values and
  1934. // the same basic blocks corresponding to the incoming values.
  1935. for (unsigned i = 0; i < PhiNum; i++) {
  1936. auto CIVI =
  1937. CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
  1938. if (CIVI == CurrentIncomingValues.end())
  1939. return false;
  1940. BasicBlock *CurrentIncomingBB = CIVI->second;
  1941. if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
  1942. return false;
  1943. }
  1944. return true;
  1945. }
  1946. // From the statepoint live set pick values that are cheaper to recompute then
  1947. // to relocate. Remove this values from the live set, rematerialize them after
  1948. // statepoint and record them in "Info" structure. Note that similar to
  1949. // relocated values we don't do any user adjustments here.
  1950. static void rematerializeLiveValues(CallBase *Call,
  1951. PartiallyConstructedSafepointRecord &Info,
  1952. PointerToBaseTy &PointerToBase,
  1953. TargetTransformInfo &TTI) {
  1954. const unsigned int ChainLengthThreshold = 10;
  1955. // Record values we are going to delete from this statepoint live set.
  1956. // We can not di this in following loop due to iterator invalidation.
  1957. SmallVector<Value *, 32> LiveValuesToBeDeleted;
  1958. for (Value *LiveValue: Info.LiveSet) {
  1959. // For each live pointer find its defining chain
  1960. SmallVector<Instruction *, 3> ChainToBase;
  1961. assert(PointerToBase.count(LiveValue));
  1962. Value *RootOfChain =
  1963. findRematerializableChainToBasePointer(ChainToBase,
  1964. LiveValue);
  1965. // Nothing to do, or chain is too long
  1966. if ( ChainToBase.size() == 0 ||
  1967. ChainToBase.size() > ChainLengthThreshold)
  1968. continue;
  1969. // Handle the scenario where the RootOfChain is not equal to the
  1970. // Base Value, but they are essentially the same phi values.
  1971. if (RootOfChain != PointerToBase[LiveValue]) {
  1972. PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
  1973. PHINode *AlternateRootPhi = dyn_cast<PHINode>(PointerToBase[LiveValue]);
  1974. if (!OrigRootPhi || !AlternateRootPhi)
  1975. continue;
  1976. // PHI nodes that have the same incoming values, and belonging to the same
  1977. // basic blocks are essentially the same SSA value. When the original phi
  1978. // has incoming values with different base pointers, the original phi is
  1979. // marked as conflict, and an additional `AlternateRootPhi` with the same
  1980. // incoming values get generated by the findBasePointer function. We need
  1981. // to identify the newly generated AlternateRootPhi (.base version of phi)
  1982. // and RootOfChain (the original phi node itself) are the same, so that we
  1983. // can rematerialize the gep and casts. This is a workaround for the
  1984. // deficiency in the findBasePointer algorithm.
  1985. if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
  1986. continue;
  1987. // Now that the phi nodes are proved to be the same, assert that
  1988. // findBasePointer's newly generated AlternateRootPhi is present in the
  1989. // liveset of the call.
  1990. assert(Info.LiveSet.count(AlternateRootPhi));
  1991. }
  1992. // Compute cost of this chain
  1993. InstructionCost Cost = chainToBasePointerCost(ChainToBase, TTI);
  1994. // TODO: We can also account for cases when we will be able to remove some
  1995. // of the rematerialized values by later optimization passes. I.e if
  1996. // we rematerialized several intersecting chains. Or if original values
  1997. // don't have any uses besides this statepoint.
  1998. // For invokes we need to rematerialize each chain twice - for normal and
  1999. // for unwind basic blocks. Model this by multiplying cost by two.
  2000. if (isa<InvokeInst>(Call)) {
  2001. Cost *= 2;
  2002. }
  2003. // If it's too expensive - skip it
  2004. if (Cost >= RematerializationThreshold)
  2005. continue;
  2006. // Remove value from the live set
  2007. LiveValuesToBeDeleted.push_back(LiveValue);
  2008. // Clone instructions and record them inside "Info" structure
  2009. // Walk backwards to visit top-most instructions first
  2010. std::reverse(ChainToBase.begin(), ChainToBase.end());
  2011. // Utility function which clones all instructions from "ChainToBase"
  2012. // and inserts them before "InsertBefore". Returns rematerialized value
  2013. // which should be used after statepoint.
  2014. auto rematerializeChain = [&ChainToBase](
  2015. Instruction *InsertBefore, Value *RootOfChain, Value *AlternateLiveBase) {
  2016. Instruction *LastClonedValue = nullptr;
  2017. Instruction *LastValue = nullptr;
  2018. for (Instruction *Instr: ChainToBase) {
  2019. // Only GEP's and casts are supported as we need to be careful to not
  2020. // introduce any new uses of pointers not in the liveset.
  2021. // Note that it's fine to introduce new uses of pointers which were
  2022. // otherwise not used after this statepoint.
  2023. assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
  2024. Instruction *ClonedValue = Instr->clone();
  2025. ClonedValue->insertBefore(InsertBefore);
  2026. ClonedValue->setName(Instr->getName() + ".remat");
  2027. // If it is not first instruction in the chain then it uses previously
  2028. // cloned value. We should update it to use cloned value.
  2029. if (LastClonedValue) {
  2030. assert(LastValue);
  2031. ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
  2032. #ifndef NDEBUG
  2033. for (auto OpValue : ClonedValue->operand_values()) {
  2034. // Assert that cloned instruction does not use any instructions from
  2035. // this chain other than LastClonedValue
  2036. assert(!is_contained(ChainToBase, OpValue) &&
  2037. "incorrect use in rematerialization chain");
  2038. // Assert that the cloned instruction does not use the RootOfChain
  2039. // or the AlternateLiveBase.
  2040. assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
  2041. }
  2042. #endif
  2043. } else {
  2044. // For the first instruction, replace the use of unrelocated base i.e.
  2045. // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
  2046. // live set. They have been proved to be the same PHI nodes. Note
  2047. // that the *only* use of the RootOfChain in the ChainToBase list is
  2048. // the first Value in the list.
  2049. if (RootOfChain != AlternateLiveBase)
  2050. ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
  2051. }
  2052. LastClonedValue = ClonedValue;
  2053. LastValue = Instr;
  2054. }
  2055. assert(LastClonedValue);
  2056. return LastClonedValue;
  2057. };
  2058. // Different cases for calls and invokes. For invokes we need to clone
  2059. // instructions both on normal and unwind path.
  2060. if (isa<CallInst>(Call)) {
  2061. Instruction *InsertBefore = Call->getNextNode();
  2062. assert(InsertBefore);
  2063. Instruction *RematerializedValue = rematerializeChain(
  2064. InsertBefore, RootOfChain, PointerToBase[LiveValue]);
  2065. Info.RematerializedValues[RematerializedValue] = LiveValue;
  2066. } else {
  2067. auto *Invoke = cast<InvokeInst>(Call);
  2068. Instruction *NormalInsertBefore =
  2069. &*Invoke->getNormalDest()->getFirstInsertionPt();
  2070. Instruction *UnwindInsertBefore =
  2071. &*Invoke->getUnwindDest()->getFirstInsertionPt();
  2072. Instruction *NormalRematerializedValue = rematerializeChain(
  2073. NormalInsertBefore, RootOfChain, PointerToBase[LiveValue]);
  2074. Instruction *UnwindRematerializedValue = rematerializeChain(
  2075. UnwindInsertBefore, RootOfChain, PointerToBase[LiveValue]);
  2076. Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
  2077. Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
  2078. }
  2079. }
  2080. // Remove rematerializaed values from the live set
  2081. for (auto LiveValue: LiveValuesToBeDeleted) {
  2082. Info.LiveSet.remove(LiveValue);
  2083. }
  2084. }
  2085. static bool inlineGetBaseAndOffset(Function &F,
  2086. SmallVectorImpl<CallInst *> &Intrinsics,
  2087. DefiningValueMapTy &DVCache) {
  2088. auto &Context = F.getContext();
  2089. auto &DL = F.getParent()->getDataLayout();
  2090. bool Changed = false;
  2091. for (auto *Callsite : Intrinsics)
  2092. switch (Callsite->getIntrinsicID()) {
  2093. case Intrinsic::experimental_gc_get_pointer_base: {
  2094. Changed = true;
  2095. Value *Base = findBasePointer(Callsite->getOperand(0), DVCache);
  2096. assert(!DVCache.count(Callsite));
  2097. auto *BaseBC = IRBuilder<>(Callsite).CreateBitCast(
  2098. Base, Callsite->getType(), suffixed_name_or(Base, ".cast", ""));
  2099. if (BaseBC != Base)
  2100. DVCache[BaseBC] = Base;
  2101. Callsite->replaceAllUsesWith(BaseBC);
  2102. if (!BaseBC->hasName())
  2103. BaseBC->takeName(Callsite);
  2104. Callsite->eraseFromParent();
  2105. break;
  2106. }
  2107. case Intrinsic::experimental_gc_get_pointer_offset: {
  2108. Changed = true;
  2109. Value *Derived = Callsite->getOperand(0);
  2110. Value *Base = findBasePointer(Derived, DVCache);
  2111. assert(!DVCache.count(Callsite));
  2112. unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
  2113. unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
  2114. IRBuilder<> Builder(Callsite);
  2115. Value *BaseInt =
  2116. Builder.CreatePtrToInt(Base, Type::getIntNTy(Context, IntPtrSize),
  2117. suffixed_name_or(Base, ".int", ""));
  2118. Value *DerivedInt =
  2119. Builder.CreatePtrToInt(Derived, Type::getIntNTy(Context, IntPtrSize),
  2120. suffixed_name_or(Derived, ".int", ""));
  2121. Value *Offset = Builder.CreateSub(DerivedInt, BaseInt);
  2122. Callsite->replaceAllUsesWith(Offset);
  2123. Offset->takeName(Callsite);
  2124. Callsite->eraseFromParent();
  2125. break;
  2126. }
  2127. default:
  2128. llvm_unreachable("Unknown intrinsic");
  2129. }
  2130. return Changed;
  2131. }
  2132. static bool insertParsePoints(Function &F, DominatorTree &DT,
  2133. TargetTransformInfo &TTI,
  2134. SmallVectorImpl<CallBase *> &ToUpdate,
  2135. DefiningValueMapTy &DVCache) {
  2136. #ifndef NDEBUG
  2137. // Validate the input
  2138. std::set<CallBase *> Uniqued;
  2139. Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
  2140. assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
  2141. for (CallBase *Call : ToUpdate)
  2142. assert(Call->getFunction() == &F);
  2143. #endif
  2144. // When inserting gc.relocates for invokes, we need to be able to insert at
  2145. // the top of the successor blocks. See the comment on
  2146. // normalForInvokeSafepoint on exactly what is needed. Note that this step
  2147. // may restructure the CFG.
  2148. for (CallBase *Call : ToUpdate) {
  2149. auto *II = dyn_cast<InvokeInst>(Call);
  2150. if (!II)
  2151. continue;
  2152. normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
  2153. normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
  2154. }
  2155. // A list of dummy calls added to the IR to keep various values obviously
  2156. // live in the IR. We'll remove all of these when done.
  2157. SmallVector<CallInst *, 64> Holders;
  2158. // Insert a dummy call with all of the deopt operands we'll need for the
  2159. // actual safepoint insertion as arguments. This ensures reference operands
  2160. // in the deopt argument list are considered live through the safepoint (and
  2161. // thus makes sure they get relocated.)
  2162. for (CallBase *Call : ToUpdate) {
  2163. SmallVector<Value *, 64> DeoptValues;
  2164. for (Value *Arg : GetDeoptBundleOperands(Call)) {
  2165. assert(!isUnhandledGCPointerType(Arg->getType()) &&
  2166. "support for FCA unimplemented");
  2167. if (isHandledGCPointerType(Arg->getType()))
  2168. DeoptValues.push_back(Arg);
  2169. }
  2170. insertUseHolderAfter(Call, DeoptValues, Holders);
  2171. }
  2172. SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
  2173. // A) Identify all gc pointers which are statically live at the given call
  2174. // site.
  2175. findLiveReferences(F, DT, ToUpdate, Records);
  2176. /// Global mapping from live pointers to a base-defining-value.
  2177. PointerToBaseTy PointerToBase;
  2178. // B) Find the base pointers for each live pointer
  2179. for (size_t i = 0; i < Records.size(); i++) {
  2180. PartiallyConstructedSafepointRecord &info = Records[i];
  2181. findBasePointers(DT, DVCache, ToUpdate[i], info, PointerToBase);
  2182. }
  2183. if (PrintBasePointers) {
  2184. errs() << "Base Pairs (w/o Relocation):\n";
  2185. for (auto &Pair : PointerToBase) {
  2186. errs() << " derived ";
  2187. Pair.first->printAsOperand(errs(), false);
  2188. errs() << " base ";
  2189. Pair.second->printAsOperand(errs(), false);
  2190. errs() << "\n";
  2191. ;
  2192. }
  2193. }
  2194. // The base phi insertion logic (for any safepoint) may have inserted new
  2195. // instructions which are now live at some safepoint. The simplest such
  2196. // example is:
  2197. // loop:
  2198. // phi a <-- will be a new base_phi here
  2199. // safepoint 1 <-- that needs to be live here
  2200. // gep a + 1
  2201. // safepoint 2
  2202. // br loop
  2203. // We insert some dummy calls after each safepoint to definitely hold live
  2204. // the base pointers which were identified for that safepoint. We'll then
  2205. // ask liveness for _every_ base inserted to see what is now live. Then we
  2206. // remove the dummy calls.
  2207. Holders.reserve(Holders.size() + Records.size());
  2208. for (size_t i = 0; i < Records.size(); i++) {
  2209. PartiallyConstructedSafepointRecord &Info = Records[i];
  2210. SmallVector<Value *, 128> Bases;
  2211. for (auto *Derived : Info.LiveSet) {
  2212. assert(PointerToBase.count(Derived) && "Missed base for derived pointer");
  2213. Bases.push_back(PointerToBase[Derived]);
  2214. }
  2215. insertUseHolderAfter(ToUpdate[i], Bases, Holders);
  2216. }
  2217. // By selecting base pointers, we've effectively inserted new uses. Thus, we
  2218. // need to rerun liveness. We may *also* have inserted new defs, but that's
  2219. // not the key issue.
  2220. recomputeLiveInValues(F, DT, ToUpdate, Records, PointerToBase);
  2221. if (PrintBasePointers) {
  2222. errs() << "Base Pairs: (w/Relocation)\n";
  2223. for (auto Pair : PointerToBase) {
  2224. errs() << " derived ";
  2225. Pair.first->printAsOperand(errs(), false);
  2226. errs() << " base ";
  2227. Pair.second->printAsOperand(errs(), false);
  2228. errs() << "\n";
  2229. }
  2230. }
  2231. // It is possible that non-constant live variables have a constant base. For
  2232. // example, a GEP with a variable offset from a global. In this case we can
  2233. // remove it from the liveset. We already don't add constants to the liveset
  2234. // because we assume they won't move at runtime and the GC doesn't need to be
  2235. // informed about them. The same reasoning applies if the base is constant.
  2236. // Note that the relocation placement code relies on this filtering for
  2237. // correctness as it expects the base to be in the liveset, which isn't true
  2238. // if the base is constant.
  2239. for (auto &Info : Records) {
  2240. Info.LiveSet.remove_if([&](Value *LiveV) {
  2241. assert(PointerToBase.count(LiveV) && "Missed base for derived pointer");
  2242. return isa<Constant>(PointerToBase[LiveV]);
  2243. });
  2244. }
  2245. for (CallInst *CI : Holders)
  2246. CI->eraseFromParent();
  2247. Holders.clear();
  2248. // In order to reduce live set of statepoint we might choose to rematerialize
  2249. // some values instead of relocating them. This is purely an optimization and
  2250. // does not influence correctness.
  2251. for (size_t i = 0; i < Records.size(); i++)
  2252. rematerializeLiveValues(ToUpdate[i], Records[i], PointerToBase, TTI);
  2253. // We need this to safely RAUW and delete call or invoke return values that
  2254. // may themselves be live over a statepoint. For details, please see usage in
  2255. // makeStatepointExplicitImpl.
  2256. std::vector<DeferredReplacement> Replacements;
  2257. // Now run through and replace the existing statepoints with new ones with
  2258. // the live variables listed. We do not yet update uses of the values being
  2259. // relocated. We have references to live variables that need to
  2260. // survive to the last iteration of this loop. (By construction, the
  2261. // previous statepoint can not be a live variable, thus we can and remove
  2262. // the old statepoint calls as we go.)
  2263. for (size_t i = 0; i < Records.size(); i++)
  2264. makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements,
  2265. PointerToBase);
  2266. ToUpdate.clear(); // prevent accident use of invalid calls.
  2267. for (auto &PR : Replacements)
  2268. PR.doReplacement();
  2269. Replacements.clear();
  2270. for (auto &Info : Records) {
  2271. // These live sets may contain state Value pointers, since we replaced calls
  2272. // with operand bundles with calls wrapped in gc.statepoint, and some of
  2273. // those calls may have been def'ing live gc pointers. Clear these out to
  2274. // avoid accidentally using them.
  2275. //
  2276. // TODO: We should create a separate data structure that does not contain
  2277. // these live sets, and migrate to using that data structure from this point
  2278. // onward.
  2279. Info.LiveSet.clear();
  2280. }
  2281. PointerToBase.clear();
  2282. // Do all the fixups of the original live variables to their relocated selves
  2283. SmallVector<Value *, 128> Live;
  2284. for (size_t i = 0; i < Records.size(); i++) {
  2285. PartiallyConstructedSafepointRecord &Info = Records[i];
  2286. // We can't simply save the live set from the original insertion. One of
  2287. // the live values might be the result of a call which needs a safepoint.
  2288. // That Value* no longer exists and we need to use the new gc_result.
  2289. // Thankfully, the live set is embedded in the statepoint (and updated), so
  2290. // we just grab that.
  2291. llvm::append_range(Live, Info.StatepointToken->gc_args());
  2292. #ifndef NDEBUG
  2293. // Do some basic validation checking on our liveness results before
  2294. // performing relocation. Relocation can and will turn mistakes in liveness
  2295. // results into non-sensical code which is must harder to debug.
  2296. // TODO: It would be nice to test consistency as well
  2297. assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
  2298. "statepoint must be reachable or liveness is meaningless");
  2299. for (Value *V : Info.StatepointToken->gc_args()) {
  2300. if (!isa<Instruction>(V))
  2301. // Non-instruction values trivial dominate all possible uses
  2302. continue;
  2303. auto *LiveInst = cast<Instruction>(V);
  2304. assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
  2305. "unreachable values should never be live");
  2306. assert(DT.dominates(LiveInst, Info.StatepointToken) &&
  2307. "basic SSA liveness expectation violated by liveness analysis");
  2308. }
  2309. #endif
  2310. }
  2311. unique_unsorted(Live);
  2312. #ifndef NDEBUG
  2313. // Validation check
  2314. for (auto *Ptr : Live)
  2315. assert(isHandledGCPointerType(Ptr->getType()) &&
  2316. "must be a gc pointer type");
  2317. #endif
  2318. relocationViaAlloca(F, DT, Live, Records);
  2319. return !Records.empty();
  2320. }
  2321. // List of all parameter and return attributes which must be stripped when
  2322. // lowering from the abstract machine model. Note that we list attributes
  2323. // here which aren't valid as return attributes, that is okay.
  2324. static AttributeMask getParamAndReturnAttributesToRemove() {
  2325. AttributeMask R;
  2326. R.addAttribute(Attribute::Dereferenceable);
  2327. R.addAttribute(Attribute::DereferenceableOrNull);
  2328. R.addAttribute(Attribute::ReadNone);
  2329. R.addAttribute(Attribute::ReadOnly);
  2330. R.addAttribute(Attribute::WriteOnly);
  2331. R.addAttribute(Attribute::NoAlias);
  2332. R.addAttribute(Attribute::NoFree);
  2333. return R;
  2334. }
  2335. static void stripNonValidAttributesFromPrototype(Function &F) {
  2336. LLVMContext &Ctx = F.getContext();
  2337. // Intrinsics are very delicate. Lowering sometimes depends the presence
  2338. // of certain attributes for correctness, but we may have also inferred
  2339. // additional ones in the abstract machine model which need stripped. This
  2340. // assumes that the attributes defined in Intrinsic.td are conservatively
  2341. // correct for both physical and abstract model.
  2342. if (Intrinsic::ID id = F.getIntrinsicID()) {
  2343. F.setAttributes(Intrinsic::getAttributes(Ctx, id));
  2344. return;
  2345. }
  2346. AttributeMask R = getParamAndReturnAttributesToRemove();
  2347. for (Argument &A : F.args())
  2348. if (isa<PointerType>(A.getType()))
  2349. F.removeParamAttrs(A.getArgNo(), R);
  2350. if (isa<PointerType>(F.getReturnType()))
  2351. F.removeRetAttrs(R);
  2352. for (auto Attr : FnAttrsToStrip)
  2353. F.removeFnAttr(Attr);
  2354. }
  2355. /// Certain metadata on instructions are invalid after running RS4GC.
  2356. /// Optimizations that run after RS4GC can incorrectly use this metadata to
  2357. /// optimize functions. We drop such metadata on the instruction.
  2358. static void stripInvalidMetadataFromInstruction(Instruction &I) {
  2359. if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
  2360. return;
  2361. // These are the attributes that are still valid on loads and stores after
  2362. // RS4GC.
  2363. // The metadata implying dereferenceability and noalias are (conservatively)
  2364. // dropped. This is because semantically, after RewriteStatepointsForGC runs,
  2365. // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
  2366. // touch the entire heap including noalias objects. Note: The reasoning is
  2367. // same as stripping the dereferenceability and noalias attributes that are
  2368. // analogous to the metadata counterparts.
  2369. // We also drop the invariant.load metadata on the load because that metadata
  2370. // implies the address operand to the load points to memory that is never
  2371. // changed once it became dereferenceable. This is no longer true after RS4GC.
  2372. // Similar reasoning applies to invariant.group metadata, which applies to
  2373. // loads within a group.
  2374. unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
  2375. LLVMContext::MD_range,
  2376. LLVMContext::MD_alias_scope,
  2377. LLVMContext::MD_nontemporal,
  2378. LLVMContext::MD_nonnull,
  2379. LLVMContext::MD_align,
  2380. LLVMContext::MD_type};
  2381. // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
  2382. I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
  2383. }
  2384. static void stripNonValidDataFromBody(Function &F) {
  2385. if (F.empty())
  2386. return;
  2387. LLVMContext &Ctx = F.getContext();
  2388. MDBuilder Builder(Ctx);
  2389. // Set of invariantstart instructions that we need to remove.
  2390. // Use this to avoid invalidating the instruction iterator.
  2391. SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
  2392. for (Instruction &I : instructions(F)) {
  2393. // invariant.start on memory location implies that the referenced memory
  2394. // location is constant and unchanging. This is no longer true after
  2395. // RewriteStatepointsForGC runs because there can be calls to gc.statepoint
  2396. // which frees the entire heap and the presence of invariant.start allows
  2397. // the optimizer to sink the load of a memory location past a statepoint,
  2398. // which is incorrect.
  2399. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  2400. if (II->getIntrinsicID() == Intrinsic::invariant_start) {
  2401. InvariantStartInstructions.push_back(II);
  2402. continue;
  2403. }
  2404. if (MDNode *Tag = I.getMetadata(LLVMContext::MD_tbaa)) {
  2405. MDNode *MutableTBAA = Builder.createMutableTBAAAccessTag(Tag);
  2406. I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
  2407. }
  2408. stripInvalidMetadataFromInstruction(I);
  2409. AttributeMask R = getParamAndReturnAttributesToRemove();
  2410. if (auto *Call = dyn_cast<CallBase>(&I)) {
  2411. for (int i = 0, e = Call->arg_size(); i != e; i++)
  2412. if (isa<PointerType>(Call->getArgOperand(i)->getType()))
  2413. Call->removeParamAttrs(i, R);
  2414. if (isa<PointerType>(Call->getType()))
  2415. Call->removeRetAttrs(R);
  2416. }
  2417. }
  2418. // Delete the invariant.start instructions and RAUW undef.
  2419. for (auto *II : InvariantStartInstructions) {
  2420. II->replaceAllUsesWith(UndefValue::get(II->getType()));
  2421. II->eraseFromParent();
  2422. }
  2423. }
  2424. /// Returns true if this function should be rewritten by this pass. The main
  2425. /// point of this function is as an extension point for custom logic.
  2426. static bool shouldRewriteStatepointsIn(Function &F) {
  2427. // TODO: This should check the GCStrategy
  2428. if (F.hasGC()) {
  2429. const auto &FunctionGCName = F.getGC();
  2430. const StringRef StatepointExampleName("statepoint-example");
  2431. const StringRef CoreCLRName("coreclr");
  2432. return (StatepointExampleName == FunctionGCName) ||
  2433. (CoreCLRName == FunctionGCName);
  2434. } else
  2435. return false;
  2436. }
  2437. static void stripNonValidData(Module &M) {
  2438. #ifndef NDEBUG
  2439. assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
  2440. #endif
  2441. for (Function &F : M)
  2442. stripNonValidAttributesFromPrototype(F);
  2443. for (Function &F : M)
  2444. stripNonValidDataFromBody(F);
  2445. }
  2446. bool RewriteStatepointsForGC::runOnFunction(Function &F, DominatorTree &DT,
  2447. TargetTransformInfo &TTI,
  2448. const TargetLibraryInfo &TLI) {
  2449. assert(!F.isDeclaration() && !F.empty() &&
  2450. "need function body to rewrite statepoints in");
  2451. assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
  2452. auto NeedsRewrite = [&TLI](Instruction &I) {
  2453. if (const auto *Call = dyn_cast<CallBase>(&I)) {
  2454. if (isa<GCStatepointInst>(Call))
  2455. return false;
  2456. if (callsGCLeafFunction(Call, TLI))
  2457. return false;
  2458. // Normally it's up to the frontend to make sure that non-leaf calls also
  2459. // have proper deopt state if it is required. We make an exception for
  2460. // element atomic memcpy/memmove intrinsics here. Unlike other intrinsics
  2461. // these are non-leaf by default. They might be generated by the optimizer
  2462. // which doesn't know how to produce a proper deopt state. So if we see a
  2463. // non-leaf memcpy/memmove without deopt state just treat it as a leaf
  2464. // copy and don't produce a statepoint.
  2465. if (!AllowStatepointWithNoDeoptInfo &&
  2466. !Call->getOperandBundle(LLVMContext::OB_deopt)) {
  2467. assert((isa<AtomicMemCpyInst>(Call) || isa<AtomicMemMoveInst>(Call)) &&
  2468. "Don't expect any other calls here!");
  2469. return false;
  2470. }
  2471. return true;
  2472. }
  2473. return false;
  2474. };
  2475. // Delete any unreachable statepoints so that we don't have unrewritten
  2476. // statepoints surviving this pass. This makes testing easier and the
  2477. // resulting IR less confusing to human readers.
  2478. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  2479. bool MadeChange = removeUnreachableBlocks(F, &DTU);
  2480. // Flush the Dominator Tree.
  2481. DTU.getDomTree();
  2482. // Gather all the statepoints which need rewritten. Be careful to only
  2483. // consider those in reachable code since we need to ask dominance queries
  2484. // when rewriting. We'll delete the unreachable ones in a moment.
  2485. SmallVector<CallBase *, 64> ParsePointNeeded;
  2486. SmallVector<CallInst *, 64> Intrinsics;
  2487. for (Instruction &I : instructions(F)) {
  2488. // TODO: only the ones with the flag set!
  2489. if (NeedsRewrite(I)) {
  2490. // NOTE removeUnreachableBlocks() is stronger than
  2491. // DominatorTree::isReachableFromEntry(). In other words
  2492. // removeUnreachableBlocks can remove some blocks for which
  2493. // isReachableFromEntry() returns true.
  2494. assert(DT.isReachableFromEntry(I.getParent()) &&
  2495. "no unreachable blocks expected");
  2496. ParsePointNeeded.push_back(cast<CallBase>(&I));
  2497. }
  2498. if (auto *CI = dyn_cast<CallInst>(&I))
  2499. if (CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_base ||
  2500. CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_offset)
  2501. Intrinsics.emplace_back(CI);
  2502. }
  2503. // Return early if no work to do.
  2504. if (ParsePointNeeded.empty() && Intrinsics.empty())
  2505. return MadeChange;
  2506. // As a prepass, go ahead and aggressively destroy single entry phi nodes.
  2507. // These are created by LCSSA. They have the effect of increasing the size
  2508. // of liveness sets for no good reason. It may be harder to do this post
  2509. // insertion since relocations and base phis can confuse things.
  2510. for (BasicBlock &BB : F)
  2511. if (BB.getUniquePredecessor())
  2512. MadeChange |= FoldSingleEntryPHINodes(&BB);
  2513. // Before we start introducing relocations, we want to tweak the IR a bit to
  2514. // avoid unfortunate code generation effects. The main example is that we
  2515. // want to try to make sure the comparison feeding a branch is after any
  2516. // safepoints. Otherwise, we end up with a comparison of pre-relocation
  2517. // values feeding a branch after relocation. This is semantically correct,
  2518. // but results in extra register pressure since both the pre-relocation and
  2519. // post-relocation copies must be available in registers. For code without
  2520. // relocations this is handled elsewhere, but teaching the scheduler to
  2521. // reverse the transform we're about to do would be slightly complex.
  2522. // Note: This may extend the live range of the inputs to the icmp and thus
  2523. // increase the liveset of any statepoint we move over. This is profitable
  2524. // as long as all statepoints are in rare blocks. If we had in-register
  2525. // lowering for live values this would be a much safer transform.
  2526. auto getConditionInst = [](Instruction *TI) -> Instruction * {
  2527. if (auto *BI = dyn_cast<BranchInst>(TI))
  2528. if (BI->isConditional())
  2529. return dyn_cast<Instruction>(BI->getCondition());
  2530. // TODO: Extend this to handle switches
  2531. return nullptr;
  2532. };
  2533. for (BasicBlock &BB : F) {
  2534. Instruction *TI = BB.getTerminator();
  2535. if (auto *Cond = getConditionInst(TI))
  2536. // TODO: Handle more than just ICmps here. We should be able to move
  2537. // most instructions without side effects or memory access.
  2538. if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
  2539. MadeChange = true;
  2540. Cond->moveBefore(TI);
  2541. }
  2542. }
  2543. // Nasty workaround - The base computation code in the main algorithm doesn't
  2544. // consider the fact that a GEP can be used to convert a scalar to a vector.
  2545. // The right fix for this is to integrate GEPs into the base rewriting
  2546. // algorithm properly, this is just a short term workaround to prevent
  2547. // crashes by canonicalizing such GEPs into fully vector GEPs.
  2548. for (Instruction &I : instructions(F)) {
  2549. if (!isa<GetElementPtrInst>(I))
  2550. continue;
  2551. unsigned VF = 0;
  2552. for (unsigned i = 0; i < I.getNumOperands(); i++)
  2553. if (auto *OpndVTy = dyn_cast<VectorType>(I.getOperand(i)->getType())) {
  2554. assert(VF == 0 ||
  2555. VF == cast<FixedVectorType>(OpndVTy)->getNumElements());
  2556. VF = cast<FixedVectorType>(OpndVTy)->getNumElements();
  2557. }
  2558. // It's the vector to scalar traversal through the pointer operand which
  2559. // confuses base pointer rewriting, so limit ourselves to that case.
  2560. if (!I.getOperand(0)->getType()->isVectorTy() && VF != 0) {
  2561. IRBuilder<> B(&I);
  2562. auto *Splat = B.CreateVectorSplat(VF, I.getOperand(0));
  2563. I.setOperand(0, Splat);
  2564. MadeChange = true;
  2565. }
  2566. }
  2567. // Cache the 'defining value' relation used in the computation and
  2568. // insertion of base phis and selects. This ensures that we don't insert
  2569. // large numbers of duplicate base_phis. Use one cache for both
  2570. // inlineGetBaseAndOffset() and insertParsePoints().
  2571. DefiningValueMapTy DVCache;
  2572. if (!Intrinsics.empty())
  2573. // Inline @gc.get.pointer.base() and @gc.get.pointer.offset() before finding
  2574. // live references.
  2575. MadeChange |= inlineGetBaseAndOffset(F, Intrinsics, DVCache);
  2576. if (!ParsePointNeeded.empty())
  2577. MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded, DVCache);
  2578. return MadeChange;
  2579. }
  2580. // liveness computation via standard dataflow
  2581. // -------------------------------------------------------------------
  2582. // TODO: Consider using bitvectors for liveness, the set of potentially
  2583. // interesting values should be small and easy to pre-compute.
  2584. /// Compute the live-in set for the location rbegin starting from
  2585. /// the live-out set of the basic block
  2586. static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
  2587. BasicBlock::reverse_iterator End,
  2588. SetVector<Value *> &LiveTmp) {
  2589. for (auto &I : make_range(Begin, End)) {
  2590. // KILL/Def - Remove this definition from LiveIn
  2591. LiveTmp.remove(&I);
  2592. // Don't consider *uses* in PHI nodes, we handle their contribution to
  2593. // predecessor blocks when we seed the LiveOut sets
  2594. if (isa<PHINode>(I))
  2595. continue;
  2596. // USE - Add to the LiveIn set for this instruction
  2597. for (Value *V : I.operands()) {
  2598. assert(!isUnhandledGCPointerType(V->getType()) &&
  2599. "support for FCA unimplemented");
  2600. if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
  2601. // The choice to exclude all things constant here is slightly subtle.
  2602. // There are two independent reasons:
  2603. // - We assume that things which are constant (from LLVM's definition)
  2604. // do not move at runtime. For example, the address of a global
  2605. // variable is fixed, even though it's contents may not be.
  2606. // - Second, we can't disallow arbitrary inttoptr constants even
  2607. // if the language frontend does. Optimization passes are free to
  2608. // locally exploit facts without respect to global reachability. This
  2609. // can create sections of code which are dynamically unreachable and
  2610. // contain just about anything. (see constants.ll in tests)
  2611. LiveTmp.insert(V);
  2612. }
  2613. }
  2614. }
  2615. }
  2616. static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
  2617. for (BasicBlock *Succ : successors(BB)) {
  2618. for (auto &I : *Succ) {
  2619. PHINode *PN = dyn_cast<PHINode>(&I);
  2620. if (!PN)
  2621. break;
  2622. Value *V = PN->getIncomingValueForBlock(BB);
  2623. assert(!isUnhandledGCPointerType(V->getType()) &&
  2624. "support for FCA unimplemented");
  2625. if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V))
  2626. LiveTmp.insert(V);
  2627. }
  2628. }
  2629. }
  2630. static SetVector<Value *> computeKillSet(BasicBlock *BB) {
  2631. SetVector<Value *> KillSet;
  2632. for (Instruction &I : *BB)
  2633. if (isHandledGCPointerType(I.getType()))
  2634. KillSet.insert(&I);
  2635. return KillSet;
  2636. }
  2637. #ifndef NDEBUG
  2638. /// Check that the items in 'Live' dominate 'TI'. This is used as a basic
  2639. /// validation check for the liveness computation.
  2640. static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
  2641. Instruction *TI, bool TermOkay = false) {
  2642. for (Value *V : Live) {
  2643. if (auto *I = dyn_cast<Instruction>(V)) {
  2644. // The terminator can be a member of the LiveOut set. LLVM's definition
  2645. // of instruction dominance states that V does not dominate itself. As
  2646. // such, we need to special case this to allow it.
  2647. if (TermOkay && TI == I)
  2648. continue;
  2649. assert(DT.dominates(I, TI) &&
  2650. "basic SSA liveness expectation violated by liveness analysis");
  2651. }
  2652. }
  2653. }
  2654. /// Check that all the liveness sets used during the computation of liveness
  2655. /// obey basic SSA properties. This is useful for finding cases where we miss
  2656. /// a def.
  2657. static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
  2658. BasicBlock &BB) {
  2659. checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
  2660. checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
  2661. checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
  2662. }
  2663. #endif
  2664. static void computeLiveInValues(DominatorTree &DT, Function &F,
  2665. GCPtrLivenessData &Data) {
  2666. SmallSetVector<BasicBlock *, 32> Worklist;
  2667. // Seed the liveness for each individual block
  2668. for (BasicBlock &BB : F) {
  2669. Data.KillSet[&BB] = computeKillSet(&BB);
  2670. Data.LiveSet[&BB].clear();
  2671. computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
  2672. #ifndef NDEBUG
  2673. for (Value *Kill : Data.KillSet[&BB])
  2674. assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
  2675. #endif
  2676. Data.LiveOut[&BB] = SetVector<Value *>();
  2677. computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
  2678. Data.LiveIn[&BB] = Data.LiveSet[&BB];
  2679. Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
  2680. Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
  2681. if (!Data.LiveIn[&BB].empty())
  2682. Worklist.insert(pred_begin(&BB), pred_end(&BB));
  2683. }
  2684. // Propagate that liveness until stable
  2685. while (!Worklist.empty()) {
  2686. BasicBlock *BB = Worklist.pop_back_val();
  2687. // Compute our new liveout set, then exit early if it hasn't changed despite
  2688. // the contribution of our successor.
  2689. SetVector<Value *> LiveOut = Data.LiveOut[BB];
  2690. const auto OldLiveOutSize = LiveOut.size();
  2691. for (BasicBlock *Succ : successors(BB)) {
  2692. assert(Data.LiveIn.count(Succ));
  2693. LiveOut.set_union(Data.LiveIn[Succ]);
  2694. }
  2695. // assert OutLiveOut is a subset of LiveOut
  2696. if (OldLiveOutSize == LiveOut.size()) {
  2697. // If the sets are the same size, then we didn't actually add anything
  2698. // when unioning our successors LiveIn. Thus, the LiveIn of this block
  2699. // hasn't changed.
  2700. continue;
  2701. }
  2702. Data.LiveOut[BB] = LiveOut;
  2703. // Apply the effects of this basic block
  2704. SetVector<Value *> LiveTmp = LiveOut;
  2705. LiveTmp.set_union(Data.LiveSet[BB]);
  2706. LiveTmp.set_subtract(Data.KillSet[BB]);
  2707. assert(Data.LiveIn.count(BB));
  2708. const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
  2709. // assert: OldLiveIn is a subset of LiveTmp
  2710. if (OldLiveIn.size() != LiveTmp.size()) {
  2711. Data.LiveIn[BB] = LiveTmp;
  2712. Worklist.insert(pred_begin(BB), pred_end(BB));
  2713. }
  2714. } // while (!Worklist.empty())
  2715. #ifndef NDEBUG
  2716. // Verify our output against SSA properties. This helps catch any
  2717. // missing kills during the above iteration.
  2718. for (BasicBlock &BB : F)
  2719. checkBasicSSA(DT, Data, BB);
  2720. #endif
  2721. }
  2722. static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
  2723. StatepointLiveSetTy &Out) {
  2724. BasicBlock *BB = Inst->getParent();
  2725. // Note: The copy is intentional and required
  2726. assert(Data.LiveOut.count(BB));
  2727. SetVector<Value *> LiveOut = Data.LiveOut[BB];
  2728. // We want to handle the statepoint itself oddly. It's
  2729. // call result is not live (normal), nor are it's arguments
  2730. // (unless they're used again later). This adjustment is
  2731. // specifically what we need to relocate
  2732. computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
  2733. LiveOut);
  2734. LiveOut.remove(Inst);
  2735. Out.insert(LiveOut.begin(), LiveOut.end());
  2736. }
  2737. static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
  2738. CallBase *Call,
  2739. PartiallyConstructedSafepointRecord &Info,
  2740. PointerToBaseTy &PointerToBase) {
  2741. StatepointLiveSetTy Updated;
  2742. findLiveSetAtInst(Call, RevisedLivenessData, Updated);
  2743. // We may have base pointers which are now live that weren't before. We need
  2744. // to update the PointerToBase structure to reflect this.
  2745. for (auto V : Updated)
  2746. PointerToBase.insert({ V, V });
  2747. Info.LiveSet = Updated;
  2748. }