1//===-- OProfileJITEventListener.cpp - Tell OProfile about JITted code ----===//
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 defines a JITEventListener object that uses OProfileWrapper to tell
11// oprofile about JITted functions, including source line information.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Config/config.h"
16#include "llvm/ExecutionEngine/JITEventListener.h"
17
18#include "llvm/IR/DebugInfo.h"
19#include "llvm/IR/Function.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/ExecutionEngine/ObjectImage.h"
22#include "llvm/ExecutionEngine/OProfileWrapper.h"
23#include "llvm/Object/ObjectFile.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/Support/Errno.h"
27#include "EventListenerCommon.h"
28
29#include <dirent.h>
30#include <fcntl.h>
31
32using namespace llvm;
33using namespace llvm::jitprofiling;
34
35#define DEBUG_TYPE "oprofile-jit-event-listener"
36
37namespace {
38
39class OProfileJITEventListener : public JITEventListener {
40  OProfileWrapper& Wrapper;
41
42  void initialize();
43
44public:
45  OProfileJITEventListener(OProfileWrapper& LibraryWrapper)
46  : Wrapper(LibraryWrapper) {
47    initialize();
48  }
49
50  ~OProfileJITEventListener();
51
52  virtual void NotifyFunctionEmitted(const Function &F,
53                                void *FnStart, size_t FnSize,
54                                const JITEvent_EmittedFunctionDetails &Details);
55
56  virtual void NotifyFreeingMachineCode(void *OldPtr);
57
58  virtual void NotifyObjectEmitted(const ObjectImage &Obj);
59
60  virtual void NotifyFreeingObject(const ObjectImage &Obj);
61};
62
63void OProfileJITEventListener::initialize() {
64  if (!Wrapper.op_open_agent()) {
65    const std::string err_str = sys::StrError();
66    DEBUG(dbgs() << "Failed to connect to OProfile agent: " << err_str << "\n");
67  } else {
68    DEBUG(dbgs() << "Connected to OProfile agent.\n");
69  }
70}
71
72OProfileJITEventListener::~OProfileJITEventListener() {
73  if (Wrapper.isAgentAvailable()) {
74    if (Wrapper.op_close_agent() == -1) {
75      const std::string err_str = sys::StrError();
76      DEBUG(dbgs() << "Failed to disconnect from OProfile agent: "
77                   << err_str << "\n");
78    } else {
79      DEBUG(dbgs() << "Disconnected from OProfile agent.\n");
80    }
81  }
82}
83
84static debug_line_info LineStartToOProfileFormat(
85    const MachineFunction &MF, FilenameCache &Filenames,
86    uintptr_t Address, DebugLoc Loc) {
87  debug_line_info Result;
88  Result.vma = Address;
89  Result.lineno = Loc.getLine();
90  Result.filename = Filenames.getFilename(
91    Loc.getScope(MF.getFunction()->getContext()));
92  DEBUG(dbgs() << "Mapping " << reinterpret_cast<void*>(Result.vma) << " to "
93               << Result.filename << ":" << Result.lineno << "\n");
94  return Result;
95}
96
97// Adds the just-emitted function to the symbol table.
98void OProfileJITEventListener::NotifyFunctionEmitted(
99    const Function &F, void *FnStart, size_t FnSize,
100    const JITEvent_EmittedFunctionDetails &Details) {
101  assert(F.hasName() && FnStart != 0 && "Bad symbol to add");
102  if (Wrapper.op_write_native_code(F.getName().data(),
103                           reinterpret_cast<uint64_t>(FnStart),
104                           FnStart, FnSize) == -1) {
105    DEBUG(dbgs() << "Failed to tell OProfile about native function "
106          << F.getName() << " at ["
107          << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n");
108    return;
109  }
110
111  if (!Details.LineStarts.empty()) {
112    // Now we convert the line number information from the address/DebugLoc
113    // format in Details to the address/filename/lineno format that OProfile
114    // expects.  Note that OProfile 0.9.4 has a bug that causes it to ignore
115    // line numbers for addresses above 4G.
116    FilenameCache Filenames;
117    std::vector<debug_line_info> LineInfo;
118    LineInfo.reserve(1 + Details.LineStarts.size());
119
120    DebugLoc FirstLoc = Details.LineStarts[0].Loc;
121    assert(!FirstLoc.isUnknown()
122           && "LineStarts should not contain unknown DebugLocs");
123    MDNode *FirstLocScope = FirstLoc.getScope(F.getContext());
124    DISubprogram FunctionDI = getDISubprogram(FirstLocScope);
125    if (FunctionDI.Verify()) {
126      // If we have debug info for the function itself, use that as the line
127      // number of the first several instructions.  Otherwise, after filling
128      // LineInfo, we'll adjust the address of the first line number to point at
129      // the start of the function.
130      debug_line_info line_info;
131      line_info.vma = reinterpret_cast<uintptr_t>(FnStart);
132      line_info.lineno = FunctionDI.getLineNumber();
133      line_info.filename = Filenames.getFilename(FirstLocScope);
134      LineInfo.push_back(line_info);
135    }
136
137    for (std::vector<EmittedFunctionDetails::LineStart>::const_iterator
138           I = Details.LineStarts.begin(), E = Details.LineStarts.end();
139         I != E; ++I) {
140      LineInfo.push_back(LineStartToOProfileFormat(
141                           *Details.MF, Filenames, I->Address, I->Loc));
142    }
143
144    // In case the function didn't have line info of its own, adjust the first
145    // line info's address to include the start of the function.
146    LineInfo[0].vma = reinterpret_cast<uintptr_t>(FnStart);
147
148    if (Wrapper.op_write_debug_line_info(FnStart, LineInfo.size(),
149                                      &*LineInfo.begin()) == -1) {
150      DEBUG(dbgs()
151            << "Failed to tell OProfile about line numbers for native function "
152            << F.getName() << " at ["
153            << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n");
154    }
155  }
156}
157
158// Removes the being-deleted function from the symbol table.
159void OProfileJITEventListener::NotifyFreeingMachineCode(void *FnStart) {
160  assert(FnStart && "Invalid function pointer");
161  if (Wrapper.op_unload_native_code(reinterpret_cast<uint64_t>(FnStart)) == -1) {
162    DEBUG(dbgs()
163          << "Failed to tell OProfile about unload of native function at "
164          << FnStart << "\n");
165  }
166}
167
168void OProfileJITEventListener::NotifyObjectEmitted(const ObjectImage &Obj) {
169  if (!Wrapper.isAgentAvailable()) {
170    return;
171  }
172
173  // Use symbol info to iterate functions in the object.
174  for (object::symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols();
175       I != E; ++I) {
176    object::SymbolRef::Type SymType;
177    if (I->getType(SymType)) continue;
178    if (SymType == object::SymbolRef::ST_Function) {
179      StringRef  Name;
180      uint64_t   Addr;
181      uint64_t   Size;
182      if (I->getName(Name)) continue;
183      if (I->getAddress(Addr)) continue;
184      if (I->getSize(Size)) continue;
185
186      if (Wrapper.op_write_native_code(Name.data(), Addr, (void*)Addr, Size)
187                        == -1) {
188        DEBUG(dbgs() << "Failed to tell OProfile about native function "
189          << Name << " at ["
190          << (void*)Addr << "-" << ((char*)Addr + Size) << "]\n");
191        continue;
192      }
193      // TODO: support line number info (similar to IntelJITEventListener.cpp)
194    }
195  }
196}
197
198void OProfileJITEventListener::NotifyFreeingObject(const ObjectImage &Obj) {
199  if (!Wrapper.isAgentAvailable()) {
200    return;
201  }
202
203  // Use symbol info to iterate functions in the object.
204  for (object::symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols();
205       I != E; ++I) {
206    object::SymbolRef::Type SymType;
207    if (I->getType(SymType)) continue;
208    if (SymType == object::SymbolRef::ST_Function) {
209      uint64_t   Addr;
210      if (I->getAddress(Addr)) continue;
211
212      if (Wrapper.op_unload_native_code(Addr) == -1) {
213        DEBUG(dbgs()
214          << "Failed to tell OProfile about unload of native function at "
215          << (void*)Addr << "\n");
216        continue;
217      }
218    }
219  }
220}
221
222}  // anonymous namespace.
223
224namespace llvm {
225JITEventListener *JITEventListener::createOProfileJITEventListener() {
226  static std::unique_ptr<OProfileWrapper> JITProfilingWrapper(
227      new OProfileWrapper);
228  return new OProfileJITEventListener(*JITProfilingWrapper);
229}
230
231// for testing
232JITEventListener *JITEventListener::createOProfileJITEventListener(
233                                      OProfileWrapper* TestImpl) {
234  return new OProfileJITEventListener(*TestImpl);
235}
236
237} // namespace llvm
238
239