12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401 |
- #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
- #include "llvm/ADT/ArrayRef.h"
- #include "llvm/ADT/DenseMap.h"
- #include "llvm/ADT/DenseSet.h"
- #include "llvm/ADT/MapVector.h"
- #include "llvm/ADT/STLExtras.h"
- #include "llvm/ADT/SetVector.h"
- #include "llvm/ADT/SmallSet.h"
- #include "llvm/ADT/SmallVector.h"
- #include "llvm/ADT/StringRef.h"
- #include "llvm/ADT/iterator_range.h"
- #include "llvm/Analysis/DomTreeUpdater.h"
- #include "llvm/Analysis/TargetLibraryInfo.h"
- #include "llvm/Analysis/TargetTransformInfo.h"
- #include "llvm/IR/Argument.h"
- #include "llvm/IR/Attributes.h"
- #include "llvm/IR/BasicBlock.h"
- #include "llvm/IR/CallingConv.h"
- #include "llvm/IR/Constant.h"
- #include "llvm/IR/Constants.h"
- #include "llvm/IR/DataLayout.h"
- #include "llvm/IR/DerivedTypes.h"
- #include "llvm/IR/Dominators.h"
- #include "llvm/IR/Function.h"
- #include "llvm/IR/IRBuilder.h"
- #include "llvm/IR/InstIterator.h"
- #include "llvm/IR/InstrTypes.h"
- #include "llvm/IR/Instruction.h"
- #include "llvm/IR/Instructions.h"
- #include "llvm/IR/IntrinsicInst.h"
- #include "llvm/IR/Intrinsics.h"
- #include "llvm/IR/LLVMContext.h"
- #include "llvm/IR/MDBuilder.h"
- #include "llvm/IR/Metadata.h"
- #include "llvm/IR/Module.h"
- #include "llvm/IR/Statepoint.h"
- #include "llvm/IR/Type.h"
- #include "llvm/IR/User.h"
- #include "llvm/IR/Value.h"
- #include "llvm/IR/ValueHandle.h"
- #include "llvm/InitializePasses.h"
- #include "llvm/Pass.h"
- #include "llvm/Support/Casting.h"
- #include "llvm/Support/CommandLine.h"
- #include "llvm/Support/Compiler.h"
- #include "llvm/Support/Debug.h"
- #include "llvm/Support/ErrorHandling.h"
- #include "llvm/Support/raw_ostream.h"
- #include "llvm/Transforms/Scalar.h"
- #include "llvm/Transforms/Utils/BasicBlockUtils.h"
- #include "llvm/Transforms/Utils/Local.h"
- #include "llvm/Transforms/Utils/PromoteMemToReg.h"
- #include <algorithm>
- #include <cassert>
- #include <cstddef>
- #include <cstdint>
- #include <iterator>
- #include <optional>
- #include <set>
- #include <string>
- #include <utility>
- #include <vector>
- #define DEBUG_TYPE "rewrite-statepoints-for-gc"
- using namespace llvm;
- static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
- cl::init(false));
- static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
- cl::init(false));
- static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
- cl::init(false));
- static cl::opt<unsigned>
- RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
- cl::init(6));
- #ifdef EXPENSIVE_CHECKS
- static bool ClobberNonLive = true;
- #else
- static bool ClobberNonLive = false;
- #endif
- static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
- cl::location(ClobberNonLive),
- cl::Hidden);
- static cl::opt<bool>
- AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
- cl::Hidden, cl::init(true));
- static cl::opt<bool> RematDerivedAtUses("rs4gc-remat-derived-at-uses",
- cl::Hidden, cl::init(true));
- static void stripNonValidData(Module &M);
- static bool shouldRewriteStatepointsIn(Function &F);
- PreservedAnalyses RewriteStatepointsForGC::run(Module &M,
- ModuleAnalysisManager &AM) {
- bool Changed = false;
- auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
- for (Function &F : M) {
-
- if (F.isDeclaration() || F.empty())
- continue;
-
-
- if (!shouldRewriteStatepointsIn(F))
- continue;
- auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
- auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
- auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
- Changed |= runOnFunction(F, DT, TTI, TLI);
- }
- if (!Changed)
- return PreservedAnalyses::all();
-
-
-
- stripNonValidData(M);
- PreservedAnalyses PA;
- PA.preserve<TargetIRAnalysis>();
- PA.preserve<TargetLibraryAnalysis>();
- return PA;
- }
- namespace {
- class RewriteStatepointsForGCLegacyPass : public ModulePass {
- RewriteStatepointsForGC Impl;
- public:
- static char ID;
- RewriteStatepointsForGCLegacyPass() : ModulePass(ID), Impl() {
- initializeRewriteStatepointsForGCLegacyPassPass(
- *PassRegistry::getPassRegistry());
- }
- bool runOnModule(Module &M) override {
- bool Changed = false;
- for (Function &F : M) {
-
- if (F.isDeclaration() || F.empty())
- continue;
-
-
- if (!shouldRewriteStatepointsIn(F))
- continue;
- TargetTransformInfo &TTI =
- getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
- const TargetLibraryInfo &TLI =
- getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
- auto &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
- Changed |= Impl.runOnFunction(F, DT, TTI, TLI);
- }
- if (!Changed)
- return false;
-
-
-
- stripNonValidData(M);
- return true;
- }
- void getAnalysisUsage(AnalysisUsage &AU) const override {
-
-
- AU.addRequired<DominatorTreeWrapperPass>();
- AU.addRequired<TargetTransformInfoWrapperPass>();
- AU.addRequired<TargetLibraryInfoWrapperPass>();
- }
- };
- }
- char RewriteStatepointsForGCLegacyPass::ID = 0;
- ModulePass *llvm::createRewriteStatepointsForGCLegacyPass() {
- return new RewriteStatepointsForGCLegacyPass();
- }
- INITIALIZE_PASS_BEGIN(RewriteStatepointsForGCLegacyPass,
- "rewrite-statepoints-for-gc",
- "Make relocations explicit at statepoints", false, false)
- INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
- INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
- INITIALIZE_PASS_END(RewriteStatepointsForGCLegacyPass,
- "rewrite-statepoints-for-gc",
- "Make relocations explicit at statepoints", false, false)
- namespace {
- struct GCPtrLivenessData {
-
- MapVector<BasicBlock *, SetVector<Value *>> KillSet;
-
-
- MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
-
-
- MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
-
-
- MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
- };
- using DefiningValueMapTy = MapVector<Value *, Value *>;
- using IsKnownBaseMapTy = MapVector<Value *, bool>;
- using PointerToBaseTy = MapVector<Value *, Value *>;
- using StatepointLiveSetTy = SetVector<Value *>;
- using RematerializedValueMapTy =
- MapVector<AssertingVH<Instruction>, AssertingVH<Value>>;
- struct PartiallyConstructedSafepointRecord {
-
- StatepointLiveSetTy LiveSet;
-
-
- GCStatepointInst *StatepointToken;
-
-
- Instruction *UnwindToken;
-
-
-
- RematerializedValueMapTy RematerializedValues;
- };
- struct RematerizlizationCandidateRecord {
-
- SmallVector<Instruction *, 3> ChainToBase;
-
- Value *RootOfChain;
-
- InstructionCost Cost;
- };
- using RematCandTy = MapVector<Value *, RematerizlizationCandidateRecord>;
- }
- static ArrayRef<Use> GetDeoptBundleOperands(const CallBase *Call) {
- std::optional<OperandBundleUse> DeoptBundle =
- Call->getOperandBundle(LLVMContext::OB_deopt);
- if (!DeoptBundle) {
- assert(AllowStatepointWithNoDeoptInfo &&
- "Found non-leaf call without deopt info!");
- return std::nullopt;
- }
- return DeoptBundle->Inputs;
- }
- static void computeLiveInValues(DominatorTree &DT, Function &F,
- GCPtrLivenessData &Data);
- static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
- StatepointLiveSetTy &out);
- static bool isGCPointerType(Type *T) {
- if (auto *PT = dyn_cast<PointerType>(T))
-
-
-
- return PT->getAddressSpace() == 1;
- return false;
- }
- static bool isHandledGCPointerType(Type *T) {
-
- if (isGCPointerType(T))
- return true;
-
-
- if (auto VT = dyn_cast<VectorType>(T))
- if (isGCPointerType(VT->getElementType()))
- return true;
- return false;
- }
- #ifndef NDEBUG
- static bool containsGCPtrType(Type *Ty) {
- if (isGCPointerType(Ty))
- return true;
- if (VectorType *VT = dyn_cast<VectorType>(Ty))
- return isGCPointerType(VT->getScalarType());
- if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
- return containsGCPtrType(AT->getElementType());
- if (StructType *ST = dyn_cast<StructType>(Ty))
- return llvm::any_of(ST->elements(), containsGCPtrType);
- return false;
- }
- static bool isUnhandledGCPointerType(Type *Ty) {
- return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
- }
- #endif
- static std::string suffixed_name_or(Value *V, StringRef Suffix,
- StringRef DefaultName) {
- return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
- }
- static void analyzeParsePointLiveness(
- DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, CallBase *Call,
- PartiallyConstructedSafepointRecord &Result) {
- StatepointLiveSetTy LiveSet;
- findLiveSetAtInst(Call, OriginalLivenessData, LiveSet);
- if (PrintLiveSet) {
- dbgs() << "Live Variables:\n";
- for (Value *V : LiveSet)
- dbgs() << " " << V->getName() << " " << *V << "\n";
- }
- if (PrintLiveSetSize) {
- dbgs() << "Safepoint For: " << Call->getCalledOperand()->getName() << "\n";
- dbgs() << "Number live values: " << LiveSet.size() << "\n";
- }
- Result.LiveSet = LiveSet;
- }
- static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases);
- static void setKnownBase(Value *V, bool IsKnownBase,
- IsKnownBaseMapTy &KnownBases);
- static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
- IsKnownBaseMapTy &KnownBases);
- static Value *findBaseDefiningValueOfVector(Value *I, DefiningValueMapTy &Cache,
- IsKnownBaseMapTy &KnownBases) {
-
-
- auto Cached = Cache.find(I);
- if (Cached != Cache.end())
- return Cached->second;
- if (isa<Argument>(I)) {
-
- Cache[I] = I;
- setKnownBase(I, true, KnownBases);
- return I;
- }
- if (isa<Constant>(I)) {
-
-
- auto *CAZ = ConstantAggregateZero::get(I->getType());
- Cache[I] = CAZ;
- setKnownBase(CAZ, true, KnownBases);
- return CAZ;
- }
- if (isa<LoadInst>(I)) {
- Cache[I] = I;
- setKnownBase(I, true, KnownBases);
- return I;
- }
- if (isa<InsertElementInst>(I)) {
-
-
-
- Cache[I] = I;
- setKnownBase(I, false, KnownBases);
- return I;
- }
- if (isa<ShuffleVectorInst>(I)) {
-
-
-
-
-
- Cache[I] = I;
- setKnownBase(I, false, KnownBases);
- return I;
- }
-
-
- if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
- auto *BDV =
- findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
- Cache[GEP] = BDV;
- return BDV;
- }
-
-
- if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
- auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
- Cache[Freeze] = BDV;
- return BDV;
- }
-
-
- if (auto *BC = dyn_cast<BitCastInst>(I)) {
- auto *BDV = findBaseDefiningValue(BC->getOperand(0), Cache, KnownBases);
- Cache[BC] = BDV;
- return BDV;
- }
-
-
-
- if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
- Cache[I] = I;
- setKnownBase(I, true, KnownBases);
- return I;
- }
-
-
- assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
- "unknown vector instruction - no base found for vector element");
- Cache[I] = I;
- setKnownBase(I, false, KnownBases);
- return I;
- }
- static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
- IsKnownBaseMapTy &KnownBases) {
- assert(I->getType()->isPtrOrPtrVectorTy() &&
- "Illegal to ask for the base pointer of a non-pointer type");
- auto Cached = Cache.find(I);
- if (Cached != Cache.end())
- return Cached->second;
- if (I->getType()->isVectorTy())
- return findBaseDefiningValueOfVector(I, Cache, KnownBases);
- if (isa<Argument>(I)) {
-
-
- Cache[I] = I;
- setKnownBase(I, true, KnownBases);
- return I;
- }
- if (isa<Constant>(I)) {
-
-
-
-
-
-
-
-
-
- auto *CPN = ConstantPointerNull::get(cast<PointerType>(I->getType()));
- Cache[I] = CPN;
- setKnownBase(CPN, true, KnownBases);
- return CPN;
- }
-
-
-
-
-
- if (isa<IntToPtrInst>(I)) {
- Cache[I] = I;
- setKnownBase(I, true, KnownBases);
- return I;
- }
- if (CastInst *CI = dyn_cast<CastInst>(I)) {
- Value *Def = CI->stripPointerCasts();
-
-
- assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
- cast<PointerType>(CI->getType())->getAddressSpace() &&
- "unsupported addrspacecast");
-
-
-
- assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
- auto *BDV = findBaseDefiningValue(Def, Cache, KnownBases);
- Cache[CI] = BDV;
- return BDV;
- }
- if (isa<LoadInst>(I)) {
-
- Cache[I] = I;
- setKnownBase(I, true, KnownBases);
- return I;
- }
- if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
-
- auto *BDV =
- findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
- Cache[GEP] = BDV;
- return BDV;
- }
- if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
- auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
- Cache[Freeze] = BDV;
- return BDV;
- }
- if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
- switch (II->getIntrinsicID()) {
- default:
-
- break;
- case Intrinsic::experimental_gc_statepoint:
- llvm_unreachable("statepoints don't produce pointers");
- case Intrinsic::experimental_gc_relocate:
-
-
-
- llvm_unreachable("repeat safepoint insertion is not supported");
- case Intrinsic::gcroot:
-
-
-
- llvm_unreachable(
- "interaction with the gcroot mechanism is not supported");
- case Intrinsic::experimental_gc_get_pointer_base:
- auto *BDV = findBaseDefiningValue(II->getOperand(0), Cache, KnownBases);
- Cache[II] = BDV;
- return BDV;
- }
- }
-
-
-
- if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
- Cache[I] = I;
- setKnownBase(I, true, KnownBases);
- return I;
- }
-
-
- assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
- if (isa<AtomicCmpXchgInst>(I)) {
-
-
-
- Cache[I] = I;
- setKnownBase(I, true, KnownBases);
- return I;
- }
- assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
- "binary ops which don't apply to pointers");
-
-
-
- if (isa<ExtractValueInst>(I)) {
- Cache[I] = I;
- setKnownBase(I, true, KnownBases);
- return I;
- }
-
-
- assert(!isa<InsertValueInst>(I) &&
- "Base pointer for a struct is meaningless");
-
-
- bool IsKnownBase =
- isa<Instruction>(I) && cast<Instruction>(I)->getMetadata("is_base_value");
- setKnownBase(I, IsKnownBase, KnownBases);
- Cache[I] = I;
-
-
-
-
- if (isa<ExtractElementInst>(I))
-
-
-
- return I;
-
-
-
-
- assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
- "missing instruction case in findBaseDefiningValue");
- return I;
- }
- static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache,
- IsKnownBaseMapTy &KnownBases) {
- if (Cache.find(I) == Cache.end()) {
- auto *BDV = findBaseDefiningValue(I, Cache, KnownBases);
- Cache[I] = BDV;
- LLVM_DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
- << Cache[I]->getName() << ", is known base = "
- << KnownBases[I] << "\n");
- }
- assert(Cache[I] != nullptr);
- assert(KnownBases.find(Cache[I]) != KnownBases.end() &&
- "Cached value must be present in known bases map");
- return Cache[I];
- }
- static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache,
- IsKnownBaseMapTy &KnownBases) {
- Value *Def = findBaseDefiningValueCached(I, Cache, KnownBases);
- auto Found = Cache.find(Def);
- if (Found != Cache.end()) {
-
- return Found->second;
- }
-
- return Def;
- }
- #ifndef NDEBUG
- static bool isOriginalBaseResult(Value *V) {
-
- return !isa<PHINode>(V) && !isa<SelectInst>(V) &&
- !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
- !isa<ShuffleVectorInst>(V);
- }
- #endif
- static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases) {
- auto It = KnownBases.find(V);
- assert(It != KnownBases.end() && "Value not present in the map");
- return It->second;
- }
- static void setKnownBase(Value *V, bool IsKnownBase,
- IsKnownBaseMapTy &KnownBases) {
- #ifndef NDEBUG
- auto It = KnownBases.find(V);
- if (It != KnownBases.end())
- assert(It->second == IsKnownBase && "Changing already present value");
- #endif
- KnownBases[V] = IsKnownBase;
- }
- static bool areBothVectorOrScalar(Value *First, Value *Second) {
- return isa<VectorType>(First->getType()) ==
- isa<VectorType>(Second->getType());
- }
- namespace {
- class BDVState {
- public:
- enum StatusTy {
-
- Unknown,
-
-
-
- Base,
-
- Conflict
- };
- BDVState() {
- llvm_unreachable("missing state in map");
- }
- explicit BDVState(Value *OriginalValue)
- : OriginalValue(OriginalValue) {}
- explicit BDVState(Value *OriginalValue, StatusTy Status, Value *BaseValue = nullptr)
- : OriginalValue(OriginalValue), Status(Status), BaseValue(BaseValue) {
- assert(Status != Base || BaseValue);
- }
- StatusTy getStatus() const { return Status; }
- Value *getOriginalValue() const { return OriginalValue; }
- Value *getBaseValue() const { return BaseValue; }
- bool isBase() const { return getStatus() == Base; }
- bool isUnknown() const { return getStatus() == Unknown; }
- bool isConflict() const { return getStatus() == Conflict; }
-
-
-
- void meet(const BDVState &Other) {
- auto markConflict = [&]() {
- Status = BDVState::Conflict;
- BaseValue = nullptr;
- };
-
- if (isConflict())
- return;
-
- if (isUnknown()) {
- Status = Other.getStatus();
- BaseValue = Other.getBaseValue();
- return;
- }
-
- assert(isBase() && "Unknown state");
-
- if (Other.isUnknown())
- return;
-
- if (Other.isConflict())
- return markConflict();
-
- assert(Other.isBase() && "Unknown state");
-
- if (getBaseValue() != Other.getBaseValue())
- return markConflict();
-
- }
- bool operator==(const BDVState &Other) const {
- return OriginalValue == Other.OriginalValue && BaseValue == Other.BaseValue &&
- Status == Other.Status;
- }
- bool operator!=(const BDVState &other) const { return !(*this == other); }
- LLVM_DUMP_METHOD
- void dump() const {
- print(dbgs());
- dbgs() << '\n';
- }
- void print(raw_ostream &OS) const {
- switch (getStatus()) {
- case Unknown:
- OS << "U";
- break;
- case Base:
- OS << "B";
- break;
- case Conflict:
- OS << "C";
- break;
- }
- OS << " (base " << getBaseValue() << " - "
- << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << ")"
- << " for " << OriginalValue->getName() << ":";
- }
- private:
- AssertingVH<Value> OriginalValue;
- StatusTy Status = Unknown;
- AssertingVH<Value> BaseValue = nullptr;
- };
- }
- #ifndef NDEBUG
- static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
- State.print(OS);
- return OS;
- }
- #endif
- static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache,
- IsKnownBaseMapTy &KnownBases) {
- Value *Def = findBaseOrBDV(I, Cache, KnownBases);
- if (isKnownBase(Def, KnownBases) && areBothVectorOrScalar(Def, I))
- return Def;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #ifndef NDEBUG
- auto isExpectedBDVType = [](Value *BDV) {
- return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
- isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
- isa<ShuffleVectorInst>(BDV);
- };
- #endif
-
-
-
-
-
- MapVector<Value *, BDVState> States;
- #ifndef NDEBUG
- auto VerifyStates = [&]() {
- for (auto &Entry : States) {
- assert(Entry.first == Entry.second.getOriginalValue());
- }
- };
- #endif
- auto visitBDVOperands = [](Value *BDV, std::function<void (Value*)> F) {
- if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
- for (Value *InVal : PN->incoming_values())
- F(InVal);
- } else if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
- F(SI->getTrueValue());
- F(SI->getFalseValue());
- } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
- F(EE->getVectorOperand());
- } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)) {
- F(IE->getOperand(0));
- F(IE->getOperand(1));
- } else if (auto *SV = dyn_cast<ShuffleVectorInst>(BDV)) {
-
-
- F(SV->getOperand(0));
- if (!SV->isZeroEltSplat())
- F(SV->getOperand(1));
- } else {
- llvm_unreachable("unexpected BDV type");
- }
- };
-
-
- {
- SmallVector<Value*, 16> Worklist;
- Worklist.push_back(Def);
- States.insert({Def, BDVState(Def)});
- while (!Worklist.empty()) {
- Value *Current = Worklist.pop_back_val();
- assert(!isOriginalBaseResult(Current) && "why did it get added?");
- auto visitIncomingValue = [&](Value *InVal) {
- Value *Base = findBaseOrBDV(InVal, Cache, KnownBases);
- if (isKnownBase(Base, KnownBases) && areBothVectorOrScalar(Base, InVal))
-
-
-
-
-
- return;
- assert(isExpectedBDVType(Base) && "the only non-base values "
- "we see should be base defining values");
- if (States.insert(std::make_pair(Base, BDVState(Base))).second)
- Worklist.push_back(Base);
- };
- visitBDVOperands(Current, visitIncomingValue);
- }
- }
- #ifndef NDEBUG
- VerifyStates();
- LLVM_DEBUG(dbgs() << "States after initialization:\n");
- for (const auto &Pair : States) {
- LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
- }
- #endif
-
-
-
-
-
- SmallVector<Value *> ToRemove;
- do {
- ToRemove.clear();
- for (auto Pair : States) {
- Value *BDV = Pair.first;
- auto canPruneInput = [&](Value *V) {
-
-
- if (V->stripPointerCasts() == BDV)
- return true;
- Value *VBDV = findBaseOrBDV(V, Cache, KnownBases);
- if (V->stripPointerCasts() != VBDV)
- return false;
-
-
- return States.count(VBDV) == 0;
- };
- bool CanPrune = true;
- visitBDVOperands(BDV, [&](Value *Op) {
- CanPrune = CanPrune && canPruneInput(Op);
- });
- if (CanPrune)
- ToRemove.push_back(BDV);
- }
- for (Value *V : ToRemove) {
- States.erase(V);
-
- Cache[V] = V;
- }
- } while (!ToRemove.empty());
-
- if (!States.count(Def))
- return Def;
-
-
- auto GetStateForBDV = [&](Value *BaseValue, Value *Input) {
- auto I = States.find(BaseValue);
- if (I != States.end())
- return I->second;
- assert(areBothVectorOrScalar(BaseValue, Input));
- return BDVState(BaseValue, BDVState::Base, BaseValue);
- };
- bool Progress = true;
- while (Progress) {
- #ifndef NDEBUG
- const size_t OldSize = States.size();
- #endif
- Progress = false;
-
-
-
-
- for (auto Pair : States) {
- Value *BDV = Pair.first;
-
-
-
- assert((!isKnownBase(BDV, KnownBases) ||
- !areBothVectorOrScalar(BDV, Pair.second.getBaseValue())) &&
- "why did it get added?");
- BDVState NewState(BDV);
- visitBDVOperands(BDV, [&](Value *Op) {
- Value *BDV = findBaseOrBDV(Op, Cache, KnownBases);
- auto OpState = GetStateForBDV(BDV, Op);
- NewState.meet(OpState);
- });
- BDVState OldState = States[BDV];
- if (OldState != NewState) {
- Progress = true;
- States[BDV] = NewState;
- }
- }
- assert(OldSize == States.size() &&
- "fixed point shouldn't be adding any new nodes to state");
- }
- #ifndef NDEBUG
- VerifyStates();
- LLVM_DEBUG(dbgs() << "States after meet iteration:\n");
- for (const auto &Pair : States) {
- LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
- }
- #endif
-
-
- for (auto Pair : States) {
- Instruction *I = cast<Instruction>(Pair.first);
- BDVState State = Pair.second;
- auto *BaseValue = State.getBaseValue();
-
-
-
- assert(
- (!isKnownBase(I, KnownBases) || !areBothVectorOrScalar(I, BaseValue)) &&
- "why did it get added?");
- assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
- if (!State.isBase() || !isa<VectorType>(BaseValue->getType()))
- continue;
-
-
-
-
- if (isa<ExtractElementInst>(I)) {
- auto *EE = cast<ExtractElementInst>(I);
-
-
-
- auto *BaseInst = ExtractElementInst::Create(
- State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
- BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
- States[I] = BDVState(I, BDVState::Base, BaseInst);
- setKnownBase(BaseInst, true, KnownBases);
- } else if (!isa<VectorType>(I->getType())) {
-
-
-
-
-
- States[I] = BDVState(I, BDVState::Conflict);
- }
- }
- #ifndef NDEBUG
- VerifyStates();
- #endif
-
-
- for (auto Pair : States) {
- Instruction *I = cast<Instruction>(Pair.first);
- BDVState State = Pair.second;
-
-
-
- assert((!isKnownBase(I, KnownBases) ||
- !areBothVectorOrScalar(I, State.getBaseValue())) &&
- "why did it get added?");
- assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
-
-
-
- assert(!isa<InsertElementInst>(I) || State.isConflict());
- if (!State.isConflict())
- continue;
- auto getMangledName = [](Instruction *I) -> std::string {
- if (isa<PHINode>(I)) {
- return suffixed_name_or(I, ".base", "base_phi");
- } else if (isa<SelectInst>(I)) {
- return suffixed_name_or(I, ".base", "base_select");
- } else if (isa<ExtractElementInst>(I)) {
- return suffixed_name_or(I, ".base", "base_ee");
- } else if (isa<InsertElementInst>(I)) {
- return suffixed_name_or(I, ".base", "base_ie");
- } else {
- return suffixed_name_or(I, ".base", "base_sv");
- }
- };
- Instruction *BaseInst = I->clone();
- BaseInst->insertBefore(I);
- BaseInst->setName(getMangledName(I));
-
- BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
- States[I] = BDVState(I, BDVState::Conflict, BaseInst);
- setKnownBase(BaseInst, true, KnownBases);
- }
- #ifndef NDEBUG
- VerifyStates();
- #endif
-
-
-
-
-
-
-
-
- auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
- Value *BDV = findBaseOrBDV(Input, Cache, KnownBases);
- Value *Base = nullptr;
- if (!States.count(BDV)) {
- assert(areBothVectorOrScalar(BDV, Input));
- Base = BDV;
- } else {
-
- assert(States.count(BDV));
- Base = States[BDV].getBaseValue();
- }
- assert(Base && "Can't be null");
-
- if (Base->getType() != Input->getType() && InsertPt)
- Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
- return Base;
- };
-
-
-
- for (auto Pair : States) {
- Instruction *BDV = cast<Instruction>(Pair.first);
- BDVState State = Pair.second;
-
-
-
- assert((!isKnownBase(BDV, KnownBases) ||
- !areBothVectorOrScalar(BDV, State.getBaseValue())) &&
- "why did it get added?");
- assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
- if (!State.isConflict())
- continue;
- if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
- PHINode *PN = cast<PHINode>(BDV);
- const unsigned NumPHIValues = PN->getNumIncomingValues();
-
-
-
-
- DenseMap<BasicBlock *, Value*> BlockToValue;
- for (unsigned i = 0; i < NumPHIValues; i++) {
- Value *InVal = PN->getIncomingValue(i);
- BasicBlock *InBB = PN->getIncomingBlock(i);
- if (!BlockToValue.count(InBB))
- BlockToValue[InBB] = getBaseForInput(InVal, InBB->getTerminator());
- else {
- #ifndef NDEBUG
- Value *OldBase = BlockToValue[InBB];
- Value *Base = getBaseForInput(InVal, nullptr);
-
-
- auto StripBitCasts = [](Value *V) -> Value * {
- while (auto *BC = dyn_cast<BitCastInst>(V))
- V = BC->getOperand(0);
- return V;
- };
-
-
-
-
-
-
- assert(StripBitCasts(Base) == StripBitCasts(OldBase) &&
- "findBaseOrBDV should be pure!");
- #endif
- }
- Value *Base = BlockToValue[InBB];
- BasePHI->setIncomingValue(i, Base);
- }
- } else if (SelectInst *BaseSI =
- dyn_cast<SelectInst>(State.getBaseValue())) {
- SelectInst *SI = cast<SelectInst>(BDV);
-
-
- BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
- BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
- } else if (auto *BaseEE =
- dyn_cast<ExtractElementInst>(State.getBaseValue())) {
- Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
-
-
- BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
- } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
- auto *BdvIE = cast<InsertElementInst>(BDV);
- auto UpdateOperand = [&](int OperandIdx) {
- Value *InVal = BdvIE->getOperand(OperandIdx);
- Value *Base = getBaseForInput(InVal, BaseIE);
- BaseIE->setOperand(OperandIdx, Base);
- };
- UpdateOperand(0);
- UpdateOperand(1);
- } else {
- auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
- auto *BdvSV = cast<ShuffleVectorInst>(BDV);
- auto UpdateOperand = [&](int OperandIdx) {
- Value *InVal = BdvSV->getOperand(OperandIdx);
- Value *Base = getBaseForInput(InVal, BaseSV);
- BaseSV->setOperand(OperandIdx, Base);
- };
- UpdateOperand(0);
- if (!BdvSV->isZeroEltSplat())
- UpdateOperand(1);
- else {
-
- Value *InVal = BdvSV->getOperand(1);
- BaseSV->setOperand(1, UndefValue::get(InVal->getType()));
- }
- }
- }
- #ifndef NDEBUG
- VerifyStates();
- #endif
-
-
-
- for (auto Pair : States) {
- auto *BDV = Pair.first;
- Value *Base = Pair.second.getBaseValue();
- assert(BDV && Base);
-
-
-
- assert(
- (!isKnownBase(BDV, KnownBases) || !areBothVectorOrScalar(BDV, Base)) &&
- "why did it get added?");
- LLVM_DEBUG(
- dbgs() << "Updating base value cache"
- << " for: " << BDV->getName() << " from: "
- << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
- << " to: " << Base->getName() << "\n");
- Cache[BDV] = Base;
- }
- assert(Cache.count(Def));
- return Cache[Def];
- }
- static void findBasePointers(const StatepointLiveSetTy &live,
- PointerToBaseTy &PointerToBase, DominatorTree *DT,
- DefiningValueMapTy &DVCache,
- IsKnownBaseMapTy &KnownBases) {
- for (Value *ptr : live) {
- Value *base = findBasePointer(ptr, DVCache, KnownBases);
- assert(base && "failed to find base pointer");
- PointerToBase[ptr] = base;
- assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
- DT->dominates(cast<Instruction>(base)->getParent(),
- cast<Instruction>(ptr)->getParent())) &&
- "The base we found better dominate the derived pointer");
- }
- }
- static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
- CallBase *Call,
- PartiallyConstructedSafepointRecord &result,
- PointerToBaseTy &PointerToBase,
- IsKnownBaseMapTy &KnownBases) {
- StatepointLiveSetTy PotentiallyDerivedPointers = result.LiveSet;
-
-
-
-
-
- if (auto Opt = Call->getOperandBundle(LLVMContext::OB_deopt))
- for (Value *V : Opt->Inputs) {
- if (!PotentiallyDerivedPointers.count(V))
- continue;
- PotentiallyDerivedPointers.remove(V);
- PointerToBase[V] = V;
- }
- findBasePointers(PotentiallyDerivedPointers, PointerToBase, &DT, DVCache,
- KnownBases);
- }
- static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
- CallBase *Call,
- PartiallyConstructedSafepointRecord &result,
- PointerToBaseTy &PointerToBase);
- static void recomputeLiveInValues(
- Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
- MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,
- PointerToBaseTy &PointerToBase) {
-
-
- GCPtrLivenessData RevisedLivenessData;
- computeLiveInValues(DT, F, RevisedLivenessData);
- for (size_t i = 0; i < records.size(); i++) {
- struct PartiallyConstructedSafepointRecord &info = records[i];
- recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info,
- PointerToBase);
- }
- }
- static Instruction *rematerializeChain(ArrayRef<Instruction *> ChainToBase,
- Instruction *InsertBefore,
- Value *RootOfChain,
- Value *AlternateLiveBase) {
- Instruction *LastClonedValue = nullptr;
- Instruction *LastValue = nullptr;
-
- for (Instruction *Instr :
- make_range(ChainToBase.rbegin(), ChainToBase.rend())) {
-
-
-
-
- assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
- Instruction *ClonedValue = Instr->clone();
- ClonedValue->insertBefore(InsertBefore);
- ClonedValue->setName(Instr->getName() + ".remat");
-
-
- if (LastClonedValue) {
- assert(LastValue);
- ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
- #ifndef NDEBUG
- for (auto *OpValue : ClonedValue->operand_values()) {
-
-
- assert(!is_contained(ChainToBase, OpValue) &&
- "incorrect use in rematerialization chain");
-
-
- assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
- }
- #endif
- } else {
-
-
-
-
-
- if (RootOfChain != AlternateLiveBase)
- ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
- }
- LastClonedValue = ClonedValue;
- LastValue = Instr;
- }
- assert(LastClonedValue);
- return LastClonedValue;
- }
- static BasicBlock *
- normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
- DominatorTree &DT) {
- BasicBlock *Ret = BB;
- if (!BB->getUniquePredecessor())
- Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
-
-
- FoldSingleEntryPHINodes(Ret);
- assert(!isa<PHINode>(Ret->begin()) &&
- "All PHI nodes should have been removed!");
-
-
- return Ret;
- }
- static constexpr Attribute::AttrKind FnAttrsToStrip[] =
- {Attribute::Memory, Attribute::NoSync, Attribute::NoFree};
- static AttributeList legalizeCallAttributes(LLVMContext &Ctx,
- AttributeList OrigAL,
- AttributeList StatepointAL) {
- if (OrigAL.isEmpty())
- return StatepointAL;
-
- AttrBuilder FnAttrs(Ctx, OrigAL.getFnAttrs());
- for (auto Attr : FnAttrsToStrip)
- FnAttrs.removeAttribute(Attr);
- for (Attribute A : OrigAL.getFnAttrs()) {
- if (isStatepointDirectiveAttr(A))
- FnAttrs.removeAttribute(A);
- }
-
- return StatepointAL.addFnAttributes(Ctx, FnAttrs);
- }
- static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
- ArrayRef<Value *> BasePtrs,
- Instruction *StatepointToken,
- IRBuilder<> &Builder) {
- if (LiveVariables.empty())
- return;
- auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
- auto ValIt = llvm::find(LiveVec, Val);
- assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
- size_t Index = std::distance(LiveVec.begin(), ValIt);
- assert(Index < LiveVec.size() && "Bug in std::find?");
- return Index;
- };
- Module *M = StatepointToken->getModule();
-
-
-
-
-
-
-
- auto getGCRelocateDecl = [&] (Type *Ty) {
- assert(isHandledGCPointerType(Ty));
- auto AS = Ty->getScalarType()->getPointerAddressSpace();
- Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
- if (auto *VT = dyn_cast<VectorType>(Ty))
- NewTy = FixedVectorType::get(NewTy,
- cast<FixedVectorType>(VT)->getNumElements());
- return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
- {NewTy});
- };
-
-
-
- DenseMap<Type *, Function *> TypeToDeclMap;
- for (unsigned i = 0; i < LiveVariables.size(); i++) {
-
- Value *BaseIdx = Builder.getInt32(FindIndex(LiveVariables, BasePtrs[i]));
- Value *LiveIdx = Builder.getInt32(i);
- Type *Ty = LiveVariables[i]->getType();
- if (!TypeToDeclMap.count(Ty))
- TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
- Function *GCRelocateDecl = TypeToDeclMap[Ty];
-
- CallInst *Reloc = Builder.CreateCall(
- GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
- suffixed_name_or(LiveVariables[i], ".relocated", ""));
-
-
- Reloc->setCallingConv(CallingConv::Cold);
- }
- }
- namespace {
- class DeferredReplacement {
- AssertingVH<Instruction> Old;
- AssertingVH<Instruction> New;
- bool IsDeoptimize = false;
- DeferredReplacement() = default;
- public:
- static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
- assert(Old != New && Old && New &&
- "Cannot RAUW equal values or to / from null!");
- DeferredReplacement D;
- D.Old = Old;
- D.New = New;
- return D;
- }
- static DeferredReplacement createDelete(Instruction *ToErase) {
- DeferredReplacement D;
- D.Old = ToErase;
- return D;
- }
- static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
- #ifndef NDEBUG
- auto *F = cast<CallInst>(Old)->getCalledFunction();
- assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
- "Only way to construct a deoptimize deferred replacement");
- #endif
- DeferredReplacement D;
- D.Old = Old;
- D.IsDeoptimize = true;
- return D;
- }
-
- void doReplacement() {
- Instruction *OldI = Old;
- Instruction *NewI = New;
- assert(OldI != NewI && "Disallowed at construction?!");
- assert((!IsDeoptimize || !New) &&
- "Deoptimize intrinsics are not replaced!");
- Old = nullptr;
- New = nullptr;
- if (NewI)
- OldI->replaceAllUsesWith(NewI);
- if (IsDeoptimize) {
-
-
- auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
- new UnreachableInst(RI->getContext(), RI);
- RI->eraseFromParent();
- }
- OldI->eraseFromParent();
- }
- };
- }
- static StringRef getDeoptLowering(CallBase *Call) {
- const char *DeoptLowering = "deopt-lowering";
- if (Call->hasFnAttr(DeoptLowering)) {
-
-
- const AttributeList &CSAS = Call->getAttributes();
- if (CSAS.hasFnAttr(DeoptLowering))
- return CSAS.getFnAttr(DeoptLowering).getValueAsString();
- Function *F = Call->getCalledFunction();
- assert(F && F->hasFnAttribute(DeoptLowering));
- return F->getFnAttribute(DeoptLowering).getValueAsString();
- }
- return "live-through";
- }
- static void
- makeStatepointExplicitImpl(CallBase *Call,
- const SmallVectorImpl<Value *> &BasePtrs,
- const SmallVectorImpl<Value *> &LiveVariables,
- PartiallyConstructedSafepointRecord &Result,
- std::vector<DeferredReplacement> &Replacements,
- const PointerToBaseTy &PointerToBase) {
- assert(BasePtrs.size() == LiveVariables.size());
-
-
-
-
- IRBuilder<> Builder(Call);
- ArrayRef<Value *> GCArgs(LiveVariables);
- uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
- uint32_t NumPatchBytes = 0;
- uint32_t Flags = uint32_t(StatepointFlags::None);
- SmallVector<Value *, 8> CallArgs(Call->args());
- std::optional<ArrayRef<Use>> DeoptArgs;
- if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_deopt))
- DeoptArgs = Bundle->Inputs;
- std::optional<ArrayRef<Use>> TransitionArgs;
- if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_gc_transition)) {
- TransitionArgs = Bundle->Inputs;
-
- Flags |= uint32_t(StatepointFlags::GCTransition);
- }
-
-
-
- bool IsDeoptimize = false;
- StatepointDirectives SD =
- parseStatepointDirectivesFromAttrs(Call->getAttributes());
- if (SD.NumPatchBytes)
- NumPatchBytes = *SD.NumPatchBytes;
- if (SD.StatepointID)
- StatepointID = *SD.StatepointID;
-
- StringRef DeoptLowering = getDeoptLowering(Call);
- if (DeoptLowering.equals("live-in"))
- Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
- else {
- assert(DeoptLowering.equals("live-through") && "Unsupported value!");
- }
- FunctionCallee CallTarget(Call->getFunctionType(), Call->getCalledOperand());
- if (Function *F = dyn_cast<Function>(CallTarget.getCallee())) {
- auto IID = F->getIntrinsicID();
- if (IID == Intrinsic::experimental_deoptimize) {
-
-
-
- SmallVector<Type *, 8> DomainTy;
- for (Value *Arg : CallArgs)
- DomainTy.push_back(Arg->getType());
- auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
- false);
-
-
-
-
- CallTarget = F->getParent()
- ->getOrInsertFunction("__llvm_deoptimize", FTy);
- IsDeoptimize = true;
- } else if (IID == Intrinsic::memcpy_element_unordered_atomic ||
- IID == Intrinsic::memmove_element_unordered_atomic) {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- auto &Context = Call->getContext();
- auto &DL = Call->getModule()->getDataLayout();
- auto GetBaseAndOffset = [&](Value *Derived) {
- Value *Base = nullptr;
-
-
-
-
- if (isa<Constant>(Derived))
- Base =
- ConstantPointerNull::get(cast<PointerType>(Derived->getType()));
- else {
- assert(PointerToBase.count(Derived));
- Base = PointerToBase.find(Derived)->second;
- }
- unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
- unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
- Value *Base_int = Builder.CreatePtrToInt(
- Base, Type::getIntNTy(Context, IntPtrSize));
- Value *Derived_int = Builder.CreatePtrToInt(
- Derived, Type::getIntNTy(Context, IntPtrSize));
- return std::make_pair(Base, Builder.CreateSub(Derived_int, Base_int));
- };
- auto *Dest = CallArgs[0];
- Value *DestBase, *DestOffset;
- std::tie(DestBase, DestOffset) = GetBaseAndOffset(Dest);
- auto *Source = CallArgs[1];
- Value *SourceBase, *SourceOffset;
- std::tie(SourceBase, SourceOffset) = GetBaseAndOffset(Source);
- auto *LengthInBytes = CallArgs[2];
- auto *ElementSizeCI = cast<ConstantInt>(CallArgs[3]);
- CallArgs.clear();
- CallArgs.push_back(DestBase);
- CallArgs.push_back(DestOffset);
- CallArgs.push_back(SourceBase);
- CallArgs.push_back(SourceOffset);
- CallArgs.push_back(LengthInBytes);
- SmallVector<Type *, 8> DomainTy;
- for (Value *Arg : CallArgs)
- DomainTy.push_back(Arg->getType());
- auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
- false);
- auto GetFunctionName = [](Intrinsic::ID IID, ConstantInt *ElementSizeCI) {
- uint64_t ElementSize = ElementSizeCI->getZExtValue();
- if (IID == Intrinsic::memcpy_element_unordered_atomic) {
- switch (ElementSize) {
- case 1:
- return "__llvm_memcpy_element_unordered_atomic_safepoint_1";
- case 2:
- return "__llvm_memcpy_element_unordered_atomic_safepoint_2";
- case 4:
- return "__llvm_memcpy_element_unordered_atomic_safepoint_4";
- case 8:
- return "__llvm_memcpy_element_unordered_atomic_safepoint_8";
- case 16:
- return "__llvm_memcpy_element_unordered_atomic_safepoint_16";
- default:
- llvm_unreachable("unexpected element size!");
- }
- }
- assert(IID == Intrinsic::memmove_element_unordered_atomic);
- switch (ElementSize) {
- case 1:
- return "__llvm_memmove_element_unordered_atomic_safepoint_1";
- case 2:
- return "__llvm_memmove_element_unordered_atomic_safepoint_2";
- case 4:
- return "__llvm_memmove_element_unordered_atomic_safepoint_4";
- case 8:
- return "__llvm_memmove_element_unordered_atomic_safepoint_8";
- case 16:
- return "__llvm_memmove_element_unordered_atomic_safepoint_16";
- default:
- llvm_unreachable("unexpected element size!");
- }
- };
- CallTarget =
- F->getParent()
- ->getOrInsertFunction(GetFunctionName(IID, ElementSizeCI), FTy);
- }
- }
-
- GCStatepointInst *Token = nullptr;
- if (auto *CI = dyn_cast<CallInst>(Call)) {
- CallInst *SPCall = Builder.CreateGCStatepointCall(
- StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
- TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
- SPCall->setTailCallKind(CI->getTailCallKind());
- SPCall->setCallingConv(CI->getCallingConv());
-
-
-
-
- SPCall->setAttributes(legalizeCallAttributes(
- CI->getContext(), CI->getAttributes(), SPCall->getAttributes()));
- Token = cast<GCStatepointInst>(SPCall);
-
-
- assert(CI->getNextNode() && "Not a terminator, must have next!");
- Builder.SetInsertPoint(CI->getNextNode());
- Builder.SetCurrentDebugLocation(CI->getNextNode()->getDebugLoc());
- } else {
- auto *II = cast<InvokeInst>(Call);
-
-
-
- InvokeInst *SPInvoke = Builder.CreateGCStatepointInvoke(
- StatepointID, NumPatchBytes, CallTarget, II->getNormalDest(),
- II->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs, GCArgs,
- "statepoint_token");
- SPInvoke->setCallingConv(II->getCallingConv());
-
-
-
-
- SPInvoke->setAttributes(legalizeCallAttributes(
- II->getContext(), II->getAttributes(), SPInvoke->getAttributes()));
- Token = cast<GCStatepointInst>(SPInvoke);
-
- BasicBlock *UnwindBlock = II->getUnwindDest();
- assert(!isa<PHINode>(UnwindBlock->begin()) &&
- UnwindBlock->getUniquePredecessor() &&
- "can't safely insert in this block!");
- Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
- Builder.SetCurrentDebugLocation(II->getDebugLoc());
-
- Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
- Result.UnwindToken = ExceptionalToken;
- CreateGCRelocates(LiveVariables, BasePtrs, ExceptionalToken, Builder);
-
- BasicBlock *NormalDest = II->getNormalDest();
- assert(!isa<PHINode>(NormalDest->begin()) &&
- NormalDest->getUniquePredecessor() &&
- "can't safely insert in this block!");
- Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
-
-
- }
- assert(Token && "Should be set in one of the above branches!");
- if (IsDeoptimize) {
-
-
-
- Replacements.push_back(
- DeferredReplacement::createDeoptimizeReplacement(Call));
- } else {
- Token->setName("statepoint_token");
- if (!Call->getType()->isVoidTy() && !Call->use_empty()) {
- StringRef Name = Call->hasName() ? Call->getName() : "";
- CallInst *GCResult = Builder.CreateGCResult(Token, Call->getType(), Name);
- GCResult->setAttributes(
- AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
- Call->getAttributes().getRetAttrs()));
-
-
-
-
-
-
- Replacements.emplace_back(
- DeferredReplacement::createRAUW(Call, GCResult));
- } else {
- Replacements.emplace_back(DeferredReplacement::createDelete(Call));
- }
- }
- Result.StatepointToken = Token;
-
- CreateGCRelocates(LiveVariables, BasePtrs, Token, Builder);
- }
- static void
- makeStatepointExplicit(DominatorTree &DT, CallBase *Call,
- PartiallyConstructedSafepointRecord &Result,
- std::vector<DeferredReplacement> &Replacements,
- const PointerToBaseTy &PointerToBase) {
- const auto &LiveSet = Result.LiveSet;
-
- SmallVector<Value *, 64> BaseVec, LiveVec;
- LiveVec.reserve(LiveSet.size());
- BaseVec.reserve(LiveSet.size());
- for (Value *L : LiveSet) {
- LiveVec.push_back(L);
- assert(PointerToBase.count(L));
- Value *Base = PointerToBase.find(L)->second;
- BaseVec.push_back(Base);
- }
- assert(LiveVec.size() == BaseVec.size());
-
- makeStatepointExplicitImpl(Call, BaseVec, LiveVec, Result, Replacements,
- PointerToBase);
- }
- static void
- insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
- DenseMap<Value *, AllocaInst *> &AllocaMap,
- DenseSet<Value *> &VisitedLiveValues) {
- for (User *U : GCRelocs) {
- GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
- if (!Relocate)
- continue;
- Value *OriginalValue = Relocate->getDerivedPtr();
- assert(AllocaMap.count(OriginalValue));
- Value *Alloca = AllocaMap[OriginalValue];
-
-
-
- assert(Relocate->getNextNode() &&
- "Should always have one since it's not a terminator");
- IRBuilder<> Builder(Relocate->getNextNode());
- Value *CastedRelocatedValue =
- Builder.CreateBitCast(Relocate,
- cast<AllocaInst>(Alloca)->getAllocatedType(),
- suffixed_name_or(Relocate, ".casted", ""));
- new StoreInst(CastedRelocatedValue, Alloca,
- cast<Instruction>(CastedRelocatedValue)->getNextNode());
- #ifndef NDEBUG
- VisitedLiveValues.insert(OriginalValue);
- #endif
- }
- }
- static void insertRematerializationStores(
- const RematerializedValueMapTy &RematerializedValues,
- DenseMap<Value *, AllocaInst *> &AllocaMap,
- DenseSet<Value *> &VisitedLiveValues) {
- for (auto RematerializedValuePair: RematerializedValues) {
- Instruction *RematerializedValue = RematerializedValuePair.first;
- Value *OriginalValue = RematerializedValuePair.second;
- assert(AllocaMap.count(OriginalValue) &&
- "Can not find alloca for rematerialized value");
- Value *Alloca = AllocaMap[OriginalValue];
- new StoreInst(RematerializedValue, Alloca,
- RematerializedValue->getNextNode());
- #ifndef NDEBUG
- VisitedLiveValues.insert(OriginalValue);
- #endif
- }
- }
- static void relocationViaAlloca(
- Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
- ArrayRef<PartiallyConstructedSafepointRecord> Records) {
- #ifndef NDEBUG
-
-
- int InitialAllocaNum = 0;
- for (Instruction &I : F.getEntryBlock())
- if (isa<AllocaInst>(I))
- InitialAllocaNum++;
- #endif
-
- DenseMap<Value *, AllocaInst *> AllocaMap;
- SmallVector<AllocaInst *, 200> PromotableAllocas;
-
- std::size_t NumRematerializedValues = 0;
- PromotableAllocas.reserve(Live.size());
-
-
- const DataLayout &DL = F.getParent()->getDataLayout();
- auto emitAllocaFor = [&](Value *LiveValue) {
- AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
- DL.getAllocaAddrSpace(), "",
- F.getEntryBlock().getFirstNonPHI());
- AllocaMap[LiveValue] = Alloca;
- PromotableAllocas.push_back(Alloca);
- };
-
- for (Value *V : Live)
- emitAllocaFor(V);
-
- for (const auto &Info : Records)
- for (auto RematerializedValuePair : Info.RematerializedValues) {
- Value *OriginalValue = RematerializedValuePair.second;
- if (AllocaMap.count(OriginalValue) != 0)
- continue;
- emitAllocaFor(OriginalValue);
- ++NumRematerializedValues;
- }
-
-
-
-
-
-
-
-
- for (const auto &Info : Records) {
- Value *Statepoint = Info.StatepointToken;
-
- DenseSet<Value *> VisitedLiveValues;
-
- insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
-
-
- if (isa<InvokeInst>(Statepoint)) {
- insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
- VisitedLiveValues);
- }
-
- insertRematerializationStores(Info.RematerializedValues, AllocaMap,
- VisitedLiveValues);
- if (ClobberNonLive) {
-
-
-
-
-
- SmallVector<AllocaInst *, 64> ToClobber;
- for (auto Pair : AllocaMap) {
- Value *Def = Pair.first;
- AllocaInst *Alloca = Pair.second;
-
- if (VisitedLiveValues.count(Def)) {
- continue;
- }
- ToClobber.push_back(Alloca);
- }
- auto InsertClobbersAt = [&](Instruction *IP) {
- for (auto *AI : ToClobber) {
- auto AT = AI->getAllocatedType();
- Constant *CPN;
- if (AT->isVectorTy())
- CPN = ConstantAggregateZero::get(AT);
- else
- CPN = ConstantPointerNull::get(cast<PointerType>(AT));
- new StoreInst(CPN, AI, IP);
- }
- };
-
-
- if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
- InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
- InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
- } else {
- InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
- }
- }
- }
-
- for (auto Pair : AllocaMap) {
- Value *Def = Pair.first;
- AllocaInst *Alloca = Pair.second;
-
-
- SmallVector<Instruction *, 20> Uses;
-
- Uses.reserve(Def->getNumUses());
- for (User *U : Def->users()) {
- if (!isa<ConstantExpr>(U)) {
-
-
-
-
-
- Uses.push_back(cast<Instruction>(U));
- }
- }
- llvm::sort(Uses);
- auto Last = std::unique(Uses.begin(), Uses.end());
- Uses.erase(Last, Uses.end());
- for (Instruction *Use : Uses) {
- if (isa<PHINode>(Use)) {
- PHINode *Phi = cast<PHINode>(Use);
- for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
- if (Def == Phi->getIncomingValue(i)) {
- LoadInst *Load =
- new LoadInst(Alloca->getAllocatedType(), Alloca, "",
- Phi->getIncomingBlock(i)->getTerminator());
- Phi->setIncomingValue(i, Load);
- }
- }
- } else {
- LoadInst *Load =
- new LoadInst(Alloca->getAllocatedType(), Alloca, "", Use);
- Use->replaceUsesOfWith(Def, Load);
- }
- }
-
-
-
- StoreInst *Store = new StoreInst(Def, Alloca, false,
- DL.getABITypeAlign(Def->getType()));
- if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
- if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
-
-
- BasicBlock *NormalDest = Invoke->getNormalDest();
- Store->insertBefore(NormalDest->getFirstNonPHI());
- } else {
- assert(!Inst->isTerminator() &&
- "The only terminator that can produce a value is "
- "InvokeInst which is handled above.");
- Store->insertAfter(Inst);
- }
- } else {
- assert(isa<Argument>(Def));
- Store->insertAfter(cast<Instruction>(Alloca));
- }
- }
- assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
- "we must have the same allocas with lives");
- (void) NumRematerializedValues;
- if (!PromotableAllocas.empty()) {
-
- PromoteMemToReg(PromotableAllocas, DT);
- }
- #ifndef NDEBUG
- for (auto &I : F.getEntryBlock())
- if (isa<AllocaInst>(I))
- InitialAllocaNum--;
- assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
- #endif
- }
- template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
- SmallSet<T, 8> Seen;
- erase_if(Vec, [&](const T &V) { return !Seen.insert(V).second; });
- }
- static void insertUseHolderAfter(CallBase *Call, const ArrayRef<Value *> Values,
- SmallVectorImpl<CallInst *> &Holders) {
- if (Values.empty())
-
- return;
- Module *M = Call->getModule();
-
- FunctionCallee Func = M->getOrInsertFunction(
- "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true));
- if (isa<CallInst>(Call)) {
-
- Holders.push_back(
- CallInst::Create(Func, Values, "", &*++Call->getIterator()));
- return;
- }
-
-
- auto *II = cast<InvokeInst>(Call);
- Holders.push_back(CallInst::Create(
- Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
- Holders.push_back(CallInst::Create(
- Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
- }
- static void findLiveReferences(
- Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
- MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
- GCPtrLivenessData OriginalLivenessData;
- computeLiveInValues(DT, F, OriginalLivenessData);
- for (size_t i = 0; i < records.size(); i++) {
- struct PartiallyConstructedSafepointRecord &info = records[i];
- analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
- }
- }
- static Value* findRematerializableChainToBasePointer(
- SmallVectorImpl<Instruction*> &ChainToBase,
- Value *CurrentValue) {
- if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
- ChainToBase.push_back(GEP);
- return findRematerializableChainToBasePointer(ChainToBase,
- GEP->getPointerOperand());
- }
- if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
- if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
- return CI;
- ChainToBase.push_back(CI);
- return findRematerializableChainToBasePointer(ChainToBase,
- CI->getOperand(0));
- }
-
-
- return CurrentValue;
- }
- static InstructionCost
- chainToBasePointerCost(SmallVectorImpl<Instruction *> &Chain,
- TargetTransformInfo &TTI) {
- InstructionCost Cost = 0;
- for (Instruction *Instr : Chain) {
- if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
- assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
- "non noop cast is found during rematerialization");
- Type *SrcTy = CI->getOperand(0)->getType();
- Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy,
- TTI::getCastContextHint(CI),
- TargetTransformInfo::TCK_SizeAndLatency, CI);
- } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
-
- Type *ValTy = GEP->getSourceElementType();
- Cost += TTI.getAddressComputationCost(ValTy);
-
-
-
- if (!GEP->hasAllConstantIndices())
- Cost += 2;
- } else {
- llvm_unreachable("unsupported instruction type during rematerialization");
- }
- }
- return Cost;
- }
- static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
- unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
- if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
- OrigRootPhi.getParent() != AlternateRootPhi.getParent())
- return false;
-
-
- SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
- for (unsigned i = 0; i < PhiNum; i++)
- CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
- OrigRootPhi.getIncomingBlock(i);
-
-
- for (unsigned i = 0; i < PhiNum; i++) {
- auto CIVI =
- CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
- if (CIVI == CurrentIncomingValues.end())
- return false;
- BasicBlock *CurrentIncomingBB = CIVI->second;
- if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
- return false;
- }
- return true;
- }
- static void
- findRematerializationCandidates(PointerToBaseTy PointerToBase,
- RematCandTy &RematerizationCandidates,
- TargetTransformInfo &TTI) {
- const unsigned int ChainLengthThreshold = 10;
- for (auto P2B : PointerToBase) {
- auto *Derived = P2B.first;
- auto *Base = P2B.second;
-
- if (Derived == Base)
- continue;
-
- SmallVector<Instruction *, 3> ChainToBase;
- Value *RootOfChain =
- findRematerializableChainToBasePointer(ChainToBase, Derived);
-
- if ( ChainToBase.size() == 0 ||
- ChainToBase.size() > ChainLengthThreshold)
- continue;
-
-
- if (RootOfChain != PointerToBase[Derived]) {
- PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
- PHINode *AlternateRootPhi = dyn_cast<PHINode>(PointerToBase[Derived]);
- if (!OrigRootPhi || !AlternateRootPhi)
- continue;
-
-
-
-
-
-
-
-
-
- if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
- continue;
- }
-
- InstructionCost Cost = chainToBasePointerCost(ChainToBase, TTI);
-
-
-
-
-
- RematerizlizationCandidateRecord Record;
- Record.ChainToBase = ChainToBase;
- Record.RootOfChain = RootOfChain;
- Record.Cost = Cost;
- RematerizationCandidates.insert({ Derived, Record });
- }
- }
- static void rematerializeLiveValuesAtUses(
- RematCandTy &RematerizationCandidates,
- MutableArrayRef<PartiallyConstructedSafepointRecord> Records,
- PointerToBaseTy &PointerToBase) {
- if (!RematDerivedAtUses)
- return;
- SmallVector<Instruction *, 32> LiveValuesToBeDeleted;
- LLVM_DEBUG(dbgs() << "Rematerialize derived pointers at uses, "
- << "Num statepoints: " << Records.size() << '\n');
- for (auto &It : RematerizationCandidates) {
- Instruction *Cand = cast<Instruction>(It.first);
- auto &Record = It.second;
- if (Record.Cost >= RematerializationThreshold)
- continue;
- if (Cand->user_empty())
- continue;
- if (Cand->hasOneUse())
- if (auto *U = dyn_cast<Instruction>(Cand->getUniqueUndroppableUser()))
- if (U->getParent() == Cand->getParent())
- continue;
-
- if (llvm::any_of(Cand->users(),
- [](const auto *U) { return isa<PHINode>(U); }))
- continue;
- LLVM_DEBUG(dbgs() << "Trying cand " << *Cand << " ... ");
-
-
-
-
-
-
- unsigned NumLiveStatepoints = llvm::count_if(
- Records, [Cand](const auto &R) { return R.LiveSet.contains(Cand); });
- unsigned NumUses = Cand->getNumUses();
- LLVM_DEBUG(dbgs() << "Num uses: " << NumUses << " Num live statepoints: "
- << NumLiveStatepoints << " ");
- if (NumLiveStatepoints < NumUses) {
- LLVM_DEBUG(dbgs() << "not profitable\n");
- continue;
- }
-
-
-
- if (NumLiveStatepoints == NumUses && Record.Cost > 0) {
- LLVM_DEBUG(dbgs() << "not profitable\n");
- continue;
- }
- LLVM_DEBUG(dbgs() << "looks profitable\n");
-
-
-
-
-
- if (Record.ChainToBase.size() > 1) {
- Record.ChainToBase.clear();
- findRematerializableChainToBasePointer(Record.ChainToBase, Cand);
- }
-
-
-
-
-
-
-
-
-
- while (!Cand->user_empty()) {
- Instruction *UserI = cast<Instruction>(*Cand->user_begin());
- Instruction *RematChain = rematerializeChain(
- Record.ChainToBase, UserI, Record.RootOfChain, PointerToBase[Cand]);
- UserI->replaceUsesOfWith(Cand, RematChain);
- PointerToBase[RematChain] = PointerToBase[Cand];
- }
- LiveValuesToBeDeleted.push_back(Cand);
- }
- LLVM_DEBUG(dbgs() << "Rematerialized " << LiveValuesToBeDeleted.size()
- << " derived pointers\n");
- for (auto *Cand : LiveValuesToBeDeleted) {
- assert(Cand->use_empty() && "Unexpected user remain");
- RematerizationCandidates.erase(Cand);
- for (auto &R : Records) {
- assert(!R.LiveSet.contains(Cand) ||
- R.LiveSet.contains(PointerToBase[Cand]));
- R.LiveSet.remove(Cand);
- }
- }
-
-
- if (!LiveValuesToBeDeleted.empty()) {
- for (auto &P : RematerizationCandidates) {
- auto &R = P.second;
- if (R.ChainToBase.size() > 1) {
- R.ChainToBase.clear();
- findRematerializableChainToBasePointer(R.ChainToBase, P.first);
- }
- }
- }
- }
- static void rematerializeLiveValues(CallBase *Call,
- PartiallyConstructedSafepointRecord &Info,
- PointerToBaseTy &PointerToBase,
- RematCandTy &RematerizationCandidates,
- TargetTransformInfo &TTI) {
-
-
- SmallVector<Value *, 32> LiveValuesToBeDeleted;
- for (Value *LiveValue : Info.LiveSet) {
- auto It = RematerizationCandidates.find(LiveValue);
- if (It == RematerizationCandidates.end())
- continue;
- RematerizlizationCandidateRecord &Record = It->second;
- InstructionCost Cost = Record.Cost;
-
-
- if (isa<InvokeInst>(Call))
- Cost *= 2;
-
- if (Cost >= RematerializationThreshold)
- continue;
-
- LiveValuesToBeDeleted.push_back(LiveValue);
-
-
-
- if (isa<CallInst>(Call)) {
- Instruction *InsertBefore = Call->getNextNode();
- assert(InsertBefore);
- Instruction *RematerializedValue =
- rematerializeChain(Record.ChainToBase, InsertBefore,
- Record.RootOfChain, PointerToBase[LiveValue]);
- Info.RematerializedValues[RematerializedValue] = LiveValue;
- } else {
- auto *Invoke = cast<InvokeInst>(Call);
- Instruction *NormalInsertBefore =
- &*Invoke->getNormalDest()->getFirstInsertionPt();
- Instruction *UnwindInsertBefore =
- &*Invoke->getUnwindDest()->getFirstInsertionPt();
- Instruction *NormalRematerializedValue =
- rematerializeChain(Record.ChainToBase, NormalInsertBefore,
- Record.RootOfChain, PointerToBase[LiveValue]);
- Instruction *UnwindRematerializedValue =
- rematerializeChain(Record.ChainToBase, UnwindInsertBefore,
- Record.RootOfChain, PointerToBase[LiveValue]);
- Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
- Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
- }
- }
-
- for (auto *LiveValue: LiveValuesToBeDeleted) {
- Info.LiveSet.remove(LiveValue);
- }
- }
- static bool inlineGetBaseAndOffset(Function &F,
- SmallVectorImpl<CallInst *> &Intrinsics,
- DefiningValueMapTy &DVCache,
- IsKnownBaseMapTy &KnownBases) {
- auto &Context = F.getContext();
- auto &DL = F.getParent()->getDataLayout();
- bool Changed = false;
- for (auto *Callsite : Intrinsics)
- switch (Callsite->getIntrinsicID()) {
- case Intrinsic::experimental_gc_get_pointer_base: {
- Changed = true;
- Value *Base =
- findBasePointer(Callsite->getOperand(0), DVCache, KnownBases);
- assert(!DVCache.count(Callsite));
- auto *BaseBC = IRBuilder<>(Callsite).CreateBitCast(
- Base, Callsite->getType(), suffixed_name_or(Base, ".cast", ""));
- if (BaseBC != Base)
- DVCache[BaseBC] = Base;
- Callsite->replaceAllUsesWith(BaseBC);
- if (!BaseBC->hasName())
- BaseBC->takeName(Callsite);
- Callsite->eraseFromParent();
- break;
- }
- case Intrinsic::experimental_gc_get_pointer_offset: {
- Changed = true;
- Value *Derived = Callsite->getOperand(0);
- Value *Base = findBasePointer(Derived, DVCache, KnownBases);
- assert(!DVCache.count(Callsite));
- unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
- unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
- IRBuilder<> Builder(Callsite);
- Value *BaseInt =
- Builder.CreatePtrToInt(Base, Type::getIntNTy(Context, IntPtrSize),
- suffixed_name_or(Base, ".int", ""));
- Value *DerivedInt =
- Builder.CreatePtrToInt(Derived, Type::getIntNTy(Context, IntPtrSize),
- suffixed_name_or(Derived, ".int", ""));
- Value *Offset = Builder.CreateSub(DerivedInt, BaseInt);
- Callsite->replaceAllUsesWith(Offset);
- Offset->takeName(Callsite);
- Callsite->eraseFromParent();
- break;
- }
- default:
- llvm_unreachable("Unknown intrinsic");
- }
- return Changed;
- }
- static bool insertParsePoints(Function &F, DominatorTree &DT,
- TargetTransformInfo &TTI,
- SmallVectorImpl<CallBase *> &ToUpdate,
- DefiningValueMapTy &DVCache,
- IsKnownBaseMapTy &KnownBases) {
- #ifndef NDEBUG
-
- std::set<CallBase *> Uniqued;
- Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
- assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
- for (CallBase *Call : ToUpdate)
- assert(Call->getFunction() == &F);
- #endif
-
-
-
-
- for (CallBase *Call : ToUpdate) {
- auto *II = dyn_cast<InvokeInst>(Call);
- if (!II)
- continue;
- normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
- normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
- }
-
-
- SmallVector<CallInst *, 64> Holders;
-
-
-
-
- for (CallBase *Call : ToUpdate) {
- SmallVector<Value *, 64> DeoptValues;
- for (Value *Arg : GetDeoptBundleOperands(Call)) {
- assert(!isUnhandledGCPointerType(Arg->getType()) &&
- "support for FCA unimplemented");
- if (isHandledGCPointerType(Arg->getType()))
- DeoptValues.push_back(Arg);
- }
- insertUseHolderAfter(Call, DeoptValues, Holders);
- }
- SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
-
-
- findLiveReferences(F, DT, ToUpdate, Records);
-
- PointerToBaseTy PointerToBase;
-
- for (size_t i = 0; i < Records.size(); i++) {
- PartiallyConstructedSafepointRecord &info = Records[i];
- findBasePointers(DT, DVCache, ToUpdate[i], info, PointerToBase, KnownBases);
- }
- if (PrintBasePointers) {
- errs() << "Base Pairs (w/o Relocation):\n";
- for (auto &Pair : PointerToBase) {
- errs() << " derived ";
- Pair.first->printAsOperand(errs(), false);
- errs() << " base ";
- Pair.second->printAsOperand(errs(), false);
- errs() << "\n";
- ;
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- Holders.reserve(Holders.size() + Records.size());
- for (size_t i = 0; i < Records.size(); i++) {
- PartiallyConstructedSafepointRecord &Info = Records[i];
- SmallVector<Value *, 128> Bases;
- for (auto *Derived : Info.LiveSet) {
- assert(PointerToBase.count(Derived) && "Missed base for derived pointer");
- Bases.push_back(PointerToBase[Derived]);
- }
- insertUseHolderAfter(ToUpdate[i], Bases, Holders);
- }
-
-
-
- recomputeLiveInValues(F, DT, ToUpdate, Records, PointerToBase);
- if (PrintBasePointers) {
- errs() << "Base Pairs: (w/Relocation)\n";
- for (auto Pair : PointerToBase) {
- errs() << " derived ";
- Pair.first->printAsOperand(errs(), false);
- errs() << " base ";
- Pair.second->printAsOperand(errs(), false);
- errs() << "\n";
- }
- }
-
-
-
-
-
-
-
-
- for (auto &Info : Records) {
- Info.LiveSet.remove_if([&](Value *LiveV) {
- assert(PointerToBase.count(LiveV) && "Missed base for derived pointer");
- return isa<Constant>(PointerToBase[LiveV]);
- });
- }
- for (CallInst *CI : Holders)
- CI->eraseFromParent();
- Holders.clear();
-
- RematCandTy RematerizationCandidates;
- findRematerializationCandidates(PointerToBase, RematerizationCandidates, TTI);
-
-
-
-
- rematerializeLiveValuesAtUses(RematerizationCandidates, Records,
- PointerToBase);
- for (size_t i = 0; i < Records.size(); i++)
- rematerializeLiveValues(ToUpdate[i], Records[i], PointerToBase,
- RematerizationCandidates, TTI);
-
-
-
- std::vector<DeferredReplacement> Replacements;
-
-
-
-
-
-
- for (size_t i = 0; i < Records.size(); i++)
- makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements,
- PointerToBase);
- ToUpdate.clear();
- for (auto &PR : Replacements)
- PR.doReplacement();
- Replacements.clear();
- for (auto &Info : Records) {
-
-
-
-
-
-
-
-
- Info.LiveSet.clear();
- }
- PointerToBase.clear();
-
- SmallVector<Value *, 128> Live;
- for (size_t i = 0; i < Records.size(); i++) {
- PartiallyConstructedSafepointRecord &Info = Records[i];
-
-
-
-
-
- llvm::append_range(Live, Info.StatepointToken->gc_args());
- #ifndef NDEBUG
-
-
-
-
- assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
- "statepoint must be reachable or liveness is meaningless");
- for (Value *V : Info.StatepointToken->gc_args()) {
- if (!isa<Instruction>(V))
-
- continue;
- auto *LiveInst = cast<Instruction>(V);
- assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
- "unreachable values should never be live");
- assert(DT.dominates(LiveInst, Info.StatepointToken) &&
- "basic SSA liveness expectation violated by liveness analysis");
- }
- #endif
- }
- unique_unsorted(Live);
- #ifndef NDEBUG
-
- for (auto *Ptr : Live)
- assert(isHandledGCPointerType(Ptr->getType()) &&
- "must be a gc pointer type");
- #endif
- relocationViaAlloca(F, DT, Live, Records);
- return !Records.empty();
- }
- static AttributeMask getParamAndReturnAttributesToRemove() {
- AttributeMask R;
- R.addAttribute(Attribute::Dereferenceable);
- R.addAttribute(Attribute::DereferenceableOrNull);
- R.addAttribute(Attribute::ReadNone);
- R.addAttribute(Attribute::ReadOnly);
- R.addAttribute(Attribute::WriteOnly);
- R.addAttribute(Attribute::NoAlias);
- R.addAttribute(Attribute::NoFree);
- return R;
- }
- static void stripNonValidAttributesFromPrototype(Function &F) {
- LLVMContext &Ctx = F.getContext();
-
-
-
-
-
- if (Intrinsic::ID id = F.getIntrinsicID()) {
- F.setAttributes(Intrinsic::getAttributes(Ctx, id));
- return;
- }
- AttributeMask R = getParamAndReturnAttributesToRemove();
- for (Argument &A : F.args())
- if (isa<PointerType>(A.getType()))
- F.removeParamAttrs(A.getArgNo(), R);
- if (isa<PointerType>(F.getReturnType()))
- F.removeRetAttrs(R);
- for (auto Attr : FnAttrsToStrip)
- F.removeFnAttr(Attr);
- }
- static void stripInvalidMetadataFromInstruction(Instruction &I) {
- if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
- return;
-
-
-
-
-
-
-
-
-
-
-
-
-
- unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
- LLVMContext::MD_range,
- LLVMContext::MD_alias_scope,
- LLVMContext::MD_nontemporal,
- LLVMContext::MD_nonnull,
- LLVMContext::MD_align,
- LLVMContext::MD_type};
-
- I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
- }
- static void stripNonValidDataFromBody(Function &F) {
- if (F.empty())
- return;
- LLVMContext &Ctx = F.getContext();
- MDBuilder Builder(Ctx);
-
-
- SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
- for (Instruction &I : instructions(F)) {
-
-
-
-
-
-
- if (auto *II = dyn_cast<IntrinsicInst>(&I))
- if (II->getIntrinsicID() == Intrinsic::invariant_start) {
- InvariantStartInstructions.push_back(II);
- continue;
- }
- if (MDNode *Tag = I.getMetadata(LLVMContext::MD_tbaa)) {
- MDNode *MutableTBAA = Builder.createMutableTBAAAccessTag(Tag);
- I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
- }
- stripInvalidMetadataFromInstruction(I);
- AttributeMask R = getParamAndReturnAttributesToRemove();
- if (auto *Call = dyn_cast<CallBase>(&I)) {
- for (int i = 0, e = Call->arg_size(); i != e; i++)
- if (isa<PointerType>(Call->getArgOperand(i)->getType()))
- Call->removeParamAttrs(i, R);
- if (isa<PointerType>(Call->getType()))
- Call->removeRetAttrs(R);
- }
- }
-
- for (auto *II : InvariantStartInstructions) {
- II->replaceAllUsesWith(UndefValue::get(II->getType()));
- II->eraseFromParent();
- }
- }
- static bool shouldRewriteStatepointsIn(Function &F) {
-
- if (F.hasGC()) {
- const auto &FunctionGCName = F.getGC();
- const StringRef StatepointExampleName("statepoint-example");
- const StringRef CoreCLRName("coreclr");
- return (StatepointExampleName == FunctionGCName) ||
- (CoreCLRName == FunctionGCName);
- } else
- return false;
- }
- static void stripNonValidData(Module &M) {
- #ifndef NDEBUG
- assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
- #endif
- for (Function &F : M)
- stripNonValidAttributesFromPrototype(F);
- for (Function &F : M)
- stripNonValidDataFromBody(F);
- }
- bool RewriteStatepointsForGC::runOnFunction(Function &F, DominatorTree &DT,
- TargetTransformInfo &TTI,
- const TargetLibraryInfo &TLI) {
- assert(!F.isDeclaration() && !F.empty() &&
- "need function body to rewrite statepoints in");
- assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
- auto NeedsRewrite = [&TLI](Instruction &I) {
- if (const auto *Call = dyn_cast<CallBase>(&I)) {
- if (isa<GCStatepointInst>(Call))
- return false;
- if (callsGCLeafFunction(Call, TLI))
- return false;
-
-
-
-
-
-
-
- if (!AllowStatepointWithNoDeoptInfo &&
- !Call->getOperandBundle(LLVMContext::OB_deopt)) {
- assert((isa<AtomicMemCpyInst>(Call) || isa<AtomicMemMoveInst>(Call)) &&
- "Don't expect any other calls here!");
- return false;
- }
- return true;
- }
- return false;
- };
-
-
-
- DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
- bool MadeChange = removeUnreachableBlocks(F, &DTU);
-
- DTU.getDomTree();
-
-
-
- SmallVector<CallBase *, 64> ParsePointNeeded;
- SmallVector<CallInst *, 64> Intrinsics;
- for (Instruction &I : instructions(F)) {
-
- if (NeedsRewrite(I)) {
-
-
-
-
- assert(DT.isReachableFromEntry(I.getParent()) &&
- "no unreachable blocks expected");
- ParsePointNeeded.push_back(cast<CallBase>(&I));
- }
- if (auto *CI = dyn_cast<CallInst>(&I))
- if (CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_base ||
- CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_offset)
- Intrinsics.emplace_back(CI);
- }
-
- if (ParsePointNeeded.empty() && Intrinsics.empty())
- return MadeChange;
-
-
-
-
- for (BasicBlock &BB : F)
- if (BB.getUniquePredecessor())
- MadeChange |= FoldSingleEntryPHINodes(&BB);
-
-
-
-
-
-
-
-
-
-
-
-
-
- auto getConditionInst = [](Instruction *TI) -> Instruction * {
- if (auto *BI = dyn_cast<BranchInst>(TI))
- if (BI->isConditional())
- return dyn_cast<Instruction>(BI->getCondition());
-
- return nullptr;
- };
- for (BasicBlock &BB : F) {
- Instruction *TI = BB.getTerminator();
- if (auto *Cond = getConditionInst(TI))
-
-
- if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
- MadeChange = true;
- Cond->moveBefore(TI);
- }
- }
-
-
-
-
-
- for (Instruction &I : instructions(F)) {
- if (!isa<GetElementPtrInst>(I))
- continue;
- unsigned VF = 0;
- for (unsigned i = 0; i < I.getNumOperands(); i++)
- if (auto *OpndVTy = dyn_cast<VectorType>(I.getOperand(i)->getType())) {
- assert(VF == 0 ||
- VF == cast<FixedVectorType>(OpndVTy)->getNumElements());
- VF = cast<FixedVectorType>(OpndVTy)->getNumElements();
- }
-
-
- if (!I.getOperand(0)->getType()->isVectorTy() && VF != 0) {
- IRBuilder<> B(&I);
- auto *Splat = B.CreateVectorSplat(VF, I.getOperand(0));
- I.setOperand(0, Splat);
- MadeChange = true;
- }
- }
-
-
-
-
- DefiningValueMapTy DVCache;
-
-
- IsKnownBaseMapTy KnownBases;
- if (!Intrinsics.empty())
-
-
- MadeChange |= inlineGetBaseAndOffset(F, Intrinsics, DVCache, KnownBases);
- if (!ParsePointNeeded.empty())
- MadeChange |=
- insertParsePoints(F, DT, TTI, ParsePointNeeded, DVCache, KnownBases);
- return MadeChange;
- }
- static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
- BasicBlock::reverse_iterator End,
- SetVector<Value *> &LiveTmp) {
- for (auto &I : make_range(Begin, End)) {
-
- LiveTmp.remove(&I);
-
-
- if (isa<PHINode>(I))
- continue;
-
- for (Value *V : I.operands()) {
- assert(!isUnhandledGCPointerType(V->getType()) &&
- "support for FCA unimplemented");
- if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
-
-
-
-
-
-
-
-
-
-
- LiveTmp.insert(V);
- }
- }
- }
- }
- static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
- for (BasicBlock *Succ : successors(BB)) {
- for (auto &I : *Succ) {
- PHINode *PN = dyn_cast<PHINode>(&I);
- if (!PN)
- break;
- Value *V = PN->getIncomingValueForBlock(BB);
- assert(!isUnhandledGCPointerType(V->getType()) &&
- "support for FCA unimplemented");
- if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V))
- LiveTmp.insert(V);
- }
- }
- }
- static SetVector<Value *> computeKillSet(BasicBlock *BB) {
- SetVector<Value *> KillSet;
- for (Instruction &I : *BB)
- if (isHandledGCPointerType(I.getType()))
- KillSet.insert(&I);
- return KillSet;
- }
- #ifndef NDEBUG
- static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
- Instruction *TI, bool TermOkay = false) {
- for (Value *V : Live) {
- if (auto *I = dyn_cast<Instruction>(V)) {
-
-
-
- if (TermOkay && TI == I)
- continue;
- assert(DT.dominates(I, TI) &&
- "basic SSA liveness expectation violated by liveness analysis");
- }
- }
- }
- static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
- BasicBlock &BB) {
- checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
- checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
- checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
- }
- #endif
- static void computeLiveInValues(DominatorTree &DT, Function &F,
- GCPtrLivenessData &Data) {
- SmallSetVector<BasicBlock *, 32> Worklist;
-
- for (BasicBlock &BB : F) {
- Data.KillSet[&BB] = computeKillSet(&BB);
- Data.LiveSet[&BB].clear();
- computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
- #ifndef NDEBUG
- for (Value *Kill : Data.KillSet[&BB])
- assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
- #endif
- Data.LiveOut[&BB] = SetVector<Value *>();
- computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
- Data.LiveIn[&BB] = Data.LiveSet[&BB];
- Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
- Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
- if (!Data.LiveIn[&BB].empty())
- Worklist.insert(pred_begin(&BB), pred_end(&BB));
- }
-
- while (!Worklist.empty()) {
- BasicBlock *BB = Worklist.pop_back_val();
-
-
- SetVector<Value *> LiveOut = Data.LiveOut[BB];
- const auto OldLiveOutSize = LiveOut.size();
- for (BasicBlock *Succ : successors(BB)) {
- assert(Data.LiveIn.count(Succ));
- LiveOut.set_union(Data.LiveIn[Succ]);
- }
-
- if (OldLiveOutSize == LiveOut.size()) {
-
-
-
- continue;
- }
- Data.LiveOut[BB] = LiveOut;
-
- SetVector<Value *> LiveTmp = LiveOut;
- LiveTmp.set_union(Data.LiveSet[BB]);
- LiveTmp.set_subtract(Data.KillSet[BB]);
- assert(Data.LiveIn.count(BB));
- const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
-
- if (OldLiveIn.size() != LiveTmp.size()) {
- Data.LiveIn[BB] = LiveTmp;
- Worklist.insert(pred_begin(BB), pred_end(BB));
- }
- }
- #ifndef NDEBUG
-
-
- for (BasicBlock &BB : F)
- checkBasicSSA(DT, Data, BB);
- #endif
- }
- static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
- StatepointLiveSetTy &Out) {
- BasicBlock *BB = Inst->getParent();
-
- assert(Data.LiveOut.count(BB));
- SetVector<Value *> LiveOut = Data.LiveOut[BB];
-
-
-
-
- computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
- LiveOut);
- LiveOut.remove(Inst);
- Out.insert(LiveOut.begin(), LiveOut.end());
- }
- static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
- CallBase *Call,
- PartiallyConstructedSafepointRecord &Info,
- PointerToBaseTy &PointerToBase) {
- StatepointLiveSetTy Updated;
- findLiveSetAtInst(Call, RevisedLivenessData, Updated);
-
-
- for (auto *V : Updated)
- PointerToBase.insert({ V, V });
- Info.LiveSet = Updated;
- }
|