GlobalOpt.cpp 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626
  1. //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass transforms simple global variables that never have their address
  10. // taken. If obviously true, it marks read/write globals as constant, deletes
  11. // variables only stored to, etc.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/IPO/GlobalOpt.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/SetVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/ADT/Twine.h"
  22. #include "llvm/ADT/iterator_range.h"
  23. #include "llvm/Analysis/BlockFrequencyInfo.h"
  24. #include "llvm/Analysis/ConstantFolding.h"
  25. #include "llvm/Analysis/MemoryBuiltins.h"
  26. #include "llvm/Analysis/TargetLibraryInfo.h"
  27. #include "llvm/Analysis/TargetTransformInfo.h"
  28. #include "llvm/Analysis/ValueTracking.h"
  29. #include "llvm/BinaryFormat/Dwarf.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/DebugInfoMetadata.h"
  37. #include "llvm/IR/DerivedTypes.h"
  38. #include "llvm/IR/Dominators.h"
  39. #include "llvm/IR/Function.h"
  40. #include "llvm/IR/GlobalAlias.h"
  41. #include "llvm/IR/GlobalValue.h"
  42. #include "llvm/IR/GlobalVariable.h"
  43. #include "llvm/IR/IRBuilder.h"
  44. #include "llvm/IR/InstrTypes.h"
  45. #include "llvm/IR/Instruction.h"
  46. #include "llvm/IR/Instructions.h"
  47. #include "llvm/IR/IntrinsicInst.h"
  48. #include "llvm/IR/Module.h"
  49. #include "llvm/IR/Operator.h"
  50. #include "llvm/IR/Type.h"
  51. #include "llvm/IR/Use.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/AtomicOrdering.h"
  58. #include "llvm/Support/Casting.h"
  59. #include "llvm/Support/CommandLine.h"
  60. #include "llvm/Support/Debug.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Support/raw_ostream.h"
  63. #include "llvm/Transforms/IPO.h"
  64. #include "llvm/Transforms/Utils/CtorUtils.h"
  65. #include "llvm/Transforms/Utils/Evaluator.h"
  66. #include "llvm/Transforms/Utils/GlobalStatus.h"
  67. #include "llvm/Transforms/Utils/Local.h"
  68. #include <cassert>
  69. #include <cstdint>
  70. #include <optional>
  71. #include <utility>
  72. #include <vector>
  73. using namespace llvm;
  74. #define DEBUG_TYPE "globalopt"
  75. STATISTIC(NumMarked , "Number of globals marked constant");
  76. STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
  77. STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
  78. STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
  79. STATISTIC(NumDeleted , "Number of globals deleted");
  80. STATISTIC(NumGlobUses , "Number of global uses devirtualized");
  81. STATISTIC(NumLocalized , "Number of globals localized");
  82. STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
  83. STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
  84. STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
  85. STATISTIC(NumNestRemoved , "Number of nest attributes removed");
  86. STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
  87. STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
  88. STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
  89. STATISTIC(NumInternalFunc, "Number of internal functions");
  90. STATISTIC(NumColdCC, "Number of functions marked coldcc");
  91. static cl::opt<bool>
  92. EnableColdCCStressTest("enable-coldcc-stress-test",
  93. cl::desc("Enable stress test of coldcc by adding "
  94. "calling conv to all internal functions."),
  95. cl::init(false), cl::Hidden);
  96. static cl::opt<int> ColdCCRelFreq(
  97. "coldcc-rel-freq", cl::Hidden, cl::init(2),
  98. cl::desc(
  99. "Maximum block frequency, expressed as a percentage of caller's "
  100. "entry frequency, for a call site to be considered cold for enabling"
  101. "coldcc"));
  102. /// Is this global variable possibly used by a leak checker as a root? If so,
  103. /// we might not really want to eliminate the stores to it.
  104. static bool isLeakCheckerRoot(GlobalVariable *GV) {
  105. // A global variable is a root if it is a pointer, or could plausibly contain
  106. // a pointer. There are two challenges; one is that we could have a struct
  107. // the has an inner member which is a pointer. We recurse through the type to
  108. // detect these (up to a point). The other is that we may actually be a union
  109. // of a pointer and another type, and so our LLVM type is an integer which
  110. // gets converted into a pointer, or our type is an [i8 x #] with a pointer
  111. // potentially contained here.
  112. if (GV->hasPrivateLinkage())
  113. return false;
  114. SmallVector<Type *, 4> Types;
  115. Types.push_back(GV->getValueType());
  116. unsigned Limit = 20;
  117. do {
  118. Type *Ty = Types.pop_back_val();
  119. switch (Ty->getTypeID()) {
  120. default: break;
  121. case Type::PointerTyID:
  122. return true;
  123. case Type::FixedVectorTyID:
  124. case Type::ScalableVectorTyID:
  125. if (cast<VectorType>(Ty)->getElementType()->isPointerTy())
  126. return true;
  127. break;
  128. case Type::ArrayTyID:
  129. Types.push_back(cast<ArrayType>(Ty)->getElementType());
  130. break;
  131. case Type::StructTyID: {
  132. StructType *STy = cast<StructType>(Ty);
  133. if (STy->isOpaque()) return true;
  134. for (Type *InnerTy : STy->elements()) {
  135. if (isa<PointerType>(InnerTy)) return true;
  136. if (isa<StructType>(InnerTy) || isa<ArrayType>(InnerTy) ||
  137. isa<VectorType>(InnerTy))
  138. Types.push_back(InnerTy);
  139. }
  140. break;
  141. }
  142. }
  143. if (--Limit == 0) return true;
  144. } while (!Types.empty());
  145. return false;
  146. }
  147. /// Given a value that is stored to a global but never read, determine whether
  148. /// it's safe to remove the store and the chain of computation that feeds the
  149. /// store.
  150. static bool IsSafeComputationToRemove(
  151. Value *V, function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
  152. do {
  153. if (isa<Constant>(V))
  154. return true;
  155. if (!V->hasOneUse())
  156. return false;
  157. if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
  158. isa<GlobalValue>(V))
  159. return false;
  160. if (isAllocationFn(V, GetTLI))
  161. return true;
  162. Instruction *I = cast<Instruction>(V);
  163. if (I->mayHaveSideEffects())
  164. return false;
  165. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
  166. if (!GEP->hasAllConstantIndices())
  167. return false;
  168. } else if (I->getNumOperands() != 1) {
  169. return false;
  170. }
  171. V = I->getOperand(0);
  172. } while (true);
  173. }
  174. /// This GV is a pointer root. Loop over all users of the global and clean up
  175. /// any that obviously don't assign the global a value that isn't dynamically
  176. /// allocated.
  177. static bool
  178. CleanupPointerRootUsers(GlobalVariable *GV,
  179. function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
  180. // A brief explanation of leak checkers. The goal is to find bugs where
  181. // pointers are forgotten, causing an accumulating growth in memory
  182. // usage over time. The common strategy for leak checkers is to explicitly
  183. // allow the memory pointed to by globals at exit. This is popular because it
  184. // also solves another problem where the main thread of a C++ program may shut
  185. // down before other threads that are still expecting to use those globals. To
  186. // handle that case, we expect the program may create a singleton and never
  187. // destroy it.
  188. bool Changed = false;
  189. // If Dead[n].first is the only use of a malloc result, we can delete its
  190. // chain of computation and the store to the global in Dead[n].second.
  191. SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
  192. // Constants can't be pointers to dynamically allocated memory.
  193. for (User *U : llvm::make_early_inc_range(GV->users())) {
  194. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  195. Value *V = SI->getValueOperand();
  196. if (isa<Constant>(V)) {
  197. Changed = true;
  198. SI->eraseFromParent();
  199. } else if (Instruction *I = dyn_cast<Instruction>(V)) {
  200. if (I->hasOneUse())
  201. Dead.push_back(std::make_pair(I, SI));
  202. }
  203. } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
  204. if (isa<Constant>(MSI->getValue())) {
  205. Changed = true;
  206. MSI->eraseFromParent();
  207. } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
  208. if (I->hasOneUse())
  209. Dead.push_back(std::make_pair(I, MSI));
  210. }
  211. } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
  212. GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
  213. if (MemSrc && MemSrc->isConstant()) {
  214. Changed = true;
  215. MTI->eraseFromParent();
  216. } else if (Instruction *I = dyn_cast<Instruction>(MTI->getSource())) {
  217. if (I->hasOneUse())
  218. Dead.push_back(std::make_pair(I, MTI));
  219. }
  220. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
  221. if (CE->use_empty()) {
  222. CE->destroyConstant();
  223. Changed = true;
  224. }
  225. } else if (Constant *C = dyn_cast<Constant>(U)) {
  226. if (isSafeToDestroyConstant(C)) {
  227. C->destroyConstant();
  228. // This could have invalidated UI, start over from scratch.
  229. Dead.clear();
  230. CleanupPointerRootUsers(GV, GetTLI);
  231. return true;
  232. }
  233. }
  234. }
  235. for (int i = 0, e = Dead.size(); i != e; ++i) {
  236. if (IsSafeComputationToRemove(Dead[i].first, GetTLI)) {
  237. Dead[i].second->eraseFromParent();
  238. Instruction *I = Dead[i].first;
  239. do {
  240. if (isAllocationFn(I, GetTLI))
  241. break;
  242. Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
  243. if (!J)
  244. break;
  245. I->eraseFromParent();
  246. I = J;
  247. } while (true);
  248. I->eraseFromParent();
  249. Changed = true;
  250. }
  251. }
  252. return Changed;
  253. }
  254. /// We just marked GV constant. Loop over all users of the global, cleaning up
  255. /// the obvious ones. This is largely just a quick scan over the use list to
  256. /// clean up the easy and obvious cruft. This returns true if it made a change.
  257. static bool CleanupConstantGlobalUsers(GlobalVariable *GV,
  258. const DataLayout &DL) {
  259. Constant *Init = GV->getInitializer();
  260. SmallVector<User *, 8> WorkList(GV->users());
  261. SmallPtrSet<User *, 8> Visited;
  262. bool Changed = false;
  263. SmallVector<WeakTrackingVH> MaybeDeadInsts;
  264. auto EraseFromParent = [&](Instruction *I) {
  265. for (Value *Op : I->operands())
  266. if (auto *OpI = dyn_cast<Instruction>(Op))
  267. MaybeDeadInsts.push_back(OpI);
  268. I->eraseFromParent();
  269. Changed = true;
  270. };
  271. while (!WorkList.empty()) {
  272. User *U = WorkList.pop_back_val();
  273. if (!Visited.insert(U).second)
  274. continue;
  275. if (auto *BO = dyn_cast<BitCastOperator>(U))
  276. append_range(WorkList, BO->users());
  277. if (auto *ASC = dyn_cast<AddrSpaceCastOperator>(U))
  278. append_range(WorkList, ASC->users());
  279. else if (auto *GEP = dyn_cast<GEPOperator>(U))
  280. append_range(WorkList, GEP->users());
  281. else if (auto *LI = dyn_cast<LoadInst>(U)) {
  282. // A load from a uniform value is always the same, regardless of any
  283. // applied offset.
  284. Type *Ty = LI->getType();
  285. if (Constant *Res = ConstantFoldLoadFromUniformValue(Init, Ty)) {
  286. LI->replaceAllUsesWith(Res);
  287. EraseFromParent(LI);
  288. continue;
  289. }
  290. Value *PtrOp = LI->getPointerOperand();
  291. APInt Offset(DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
  292. PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
  293. DL, Offset, /* AllowNonInbounds */ true);
  294. if (PtrOp == GV) {
  295. if (auto *Value = ConstantFoldLoadFromConst(Init, Ty, Offset, DL)) {
  296. LI->replaceAllUsesWith(Value);
  297. EraseFromParent(LI);
  298. }
  299. }
  300. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  301. // Store must be unreachable or storing Init into the global.
  302. EraseFromParent(SI);
  303. } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
  304. if (getUnderlyingObject(MI->getRawDest()) == GV)
  305. EraseFromParent(MI);
  306. }
  307. }
  308. Changed |=
  309. RecursivelyDeleteTriviallyDeadInstructionsPermissive(MaybeDeadInsts);
  310. GV->removeDeadConstantUsers();
  311. return Changed;
  312. }
  313. /// Look at all uses of the global and determine which (offset, type) pairs it
  314. /// can be split into.
  315. static bool collectSRATypes(DenseMap<uint64_t, Type *> &Types, GlobalValue *GV,
  316. const DataLayout &DL) {
  317. SmallVector<Use *, 16> Worklist;
  318. SmallPtrSet<Use *, 16> Visited;
  319. auto AppendUses = [&](Value *V) {
  320. for (Use &U : V->uses())
  321. if (Visited.insert(&U).second)
  322. Worklist.push_back(&U);
  323. };
  324. AppendUses(GV);
  325. while (!Worklist.empty()) {
  326. Use *U = Worklist.pop_back_val();
  327. User *V = U->getUser();
  328. auto *GEP = dyn_cast<GEPOperator>(V);
  329. if (isa<BitCastOperator>(V) || isa<AddrSpaceCastOperator>(V) ||
  330. (GEP && GEP->hasAllConstantIndices())) {
  331. AppendUses(V);
  332. continue;
  333. }
  334. if (Value *Ptr = getLoadStorePointerOperand(V)) {
  335. // This is storing the global address into somewhere, not storing into
  336. // the global.
  337. if (isa<StoreInst>(V) && U->getOperandNo() == 0)
  338. return false;
  339. APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
  340. Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset,
  341. /* AllowNonInbounds */ true);
  342. if (Ptr != GV || Offset.getActiveBits() >= 64)
  343. return false;
  344. // TODO: We currently require that all accesses at a given offset must
  345. // use the same type. This could be relaxed.
  346. Type *Ty = getLoadStoreType(V);
  347. auto It = Types.try_emplace(Offset.getZExtValue(), Ty).first;
  348. if (Ty != It->second)
  349. return false;
  350. // Scalable types not currently supported.
  351. if (isa<ScalableVectorType>(Ty))
  352. return false;
  353. continue;
  354. }
  355. // Ignore dead constant users.
  356. if (auto *C = dyn_cast<Constant>(V)) {
  357. if (!isSafeToDestroyConstant(C))
  358. return false;
  359. continue;
  360. }
  361. // Unknown user.
  362. return false;
  363. }
  364. return true;
  365. }
  366. /// Copy over the debug info for a variable to its SRA replacements.
  367. static void transferSRADebugInfo(GlobalVariable *GV, GlobalVariable *NGV,
  368. uint64_t FragmentOffsetInBits,
  369. uint64_t FragmentSizeInBits,
  370. uint64_t VarSize) {
  371. SmallVector<DIGlobalVariableExpression *, 1> GVs;
  372. GV->getDebugInfo(GVs);
  373. for (auto *GVE : GVs) {
  374. DIVariable *Var = GVE->getVariable();
  375. DIExpression *Expr = GVE->getExpression();
  376. int64_t CurVarOffsetInBytes = 0;
  377. uint64_t CurVarOffsetInBits = 0;
  378. // Calculate the offset (Bytes), Continue if unknown.
  379. if (!Expr->extractIfOffset(CurVarOffsetInBytes))
  380. continue;
  381. // Ignore negative offset.
  382. if (CurVarOffsetInBytes < 0)
  383. continue;
  384. // Convert offset to bits.
  385. CurVarOffsetInBits = CHAR_BIT * (uint64_t)CurVarOffsetInBytes;
  386. // Current var starts after the fragment, ignore.
  387. if (CurVarOffsetInBits >= (FragmentOffsetInBits + FragmentSizeInBits))
  388. continue;
  389. uint64_t CurVarSize = Var->getType()->getSizeInBits();
  390. // Current variable ends before start of fragment, ignore.
  391. if (CurVarSize != 0 &&
  392. (CurVarOffsetInBits + CurVarSize) <= FragmentOffsetInBits)
  393. continue;
  394. // Current variable fits in the fragment.
  395. if (CurVarOffsetInBits == FragmentOffsetInBits &&
  396. CurVarSize == FragmentSizeInBits)
  397. Expr = DIExpression::get(Expr->getContext(), {});
  398. // If the FragmentSize is smaller than the variable,
  399. // emit a fragment expression.
  400. else if (FragmentSizeInBits < VarSize) {
  401. if (auto E = DIExpression::createFragmentExpression(
  402. Expr, FragmentOffsetInBits, FragmentSizeInBits))
  403. Expr = *E;
  404. else
  405. return;
  406. }
  407. auto *NGVE = DIGlobalVariableExpression::get(GVE->getContext(), Var, Expr);
  408. NGV->addDebugInfo(NGVE);
  409. }
  410. }
  411. /// Perform scalar replacement of aggregates on the specified global variable.
  412. /// This opens the door for other optimizations by exposing the behavior of the
  413. /// program in a more fine-grained way. We have determined that this
  414. /// transformation is safe already. We return the first global variable we
  415. /// insert so that the caller can reprocess it.
  416. static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) {
  417. assert(GV->hasLocalLinkage());
  418. // Collect types to split into.
  419. DenseMap<uint64_t, Type *> Types;
  420. if (!collectSRATypes(Types, GV, DL) || Types.empty())
  421. return nullptr;
  422. // Make sure we don't SRA back to the same type.
  423. if (Types.size() == 1 && Types.begin()->second == GV->getValueType())
  424. return nullptr;
  425. // Don't perform SRA if we would have to split into many globals.
  426. if (Types.size() > 16)
  427. return nullptr;
  428. // Sort by offset.
  429. SmallVector<std::pair<uint64_t, Type *>, 16> TypesVector;
  430. append_range(TypesVector, Types);
  431. sort(TypesVector, llvm::less_first());
  432. // Check that the types are non-overlapping.
  433. uint64_t Offset = 0;
  434. for (const auto &Pair : TypesVector) {
  435. // Overlaps with previous type.
  436. if (Pair.first < Offset)
  437. return nullptr;
  438. Offset = Pair.first + DL.getTypeAllocSize(Pair.second);
  439. }
  440. // Some accesses go beyond the end of the global, don't bother.
  441. if (Offset > DL.getTypeAllocSize(GV->getValueType()))
  442. return nullptr;
  443. // Collect initializers for new globals.
  444. Constant *OrigInit = GV->getInitializer();
  445. DenseMap<uint64_t, Constant *> Initializers;
  446. for (const auto &Pair : Types) {
  447. Constant *NewInit = ConstantFoldLoadFromConst(OrigInit, Pair.second,
  448. APInt(64, Pair.first), DL);
  449. if (!NewInit) {
  450. LLVM_DEBUG(dbgs() << "Global SRA: Failed to evaluate initializer of "
  451. << *GV << " with type " << *Pair.second << " at offset "
  452. << Pair.first << "\n");
  453. return nullptr;
  454. }
  455. Initializers.insert({Pair.first, NewInit});
  456. }
  457. LLVM_DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n");
  458. // Get the alignment of the global, either explicit or target-specific.
  459. Align StartAlignment =
  460. DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType());
  461. uint64_t VarSize = DL.getTypeSizeInBits(GV->getValueType());
  462. // Create replacement globals.
  463. DenseMap<uint64_t, GlobalVariable *> NewGlobals;
  464. unsigned NameSuffix = 0;
  465. for (auto &Pair : TypesVector) {
  466. uint64_t Offset = Pair.first;
  467. Type *Ty = Pair.second;
  468. GlobalVariable *NGV = new GlobalVariable(
  469. *GV->getParent(), Ty, false, GlobalVariable::InternalLinkage,
  470. Initializers[Offset], GV->getName() + "." + Twine(NameSuffix++), GV,
  471. GV->getThreadLocalMode(), GV->getAddressSpace());
  472. NGV->copyAttributesFrom(GV);
  473. NewGlobals.insert({Offset, NGV});
  474. // Calculate the known alignment of the field. If the original aggregate
  475. // had 256 byte alignment for example, something might depend on that:
  476. // propagate info to each field.
  477. Align NewAlign = commonAlignment(StartAlignment, Offset);
  478. if (NewAlign > DL.getABITypeAlign(Ty))
  479. NGV->setAlignment(NewAlign);
  480. // Copy over the debug info for the variable.
  481. transferSRADebugInfo(GV, NGV, Offset * 8, DL.getTypeAllocSizeInBits(Ty),
  482. VarSize);
  483. }
  484. // Replace uses of the original global with uses of the new global.
  485. SmallVector<Value *, 16> Worklist;
  486. SmallPtrSet<Value *, 16> Visited;
  487. SmallVector<WeakTrackingVH, 16> DeadInsts;
  488. auto AppendUsers = [&](Value *V) {
  489. for (User *U : V->users())
  490. if (Visited.insert(U).second)
  491. Worklist.push_back(U);
  492. };
  493. AppendUsers(GV);
  494. while (!Worklist.empty()) {
  495. Value *V = Worklist.pop_back_val();
  496. if (isa<BitCastOperator>(V) || isa<AddrSpaceCastOperator>(V) ||
  497. isa<GEPOperator>(V)) {
  498. AppendUsers(V);
  499. if (isa<Instruction>(V))
  500. DeadInsts.push_back(V);
  501. continue;
  502. }
  503. if (Value *Ptr = getLoadStorePointerOperand(V)) {
  504. APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
  505. Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset,
  506. /* AllowNonInbounds */ true);
  507. assert(Ptr == GV && "Load/store must be from/to global");
  508. GlobalVariable *NGV = NewGlobals[Offset.getZExtValue()];
  509. assert(NGV && "Must have replacement global for this offset");
  510. // Update the pointer operand and recalculate alignment.
  511. Align PrefAlign = DL.getPrefTypeAlign(getLoadStoreType(V));
  512. Align NewAlign =
  513. getOrEnforceKnownAlignment(NGV, PrefAlign, DL, cast<Instruction>(V));
  514. if (auto *LI = dyn_cast<LoadInst>(V)) {
  515. LI->setOperand(0, NGV);
  516. LI->setAlignment(NewAlign);
  517. } else {
  518. auto *SI = cast<StoreInst>(V);
  519. SI->setOperand(1, NGV);
  520. SI->setAlignment(NewAlign);
  521. }
  522. continue;
  523. }
  524. assert(isa<Constant>(V) && isSafeToDestroyConstant(cast<Constant>(V)) &&
  525. "Other users can only be dead constants");
  526. }
  527. // Delete old instructions and global.
  528. RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
  529. GV->removeDeadConstantUsers();
  530. GV->eraseFromParent();
  531. ++NumSRA;
  532. assert(NewGlobals.size() > 0);
  533. return NewGlobals.begin()->second;
  534. }
  535. /// Return true if all users of the specified value will trap if the value is
  536. /// dynamically null. PHIs keeps track of any phi nodes we've seen to avoid
  537. /// reprocessing them.
  538. static bool AllUsesOfValueWillTrapIfNull(const Value *V,
  539. SmallPtrSetImpl<const PHINode*> &PHIs) {
  540. for (const User *U : V->users()) {
  541. if (const Instruction *I = dyn_cast<Instruction>(U)) {
  542. // If null pointer is considered valid, then all uses are non-trapping.
  543. // Non address-space 0 globals have already been pruned by the caller.
  544. if (NullPointerIsDefined(I->getFunction()))
  545. return false;
  546. }
  547. if (isa<LoadInst>(U)) {
  548. // Will trap.
  549. } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
  550. if (SI->getOperand(0) == V) {
  551. return false; // Storing the value.
  552. }
  553. } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
  554. if (CI->getCalledOperand() != V) {
  555. return false; // Not calling the ptr
  556. }
  557. } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
  558. if (II->getCalledOperand() != V) {
  559. return false; // Not calling the ptr
  560. }
  561. } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
  562. if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
  563. } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
  564. if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
  565. } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
  566. // If we've already seen this phi node, ignore it, it has already been
  567. // checked.
  568. if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
  569. return false;
  570. } else if (isa<ICmpInst>(U) &&
  571. !ICmpInst::isSigned(cast<ICmpInst>(U)->getPredicate()) &&
  572. isa<LoadInst>(U->getOperand(0)) &&
  573. isa<ConstantPointerNull>(U->getOperand(1))) {
  574. assert(isa<GlobalValue>(cast<LoadInst>(U->getOperand(0))
  575. ->getPointerOperand()
  576. ->stripPointerCasts()) &&
  577. "Should be GlobalVariable");
  578. // This and only this kind of non-signed ICmpInst is to be replaced with
  579. // the comparing of the value of the created global init bool later in
  580. // optimizeGlobalAddressOfAllocation for the global variable.
  581. } else {
  582. return false;
  583. }
  584. }
  585. return true;
  586. }
  587. /// Return true if all uses of any loads from GV will trap if the loaded value
  588. /// is null. Note that this also permits comparisons of the loaded value
  589. /// against null, as a special case.
  590. static bool allUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
  591. SmallVector<const Value *, 4> Worklist;
  592. Worklist.push_back(GV);
  593. while (!Worklist.empty()) {
  594. const Value *P = Worklist.pop_back_val();
  595. for (const auto *U : P->users()) {
  596. if (auto *LI = dyn_cast<LoadInst>(U)) {
  597. SmallPtrSet<const PHINode *, 8> PHIs;
  598. if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
  599. return false;
  600. } else if (auto *SI = dyn_cast<StoreInst>(U)) {
  601. // Ignore stores to the global.
  602. if (SI->getPointerOperand() != P)
  603. return false;
  604. } else if (auto *CE = dyn_cast<ConstantExpr>(U)) {
  605. if (CE->stripPointerCasts() != GV)
  606. return false;
  607. // Check further the ConstantExpr.
  608. Worklist.push_back(CE);
  609. } else {
  610. // We don't know or understand this user, bail out.
  611. return false;
  612. }
  613. }
  614. }
  615. return true;
  616. }
  617. /// Get all the loads/store uses for global variable \p GV.
  618. static void allUsesOfLoadAndStores(GlobalVariable *GV,
  619. SmallVector<Value *, 4> &Uses) {
  620. SmallVector<Value *, 4> Worklist;
  621. Worklist.push_back(GV);
  622. while (!Worklist.empty()) {
  623. auto *P = Worklist.pop_back_val();
  624. for (auto *U : P->users()) {
  625. if (auto *CE = dyn_cast<ConstantExpr>(U)) {
  626. Worklist.push_back(CE);
  627. continue;
  628. }
  629. assert((isa<LoadInst>(U) || isa<StoreInst>(U)) &&
  630. "Expect only load or store instructions");
  631. Uses.push_back(U);
  632. }
  633. }
  634. }
  635. static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
  636. bool Changed = false;
  637. for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) {
  638. Instruction *I = cast<Instruction>(*UI++);
  639. // Uses are non-trapping if null pointer is considered valid.
  640. // Non address-space 0 globals are already pruned by the caller.
  641. if (NullPointerIsDefined(I->getFunction()))
  642. return false;
  643. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  644. LI->setOperand(0, NewV);
  645. Changed = true;
  646. } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  647. if (SI->getOperand(1) == V) {
  648. SI->setOperand(1, NewV);
  649. Changed = true;
  650. }
  651. } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
  652. CallBase *CB = cast<CallBase>(I);
  653. if (CB->getCalledOperand() == V) {
  654. // Calling through the pointer! Turn into a direct call, but be careful
  655. // that the pointer is not also being passed as an argument.
  656. CB->setCalledOperand(NewV);
  657. Changed = true;
  658. bool PassedAsArg = false;
  659. for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
  660. if (CB->getArgOperand(i) == V) {
  661. PassedAsArg = true;
  662. CB->setArgOperand(i, NewV);
  663. }
  664. if (PassedAsArg) {
  665. // Being passed as an argument also. Be careful to not invalidate UI!
  666. UI = V->user_begin();
  667. }
  668. }
  669. } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
  670. Changed |= OptimizeAwayTrappingUsesOfValue(CI,
  671. ConstantExpr::getCast(CI->getOpcode(),
  672. NewV, CI->getType()));
  673. if (CI->use_empty()) {
  674. Changed = true;
  675. CI->eraseFromParent();
  676. }
  677. } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  678. // Should handle GEP here.
  679. SmallVector<Constant*, 8> Idxs;
  680. Idxs.reserve(GEPI->getNumOperands()-1);
  681. for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
  682. i != e; ++i)
  683. if (Constant *C = dyn_cast<Constant>(*i))
  684. Idxs.push_back(C);
  685. else
  686. break;
  687. if (Idxs.size() == GEPI->getNumOperands()-1)
  688. Changed |= OptimizeAwayTrappingUsesOfValue(
  689. GEPI, ConstantExpr::getGetElementPtr(GEPI->getSourceElementType(),
  690. NewV, Idxs));
  691. if (GEPI->use_empty()) {
  692. Changed = true;
  693. GEPI->eraseFromParent();
  694. }
  695. }
  696. }
  697. return Changed;
  698. }
  699. /// The specified global has only one non-null value stored into it. If there
  700. /// are uses of the loaded value that would trap if the loaded value is
  701. /// dynamically null, then we know that they cannot be reachable with a null
  702. /// optimize away the load.
  703. static bool OptimizeAwayTrappingUsesOfLoads(
  704. GlobalVariable *GV, Constant *LV, const DataLayout &DL,
  705. function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
  706. bool Changed = false;
  707. // Keep track of whether we are able to remove all the uses of the global
  708. // other than the store that defines it.
  709. bool AllNonStoreUsesGone = true;
  710. // Replace all uses of loads with uses of uses of the stored value.
  711. for (User *GlobalUser : llvm::make_early_inc_range(GV->users())) {
  712. if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
  713. Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
  714. // If we were able to delete all uses of the loads
  715. if (LI->use_empty()) {
  716. LI->eraseFromParent();
  717. Changed = true;
  718. } else {
  719. AllNonStoreUsesGone = false;
  720. }
  721. } else if (isa<StoreInst>(GlobalUser)) {
  722. // Ignore the store that stores "LV" to the global.
  723. assert(GlobalUser->getOperand(1) == GV &&
  724. "Must be storing *to* the global");
  725. } else {
  726. AllNonStoreUsesGone = false;
  727. // If we get here we could have other crazy uses that are transitively
  728. // loaded.
  729. assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
  730. isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
  731. isa<BitCastInst>(GlobalUser) ||
  732. isa<GetElementPtrInst>(GlobalUser)) &&
  733. "Only expect load and stores!");
  734. }
  735. }
  736. if (Changed) {
  737. LLVM_DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV
  738. << "\n");
  739. ++NumGlobUses;
  740. }
  741. // If we nuked all of the loads, then none of the stores are needed either,
  742. // nor is the global.
  743. if (AllNonStoreUsesGone) {
  744. if (isLeakCheckerRoot(GV)) {
  745. Changed |= CleanupPointerRootUsers(GV, GetTLI);
  746. } else {
  747. Changed = true;
  748. CleanupConstantGlobalUsers(GV, DL);
  749. }
  750. if (GV->use_empty()) {
  751. LLVM_DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
  752. Changed = true;
  753. GV->eraseFromParent();
  754. ++NumDeleted;
  755. }
  756. }
  757. return Changed;
  758. }
  759. /// Walk the use list of V, constant folding all of the instructions that are
  760. /// foldable.
  761. static void ConstantPropUsersOf(Value *V, const DataLayout &DL,
  762. TargetLibraryInfo *TLI) {
  763. for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; )
  764. if (Instruction *I = dyn_cast<Instruction>(*UI++))
  765. if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) {
  766. I->replaceAllUsesWith(NewC);
  767. // Advance UI to the next non-I use to avoid invalidating it!
  768. // Instructions could multiply use V.
  769. while (UI != E && *UI == I)
  770. ++UI;
  771. if (isInstructionTriviallyDead(I, TLI))
  772. I->eraseFromParent();
  773. }
  774. }
  775. /// This function takes the specified global variable, and transforms the
  776. /// program as if it always contained the result of the specified malloc.
  777. /// Because it is always the result of the specified malloc, there is no reason
  778. /// to actually DO the malloc. Instead, turn the malloc into a global, and any
  779. /// loads of GV as uses of the new global.
  780. static GlobalVariable *
  781. OptimizeGlobalAddressOfAllocation(GlobalVariable *GV, CallInst *CI,
  782. uint64_t AllocSize, Constant *InitVal,
  783. const DataLayout &DL,
  784. TargetLibraryInfo *TLI) {
  785. LLVM_DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI
  786. << '\n');
  787. // Create global of type [AllocSize x i8].
  788. Type *GlobalType = ArrayType::get(Type::getInt8Ty(GV->getContext()),
  789. AllocSize);
  790. // Create the new global variable. The contents of the allocated memory is
  791. // undefined initially, so initialize with an undef value.
  792. GlobalVariable *NewGV = new GlobalVariable(
  793. *GV->getParent(), GlobalType, false, GlobalValue::InternalLinkage,
  794. UndefValue::get(GlobalType), GV->getName() + ".body", nullptr,
  795. GV->getThreadLocalMode());
  796. // Initialize the global at the point of the original call. Note that this
  797. // is a different point from the initialization referred to below for the
  798. // nullability handling. Sublety: We have not proven the original global was
  799. // only initialized once. As such, we can not fold this into the initializer
  800. // of the new global as may need to re-init the storage multiple times.
  801. if (!isa<UndefValue>(InitVal)) {
  802. IRBuilder<> Builder(CI->getNextNode());
  803. // TODO: Use alignment above if align!=1
  804. Builder.CreateMemSet(NewGV, InitVal, AllocSize, std::nullopt);
  805. }
  806. // Update users of the allocation to use the new global instead.
  807. BitCastInst *TheBC = nullptr;
  808. while (!CI->use_empty()) {
  809. Instruction *User = cast<Instruction>(CI->user_back());
  810. if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
  811. if (BCI->getType() == NewGV->getType()) {
  812. BCI->replaceAllUsesWith(NewGV);
  813. BCI->eraseFromParent();
  814. } else {
  815. BCI->setOperand(0, NewGV);
  816. }
  817. } else {
  818. if (!TheBC)
  819. TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
  820. User->replaceUsesOfWith(CI, TheBC);
  821. }
  822. }
  823. SmallSetVector<Constant *, 1> RepValues;
  824. RepValues.insert(NewGV);
  825. // If there is a comparison against null, we will insert a global bool to
  826. // keep track of whether the global was initialized yet or not.
  827. GlobalVariable *InitBool =
  828. new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
  829. GlobalValue::InternalLinkage,
  830. ConstantInt::getFalse(GV->getContext()),
  831. GV->getName()+".init", GV->getThreadLocalMode());
  832. bool InitBoolUsed = false;
  833. // Loop over all instruction uses of GV, processing them in turn.
  834. SmallVector<Value *, 4> Guses;
  835. allUsesOfLoadAndStores(GV, Guses);
  836. for (auto *U : Guses) {
  837. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  838. // The global is initialized when the store to it occurs. If the stored
  839. // value is null value, the global bool is set to false, otherwise true.
  840. new StoreInst(ConstantInt::getBool(
  841. GV->getContext(),
  842. !isa<ConstantPointerNull>(SI->getValueOperand())),
  843. InitBool, false, Align(1), SI->getOrdering(),
  844. SI->getSyncScopeID(), SI);
  845. SI->eraseFromParent();
  846. continue;
  847. }
  848. LoadInst *LI = cast<LoadInst>(U);
  849. while (!LI->use_empty()) {
  850. Use &LoadUse = *LI->use_begin();
  851. ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser());
  852. if (!ICI) {
  853. auto *CE = ConstantExpr::getBitCast(NewGV, LI->getType());
  854. RepValues.insert(CE);
  855. LoadUse.set(CE);
  856. continue;
  857. }
  858. // Replace the cmp X, 0 with a use of the bool value.
  859. Value *LV = new LoadInst(InitBool->getValueType(), InitBool,
  860. InitBool->getName() + ".val", false, Align(1),
  861. LI->getOrdering(), LI->getSyncScopeID(), LI);
  862. InitBoolUsed = true;
  863. switch (ICI->getPredicate()) {
  864. default: llvm_unreachable("Unknown ICmp Predicate!");
  865. case ICmpInst::ICMP_ULT: // X < null -> always false
  866. LV = ConstantInt::getFalse(GV->getContext());
  867. break;
  868. case ICmpInst::ICMP_UGE: // X >= null -> always true
  869. LV = ConstantInt::getTrue(GV->getContext());
  870. break;
  871. case ICmpInst::ICMP_ULE:
  872. case ICmpInst::ICMP_EQ:
  873. LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
  874. break;
  875. case ICmpInst::ICMP_NE:
  876. case ICmpInst::ICMP_UGT:
  877. break; // no change.
  878. }
  879. ICI->replaceAllUsesWith(LV);
  880. ICI->eraseFromParent();
  881. }
  882. LI->eraseFromParent();
  883. }
  884. // If the initialization boolean was used, insert it, otherwise delete it.
  885. if (!InitBoolUsed) {
  886. while (!InitBool->use_empty()) // Delete initializations
  887. cast<StoreInst>(InitBool->user_back())->eraseFromParent();
  888. delete InitBool;
  889. } else
  890. GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool);
  891. // Now the GV is dead, nuke it and the allocation..
  892. GV->eraseFromParent();
  893. CI->eraseFromParent();
  894. // To further other optimizations, loop over all users of NewGV and try to
  895. // constant prop them. This will promote GEP instructions with constant
  896. // indices into GEP constant-exprs, which will allow global-opt to hack on it.
  897. for (auto *CE : RepValues)
  898. ConstantPropUsersOf(CE, DL, TLI);
  899. return NewGV;
  900. }
  901. /// Scan the use-list of GV checking to make sure that there are no complex uses
  902. /// of GV. We permit simple things like dereferencing the pointer, but not
  903. /// storing through the address, unless it is to the specified global.
  904. static bool
  905. valueIsOnlyUsedLocallyOrStoredToOneGlobal(const CallInst *CI,
  906. const GlobalVariable *GV) {
  907. SmallPtrSet<const Value *, 4> Visited;
  908. SmallVector<const Value *, 4> Worklist;
  909. Worklist.push_back(CI);
  910. while (!Worklist.empty()) {
  911. const Value *V = Worklist.pop_back_val();
  912. if (!Visited.insert(V).second)
  913. continue;
  914. for (const Use &VUse : V->uses()) {
  915. const User *U = VUse.getUser();
  916. if (isa<LoadInst>(U) || isa<CmpInst>(U))
  917. continue; // Fine, ignore.
  918. if (auto *SI = dyn_cast<StoreInst>(U)) {
  919. if (SI->getValueOperand() == V &&
  920. SI->getPointerOperand()->stripPointerCasts() != GV)
  921. return false; // Storing the pointer not into GV... bad.
  922. continue; // Otherwise, storing through it, or storing into GV... fine.
  923. }
  924. if (auto *BCI = dyn_cast<BitCastInst>(U)) {
  925. Worklist.push_back(BCI);
  926. continue;
  927. }
  928. if (auto *GEPI = dyn_cast<GetElementPtrInst>(U)) {
  929. Worklist.push_back(GEPI);
  930. continue;
  931. }
  932. return false;
  933. }
  934. }
  935. return true;
  936. }
  937. /// If we have a global that is only initialized with a fixed size allocation
  938. /// try to transform the program to use global memory instead of heap
  939. /// allocated memory. This eliminates dynamic allocation, avoids an indirection
  940. /// accessing the data, and exposes the resultant global to further GlobalOpt.
  941. static bool tryToOptimizeStoreOfAllocationToGlobal(GlobalVariable *GV,
  942. CallInst *CI,
  943. const DataLayout &DL,
  944. TargetLibraryInfo *TLI) {
  945. if (!isRemovableAlloc(CI, TLI))
  946. // Must be able to remove the call when we get done..
  947. return false;
  948. Type *Int8Ty = Type::getInt8Ty(CI->getFunction()->getContext());
  949. Constant *InitVal = getInitialValueOfAllocation(CI, TLI, Int8Ty);
  950. if (!InitVal)
  951. // Must be able to emit a memset for initialization
  952. return false;
  953. uint64_t AllocSize;
  954. if (!getObjectSize(CI, AllocSize, DL, TLI, ObjectSizeOpts()))
  955. return false;
  956. // Restrict this transformation to only working on small allocations
  957. // (2048 bytes currently), as we don't want to introduce a 16M global or
  958. // something.
  959. if (AllocSize >= 2048)
  960. return false;
  961. // We can't optimize this global unless all uses of it are *known* to be
  962. // of the malloc value, not of the null initializer value (consider a use
  963. // that compares the global's value against zero to see if the malloc has
  964. // been reached). To do this, we check to see if all uses of the global
  965. // would trap if the global were null: this proves that they must all
  966. // happen after the malloc.
  967. if (!allUsesOfLoadedValueWillTrapIfNull(GV))
  968. return false;
  969. // We can't optimize this if the malloc itself is used in a complex way,
  970. // for example, being stored into multiple globals. This allows the
  971. // malloc to be stored into the specified global, loaded, gep, icmp'd.
  972. // These are all things we could transform to using the global for.
  973. if (!valueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV))
  974. return false;
  975. OptimizeGlobalAddressOfAllocation(GV, CI, AllocSize, InitVal, DL, TLI);
  976. return true;
  977. }
  978. // Try to optimize globals based on the knowledge that only one value (besides
  979. // its initializer) is ever stored to the global.
  980. static bool
  981. optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
  982. const DataLayout &DL,
  983. function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
  984. // Ignore no-op GEPs and bitcasts.
  985. StoredOnceVal = StoredOnceVal->stripPointerCasts();
  986. // If we are dealing with a pointer global that is initialized to null and
  987. // only has one (non-null) value stored into it, then we can optimize any
  988. // users of the loaded value (often calls and loads) that would trap if the
  989. // value was null.
  990. if (GV->getInitializer()->getType()->isPointerTy() &&
  991. GV->getInitializer()->isNullValue() &&
  992. StoredOnceVal->getType()->isPointerTy() &&
  993. !NullPointerIsDefined(
  994. nullptr /* F */,
  995. GV->getInitializer()->getType()->getPointerAddressSpace())) {
  996. if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
  997. if (GV->getInitializer()->getType() != SOVC->getType())
  998. SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
  999. // Optimize away any trapping uses of the loaded value.
  1000. if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, GetTLI))
  1001. return true;
  1002. } else if (isAllocationFn(StoredOnceVal, GetTLI)) {
  1003. if (auto *CI = dyn_cast<CallInst>(StoredOnceVal)) {
  1004. auto *TLI = &GetTLI(*CI->getFunction());
  1005. if (tryToOptimizeStoreOfAllocationToGlobal(GV, CI, DL, TLI))
  1006. return true;
  1007. }
  1008. }
  1009. }
  1010. return false;
  1011. }
  1012. /// At this point, we have learned that the only two values ever stored into GV
  1013. /// are its initializer and OtherVal. See if we can shrink the global into a
  1014. /// boolean and select between the two values whenever it is used. This exposes
  1015. /// the values to other scalar optimizations.
  1016. static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
  1017. Type *GVElType = GV->getValueType();
  1018. // If GVElType is already i1, it is already shrunk. If the type of the GV is
  1019. // an FP value, pointer or vector, don't do this optimization because a select
  1020. // between them is very expensive and unlikely to lead to later
  1021. // simplification. In these cases, we typically end up with "cond ? v1 : v2"
  1022. // where v1 and v2 both require constant pool loads, a big loss.
  1023. if (GVElType == Type::getInt1Ty(GV->getContext()) ||
  1024. GVElType->isFloatingPointTy() ||
  1025. GVElType->isPointerTy() || GVElType->isVectorTy())
  1026. return false;
  1027. // Walk the use list of the global seeing if all the uses are load or store.
  1028. // If there is anything else, bail out.
  1029. for (User *U : GV->users()) {
  1030. if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
  1031. return false;
  1032. if (getLoadStoreType(U) != GVElType)
  1033. return false;
  1034. }
  1035. LLVM_DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV << "\n");
  1036. // Create the new global, initializing it to false.
  1037. GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
  1038. false,
  1039. GlobalValue::InternalLinkage,
  1040. ConstantInt::getFalse(GV->getContext()),
  1041. GV->getName()+".b",
  1042. GV->getThreadLocalMode(),
  1043. GV->getType()->getAddressSpace());
  1044. NewGV->copyAttributesFrom(GV);
  1045. GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV);
  1046. Constant *InitVal = GV->getInitializer();
  1047. assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
  1048. "No reason to shrink to bool!");
  1049. SmallVector<DIGlobalVariableExpression *, 1> GVs;
  1050. GV->getDebugInfo(GVs);
  1051. // If initialized to zero and storing one into the global, we can use a cast
  1052. // instead of a select to synthesize the desired value.
  1053. bool IsOneZero = false;
  1054. bool EmitOneOrZero = true;
  1055. auto *CI = dyn_cast<ConstantInt>(OtherVal);
  1056. if (CI && CI->getValue().getActiveBits() <= 64) {
  1057. IsOneZero = InitVal->isNullValue() && CI->isOne();
  1058. auto *CIInit = dyn_cast<ConstantInt>(GV->getInitializer());
  1059. if (CIInit && CIInit->getValue().getActiveBits() <= 64) {
  1060. uint64_t ValInit = CIInit->getZExtValue();
  1061. uint64_t ValOther = CI->getZExtValue();
  1062. uint64_t ValMinus = ValOther - ValInit;
  1063. for(auto *GVe : GVs){
  1064. DIGlobalVariable *DGV = GVe->getVariable();
  1065. DIExpression *E = GVe->getExpression();
  1066. const DataLayout &DL = GV->getParent()->getDataLayout();
  1067. unsigned SizeInOctets =
  1068. DL.getTypeAllocSizeInBits(NewGV->getValueType()) / 8;
  1069. // It is expected that the address of global optimized variable is on
  1070. // top of the stack. After optimization, value of that variable will
  1071. // be ether 0 for initial value or 1 for other value. The following
  1072. // expression should return constant integer value depending on the
  1073. // value at global object address:
  1074. // val * (ValOther - ValInit) + ValInit:
  1075. // DW_OP_deref DW_OP_constu <ValMinus>
  1076. // DW_OP_mul DW_OP_constu <ValInit> DW_OP_plus DW_OP_stack_value
  1077. SmallVector<uint64_t, 12> Ops = {
  1078. dwarf::DW_OP_deref_size, SizeInOctets,
  1079. dwarf::DW_OP_constu, ValMinus,
  1080. dwarf::DW_OP_mul, dwarf::DW_OP_constu, ValInit,
  1081. dwarf::DW_OP_plus};
  1082. bool WithStackValue = true;
  1083. E = DIExpression::prependOpcodes(E, Ops, WithStackValue);
  1084. DIGlobalVariableExpression *DGVE =
  1085. DIGlobalVariableExpression::get(NewGV->getContext(), DGV, E);
  1086. NewGV->addDebugInfo(DGVE);
  1087. }
  1088. EmitOneOrZero = false;
  1089. }
  1090. }
  1091. if (EmitOneOrZero) {
  1092. // FIXME: This will only emit address for debugger on which will
  1093. // be written only 0 or 1.
  1094. for(auto *GV : GVs)
  1095. NewGV->addDebugInfo(GV);
  1096. }
  1097. while (!GV->use_empty()) {
  1098. Instruction *UI = cast<Instruction>(GV->user_back());
  1099. if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
  1100. // Change the store into a boolean store.
  1101. bool StoringOther = SI->getOperand(0) == OtherVal;
  1102. // Only do this if we weren't storing a loaded value.
  1103. Value *StoreVal;
  1104. if (StoringOther || SI->getOperand(0) == InitVal) {
  1105. StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
  1106. StoringOther);
  1107. } else {
  1108. // Otherwise, we are storing a previously loaded copy. To do this,
  1109. // change the copy from copying the original value to just copying the
  1110. // bool.
  1111. Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
  1112. // If we've already replaced the input, StoredVal will be a cast or
  1113. // select instruction. If not, it will be a load of the original
  1114. // global.
  1115. if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
  1116. assert(LI->getOperand(0) == GV && "Not a copy!");
  1117. // Insert a new load, to preserve the saved value.
  1118. StoreVal = new LoadInst(NewGV->getValueType(), NewGV,
  1119. LI->getName() + ".b", false, Align(1),
  1120. LI->getOrdering(), LI->getSyncScopeID(), LI);
  1121. } else {
  1122. assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
  1123. "This is not a form that we understand!");
  1124. StoreVal = StoredVal->getOperand(0);
  1125. assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
  1126. }
  1127. }
  1128. StoreInst *NSI =
  1129. new StoreInst(StoreVal, NewGV, false, Align(1), SI->getOrdering(),
  1130. SI->getSyncScopeID(), SI);
  1131. NSI->setDebugLoc(SI->getDebugLoc());
  1132. } else {
  1133. // Change the load into a load of bool then a select.
  1134. LoadInst *LI = cast<LoadInst>(UI);
  1135. LoadInst *NLI = new LoadInst(NewGV->getValueType(), NewGV,
  1136. LI->getName() + ".b", false, Align(1),
  1137. LI->getOrdering(), LI->getSyncScopeID(), LI);
  1138. Instruction *NSI;
  1139. if (IsOneZero)
  1140. NSI = new ZExtInst(NLI, LI->getType(), "", LI);
  1141. else
  1142. NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
  1143. NSI->takeName(LI);
  1144. // Since LI is split into two instructions, NLI and NSI both inherit the
  1145. // same DebugLoc
  1146. NLI->setDebugLoc(LI->getDebugLoc());
  1147. NSI->setDebugLoc(LI->getDebugLoc());
  1148. LI->replaceAllUsesWith(NSI);
  1149. }
  1150. UI->eraseFromParent();
  1151. }
  1152. // Retain the name of the old global variable. People who are debugging their
  1153. // programs may expect these variables to be named the same.
  1154. NewGV->takeName(GV);
  1155. GV->eraseFromParent();
  1156. return true;
  1157. }
  1158. static bool
  1159. deleteIfDead(GlobalValue &GV,
  1160. SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats,
  1161. function_ref<void(Function &)> DeleteFnCallback = nullptr) {
  1162. GV.removeDeadConstantUsers();
  1163. if (!GV.isDiscardableIfUnused() && !GV.isDeclaration())
  1164. return false;
  1165. if (const Comdat *C = GV.getComdat())
  1166. if (!GV.hasLocalLinkage() && NotDiscardableComdats.count(C))
  1167. return false;
  1168. bool Dead;
  1169. if (auto *F = dyn_cast<Function>(&GV))
  1170. Dead = (F->isDeclaration() && F->use_empty()) || F->isDefTriviallyDead();
  1171. else
  1172. Dead = GV.use_empty();
  1173. if (!Dead)
  1174. return false;
  1175. LLVM_DEBUG(dbgs() << "GLOBAL DEAD: " << GV << "\n");
  1176. if (auto *F = dyn_cast<Function>(&GV)) {
  1177. if (DeleteFnCallback)
  1178. DeleteFnCallback(*F);
  1179. }
  1180. GV.eraseFromParent();
  1181. ++NumDeleted;
  1182. return true;
  1183. }
  1184. static bool isPointerValueDeadOnEntryToFunction(
  1185. const Function *F, GlobalValue *GV,
  1186. function_ref<DominatorTree &(Function &)> LookupDomTree) {
  1187. // Find all uses of GV. We expect them all to be in F, and if we can't
  1188. // identify any of the uses we bail out.
  1189. //
  1190. // On each of these uses, identify if the memory that GV points to is
  1191. // used/required/live at the start of the function. If it is not, for example
  1192. // if the first thing the function does is store to the GV, the GV can
  1193. // possibly be demoted.
  1194. //
  1195. // We don't do an exhaustive search for memory operations - simply look
  1196. // through bitcasts as they're quite common and benign.
  1197. const DataLayout &DL = GV->getParent()->getDataLayout();
  1198. SmallVector<LoadInst *, 4> Loads;
  1199. SmallVector<StoreInst *, 4> Stores;
  1200. for (auto *U : GV->users()) {
  1201. if (Operator::getOpcode(U) == Instruction::BitCast) {
  1202. for (auto *UU : U->users()) {
  1203. if (auto *LI = dyn_cast<LoadInst>(UU))
  1204. Loads.push_back(LI);
  1205. else if (auto *SI = dyn_cast<StoreInst>(UU))
  1206. Stores.push_back(SI);
  1207. else
  1208. return false;
  1209. }
  1210. continue;
  1211. }
  1212. Instruction *I = dyn_cast<Instruction>(U);
  1213. if (!I)
  1214. return false;
  1215. assert(I->getParent()->getParent() == F);
  1216. if (auto *LI = dyn_cast<LoadInst>(I))
  1217. Loads.push_back(LI);
  1218. else if (auto *SI = dyn_cast<StoreInst>(I))
  1219. Stores.push_back(SI);
  1220. else
  1221. return false;
  1222. }
  1223. // We have identified all uses of GV into loads and stores. Now check if all
  1224. // of them are known not to depend on the value of the global at the function
  1225. // entry point. We do this by ensuring that every load is dominated by at
  1226. // least one store.
  1227. auto &DT = LookupDomTree(*const_cast<Function *>(F));
  1228. // The below check is quadratic. Check we're not going to do too many tests.
  1229. // FIXME: Even though this will always have worst-case quadratic time, we
  1230. // could put effort into minimizing the average time by putting stores that
  1231. // have been shown to dominate at least one load at the beginning of the
  1232. // Stores array, making subsequent dominance checks more likely to succeed
  1233. // early.
  1234. //
  1235. // The threshold here is fairly large because global->local demotion is a
  1236. // very powerful optimization should it fire.
  1237. const unsigned Threshold = 100;
  1238. if (Loads.size() * Stores.size() > Threshold)
  1239. return false;
  1240. for (auto *L : Loads) {
  1241. auto *LTy = L->getType();
  1242. if (none_of(Stores, [&](const StoreInst *S) {
  1243. auto *STy = S->getValueOperand()->getType();
  1244. // The load is only dominated by the store if DomTree says so
  1245. // and the number of bits loaded in L is less than or equal to
  1246. // the number of bits stored in S.
  1247. return DT.dominates(S, L) &&
  1248. DL.getTypeStoreSize(LTy).getFixedValue() <=
  1249. DL.getTypeStoreSize(STy).getFixedValue();
  1250. }))
  1251. return false;
  1252. }
  1253. // All loads have known dependences inside F, so the global can be localized.
  1254. return true;
  1255. }
  1256. /// C may have non-instruction users. Can all of those users be turned into
  1257. /// instructions?
  1258. static bool allNonInstructionUsersCanBeMadeInstructions(Constant *C) {
  1259. // We don't do this exhaustively. The most common pattern that we really need
  1260. // to care about is a constant GEP or constant bitcast - so just looking
  1261. // through one single ConstantExpr.
  1262. //
  1263. // The set of constants that this function returns true for must be able to be
  1264. // handled by makeAllConstantUsesInstructions.
  1265. for (auto *U : C->users()) {
  1266. if (isa<Instruction>(U))
  1267. continue;
  1268. if (!isa<ConstantExpr>(U))
  1269. // Non instruction, non-constantexpr user; cannot convert this.
  1270. return false;
  1271. for (auto *UU : U->users())
  1272. if (!isa<Instruction>(UU))
  1273. // A constantexpr used by another constant. We don't try and recurse any
  1274. // further but just bail out at this point.
  1275. return false;
  1276. }
  1277. return true;
  1278. }
  1279. /// C may have non-instruction users, and
  1280. /// allNonInstructionUsersCanBeMadeInstructions has returned true. Convert the
  1281. /// non-instruction users to instructions.
  1282. static void makeAllConstantUsesInstructions(Constant *C) {
  1283. SmallVector<ConstantExpr*,4> Users;
  1284. for (auto *U : C->users()) {
  1285. if (isa<ConstantExpr>(U))
  1286. Users.push_back(cast<ConstantExpr>(U));
  1287. else
  1288. // We should never get here; allNonInstructionUsersCanBeMadeInstructions
  1289. // should not have returned true for C.
  1290. assert(
  1291. isa<Instruction>(U) &&
  1292. "Can't transform non-constantexpr non-instruction to instruction!");
  1293. }
  1294. SmallVector<Value*,4> UUsers;
  1295. for (auto *U : Users) {
  1296. UUsers.clear();
  1297. append_range(UUsers, U->users());
  1298. for (auto *UU : UUsers) {
  1299. Instruction *UI = cast<Instruction>(UU);
  1300. Instruction *NewU = U->getAsInstruction(UI);
  1301. UI->replaceUsesOfWith(U, NewU);
  1302. }
  1303. // We've replaced all the uses, so destroy the constant. (destroyConstant
  1304. // will update value handles and metadata.)
  1305. U->destroyConstant();
  1306. }
  1307. }
  1308. // For a global variable with one store, if the store dominates any loads,
  1309. // those loads will always load the stored value (as opposed to the
  1310. // initializer), even in the presence of recursion.
  1311. static bool forwardStoredOnceStore(
  1312. GlobalVariable *GV, const StoreInst *StoredOnceStore,
  1313. function_ref<DominatorTree &(Function &)> LookupDomTree) {
  1314. const Value *StoredOnceValue = StoredOnceStore->getValueOperand();
  1315. // We can do this optimization for non-constants in nosync + norecurse
  1316. // functions, but globals used in exactly one norecurse functions are already
  1317. // promoted to an alloca.
  1318. if (!isa<Constant>(StoredOnceValue))
  1319. return false;
  1320. const Function *F = StoredOnceStore->getFunction();
  1321. SmallVector<LoadInst *> Loads;
  1322. for (User *U : GV->users()) {
  1323. if (auto *LI = dyn_cast<LoadInst>(U)) {
  1324. if (LI->getFunction() == F &&
  1325. LI->getType() == StoredOnceValue->getType() && LI->isSimple())
  1326. Loads.push_back(LI);
  1327. }
  1328. }
  1329. // Only compute DT if we have any loads to examine.
  1330. bool MadeChange = false;
  1331. if (!Loads.empty()) {
  1332. auto &DT = LookupDomTree(*const_cast<Function *>(F));
  1333. for (auto *LI : Loads) {
  1334. if (DT.dominates(StoredOnceStore, LI)) {
  1335. LI->replaceAllUsesWith(const_cast<Value *>(StoredOnceValue));
  1336. LI->eraseFromParent();
  1337. MadeChange = true;
  1338. }
  1339. }
  1340. }
  1341. return MadeChange;
  1342. }
  1343. /// Analyze the specified global variable and optimize
  1344. /// it if possible. If we make a change, return true.
  1345. static bool
  1346. processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS,
  1347. function_ref<TargetTransformInfo &(Function &)> GetTTI,
  1348. function_ref<TargetLibraryInfo &(Function &)> GetTLI,
  1349. function_ref<DominatorTree &(Function &)> LookupDomTree) {
  1350. auto &DL = GV->getParent()->getDataLayout();
  1351. // If this is a first class global and has only one accessing function and
  1352. // this function is non-recursive, we replace the global with a local alloca
  1353. // in this function.
  1354. //
  1355. // NOTE: It doesn't make sense to promote non-single-value types since we
  1356. // are just replacing static memory to stack memory.
  1357. //
  1358. // If the global is in different address space, don't bring it to stack.
  1359. if (!GS.HasMultipleAccessingFunctions &&
  1360. GS.AccessingFunction &&
  1361. GV->getValueType()->isSingleValueType() &&
  1362. GV->getType()->getAddressSpace() == 0 &&
  1363. !GV->isExternallyInitialized() &&
  1364. allNonInstructionUsersCanBeMadeInstructions(GV) &&
  1365. GS.AccessingFunction->doesNotRecurse() &&
  1366. isPointerValueDeadOnEntryToFunction(GS.AccessingFunction, GV,
  1367. LookupDomTree)) {
  1368. const DataLayout &DL = GV->getParent()->getDataLayout();
  1369. LLVM_DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV << "\n");
  1370. Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
  1371. ->getEntryBlock().begin());
  1372. Type *ElemTy = GV->getValueType();
  1373. // FIXME: Pass Global's alignment when globals have alignment
  1374. AllocaInst *Alloca = new AllocaInst(ElemTy, DL.getAllocaAddrSpace(), nullptr,
  1375. GV->getName(), &FirstI);
  1376. if (!isa<UndefValue>(GV->getInitializer()))
  1377. new StoreInst(GV->getInitializer(), Alloca, &FirstI);
  1378. makeAllConstantUsesInstructions(GV);
  1379. GV->replaceAllUsesWith(Alloca);
  1380. GV->eraseFromParent();
  1381. ++NumLocalized;
  1382. return true;
  1383. }
  1384. bool Changed = false;
  1385. // If the global is never loaded (but may be stored to), it is dead.
  1386. // Delete it now.
  1387. if (!GS.IsLoaded) {
  1388. LLVM_DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV << "\n");
  1389. if (isLeakCheckerRoot(GV)) {
  1390. // Delete any constant stores to the global.
  1391. Changed = CleanupPointerRootUsers(GV, GetTLI);
  1392. } else {
  1393. // Delete any stores we can find to the global. We may not be able to
  1394. // make it completely dead though.
  1395. Changed = CleanupConstantGlobalUsers(GV, DL);
  1396. }
  1397. // If the global is dead now, delete it.
  1398. if (GV->use_empty()) {
  1399. GV->eraseFromParent();
  1400. ++NumDeleted;
  1401. Changed = true;
  1402. }
  1403. return Changed;
  1404. }
  1405. if (GS.StoredType <= GlobalStatus::InitializerStored) {
  1406. LLVM_DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
  1407. // Don't actually mark a global constant if it's atomic because atomic loads
  1408. // are implemented by a trivial cmpxchg in some edge-cases and that usually
  1409. // requires write access to the variable even if it's not actually changed.
  1410. if (GS.Ordering == AtomicOrdering::NotAtomic) {
  1411. assert(!GV->isConstant() && "Expected a non-constant global");
  1412. GV->setConstant(true);
  1413. Changed = true;
  1414. }
  1415. // Clean up any obviously simplifiable users now.
  1416. Changed |= CleanupConstantGlobalUsers(GV, DL);
  1417. // If the global is dead now, just nuke it.
  1418. if (GV->use_empty()) {
  1419. LLVM_DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
  1420. << "all users and delete global!\n");
  1421. GV->eraseFromParent();
  1422. ++NumDeleted;
  1423. return true;
  1424. }
  1425. // Fall through to the next check; see if we can optimize further.
  1426. ++NumMarked;
  1427. }
  1428. if (!GV->getInitializer()->getType()->isSingleValueType()) {
  1429. const DataLayout &DL = GV->getParent()->getDataLayout();
  1430. if (SRAGlobal(GV, DL))
  1431. return true;
  1432. }
  1433. Value *StoredOnceValue = GS.getStoredOnceValue();
  1434. if (GS.StoredType == GlobalStatus::StoredOnce && StoredOnceValue) {
  1435. Function &StoreFn =
  1436. const_cast<Function &>(*GS.StoredOnceStore->getFunction());
  1437. bool CanHaveNonUndefGlobalInitializer =
  1438. GetTTI(StoreFn).canHaveNonUndefGlobalInitializerInAddressSpace(
  1439. GV->getType()->getAddressSpace());
  1440. // If the initial value for the global was an undef value, and if only
  1441. // one other value was stored into it, we can just change the
  1442. // initializer to be the stored value, then delete all stores to the
  1443. // global. This allows us to mark it constant.
  1444. // This is restricted to address spaces that allow globals to have
  1445. // initializers. NVPTX, for example, does not support initializers for
  1446. // shared memory (AS 3).
  1447. auto *SOVConstant = dyn_cast<Constant>(StoredOnceValue);
  1448. if (SOVConstant && isa<UndefValue>(GV->getInitializer()) &&
  1449. DL.getTypeAllocSize(SOVConstant->getType()) ==
  1450. DL.getTypeAllocSize(GV->getValueType()) &&
  1451. CanHaveNonUndefGlobalInitializer) {
  1452. if (SOVConstant->getType() == GV->getValueType()) {
  1453. // Change the initializer in place.
  1454. GV->setInitializer(SOVConstant);
  1455. } else {
  1456. // Create a new global with adjusted type.
  1457. auto *NGV = new GlobalVariable(
  1458. *GV->getParent(), SOVConstant->getType(), GV->isConstant(),
  1459. GV->getLinkage(), SOVConstant, "", GV, GV->getThreadLocalMode(),
  1460. GV->getAddressSpace());
  1461. NGV->takeName(GV);
  1462. NGV->copyAttributesFrom(GV);
  1463. GV->replaceAllUsesWith(ConstantExpr::getBitCast(NGV, GV->getType()));
  1464. GV->eraseFromParent();
  1465. GV = NGV;
  1466. }
  1467. // Clean up any obviously simplifiable users now.
  1468. CleanupConstantGlobalUsers(GV, DL);
  1469. if (GV->use_empty()) {
  1470. LLVM_DEBUG(dbgs() << " *** Substituting initializer allowed us to "
  1471. << "simplify all users and delete global!\n");
  1472. GV->eraseFromParent();
  1473. ++NumDeleted;
  1474. }
  1475. ++NumSubstitute;
  1476. return true;
  1477. }
  1478. // Try to optimize globals based on the knowledge that only one value
  1479. // (besides its initializer) is ever stored to the global.
  1480. if (optimizeOnceStoredGlobal(GV, StoredOnceValue, DL, GetTLI))
  1481. return true;
  1482. // Try to forward the store to any loads. If we have more than one store, we
  1483. // may have a store of the initializer between StoredOnceStore and a load.
  1484. if (GS.NumStores == 1)
  1485. if (forwardStoredOnceStore(GV, GS.StoredOnceStore, LookupDomTree))
  1486. return true;
  1487. // Otherwise, if the global was not a boolean, we can shrink it to be a
  1488. // boolean. Skip this optimization for AS that doesn't allow an initializer.
  1489. if (SOVConstant && GS.Ordering == AtomicOrdering::NotAtomic &&
  1490. (!isa<UndefValue>(GV->getInitializer()) ||
  1491. CanHaveNonUndefGlobalInitializer)) {
  1492. if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
  1493. ++NumShrunkToBool;
  1494. return true;
  1495. }
  1496. }
  1497. }
  1498. return Changed;
  1499. }
  1500. /// Analyze the specified global variable and optimize it if possible. If we
  1501. /// make a change, return true.
  1502. static bool
  1503. processGlobal(GlobalValue &GV,
  1504. function_ref<TargetTransformInfo &(Function &)> GetTTI,
  1505. function_ref<TargetLibraryInfo &(Function &)> GetTLI,
  1506. function_ref<DominatorTree &(Function &)> LookupDomTree) {
  1507. if (GV.getName().startswith("llvm."))
  1508. return false;
  1509. GlobalStatus GS;
  1510. if (GlobalStatus::analyzeGlobal(&GV, GS))
  1511. return false;
  1512. bool Changed = false;
  1513. if (!GS.IsCompared && !GV.hasGlobalUnnamedAddr()) {
  1514. auto NewUnnamedAddr = GV.hasLocalLinkage() ? GlobalValue::UnnamedAddr::Global
  1515. : GlobalValue::UnnamedAddr::Local;
  1516. if (NewUnnamedAddr != GV.getUnnamedAddr()) {
  1517. GV.setUnnamedAddr(NewUnnamedAddr);
  1518. NumUnnamed++;
  1519. Changed = true;
  1520. }
  1521. }
  1522. // Do more involved optimizations if the global is internal.
  1523. if (!GV.hasLocalLinkage())
  1524. return Changed;
  1525. auto *GVar = dyn_cast<GlobalVariable>(&GV);
  1526. if (!GVar)
  1527. return Changed;
  1528. if (GVar->isConstant() || !GVar->hasInitializer())
  1529. return Changed;
  1530. return processInternalGlobal(GVar, GS, GetTTI, GetTLI, LookupDomTree) ||
  1531. Changed;
  1532. }
  1533. /// Walk all of the direct calls of the specified function, changing them to
  1534. /// FastCC.
  1535. static void ChangeCalleesToFastCall(Function *F) {
  1536. for (User *U : F->users()) {
  1537. if (isa<BlockAddress>(U))
  1538. continue;
  1539. cast<CallBase>(U)->setCallingConv(CallingConv::Fast);
  1540. }
  1541. }
  1542. static AttributeList StripAttr(LLVMContext &C, AttributeList Attrs,
  1543. Attribute::AttrKind A) {
  1544. unsigned AttrIndex;
  1545. if (Attrs.hasAttrSomewhere(A, &AttrIndex))
  1546. return Attrs.removeAttributeAtIndex(C, AttrIndex, A);
  1547. return Attrs;
  1548. }
  1549. static void RemoveAttribute(Function *F, Attribute::AttrKind A) {
  1550. F->setAttributes(StripAttr(F->getContext(), F->getAttributes(), A));
  1551. for (User *U : F->users()) {
  1552. if (isa<BlockAddress>(U))
  1553. continue;
  1554. CallBase *CB = cast<CallBase>(U);
  1555. CB->setAttributes(StripAttr(F->getContext(), CB->getAttributes(), A));
  1556. }
  1557. }
  1558. /// Return true if this is a calling convention that we'd like to change. The
  1559. /// idea here is that we don't want to mess with the convention if the user
  1560. /// explicitly requested something with performance implications like coldcc,
  1561. /// GHC, or anyregcc.
  1562. static bool hasChangeableCC(Function *F) {
  1563. CallingConv::ID CC = F->getCallingConv();
  1564. // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
  1565. if (CC != CallingConv::C && CC != CallingConv::X86_ThisCall)
  1566. return false;
  1567. // FIXME: Change CC for the whole chain of musttail calls when possible.
  1568. //
  1569. // Can't change CC of the function that either has musttail calls, or is a
  1570. // musttail callee itself
  1571. for (User *U : F->users()) {
  1572. if (isa<BlockAddress>(U))
  1573. continue;
  1574. CallInst* CI = dyn_cast<CallInst>(U);
  1575. if (!CI)
  1576. continue;
  1577. if (CI->isMustTailCall())
  1578. return false;
  1579. }
  1580. for (BasicBlock &BB : *F)
  1581. if (BB.getTerminatingMustTailCall())
  1582. return false;
  1583. return true;
  1584. }
  1585. /// Return true if the block containing the call site has a BlockFrequency of
  1586. /// less than ColdCCRelFreq% of the entry block.
  1587. static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI) {
  1588. const BranchProbability ColdProb(ColdCCRelFreq, 100);
  1589. auto *CallSiteBB = CB.getParent();
  1590. auto CallSiteFreq = CallerBFI.getBlockFreq(CallSiteBB);
  1591. auto CallerEntryFreq =
  1592. CallerBFI.getBlockFreq(&(CB.getCaller()->getEntryBlock()));
  1593. return CallSiteFreq < CallerEntryFreq * ColdProb;
  1594. }
  1595. // This function checks if the input function F is cold at all call sites. It
  1596. // also looks each call site's containing function, returning false if the
  1597. // caller function contains other non cold calls. The input vector AllCallsCold
  1598. // contains a list of functions that only have call sites in cold blocks.
  1599. static bool
  1600. isValidCandidateForColdCC(Function &F,
  1601. function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
  1602. const std::vector<Function *> &AllCallsCold) {
  1603. if (F.user_empty())
  1604. return false;
  1605. for (User *U : F.users()) {
  1606. if (isa<BlockAddress>(U))
  1607. continue;
  1608. CallBase &CB = cast<CallBase>(*U);
  1609. Function *CallerFunc = CB.getParent()->getParent();
  1610. BlockFrequencyInfo &CallerBFI = GetBFI(*CallerFunc);
  1611. if (!isColdCallSite(CB, CallerBFI))
  1612. return false;
  1613. if (!llvm::is_contained(AllCallsCold, CallerFunc))
  1614. return false;
  1615. }
  1616. return true;
  1617. }
  1618. static void changeCallSitesToColdCC(Function *F) {
  1619. for (User *U : F->users()) {
  1620. if (isa<BlockAddress>(U))
  1621. continue;
  1622. cast<CallBase>(U)->setCallingConv(CallingConv::Cold);
  1623. }
  1624. }
  1625. // This function iterates over all the call instructions in the input Function
  1626. // and checks that all call sites are in cold blocks and are allowed to use the
  1627. // coldcc calling convention.
  1628. static bool
  1629. hasOnlyColdCalls(Function &F,
  1630. function_ref<BlockFrequencyInfo &(Function &)> GetBFI) {
  1631. for (BasicBlock &BB : F) {
  1632. for (Instruction &I : BB) {
  1633. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  1634. // Skip over isline asm instructions since they aren't function calls.
  1635. if (CI->isInlineAsm())
  1636. continue;
  1637. Function *CalledFn = CI->getCalledFunction();
  1638. if (!CalledFn)
  1639. return false;
  1640. // Skip over intrinsics since they won't remain as function calls.
  1641. // Important to do this check before the linkage check below so we
  1642. // won't bail out on debug intrinsics, possibly making the generated
  1643. // code dependent on the presence of debug info.
  1644. if (CalledFn->getIntrinsicID() != Intrinsic::not_intrinsic)
  1645. continue;
  1646. if (!CalledFn->hasLocalLinkage())
  1647. return false;
  1648. // Check if it's valid to use coldcc calling convention.
  1649. if (!hasChangeableCC(CalledFn) || CalledFn->isVarArg() ||
  1650. CalledFn->hasAddressTaken())
  1651. return false;
  1652. BlockFrequencyInfo &CallerBFI = GetBFI(F);
  1653. if (!isColdCallSite(*CI, CallerBFI))
  1654. return false;
  1655. }
  1656. }
  1657. }
  1658. return true;
  1659. }
  1660. static bool hasMustTailCallers(Function *F) {
  1661. for (User *U : F->users()) {
  1662. CallBase *CB = dyn_cast<CallBase>(U);
  1663. if (!CB) {
  1664. assert(isa<BlockAddress>(U) &&
  1665. "Expected either CallBase or BlockAddress");
  1666. continue;
  1667. }
  1668. if (CB->isMustTailCall())
  1669. return true;
  1670. }
  1671. return false;
  1672. }
  1673. static bool hasInvokeCallers(Function *F) {
  1674. for (User *U : F->users())
  1675. if (isa<InvokeInst>(U))
  1676. return true;
  1677. return false;
  1678. }
  1679. static void RemovePreallocated(Function *F) {
  1680. RemoveAttribute(F, Attribute::Preallocated);
  1681. auto *M = F->getParent();
  1682. IRBuilder<> Builder(M->getContext());
  1683. // Cannot modify users() while iterating over it, so make a copy.
  1684. SmallVector<User *, 4> PreallocatedCalls(F->users());
  1685. for (User *U : PreallocatedCalls) {
  1686. CallBase *CB = dyn_cast<CallBase>(U);
  1687. if (!CB)
  1688. continue;
  1689. assert(
  1690. !CB->isMustTailCall() &&
  1691. "Shouldn't call RemotePreallocated() on a musttail preallocated call");
  1692. // Create copy of call without "preallocated" operand bundle.
  1693. SmallVector<OperandBundleDef, 1> OpBundles;
  1694. CB->getOperandBundlesAsDefs(OpBundles);
  1695. CallBase *PreallocatedSetup = nullptr;
  1696. for (auto *It = OpBundles.begin(); It != OpBundles.end(); ++It) {
  1697. if (It->getTag() == "preallocated") {
  1698. PreallocatedSetup = cast<CallBase>(*It->input_begin());
  1699. OpBundles.erase(It);
  1700. break;
  1701. }
  1702. }
  1703. assert(PreallocatedSetup && "Did not find preallocated bundle");
  1704. uint64_t ArgCount =
  1705. cast<ConstantInt>(PreallocatedSetup->getArgOperand(0))->getZExtValue();
  1706. assert((isa<CallInst>(CB) || isa<InvokeInst>(CB)) &&
  1707. "Unknown indirect call type");
  1708. CallBase *NewCB = CallBase::Create(CB, OpBundles, CB);
  1709. CB->replaceAllUsesWith(NewCB);
  1710. NewCB->takeName(CB);
  1711. CB->eraseFromParent();
  1712. Builder.SetInsertPoint(PreallocatedSetup);
  1713. auto *StackSave =
  1714. Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stacksave));
  1715. Builder.SetInsertPoint(NewCB->getNextNonDebugInstruction());
  1716. Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackrestore),
  1717. StackSave);
  1718. // Replace @llvm.call.preallocated.arg() with alloca.
  1719. // Cannot modify users() while iterating over it, so make a copy.
  1720. // @llvm.call.preallocated.arg() can be called with the same index multiple
  1721. // times. So for each @llvm.call.preallocated.arg(), we see if we have
  1722. // already created a Value* for the index, and if not, create an alloca and
  1723. // bitcast right after the @llvm.call.preallocated.setup() so that it
  1724. // dominates all uses.
  1725. SmallVector<Value *, 2> ArgAllocas(ArgCount);
  1726. SmallVector<User *, 2> PreallocatedArgs(PreallocatedSetup->users());
  1727. for (auto *User : PreallocatedArgs) {
  1728. auto *UseCall = cast<CallBase>(User);
  1729. assert(UseCall->getCalledFunction()->getIntrinsicID() ==
  1730. Intrinsic::call_preallocated_arg &&
  1731. "preallocated token use was not a llvm.call.preallocated.arg");
  1732. uint64_t AllocArgIndex =
  1733. cast<ConstantInt>(UseCall->getArgOperand(1))->getZExtValue();
  1734. Value *AllocaReplacement = ArgAllocas[AllocArgIndex];
  1735. if (!AllocaReplacement) {
  1736. auto AddressSpace = UseCall->getType()->getPointerAddressSpace();
  1737. auto *ArgType =
  1738. UseCall->getFnAttr(Attribute::Preallocated).getValueAsType();
  1739. auto *InsertBefore = PreallocatedSetup->getNextNonDebugInstruction();
  1740. Builder.SetInsertPoint(InsertBefore);
  1741. auto *Alloca =
  1742. Builder.CreateAlloca(ArgType, AddressSpace, nullptr, "paarg");
  1743. auto *BitCast = Builder.CreateBitCast(
  1744. Alloca, Type::getInt8PtrTy(M->getContext()), UseCall->getName());
  1745. ArgAllocas[AllocArgIndex] = BitCast;
  1746. AllocaReplacement = BitCast;
  1747. }
  1748. UseCall->replaceAllUsesWith(AllocaReplacement);
  1749. UseCall->eraseFromParent();
  1750. }
  1751. // Remove @llvm.call.preallocated.setup().
  1752. cast<Instruction>(PreallocatedSetup)->eraseFromParent();
  1753. }
  1754. }
  1755. static bool
  1756. OptimizeFunctions(Module &M,
  1757. function_ref<TargetLibraryInfo &(Function &)> GetTLI,
  1758. function_ref<TargetTransformInfo &(Function &)> GetTTI,
  1759. function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
  1760. function_ref<DominatorTree &(Function &)> LookupDomTree,
  1761. SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats,
  1762. function_ref<void(Function &F)> ChangedCFGCallback,
  1763. function_ref<void(Function &F)> DeleteFnCallback) {
  1764. bool Changed = false;
  1765. std::vector<Function *> AllCallsCold;
  1766. for (Function &F : llvm::make_early_inc_range(M))
  1767. if (hasOnlyColdCalls(F, GetBFI))
  1768. AllCallsCold.push_back(&F);
  1769. // Optimize functions.
  1770. for (Function &F : llvm::make_early_inc_range(M)) {
  1771. // Don't perform global opt pass on naked functions; we don't want fast
  1772. // calling conventions for naked functions.
  1773. if (F.hasFnAttribute(Attribute::Naked))
  1774. continue;
  1775. // Functions without names cannot be referenced outside this module.
  1776. if (!F.hasName() && !F.isDeclaration() && !F.hasLocalLinkage())
  1777. F.setLinkage(GlobalValue::InternalLinkage);
  1778. if (deleteIfDead(F, NotDiscardableComdats, DeleteFnCallback)) {
  1779. Changed = true;
  1780. continue;
  1781. }
  1782. // LLVM's definition of dominance allows instructions that are cyclic
  1783. // in unreachable blocks, e.g.:
  1784. // %pat = select i1 %condition, @global, i16* %pat
  1785. // because any instruction dominates an instruction in a block that's
  1786. // not reachable from entry.
  1787. // So, remove unreachable blocks from the function, because a) there's
  1788. // no point in analyzing them and b) GlobalOpt should otherwise grow
  1789. // some more complicated logic to break these cycles.
  1790. // Notify the analysis manager that we've modified the function's CFG.
  1791. if (!F.isDeclaration()) {
  1792. if (removeUnreachableBlocks(F)) {
  1793. Changed = true;
  1794. ChangedCFGCallback(F);
  1795. }
  1796. }
  1797. Changed |= processGlobal(F, GetTTI, GetTLI, LookupDomTree);
  1798. if (!F.hasLocalLinkage())
  1799. continue;
  1800. // If we have an inalloca parameter that we can safely remove the
  1801. // inalloca attribute from, do so. This unlocks optimizations that
  1802. // wouldn't be safe in the presence of inalloca.
  1803. // FIXME: We should also hoist alloca affected by this to the entry
  1804. // block if possible.
  1805. if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) &&
  1806. !F.hasAddressTaken() && !hasMustTailCallers(&F) && !F.isVarArg()) {
  1807. RemoveAttribute(&F, Attribute::InAlloca);
  1808. Changed = true;
  1809. }
  1810. // FIXME: handle invokes
  1811. // FIXME: handle musttail
  1812. if (F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) {
  1813. if (!F.hasAddressTaken() && !hasMustTailCallers(&F) &&
  1814. !hasInvokeCallers(&F)) {
  1815. RemovePreallocated(&F);
  1816. Changed = true;
  1817. }
  1818. continue;
  1819. }
  1820. if (hasChangeableCC(&F) && !F.isVarArg() && !F.hasAddressTaken()) {
  1821. NumInternalFunc++;
  1822. TargetTransformInfo &TTI = GetTTI(F);
  1823. // Change the calling convention to coldcc if either stress testing is
  1824. // enabled or the target would like to use coldcc on functions which are
  1825. // cold at all call sites and the callers contain no other non coldcc
  1826. // calls.
  1827. if (EnableColdCCStressTest ||
  1828. (TTI.useColdCCForColdCall(F) &&
  1829. isValidCandidateForColdCC(F, GetBFI, AllCallsCold))) {
  1830. F.setCallingConv(CallingConv::Cold);
  1831. changeCallSitesToColdCC(&F);
  1832. Changed = true;
  1833. NumColdCC++;
  1834. }
  1835. }
  1836. if (hasChangeableCC(&F) && !F.isVarArg() && !F.hasAddressTaken()) {
  1837. // If this function has a calling convention worth changing, is not a
  1838. // varargs function, and is only called directly, promote it to use the
  1839. // Fast calling convention.
  1840. F.setCallingConv(CallingConv::Fast);
  1841. ChangeCalleesToFastCall(&F);
  1842. ++NumFastCallFns;
  1843. Changed = true;
  1844. }
  1845. if (F.getAttributes().hasAttrSomewhere(Attribute::Nest) &&
  1846. !F.hasAddressTaken()) {
  1847. // The function is not used by a trampoline intrinsic, so it is safe
  1848. // to remove the 'nest' attribute.
  1849. RemoveAttribute(&F, Attribute::Nest);
  1850. ++NumNestRemoved;
  1851. Changed = true;
  1852. }
  1853. }
  1854. return Changed;
  1855. }
  1856. static bool
  1857. OptimizeGlobalVars(Module &M,
  1858. function_ref<TargetTransformInfo &(Function &)> GetTTI,
  1859. function_ref<TargetLibraryInfo &(Function &)> GetTLI,
  1860. function_ref<DominatorTree &(Function &)> LookupDomTree,
  1861. SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
  1862. bool Changed = false;
  1863. for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
  1864. // Global variables without names cannot be referenced outside this module.
  1865. if (!GV.hasName() && !GV.isDeclaration() && !GV.hasLocalLinkage())
  1866. GV.setLinkage(GlobalValue::InternalLinkage);
  1867. // Simplify the initializer.
  1868. if (GV.hasInitializer())
  1869. if (auto *C = dyn_cast<Constant>(GV.getInitializer())) {
  1870. auto &DL = M.getDataLayout();
  1871. // TLI is not used in the case of a Constant, so use default nullptr
  1872. // for that optional parameter, since we don't have a Function to
  1873. // provide GetTLI anyway.
  1874. Constant *New = ConstantFoldConstant(C, DL, /*TLI*/ nullptr);
  1875. if (New != C)
  1876. GV.setInitializer(New);
  1877. }
  1878. if (deleteIfDead(GV, NotDiscardableComdats)) {
  1879. Changed = true;
  1880. continue;
  1881. }
  1882. Changed |= processGlobal(GV, GetTTI, GetTLI, LookupDomTree);
  1883. }
  1884. return Changed;
  1885. }
  1886. /// Evaluate static constructors in the function, if we can. Return true if we
  1887. /// can, false otherwise.
  1888. static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL,
  1889. TargetLibraryInfo *TLI) {
  1890. // Skip external functions.
  1891. if (F->isDeclaration())
  1892. return false;
  1893. // Call the function.
  1894. Evaluator Eval(DL, TLI);
  1895. Constant *RetValDummy;
  1896. bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
  1897. SmallVector<Constant*, 0>());
  1898. if (EvalSuccess) {
  1899. ++NumCtorsEvaluated;
  1900. // We succeeded at evaluation: commit the result.
  1901. auto NewInitializers = Eval.getMutatedInitializers();
  1902. LLVM_DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
  1903. << F->getName() << "' to " << NewInitializers.size()
  1904. << " stores.\n");
  1905. for (const auto &Pair : NewInitializers)
  1906. Pair.first->setInitializer(Pair.second);
  1907. for (GlobalVariable *GV : Eval.getInvariants())
  1908. GV->setConstant(true);
  1909. }
  1910. return EvalSuccess;
  1911. }
  1912. static int compareNames(Constant *const *A, Constant *const *B) {
  1913. Value *AStripped = (*A)->stripPointerCasts();
  1914. Value *BStripped = (*B)->stripPointerCasts();
  1915. return AStripped->getName().compare(BStripped->getName());
  1916. }
  1917. static void setUsedInitializer(GlobalVariable &V,
  1918. const SmallPtrSetImpl<GlobalValue *> &Init) {
  1919. if (Init.empty()) {
  1920. V.eraseFromParent();
  1921. return;
  1922. }
  1923. // Type of pointer to the array of pointers.
  1924. PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
  1925. SmallVector<Constant *, 8> UsedArray;
  1926. for (GlobalValue *GV : Init) {
  1927. Constant *Cast
  1928. = ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy);
  1929. UsedArray.push_back(Cast);
  1930. }
  1931. // Sort to get deterministic order.
  1932. array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
  1933. ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
  1934. Module *M = V.getParent();
  1935. V.removeFromParent();
  1936. GlobalVariable *NV =
  1937. new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
  1938. ConstantArray::get(ATy, UsedArray), "");
  1939. NV->takeName(&V);
  1940. NV->setSection("llvm.metadata");
  1941. delete &V;
  1942. }
  1943. namespace {
  1944. /// An easy to access representation of llvm.used and llvm.compiler.used.
  1945. class LLVMUsed {
  1946. SmallPtrSet<GlobalValue *, 4> Used;
  1947. SmallPtrSet<GlobalValue *, 4> CompilerUsed;
  1948. GlobalVariable *UsedV;
  1949. GlobalVariable *CompilerUsedV;
  1950. public:
  1951. LLVMUsed(Module &M) {
  1952. SmallVector<GlobalValue *, 4> Vec;
  1953. UsedV = collectUsedGlobalVariables(M, Vec, false);
  1954. Used = {Vec.begin(), Vec.end()};
  1955. Vec.clear();
  1956. CompilerUsedV = collectUsedGlobalVariables(M, Vec, true);
  1957. CompilerUsed = {Vec.begin(), Vec.end()};
  1958. }
  1959. using iterator = SmallPtrSet<GlobalValue *, 4>::iterator;
  1960. using used_iterator_range = iterator_range<iterator>;
  1961. iterator usedBegin() { return Used.begin(); }
  1962. iterator usedEnd() { return Used.end(); }
  1963. used_iterator_range used() {
  1964. return used_iterator_range(usedBegin(), usedEnd());
  1965. }
  1966. iterator compilerUsedBegin() { return CompilerUsed.begin(); }
  1967. iterator compilerUsedEnd() { return CompilerUsed.end(); }
  1968. used_iterator_range compilerUsed() {
  1969. return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
  1970. }
  1971. bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
  1972. bool compilerUsedCount(GlobalValue *GV) const {
  1973. return CompilerUsed.count(GV);
  1974. }
  1975. bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
  1976. bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
  1977. bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; }
  1978. bool compilerUsedInsert(GlobalValue *GV) {
  1979. return CompilerUsed.insert(GV).second;
  1980. }
  1981. void syncVariablesAndSets() {
  1982. if (UsedV)
  1983. setUsedInitializer(*UsedV, Used);
  1984. if (CompilerUsedV)
  1985. setUsedInitializer(*CompilerUsedV, CompilerUsed);
  1986. }
  1987. };
  1988. } // end anonymous namespace
  1989. static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
  1990. if (GA.use_empty()) // No use at all.
  1991. return false;
  1992. assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
  1993. "We should have removed the duplicated "
  1994. "element from llvm.compiler.used");
  1995. if (!GA.hasOneUse())
  1996. // Strictly more than one use. So at least one is not in llvm.used and
  1997. // llvm.compiler.used.
  1998. return true;
  1999. // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
  2000. return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
  2001. }
  2002. static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
  2003. const LLVMUsed &U) {
  2004. unsigned N = 2;
  2005. assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
  2006. "We should have removed the duplicated "
  2007. "element from llvm.compiler.used");
  2008. if (U.usedCount(&V) || U.compilerUsedCount(&V))
  2009. ++N;
  2010. return V.hasNUsesOrMore(N);
  2011. }
  2012. static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
  2013. if (!GA.hasLocalLinkage())
  2014. return true;
  2015. return U.usedCount(&GA) || U.compilerUsedCount(&GA);
  2016. }
  2017. static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U,
  2018. bool &RenameTarget) {
  2019. RenameTarget = false;
  2020. bool Ret = false;
  2021. if (hasUseOtherThanLLVMUsed(GA, U))
  2022. Ret = true;
  2023. // If the alias is externally visible, we may still be able to simplify it.
  2024. if (!mayHaveOtherReferences(GA, U))
  2025. return Ret;
  2026. // If the aliasee has internal linkage, give it the name and linkage
  2027. // of the alias, and delete the alias. This turns:
  2028. // define internal ... @f(...)
  2029. // @a = alias ... @f
  2030. // into:
  2031. // define ... @a(...)
  2032. Constant *Aliasee = GA.getAliasee();
  2033. GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
  2034. if (!Target->hasLocalLinkage())
  2035. return Ret;
  2036. // Do not perform the transform if multiple aliases potentially target the
  2037. // aliasee. This check also ensures that it is safe to replace the section
  2038. // and other attributes of the aliasee with those of the alias.
  2039. if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
  2040. return Ret;
  2041. RenameTarget = true;
  2042. return true;
  2043. }
  2044. static bool
  2045. OptimizeGlobalAliases(Module &M,
  2046. SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
  2047. bool Changed = false;
  2048. LLVMUsed Used(M);
  2049. for (GlobalValue *GV : Used.used())
  2050. Used.compilerUsedErase(GV);
  2051. // Return whether GV is explicitly or implicitly dso_local and not replaceable
  2052. // by another definition in the current linkage unit.
  2053. auto IsModuleLocal = [](GlobalValue &GV) {
  2054. return !GlobalValue::isInterposableLinkage(GV.getLinkage()) &&
  2055. (GV.isDSOLocal() || GV.isImplicitDSOLocal());
  2056. };
  2057. for (GlobalAlias &J : llvm::make_early_inc_range(M.aliases())) {
  2058. // Aliases without names cannot be referenced outside this module.
  2059. if (!J.hasName() && !J.isDeclaration() && !J.hasLocalLinkage())
  2060. J.setLinkage(GlobalValue::InternalLinkage);
  2061. if (deleteIfDead(J, NotDiscardableComdats)) {
  2062. Changed = true;
  2063. continue;
  2064. }
  2065. // If the alias can change at link time, nothing can be done - bail out.
  2066. if (!IsModuleLocal(J))
  2067. continue;
  2068. Constant *Aliasee = J.getAliasee();
  2069. GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts());
  2070. // We can't trivially replace the alias with the aliasee if the aliasee is
  2071. // non-trivial in some way. We also can't replace the alias with the aliasee
  2072. // if the aliasee may be preemptible at runtime. On ELF, a non-preemptible
  2073. // alias can be used to access the definition as if preemption did not
  2074. // happen.
  2075. // TODO: Try to handle non-zero GEPs of local aliasees.
  2076. if (!Target || !IsModuleLocal(*Target))
  2077. continue;
  2078. Target->removeDeadConstantUsers();
  2079. // Make all users of the alias use the aliasee instead.
  2080. bool RenameTarget;
  2081. if (!hasUsesToReplace(J, Used, RenameTarget))
  2082. continue;
  2083. J.replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J.getType()));
  2084. ++NumAliasesResolved;
  2085. Changed = true;
  2086. if (RenameTarget) {
  2087. // Give the aliasee the name, linkage and other attributes of the alias.
  2088. Target->takeName(&J);
  2089. Target->setLinkage(J.getLinkage());
  2090. Target->setDSOLocal(J.isDSOLocal());
  2091. Target->setVisibility(J.getVisibility());
  2092. Target->setDLLStorageClass(J.getDLLStorageClass());
  2093. if (Used.usedErase(&J))
  2094. Used.usedInsert(Target);
  2095. if (Used.compilerUsedErase(&J))
  2096. Used.compilerUsedInsert(Target);
  2097. } else if (mayHaveOtherReferences(J, Used))
  2098. continue;
  2099. // Delete the alias.
  2100. M.getAliasList().erase(&J);
  2101. ++NumAliasesRemoved;
  2102. Changed = true;
  2103. }
  2104. Used.syncVariablesAndSets();
  2105. return Changed;
  2106. }
  2107. static Function *
  2108. FindCXAAtExit(Module &M, function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
  2109. // Hack to get a default TLI before we have actual Function.
  2110. auto FuncIter = M.begin();
  2111. if (FuncIter == M.end())
  2112. return nullptr;
  2113. auto *TLI = &GetTLI(*FuncIter);
  2114. LibFunc F = LibFunc_cxa_atexit;
  2115. if (!TLI->has(F))
  2116. return nullptr;
  2117. Function *Fn = M.getFunction(TLI->getName(F));
  2118. if (!Fn)
  2119. return nullptr;
  2120. // Now get the actual TLI for Fn.
  2121. TLI = &GetTLI(*Fn);
  2122. // Make sure that the function has the correct prototype.
  2123. if (!TLI->getLibFunc(*Fn, F) || F != LibFunc_cxa_atexit)
  2124. return nullptr;
  2125. return Fn;
  2126. }
  2127. /// Returns whether the given function is an empty C++ destructor and can
  2128. /// therefore be eliminated.
  2129. /// Note that we assume that other optimization passes have already simplified
  2130. /// the code so we simply check for 'ret'.
  2131. static bool cxxDtorIsEmpty(const Function &Fn) {
  2132. // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
  2133. // nounwind, but that doesn't seem worth doing.
  2134. if (Fn.isDeclaration())
  2135. return false;
  2136. for (const auto &I : Fn.getEntryBlock()) {
  2137. if (I.isDebugOrPseudoInst())
  2138. continue;
  2139. if (isa<ReturnInst>(I))
  2140. return true;
  2141. break;
  2142. }
  2143. return false;
  2144. }
  2145. static bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
  2146. /// Itanium C++ ABI p3.3.5:
  2147. ///
  2148. /// After constructing a global (or local static) object, that will require
  2149. /// destruction on exit, a termination function is registered as follows:
  2150. ///
  2151. /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
  2152. ///
  2153. /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
  2154. /// call f(p) when DSO d is unloaded, before all such termination calls
  2155. /// registered before this one. It returns zero if registration is
  2156. /// successful, nonzero on failure.
  2157. // This pass will look for calls to __cxa_atexit where the function is trivial
  2158. // and remove them.
  2159. bool Changed = false;
  2160. for (User *U : llvm::make_early_inc_range(CXAAtExitFn->users())) {
  2161. // We're only interested in calls. Theoretically, we could handle invoke
  2162. // instructions as well, but neither llvm-gcc nor clang generate invokes
  2163. // to __cxa_atexit.
  2164. CallInst *CI = dyn_cast<CallInst>(U);
  2165. if (!CI)
  2166. continue;
  2167. Function *DtorFn =
  2168. dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
  2169. if (!DtorFn || !cxxDtorIsEmpty(*DtorFn))
  2170. continue;
  2171. // Just remove the call.
  2172. CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
  2173. CI->eraseFromParent();
  2174. ++NumCXXDtorsRemoved;
  2175. Changed |= true;
  2176. }
  2177. return Changed;
  2178. }
  2179. static bool
  2180. optimizeGlobalsInModule(Module &M, const DataLayout &DL,
  2181. function_ref<TargetLibraryInfo &(Function &)> GetTLI,
  2182. function_ref<TargetTransformInfo &(Function &)> GetTTI,
  2183. function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
  2184. function_ref<DominatorTree &(Function &)> LookupDomTree,
  2185. function_ref<void(Function &F)> ChangedCFGCallback,
  2186. function_ref<void(Function &F)> DeleteFnCallback) {
  2187. SmallPtrSet<const Comdat *, 8> NotDiscardableComdats;
  2188. bool Changed = false;
  2189. bool LocalChange = true;
  2190. std::optional<uint32_t> FirstNotFullyEvaluatedPriority;
  2191. while (LocalChange) {
  2192. LocalChange = false;
  2193. NotDiscardableComdats.clear();
  2194. for (const GlobalVariable &GV : M.globals())
  2195. if (const Comdat *C = GV.getComdat())
  2196. if (!GV.isDiscardableIfUnused() || !GV.use_empty())
  2197. NotDiscardableComdats.insert(C);
  2198. for (Function &F : M)
  2199. if (const Comdat *C = F.getComdat())
  2200. if (!F.isDefTriviallyDead())
  2201. NotDiscardableComdats.insert(C);
  2202. for (GlobalAlias &GA : M.aliases())
  2203. if (const Comdat *C = GA.getComdat())
  2204. if (!GA.isDiscardableIfUnused() || !GA.use_empty())
  2205. NotDiscardableComdats.insert(C);
  2206. // Delete functions that are trivially dead, ccc -> fastcc
  2207. LocalChange |= OptimizeFunctions(M, GetTLI, GetTTI, GetBFI, LookupDomTree,
  2208. NotDiscardableComdats, ChangedCFGCallback,
  2209. DeleteFnCallback);
  2210. // Optimize global_ctors list.
  2211. LocalChange |=
  2212. optimizeGlobalCtorsList(M, [&](uint32_t Priority, Function *F) {
  2213. if (FirstNotFullyEvaluatedPriority &&
  2214. *FirstNotFullyEvaluatedPriority != Priority)
  2215. return false;
  2216. bool Evaluated = EvaluateStaticConstructor(F, DL, &GetTLI(*F));
  2217. if (!Evaluated)
  2218. FirstNotFullyEvaluatedPriority = Priority;
  2219. return Evaluated;
  2220. });
  2221. // Optimize non-address-taken globals.
  2222. LocalChange |= OptimizeGlobalVars(M, GetTTI, GetTLI, LookupDomTree,
  2223. NotDiscardableComdats);
  2224. // Resolve aliases, when possible.
  2225. LocalChange |= OptimizeGlobalAliases(M, NotDiscardableComdats);
  2226. // Try to remove trivial global destructors if they are not removed
  2227. // already.
  2228. Function *CXAAtExitFn = FindCXAAtExit(M, GetTLI);
  2229. if (CXAAtExitFn)
  2230. LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
  2231. Changed |= LocalChange;
  2232. }
  2233. // TODO: Move all global ctors functions to the end of the module for code
  2234. // layout.
  2235. return Changed;
  2236. }
  2237. PreservedAnalyses GlobalOptPass::run(Module &M, ModuleAnalysisManager &AM) {
  2238. auto &DL = M.getDataLayout();
  2239. auto &FAM =
  2240. AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  2241. auto LookupDomTree = [&FAM](Function &F) -> DominatorTree &{
  2242. return FAM.getResult<DominatorTreeAnalysis>(F);
  2243. };
  2244. auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
  2245. return FAM.getResult<TargetLibraryAnalysis>(F);
  2246. };
  2247. auto GetTTI = [&FAM](Function &F) -> TargetTransformInfo & {
  2248. return FAM.getResult<TargetIRAnalysis>(F);
  2249. };
  2250. auto GetBFI = [&FAM](Function &F) -> BlockFrequencyInfo & {
  2251. return FAM.getResult<BlockFrequencyAnalysis>(F);
  2252. };
  2253. auto ChangedCFGCallback = [&FAM](Function &F) {
  2254. FAM.invalidate(F, PreservedAnalyses::none());
  2255. };
  2256. auto DeleteFnCallback = [&FAM](Function &F) { FAM.clear(F, F.getName()); };
  2257. if (!optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, LookupDomTree,
  2258. ChangedCFGCallback, DeleteFnCallback))
  2259. return PreservedAnalyses::all();
  2260. PreservedAnalyses PA = PreservedAnalyses::none();
  2261. // We made sure to clear analyses for deleted functions.
  2262. PA.preserve<FunctionAnalysisManagerModuleProxy>();
  2263. // The only place we modify the CFG is when calling
  2264. // removeUnreachableBlocks(), but there we make sure to invalidate analyses
  2265. // for modified functions.
  2266. PA.preserveSet<CFGAnalyses>();
  2267. return PA;
  2268. }
  2269. namespace {
  2270. struct GlobalOptLegacyPass : public ModulePass {
  2271. static char ID; // Pass identification, replacement for typeid
  2272. GlobalOptLegacyPass() : ModulePass(ID) {
  2273. initializeGlobalOptLegacyPassPass(*PassRegistry::getPassRegistry());
  2274. }
  2275. bool runOnModule(Module &M) override {
  2276. if (skipModule(M))
  2277. return false;
  2278. auto &DL = M.getDataLayout();
  2279. auto LookupDomTree = [this](Function &F) -> DominatorTree & {
  2280. return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
  2281. };
  2282. auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
  2283. return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  2284. };
  2285. auto GetTTI = [this](Function &F) -> TargetTransformInfo & {
  2286. return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  2287. };
  2288. auto GetBFI = [this](Function &F) -> BlockFrequencyInfo & {
  2289. return this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
  2290. };
  2291. auto ChangedCFGCallback = [&LookupDomTree](Function &F) {
  2292. auto &DT = LookupDomTree(F);
  2293. DT.recalculate(F);
  2294. };
  2295. return optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, LookupDomTree,
  2296. ChangedCFGCallback, nullptr);
  2297. }
  2298. void getAnalysisUsage(AnalysisUsage &AU) const override {
  2299. AU.addRequired<TargetLibraryInfoWrapperPass>();
  2300. AU.addRequired<TargetTransformInfoWrapperPass>();
  2301. AU.addRequired<DominatorTreeWrapperPass>();
  2302. AU.addRequired<BlockFrequencyInfoWrapperPass>();
  2303. }
  2304. };
  2305. } // end anonymous namespace
  2306. char GlobalOptLegacyPass::ID = 0;
  2307. INITIALIZE_PASS_BEGIN(GlobalOptLegacyPass, "globalopt",
  2308. "Global Variable Optimizer", false, false)
  2309. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  2310. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  2311. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
  2312. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  2313. INITIALIZE_PASS_END(GlobalOptLegacyPass, "globalopt",
  2314. "Global Variable Optimizer", false, false)
  2315. ModulePass *llvm::createGlobalOptimizerPass() {
  2316. return new GlobalOptLegacyPass();
  2317. }