GCStrategy.cpp 13 KB

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