1 #===- core.py - Python LLVM Bindings -------------------------*- python -*--===#
3 # The LLVM Compiler Infrastructure
5 # This file is distributed under the University of Illinois Open Source
6 # License. See LICENSE.TXT for details.
8 #===------------------------------------------------------------------------===#
10 from .common import LLVMObject
11 from .common import c_object_p
12 from .common import get_library
14 from . import enumerations
16 from ctypes import POINTER
17 from ctypes import byref
18 from ctypes import c_char_p
19 from ctypes import c_uint
36 """Represents an individual OpCode enumeration."""
40 def __init__(self, name, value):
45 return 'OpCode.%s' % self.name
48 def from_value(value):
49 """Obtain an OpCode instance from a numeric value."""
50 result = OpCode._value_map.get(value, None)
53 raise ValueError('Unknown OpCode: %d' % value)
58 def register(name, value):
59 """Registers a new OpCode enumeration.
61 This is called by this module for each enumeration defined in
62 enumerations. You should not need to call this outside this module.
64 if value in OpCode._value_map:
65 raise ValueError('OpCode value already registered: %d' % value)
67 opcode = OpCode(name, value)
68 OpCode._value_map[value] = opcode
69 setattr(OpCode, name, opcode)
71 class MemoryBuffer(LLVMObject):
72 """Represents an opaque memory buffer."""
74 def __init__(self, filename=None):
75 """Create a new memory buffer.
77 Currently, we support creating from the contents of a file at the
81 raise Exception("filename argument must be defined")
86 result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename,
87 byref(memory), byref(out))
90 raise Exception("Could not create memory buffer: %s" % out.value)
92 LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer)
95 return lib.LLVMGetBufferSize(self)
97 class Value(LLVMObject):
99 def __init__(self, value):
100 LLVMObject.__init__(self, value)
104 return lib.LLVMGetValueName(self)
107 lib.LLVMDumpValue(self)
109 class Module(LLVMObject):
110 """Represents the top-level structure of an llvm program in an opaque object."""
112 def __init__(self, module, name=None, context=None):
113 LLVMObject.__init__(self, module, disposer=lib.LLVMDisposeModule)
116 def CreateWithName(cls, module_id):
117 m = Module(lib.LLVMModuleCreateWithName(module_id))
118 c = Context.GetGlobalContext().take_ownership(m)
122 def datalayout(self):
123 return lib.LLVMGetDataLayout(self)
126 def datalayout(self, new_data_layout):
127 """new_data_layout is a string."""
128 lib.LLVMSetDataLayout(self, new_data_layout)
132 return lib.LLVMGetTarget(self)
135 def target(self, new_target):
136 """new_target is a string."""
137 lib.LLVMSetTarget(self, new_target)
140 lib.LLVMDumpModule(self)
142 class __function_iterator(object):
143 def __init__(self, module, reverse=False):
145 self.reverse = reverse
147 self.function = self.module.last
149 self.function = self.module.first
155 if not isinstance(self.function, Function):
156 raise StopIteration("")
157 result = self.function
159 self.function = self.function.prev
161 self.function = self.function.next
165 return Module.__function_iterator(self)
167 def __reversed__(self):
168 return Module.__function_iterator(self, reverse=True)
172 return Function(lib.LLVMGetFirstFunction(self))
176 return Function(lib.LLVMGetLastFunction(self))
178 def print_module_to_file(self, filename):
180 # Result is inverted so 0 means everything was ok.
181 result = lib.LLVMPrintModuleToFile(self, filename, byref(out))
183 raise RuntimeError("LLVM Error: %s" % out.value)
185 class Function(Value):
187 def __init__(self, value):
188 Value.__init__(self, value)
192 f = lib.LLVMGetNextFunction(self)
193 return f and Function(f)
197 f = lib.LLVMGetPreviousFunction(self)
198 return f and Function(f)
202 b = lib.LLVMGetFirstBasicBlock(self)
203 return b and BasicBlock(b)
207 b = lib.LLVMGetLastBasicBlock(self)
208 return b and BasicBlock(b)
210 class __bb_iterator(object):
211 def __init__(self, function, reverse=False):
212 self.function = function
213 self.reverse = reverse
215 self.bb = function.last
217 self.bb = function.first
223 if not isinstance(self.bb, BasicBlock):
224 raise StopIteration("")
227 self.bb = self.bb.prev
229 self.bb = self.bb.next
233 return Function.__bb_iterator(self)
235 def __reversed__(self):
236 return Function.__bb_iterator(self, reverse=True)
239 return lib.LLVMCountBasicBlocks(self)
241 class BasicBlock(LLVMObject):
243 def __init__(self, value):
244 LLVMObject.__init__(self, value)
248 b = lib.LLVMGetNextBasicBlock(self)
249 return b and BasicBlock(b)
253 b = lib.LLVMGetPreviousBasicBlock(self)
254 return b and BasicBlock(b)
258 return lib.LLVMGetValueName(Value(lib.LLVMBasicBlockAsValue(self)))
261 lib.LLVMDumpValue(Value(lib.LLVMBasicBlockAsValue(self)))
263 class Context(LLVMObject):
265 def __init__(self, context=None):
267 context = lib.LLVMContextCreate()
268 LLVMObject.__init__(self, context, disposer=lib.LLVMContextDispose)
270 LLVMObject.__init__(self, context)
273 def GetGlobalContext(cls):
274 return Context(lib.LLVMGetGlobalContext())
276 class PassRegistry(LLVMObject):
277 """Represents an opaque pass registry object."""
280 LLVMObject.__init__(self,
281 lib.LLVMGetGlobalPassRegistry())
283 def register_library(library):
284 # Initialization/Shutdown declarations.
285 library.LLVMInitializeCore.argtypes = [PassRegistry]
286 library.LLVMInitializeCore.restype = None
288 library.LLVMInitializeTransformUtils.argtypes = [PassRegistry]
289 library.LLVMInitializeTransformUtils.restype = None
291 library.LLVMInitializeScalarOpts.argtypes = [PassRegistry]
292 library.LLVMInitializeScalarOpts.restype = None
294 library.LLVMInitializeObjCARCOpts.argtypes = [PassRegistry]
295 library.LLVMInitializeObjCARCOpts.restype = None
297 library.LLVMInitializeVectorization.argtypes = [PassRegistry]
298 library.LLVMInitializeVectorization.restype = None
300 library.LLVMInitializeInstCombine.argtypes = [PassRegistry]
301 library.LLVMInitializeInstCombine.restype = None
303 library.LLVMInitializeIPO.argtypes = [PassRegistry]
304 library.LLVMInitializeIPO.restype = None
306 library.LLVMInitializeInstrumentation.argtypes = [PassRegistry]
307 library.LLVMInitializeInstrumentation.restype = None
309 library.LLVMInitializeAnalysis.argtypes = [PassRegistry]
310 library.LLVMInitializeAnalysis.restype = None
312 library.LLVMInitializeIPA.argtypes = [PassRegistry]
313 library.LLVMInitializeIPA.restype = None
315 library.LLVMInitializeCodeGen.argtypes = [PassRegistry]
316 library.LLVMInitializeCodeGen.restype = None
318 library.LLVMInitializeTarget.argtypes = [PassRegistry]
319 library.LLVMInitializeTarget.restype = None
321 library.LLVMShutdown.argtypes = []
322 library.LLVMShutdown.restype = None
324 # Pass Registry declarations.
325 library.LLVMGetGlobalPassRegistry.argtypes = []
326 library.LLVMGetGlobalPassRegistry.restype = c_object_p
328 # Context declarations.
329 library.LLVMContextCreate.argtypes = []
330 library.LLVMContextCreate.restype = c_object_p
332 library.LLVMContextDispose.argtypes = [Context]
333 library.LLVMContextDispose.restype = None
335 library.LLVMGetGlobalContext.argtypes = []
336 library.LLVMGetGlobalContext.restype = c_object_p
338 # Memory buffer declarations
339 library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p,
340 POINTER(c_object_p), POINTER(c_char_p)]
341 library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool
343 library.LLVMGetBufferSize.argtypes = [MemoryBuffer]
345 library.LLVMDisposeMemoryBuffer.argtypes = [MemoryBuffer]
347 # Module declarations
348 library.LLVMModuleCreateWithName.argtypes = [c_char_p]
349 library.LLVMModuleCreateWithName.restype = c_object_p
351 library.LLVMDisposeModule.argtypes = [Module]
352 library.LLVMDisposeModule.restype = None
354 library.LLVMGetDataLayout.argtypes = [Module]
355 library.LLVMGetDataLayout.restype = c_char_p
357 library.LLVMSetDataLayout.argtypes = [Module, c_char_p]
358 library.LLVMSetDataLayout.restype = None
360 library.LLVMGetTarget.argtypes = [Module]
361 library.LLVMGetTarget.restype = c_char_p
363 library.LLVMSetTarget.argtypes = [Module, c_char_p]
364 library.LLVMSetTarget.restype = None
366 library.LLVMDumpModule.argtypes = [Module]
367 library.LLVMDumpModule.restype = None
369 library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p,
371 library.LLVMPrintModuleToFile.restype = bool
373 library.LLVMGetFirstFunction.argtypes = [Module]
374 library.LLVMGetFirstFunction.restype = c_object_p
376 library.LLVMGetLastFunction.argtypes = [Module]
377 library.LLVMGetLastFunction.restype = c_object_p
379 library.LLVMGetNextFunction.argtypes = [Function]
380 library.LLVMGetNextFunction.restype = c_object_p
382 library.LLVMGetPreviousFunction.argtypes = [Function]
383 library.LLVMGetPreviousFunction.restype = c_object_p
385 # Value declarations.
386 library.LLVMGetValueName.argtypes = [Value]
387 library.LLVMGetValueName.restype = c_char_p
389 library.LLVMDumpValue.argtypes = [Value]
390 library.LLVMDumpValue.restype = None
392 # Basic Block Declarations.
393 library.LLVMGetFirstBasicBlock.argtypes = [Function]
394 library.LLVMGetFirstBasicBlock.restype = c_object_p
396 library.LLVMGetLastBasicBlock.argtypes = [Function]
397 library.LLVMGetLastBasicBlock.restype = c_object_p
399 library.LLVMGetNextBasicBlock.argtypes = [BasicBlock]
400 library.LLVMGetNextBasicBlock.restype = c_object_p
402 library.LLVMGetPreviousBasicBlock.argtypes = [BasicBlock]
403 library.LLVMGetPreviousBasicBlock.restype = c_object_p
405 library.LLVMBasicBlockAsValue.argtypes = [BasicBlock]
406 library.LLVMBasicBlockAsValue.restype = c_object_p
408 library.LLVMCountBasicBlocks.argtypes = [Function]
409 library.LLVMCountBasicBlocks.restype = c_uint
411 def register_enumerations():
412 for name, value in enumerations.OpCodes:
413 OpCode.register(name, value)
415 def initialize_llvm():
416 c = Context.GetGlobalContext()
418 lib.LLVMInitializeCore(p)
419 lib.LLVMInitializeTransformUtils(p)
420 lib.LLVMInitializeScalarOpts(p)
421 lib.LLVMInitializeObjCARCOpts(p)
422 lib.LLVMInitializeVectorization(p)
423 lib.LLVMInitializeInstCombine(p)
424 lib.LLVMInitializeIPO(p)
425 lib.LLVMInitializeInstrumentation(p)
426 lib.LLVMInitializeAnalysis(p)
427 lib.LLVMInitializeIPA(p)
428 lib.LLVMInitializeCodeGen(p)
429 lib.LLVMInitializeTarget(p)
431 register_library(lib)
432 register_enumerations()