GCStrategy.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. //===-- GCStrategy.cpp - Garbage collection infrastructure -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements target- and collector-independent garbage collection
  11. // infrastructure.
  12. //
  13. // GCMachineCodeAnalysis identifies the GC safe points in the machine code.
  14. // Roots are identified in SelectionDAGISel.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/CodeGen/GCStrategy.h"
  18. #include "llvm/Analysis/DominatorInternals.h"
  19. #include "llvm/Analysis/Dominators.h"
  20. #include "llvm/CodeGen/MachineFrameInfo.h"
  21. #include "llvm/CodeGen/MachineFunctionPass.h"
  22. #include "llvm/CodeGen/MachineInstrBuilder.h"
  23. #include "llvm/CodeGen/MachineModuleInfo.h"
  24. #include "llvm/CodeGen/Passes.h"
  25. #include "llvm/IntrinsicInst.h"
  26. #include "llvm/Module.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/Target/TargetFrameLowering.h"
  31. #include "llvm/Target/TargetInstrInfo.h"
  32. #include "llvm/Target/TargetMachine.h"
  33. #include "llvm/Target/TargetRegisterInfo.h"
  34. using namespace llvm;
  35. namespace {
  36. /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
  37. /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
  38. /// directed by the GCStrategy. It also performs automatic root initialization
  39. /// and custom intrinsic lowering.
  40. class LowerIntrinsics : public FunctionPass {
  41. static bool NeedsDefaultLoweringPass(const GCStrategy &C);
  42. static bool NeedsCustomLoweringPass(const GCStrategy &C);
  43. static bool CouldBecomeSafePoint(Instruction *I);
  44. bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
  45. static bool InsertRootInitializers(Function &F,
  46. AllocaInst **Roots, unsigned Count);
  47. public:
  48. static char ID;
  49. LowerIntrinsics();
  50. const char *getPassName() const;
  51. void getAnalysisUsage(AnalysisUsage &AU) const;
  52. bool doInitialization(Module &M);
  53. bool runOnFunction(Function &F);
  54. };
  55. /// GCMachineCodeAnalysis - This is a target-independent pass over the machine
  56. /// function representation to identify safe points for the garbage collector
  57. /// in the machine code. It inserts labels at safe points and populates a
  58. /// GCMetadata record for each function.
  59. class GCMachineCodeAnalysis : public MachineFunctionPass {
  60. const TargetMachine *TM;
  61. GCFunctionInfo *FI;
  62. MachineModuleInfo *MMI;
  63. const TargetInstrInfo *TII;
  64. void FindSafePoints(MachineFunction &MF);
  65. void VisitCallPoint(MachineBasicBlock::iterator MI);
  66. MCSymbol *InsertLabel(MachineBasicBlock &MBB,
  67. MachineBasicBlock::iterator MI,
  68. DebugLoc DL) const;
  69. void FindStackOffsets(MachineFunction &MF);
  70. public:
  71. static char ID;
  72. GCMachineCodeAnalysis();
  73. void getAnalysisUsage(AnalysisUsage &AU) const;
  74. bool runOnMachineFunction(MachineFunction &MF);
  75. };
  76. }
  77. // -----------------------------------------------------------------------------
  78. GCStrategy::GCStrategy() :
  79. NeededSafePoints(0),
  80. CustomReadBarriers(false),
  81. CustomWriteBarriers(false),
  82. CustomRoots(false),
  83. CustomSafePoints(false),
  84. InitRoots(true),
  85. UsesMetadata(false)
  86. {}
  87. GCStrategy::~GCStrategy() {
  88. for (iterator I = begin(), E = end(); I != E; ++I)
  89. delete *I;
  90. Functions.clear();
  91. }
  92. bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
  93. bool GCStrategy::performCustomLowering(Function &F) {
  94. dbgs() << "gc " << getName() << " must override performCustomLowering.\n";
  95. llvm_unreachable("must override performCustomLowering");
  96. }
  97. bool GCStrategy::findCustomSafePoints(GCFunctionInfo& FI, MachineFunction &F) {
  98. dbgs() << "gc " << getName() << " must override findCustomSafePoints.\n";
  99. llvm_unreachable(0);
  100. }
  101. GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
  102. GCFunctionInfo *FI = new GCFunctionInfo(F, *this);
  103. Functions.push_back(FI);
  104. return FI;
  105. }
  106. // -----------------------------------------------------------------------------
  107. INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering",
  108. false, false)
  109. INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
  110. INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
  111. FunctionPass *llvm::createGCLoweringPass() {
  112. return new LowerIntrinsics();
  113. }
  114. char LowerIntrinsics::ID = 0;
  115. LowerIntrinsics::LowerIntrinsics()
  116. : FunctionPass(ID) {
  117. initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
  118. }
  119. const char *LowerIntrinsics::getPassName() const {
  120. return "Lower Garbage Collection Instructions";
  121. }
  122. void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
  123. FunctionPass::getAnalysisUsage(AU);
  124. AU.addRequired<GCModuleInfo>();
  125. AU.addPreserved<DominatorTree>();
  126. }
  127. /// doInitialization - If this module uses the GC intrinsics, find them now.
  128. bool LowerIntrinsics::doInitialization(Module &M) {
  129. // FIXME: This is rather antisocial in the context of a JIT since it performs
  130. // work against the entire module. But this cannot be done at
  131. // runFunction time (initializeCustomLowering likely needs to change
  132. // the module).
  133. GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
  134. assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
  135. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
  136. if (!I->isDeclaration() && I->hasGC())
  137. MI->getFunctionInfo(*I); // Instantiate the GC strategy.
  138. bool MadeChange = false;
  139. for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
  140. if (NeedsCustomLoweringPass(**I))
  141. if ((*I)->initializeCustomLowering(M))
  142. MadeChange = true;
  143. return MadeChange;
  144. }
  145. bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
  146. unsigned Count) {
  147. // Scroll past alloca instructions.
  148. BasicBlock::iterator IP = F.getEntryBlock().begin();
  149. while (isa<AllocaInst>(IP)) ++IP;
  150. // Search for initializers in the initial BB.
  151. SmallPtrSet<AllocaInst*,16> InitedRoots;
  152. for (; !CouldBecomeSafePoint(IP); ++IP)
  153. if (StoreInst *SI = dyn_cast<StoreInst>(IP))
  154. if (AllocaInst *AI =
  155. dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
  156. InitedRoots.insert(AI);
  157. // Add root initializers.
  158. bool MadeChange = false;
  159. for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
  160. if (!InitedRoots.count(*I)) {
  161. StoreInst* SI = new StoreInst(ConstantPointerNull::get(cast<PointerType>(
  162. cast<PointerType>((*I)->getType())->getElementType())),
  163. *I);
  164. SI->insertAfter(*I);
  165. MadeChange = true;
  166. }
  167. return MadeChange;
  168. }
  169. bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
  170. // Default lowering is necessary only if read or write barriers have a default
  171. // action. The default for roots is no action.
  172. return !C.customWriteBarrier()
  173. || !C.customReadBarrier()
  174. || C.initializeRoots();
  175. }
  176. bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
  177. // Custom lowering is only necessary if enabled for some action.
  178. return C.customWriteBarrier()
  179. || C.customReadBarrier()
  180. || C.customRoots();
  181. }
  182. /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
  183. /// instruction could introduce a safe point.
  184. bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
  185. // The natural definition of instructions which could introduce safe points
  186. // are:
  187. //
  188. // - call, invoke (AfterCall, BeforeCall)
  189. // - phis (Loops)
  190. // - invoke, ret, unwind (Exit)
  191. //
  192. // However, instructions as seemingly inoccuous as arithmetic can become
  193. // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
  194. // it is necessary to take a conservative approach.
  195. if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
  196. isa<StoreInst>(I) || isa<LoadInst>(I))
  197. return false;
  198. // llvm.gcroot is safe because it doesn't do anything at runtime.
  199. if (CallInst *CI = dyn_cast<CallInst>(I))
  200. if (Function *F = CI->getCalledFunction())
  201. if (unsigned IID = F->getIntrinsicID())
  202. if (IID == Intrinsic::gcroot)
  203. return false;
  204. return true;
  205. }
  206. /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
  207. /// Leave gcroot intrinsics; the code generator needs to see those.
  208. bool LowerIntrinsics::runOnFunction(Function &F) {
  209. // Quick exit for functions that do not use GC.
  210. if (!F.hasGC())
  211. return false;
  212. GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
  213. GCStrategy &S = FI.getStrategy();
  214. bool MadeChange = false;
  215. if (NeedsDefaultLoweringPass(S))
  216. MadeChange |= PerformDefaultLowering(F, S);
  217. bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
  218. if (UseCustomLoweringPass)
  219. MadeChange |= S.performCustomLowering(F);
  220. // Custom lowering may modify the CFG, so dominators must be recomputed.
  221. if (UseCustomLoweringPass) {
  222. if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
  223. DT->DT->recalculate(F);
  224. }
  225. return MadeChange;
  226. }
  227. bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
  228. bool LowerWr = !S.customWriteBarrier();
  229. bool LowerRd = !S.customReadBarrier();
  230. bool InitRoots = S.initializeRoots();
  231. SmallVector<AllocaInst*, 32> Roots;
  232. bool MadeChange = false;
  233. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  234. for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
  235. if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
  236. Function *F = CI->getCalledFunction();
  237. switch (F->getIntrinsicID()) {
  238. case Intrinsic::gcwrite:
  239. if (LowerWr) {
  240. // Replace a write barrier with a simple store.
  241. Value *St = new StoreInst(CI->getArgOperand(0),
  242. CI->getArgOperand(2), CI);
  243. CI->replaceAllUsesWith(St);
  244. CI->eraseFromParent();
  245. }
  246. break;
  247. case Intrinsic::gcread:
  248. if (LowerRd) {
  249. // Replace a read barrier with a simple load.
  250. Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
  251. Ld->takeName(CI);
  252. CI->replaceAllUsesWith(Ld);
  253. CI->eraseFromParent();
  254. }
  255. break;
  256. case Intrinsic::gcroot:
  257. if (InitRoots) {
  258. // Initialize the GC root, but do not delete the intrinsic. The
  259. // backend needs the intrinsic to flag the stack slot.
  260. Roots.push_back(cast<AllocaInst>(
  261. CI->getArgOperand(0)->stripPointerCasts()));
  262. }
  263. break;
  264. default:
  265. continue;
  266. }
  267. MadeChange = true;
  268. }
  269. }
  270. }
  271. if (Roots.size())
  272. MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
  273. return MadeChange;
  274. }
  275. // -----------------------------------------------------------------------------
  276. char GCMachineCodeAnalysis::ID = 0;
  277. char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
  278. INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
  279. "Analyze Machine Code For Garbage Collection", false, false)
  280. GCMachineCodeAnalysis::GCMachineCodeAnalysis()
  281. : MachineFunctionPass(ID) {}
  282. void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  283. MachineFunctionPass::getAnalysisUsage(AU);
  284. AU.setPreservesAll();
  285. AU.addRequired<MachineModuleInfo>();
  286. AU.addRequired<GCModuleInfo>();
  287. }
  288. MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
  289. MachineBasicBlock::iterator MI,
  290. DebugLoc DL) const {
  291. MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
  292. BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
  293. return Label;
  294. }
  295. void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
  296. // Find the return address (next instruction), too, so as to bracket the call
  297. // instruction.
  298. MachineBasicBlock::iterator RAI = CI;
  299. ++RAI;
  300. if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
  301. MCSymbol* Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
  302. FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
  303. }
  304. if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
  305. MCSymbol* Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
  306. FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
  307. }
  308. }
  309. void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
  310. for (MachineFunction::iterator BBI = MF.begin(),
  311. BBE = MF.end(); BBI != BBE; ++BBI)
  312. for (MachineBasicBlock::iterator MI = BBI->begin(),
  313. ME = BBI->end(); MI != ME; ++MI)
  314. if (MI->isCall())
  315. VisitCallPoint(MI);
  316. }
  317. void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
  318. const TargetFrameLowering *TFI = TM->getFrameLowering();
  319. assert(TFI && "TargetRegisterInfo not available!");
  320. for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
  321. RI != FI->roots_end();) {
  322. // If the root references a dead object, no need to keep it.
  323. if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
  324. RI = FI->removeStackRoot(RI);
  325. } else {
  326. RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
  327. ++RI;
  328. }
  329. }
  330. }
  331. bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
  332. // Quick exit for functions that do not use GC.
  333. if (!MF.getFunction()->hasGC())
  334. return false;
  335. FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
  336. if (!FI->getStrategy().needsSafePoints())
  337. return false;
  338. TM = &MF.getTarget();
  339. MMI = &getAnalysis<MachineModuleInfo>();
  340. TII = TM->getInstrInfo();
  341. // Find the size of the stack frame.
  342. FI->setFrameSize(MF.getFrameInfo()->getStackSize());
  343. // Find all safe points.
  344. if (FI->getStrategy().customSafePoints()) {
  345. FI->getStrategy().findCustomSafePoints(*FI, MF);
  346. } else {
  347. FindSafePoints(MF);
  348. }
  349. // Find the stack offsets for all roots.
  350. FindStackOffsets(MF);
  351. return false;
  352. }