blob: 3b20b6cf58bf69fd7f6b37d02f177706ac149d8d [file] [log] [blame]
Logan28325bf2010-11-26 23:27:41 +08001/*
2 * Copyright 2010, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef BCC_CODE_EMITTER_H
18#define BCC_CODE_EMITTER_H
19
20#include <bcc/bcc.h>
21#include <bcc/bcc_cache.h>
22
23#include "bcc_emitted_func_code.h"
24
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/CodeGen/MachineRelocation.h"
29#include "llvm/CodeGen/JITCodeEmitter.h"
30#include "llvm/Support/ValueHandle.h"
31
32#include <map>
33#include <vector>
34#include <set>
35
36#include <assert.h>
37#include <stdint.h>
38
39namespace llvm {
40 class Constant;
41 class GenericValue;
42 class GlobalVariable;
43 class GlobalValue;
44 class Function;
45 class MachineBasicBlock;
46 class MachineConstantPool;
47 class MachineFunction;
48 class MachineJumpTableInfo;
49 class MachineModuleInfo;
50#if defined(USE_DISASSEMBLER)
51 class MCAsmInfo;
52 class MCDisassembler;
53 class MCInstPrinter;
54#endif
55 class MCSymbol;
56 class Target;
57 class TargetData;
58 class TargetJITInfo;
59 class TargetMachine;
60 class Type;
61}
62
63namespace bcc {
64 class CodeMemoryManager;
65
66 class CodeEmitter : public llvm::JITCodeEmitter {
67 public:
68 typedef llvm::DenseMap<const llvm::GlobalValue*, void*> GlobalAddressMapTy;
69 typedef GlobalAddressMapTy::const_iterator global_addresses_const_iterator;
70
71 GlobalAddressMapTy mGlobalAddressMap;
72
73 private:
74 CodeMemoryManager *mpMemMgr;
75
76 // The JITInfo for the target we are compiling to
77 const llvm::Target *mpTarget;
78
79 llvm::TargetJITInfo *mpTJI;
80
81 const llvm::TargetData *mpTD;
82
83 EmittedFunctionCode *mpCurEmitFunction;
84
85 typedef std::map<const std::string,
86 EmittedFunctionCode *> EmittedFunctionsMapTy;
87 EmittedFunctionsMapTy mEmittedFunctions;
88
89 // This vector is a mapping from MBB ID's to their address. It is filled in
90 // by the StartMachineBasicBlock callback and queried by the
91 // getMachineBasicBlockAddress callback.
92 std::vector<uintptr_t> mMBBLocations;
93
94 // The constant pool for the current function.
95 llvm::MachineConstantPool *mpConstantPool;
96
97 // A pointer to the first entry in the constant pool.
98 void *mpConstantPoolBase;
99
100 // Addresses of individual constant pool entries.
101 llvm::SmallVector<uintptr_t, 8> mConstPoolAddresses;
102
103 // The jump tables for the current function.
104 llvm::MachineJumpTableInfo *mpJumpTable;
105
106 // A pointer to the first entry in the jump table.
107 void *mpJumpTableBase;
108
109 // When outputting a function stub in the context of some other function, we
110 // save BufferBegin/BufferEnd/CurBufferPtr here.
111 uint8_t *mpSavedBufferBegin, *mpSavedBufferEnd, *mpSavedCurBufferPtr;
112
113 // These are the relocations that the function needs, as emitted.
114 std::vector<llvm::MachineRelocation> mRelocations;
115
116 std::vector<oBCCRelocEntry> mCachingRelocations;
117
118 // This vector is a mapping from Label ID's to their address.
119 llvm::DenseMap<llvm::MCSymbol*, uintptr_t> mLabelLocations;
120
121 // Machine module info for exception informations
122 llvm::MachineModuleInfo *mpMMI;
123
124 // Replace an existing mapping for GV with a new address. This updates both
125 // maps as required. If Addr is null, the entry for the global is removed
126 // from the mappings.
127 void *UpdateGlobalMapping(const llvm::GlobalValue *GV, void *Addr);
128
129 // Tell the execution engine that the specified global is at the specified
130 // location. This is used internally as functions are JIT'd and as global
131 // variables are laid out in memory.
132 void AddGlobalMapping(const llvm::GlobalValue *GV, void *Addr);
133
134 // This returns the address of the specified global value if it is has
135 // already been codegen'd, otherwise it returns null.
136 void *GetPointerToGlobalIfAvailable(const llvm::GlobalValue *GV) {
137 GlobalAddressMapTy::iterator I = mGlobalAddressMap.find(GV);
138 return ((I != mGlobalAddressMap.end()) ? I->second : NULL);
139 }
140
141 unsigned int GetConstantPoolSizeInBytes(llvm::MachineConstantPool *MCP);
142
143 // This function converts a Constant* into a GenericValue. The interesting
144 // part is if C is a ConstantExpr.
145 void GetConstantValue(const llvm::Constant *C, llvm::GenericValue &Result);
146
147 // Stores the data in @Val of type @Ty at address @Addr.
148 void StoreValueToMemory(const llvm::GenericValue &Val, void *Addr,
149 const llvm::Type *Ty);
150
151 // Recursive function to apply a @Constant value into the specified memory
152 // location @Addr.
153 void InitializeConstantToMemory(const llvm::Constant *C, void *Addr);
154
155 void emitConstantPool(llvm::MachineConstantPool *MCP);
156
157 void initJumpTableInfo(llvm::MachineJumpTableInfo *MJTI);
158
159 void emitJumpTableInfo(llvm::MachineJumpTableInfo *MJTI);
160
161 void *GetPointerToGlobal(llvm::GlobalValue *V,
162 void *Reference,
163 bool MayNeedFarStub);
164
165 // If the specified function has been code-gen'd, return a pointer to the
166 // function. If not, compile it, or use a stub to implement lazy compilation
167 // if available.
168 void *GetPointerToFunctionOrStub(llvm::Function *F);
169
170 typedef llvm::DenseMap<const llvm::Function*,
171 void*> FunctionToLazyStubMapTy;
172 FunctionToLazyStubMapTy mFunctionToLazyStubMap;
173
174 void *GetLazyFunctionStubIfAvailable(llvm::Function *F) {
175 return mFunctionToLazyStubMap.lookup(F);
176 }
177
178 std::set<const llvm::Function*> PendingFunctions;
179 void *GetLazyFunctionStub(llvm::Function *F);
180
181 void *GetPointerToFunction(const llvm::Function *F, bool AbortOnFailure);
182
183 void *GetPointerToNamedSymbol(const std::string &Name,
184 bool AbortOnFailure);
185
186 // Return the address of the specified global variable, possibly emitting it
187 // to memory if needed. This is used by the Emitter.
188 void *GetOrEmitGlobalVariable(const llvm::GlobalVariable *GV);
189
190 // This method abstracts memory allocation of global variable so that the
191 // JIT can allocate thread local variables depending on the target.
192 void *GetMemoryForGV(const llvm::GlobalVariable *GV);
193
194 void EmitGlobalVariable(const llvm::GlobalVariable *GV);
195
196 typedef std::map<llvm::AssertingVH<llvm::GlobalValue>,
197 void *> GlobalToIndirectSymMapTy;
198
199 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
200
201 void *GetPointerToGVIndirectSym(llvm::GlobalValue *V, void *Reference);
202
203 // This is the equivalent of FunctionToLazyStubMap for external functions.
204 //
205 // TODO(llvm.org): Of course, external functions don't need a lazy stub.
206 // It's actually here to make it more likely that far calls
207 // succeed, but no single stub can guarantee that. I'll
208 // remove this in a subsequent checkin when I actually fix
209 // far calls.
210 std::map<void*, void*> ExternalFnToStubMap;
211
212 // Return a stub for the function at the specified address.
213 void *GetExternalFunctionStub(void *FnAddr);
214
215#if defined(USE_DISASSEMBLER)
216 const llvm::MCAsmInfo *mpAsmInfo;
217 const llvm::MCDisassembler *mpDisassmbler;
218 llvm::MCInstPrinter *mpIP;
219
220 public:
221 void Disassemble(const llvm::StringRef &Name, uint8_t *Start,
222 size_t Length, bool IsStub);
223#else
224 void Disassemble(const llvm::StringRef &Name, uint8_t *Start,
225 size_t Length, bool IsStub) {
226 }
227#endif // defined(USE_DISASSEMBLER)
228
229 private:
230 // Resolver to undefined symbol in CodeEmitter
231 BCCSymbolLookupFn mpSymbolLookupFn;
232 void *mpSymbolLookupContext;
233
234 public:
235 // Will take the ownership of @MemMgr
236 explicit CodeEmitter(CodeMemoryManager *pMemMgr);
237
238 ~CodeEmitter();
239
240 inline global_addresses_const_iterator global_address_begin() const {
241 return mGlobalAddressMap.begin();
242 }
243
244 inline global_addresses_const_iterator global_address_end() const {
245 return mGlobalAddressMap.end();
246 }
247
248 std::vector<oBCCRelocEntry> const &getCachingRelocations() const {
249 return mCachingRelocations;
250 }
251
252 void registerSymbolCallback(BCCSymbolLookupFn pFn, BCCvoid *pContext) {
253 mpSymbolLookupFn = pFn;
254 mpSymbolLookupContext = pContext;
255 }
256
257 void setTargetMachine(llvm::TargetMachine &TM);
258
259 // This callback is invoked when the specified function is about to be code
260 // generated. This initializes the BufferBegin/End/Ptr fields.
261 void startFunction(llvm::MachineFunction &F);
262
263 // This callback is invoked when the specified function has finished code
264 // generation. If a buffer overflow has occurred, this method returns true
265 // (the callee is required to try again).
266 bool finishFunction(llvm::MachineFunction &F);
267
268 void startGVStub(const llvm::GlobalValue *GV, unsigned StubSize,
269 unsigned Alignment);
270
271 void startGVStub(void *Buffer, unsigned StubSize);
272
273 void finishGVStub();
274
275 // Allocates and fills storage for an indirect GlobalValue, and returns the
276 // address.
277 void *allocIndirectGV(const llvm::GlobalValue *GV,
278 const uint8_t *Buffer, size_t Size,
279 unsigned Alignment);
280
281 // Emits a label
282 void emitLabel(llvm::MCSymbol *Label) {
283 mLabelLocations[Label] = getCurrentPCValue();
284 }
285
286 // Allocate memory for a global. Unlike allocateSpace, this method does not
287 // allocate memory in the current output buffer, because a global may live
288 // longer than the current function.
289 void *allocateGlobal(uintptr_t Size, unsigned Alignment);
290
291 // This should be called by the target when a new basic block is about to be
292 // emitted. This way the MCE knows where the start of the block is, and can
293 // implement getMachineBasicBlockAddress.
294 void StartMachineBasicBlock(llvm::MachineBasicBlock *MBB);
295
296 // Whenever a relocatable address is needed, it should be noted with this
297 // interface.
298 void addRelocation(const llvm::MachineRelocation &MR) {
299 mRelocations.push_back(MR);
300 }
301
302 // Return the address of the @Index entry in the constant pool that was
303 // last emitted with the emitConstantPool method.
304 uintptr_t getConstantPoolEntryAddress(unsigned Index) const {
305 assert(Index < mpConstantPool->getConstants().size() &&
306 "Invalid constant pool index!");
307 return mConstPoolAddresses[Index];
308 }
309
310 // Return the address of the jump table with index @Index in the function
311 // that last called initJumpTableInfo.
312 uintptr_t getJumpTableEntryAddress(unsigned Index) const;
313
314 // Return the address of the specified MachineBasicBlock, only usable after
315 // the label for the MBB has been emitted.
316 uintptr_t getMachineBasicBlockAddress(llvm::MachineBasicBlock *MBB) const;
317
318 // Return the address of the specified LabelID, only usable after the
319 // LabelID has been emitted.
320 uintptr_t getLabelAddress(llvm::MCSymbol *Label) const {
321 assert(mLabelLocations.count(Label) && "Label not emitted!");
322 return mLabelLocations.find(Label)->second;
323 }
324
325 // Specifies the MachineModuleInfo object. This is used for exception
326 // handling purposes.
327 void setModuleInfo(llvm::MachineModuleInfo *Info) {
328 mpMMI = Info;
329 }
330
331 void updateFunctionStub(const llvm::Function *F);
332
333 void releaseUnnecessary();
334
335 void reset();
336
337 void *lookup(const char *Name) {
338 return lookup( llvm::StringRef(Name) );
339 }
340
341 void *lookup(const llvm::StringRef &Name) {
342 EmittedFunctionsMapTy::const_iterator
343 I = mEmittedFunctions.find(Name.str());
344
345 return (I == mEmittedFunctions.end()) ? NULL : I->second->Code;
346 }
347
348 void getFunctionNames(BCCsizei *actualFunctionCount,
349 BCCsizei maxFunctionCount,
350 BCCchar **functions);
351
352 void getFunctionBinary(BCCchar *label,
353 BCCvoid **base,
354 BCCsizei *length);
355 };
356
357} // namespace bcc
358
359#endif // BCC_CODE_EMITTER_H