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
37 """Represents an individual OpCode enumeration."""
41 def __init__(self, name, value):
46 return 'OpCode.%s' % self.name
49 def from_value(value):
50 """Obtain an OpCode instance from a numeric value."""
51 result = OpCode._value_map.get(value, None)
54 raise ValueError('Unknown OpCode: %d' % value)
59 def register(name, value):
60 """Registers a new OpCode enumeration.
62 This is called by this module for each enumeration defined in
63 enumerations. You should not need to call this outside this module.
65 if value in OpCode._value_map:
66 raise ValueError('OpCode value already registered: %d' % value)
68 opcode = OpCode(name, value)
69 OpCode._value_map[value] = opcode
70 setattr(OpCode, name, opcode)
72 class MemoryBuffer(LLVMObject):
73 """Represents an opaque memory buffer."""
75 def __init__(self, filename=None):
76 """Create a new memory buffer.
78 Currently, we support creating from the contents of a file at the
82 raise Exception("filename argument must be defined")
87 result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename,
88 byref(memory), byref(out))
91 raise Exception("Could not create memory buffer: %s" % out.value)
93 LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer)
96 return lib.LLVMGetBufferSize(self)
98 class Value(LLVMObject):
100 def __init__(self, value):
101 LLVMObject.__init__(self, value)
105 return lib.LLVMGetValueName(self)
108 lib.LLVMDumpValue(self)
110 class Module(LLVMObject):
111 """Represents the top-level structure of an llvm program in an opaque object."""
113 def __init__(self, module, name=None, context=None):
114 LLVMObject.__init__(self, module, disposer=lib.LLVMDisposeModule)
117 def CreateWithName(cls, module_id):
118 m = Module(lib.LLVMModuleCreateWithName(module_id))
119 c = Context.GetGlobalContext().take_ownership(m)
123 def datalayout(self):
124 return lib.LLVMGetDataLayout(self)
127 def datalayout(self, new_data_layout):
128 """new_data_layout is a string."""
129 lib.LLVMSetDataLayout(self, new_data_layout)
133 return lib.LLVMGetTarget(self)
136 def target(self, new_target):
137 """new_target is a string."""
138 lib.LLVMSetTarget(self, new_target)
141 lib.LLVMDumpModule(self)
143 class __function_iterator(object):
144 def __init__(self, module, reverse=False):
146 self.reverse = reverse
148 self.function = self.module.last
150 self.function = self.module.first
156 if not isinstance(self.function, Function):
157 raise StopIteration("")
158 result = self.function
160 self.function = self.function.prev
162 self.function = self.function.next
166 return Module.__function_iterator(self)
168 def __reversed__(self):
169 return Module.__function_iterator(self, reverse=True)
173 return Function(lib.LLVMGetFirstFunction(self))
177 return Function(lib.LLVMGetLastFunction(self))
179 def print_module_to_file(self, filename):
181 # Result is inverted so 0 means everything was ok.
182 result = lib.LLVMPrintModuleToFile(self, filename, byref(out))
184 raise RuntimeError("LLVM Error: %s" % out.value)
186 class Function(Value):
188 def __init__(self, value):
189 Value.__init__(self, value)
193 f = lib.LLVMGetNextFunction(self)
194 return f and Function(f)
198 f = lib.LLVMGetPreviousFunction(self)
199 return f and Function(f)
203 b = lib.LLVMGetFirstBasicBlock(self)
204 return b and BasicBlock(b)
208 b = lib.LLVMGetLastBasicBlock(self)
209 return b and BasicBlock(b)
211 class __bb_iterator(object):
212 def __init__(self, function, reverse=False):
213 self.function = function
214 self.reverse = reverse
216 self.bb = function.last
218 self.bb = function.first
224 if not isinstance(self.bb, BasicBlock):
225 raise StopIteration("")
228 self.bb = self.bb.prev
230 self.bb = self.bb.next
234 return Function.__bb_iterator(self)
236 def __reversed__(self):
237 return Function.__bb_iterator(self, reverse=True)
240 return lib.LLVMCountBasicBlocks(self)
242 class BasicBlock(LLVMObject):
244 def __init__(self, value):
245 LLVMObject.__init__(self, value)
249 b = lib.LLVMGetNextBasicBlock(self)
250 return b and BasicBlock(b)
254 b = lib.LLVMGetPreviousBasicBlock(self)
255 return b and BasicBlock(b)
259 i = lib.LLVMGetFirstInstruction(self)
260 return i and Instruction(i)
264 i = lib.LLVMGetLastInstruction(self)
265 return i and Instruction(i)
269 return lib.LLVMGetValueName(Value(lib.LLVMBasicBlockAsValue(self)))
272 lib.LLVMDumpValue(Value(lib.LLVMBasicBlockAsValue(self)))
274 class __inst_iterator(object):
275 def __init__(self, bb, reverse=False):
277 self.reverse = reverse
279 self.inst = self.bb.last
281 self.inst = self.bb.first
287 if not isinstance(self.inst, Instruction):
288 raise StopIteration("")
291 self.inst = self.inst.prev
293 self.inst = self.inst.next
297 return BasicBlock.__inst_iterator(self)
299 def __reversed__(self):
300 return BasicBlock.__inst_iterator(self, reverse=True)
303 class Instruction(Value):
305 def __init__(self, value):
306 Value.__init__(self, value)
310 i = lib.LLVMGetNextInstruction(self)
311 return i and Instruction(i)
315 i = lib.LLVMGetPreviousInstruction(self)
316 return i and Instruction(i)
320 return OpCode.from_value(lib.LLVMGetInstructionOpcode(self))
322 class Context(LLVMObject):
324 def __init__(self, context=None):
326 context = lib.LLVMContextCreate()
327 LLVMObject.__init__(self, context, disposer=lib.LLVMContextDispose)
329 LLVMObject.__init__(self, context)
332 def GetGlobalContext(cls):
333 return Context(lib.LLVMGetGlobalContext())
335 class PassRegistry(LLVMObject):
336 """Represents an opaque pass registry object."""
339 LLVMObject.__init__(self,
340 lib.LLVMGetGlobalPassRegistry())
342 def register_library(library):
343 # Initialization/Shutdown declarations.
344 library.LLVMInitializeCore.argtypes = [PassRegistry]
345 library.LLVMInitializeCore.restype = None
347 library.LLVMInitializeTransformUtils.argtypes = [PassRegistry]
348 library.LLVMInitializeTransformUtils.restype = None
350 library.LLVMInitializeScalarOpts.argtypes = [PassRegistry]
351 library.LLVMInitializeScalarOpts.restype = None
353 library.LLVMInitializeObjCARCOpts.argtypes = [PassRegistry]
354 library.LLVMInitializeObjCARCOpts.restype = None
356 library.LLVMInitializeVectorization.argtypes = [PassRegistry]
357 library.LLVMInitializeVectorization.restype = None
359 library.LLVMInitializeInstCombine.argtypes = [PassRegistry]
360 library.LLVMInitializeInstCombine.restype = None
362 library.LLVMInitializeIPO.argtypes = [PassRegistry]
363 library.LLVMInitializeIPO.restype = None
365 library.LLVMInitializeInstrumentation.argtypes = [PassRegistry]
366 library.LLVMInitializeInstrumentation.restype = None
368 library.LLVMInitializeAnalysis.argtypes = [PassRegistry]
369 library.LLVMInitializeAnalysis.restype = None
371 library.LLVMInitializeIPA.argtypes = [PassRegistry]
372 library.LLVMInitializeIPA.restype = None
374 library.LLVMInitializeCodeGen.argtypes = [PassRegistry]
375 library.LLVMInitializeCodeGen.restype = None
377 library.LLVMInitializeTarget.argtypes = [PassRegistry]
378 library.LLVMInitializeTarget.restype = None
380 library.LLVMShutdown.argtypes = []
381 library.LLVMShutdown.restype = None
383 # Pass Registry declarations.
384 library.LLVMGetGlobalPassRegistry.argtypes = []
385 library.LLVMGetGlobalPassRegistry.restype = c_object_p
387 # Context declarations.
388 library.LLVMContextCreate.argtypes = []
389 library.LLVMContextCreate.restype = c_object_p
391 library.LLVMContextDispose.argtypes = [Context]
392 library.LLVMContextDispose.restype = None
394 library.LLVMGetGlobalContext.argtypes = []
395 library.LLVMGetGlobalContext.restype = c_object_p
397 # Memory buffer declarations
398 library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p,
399 POINTER(c_object_p), POINTER(c_char_p)]
400 library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool
402 library.LLVMGetBufferSize.argtypes = [MemoryBuffer]
404 library.LLVMDisposeMemoryBuffer.argtypes = [MemoryBuffer]
406 # Module declarations
407 library.LLVMModuleCreateWithName.argtypes = [c_char_p]
408 library.LLVMModuleCreateWithName.restype = c_object_p
410 library.LLVMDisposeModule.argtypes = [Module]
411 library.LLVMDisposeModule.restype = None
413 library.LLVMGetDataLayout.argtypes = [Module]
414 library.LLVMGetDataLayout.restype = c_char_p
416 library.LLVMSetDataLayout.argtypes = [Module, c_char_p]
417 library.LLVMSetDataLayout.restype = None
419 library.LLVMGetTarget.argtypes = [Module]
420 library.LLVMGetTarget.restype = c_char_p
422 library.LLVMSetTarget.argtypes = [Module, c_char_p]
423 library.LLVMSetTarget.restype = None
425 library.LLVMDumpModule.argtypes = [Module]
426 library.LLVMDumpModule.restype = None
428 library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p,
430 library.LLVMPrintModuleToFile.restype = bool
432 library.LLVMGetFirstFunction.argtypes = [Module]
433 library.LLVMGetFirstFunction.restype = c_object_p
435 library.LLVMGetLastFunction.argtypes = [Module]
436 library.LLVMGetLastFunction.restype = c_object_p
438 library.LLVMGetNextFunction.argtypes = [Function]
439 library.LLVMGetNextFunction.restype = c_object_p
441 library.LLVMGetPreviousFunction.argtypes = [Function]
442 library.LLVMGetPreviousFunction.restype = c_object_p
444 # Value declarations.
445 library.LLVMGetValueName.argtypes = [Value]
446 library.LLVMGetValueName.restype = c_char_p
448 library.LLVMDumpValue.argtypes = [Value]
449 library.LLVMDumpValue.restype = None
451 # Basic Block Declarations.
452 library.LLVMGetFirstBasicBlock.argtypes = [Function]
453 library.LLVMGetFirstBasicBlock.restype = c_object_p
455 library.LLVMGetLastBasicBlock.argtypes = [Function]
456 library.LLVMGetLastBasicBlock.restype = c_object_p
458 library.LLVMGetNextBasicBlock.argtypes = [BasicBlock]
459 library.LLVMGetNextBasicBlock.restype = c_object_p
461 library.LLVMGetPreviousBasicBlock.argtypes = [BasicBlock]
462 library.LLVMGetPreviousBasicBlock.restype = c_object_p
464 library.LLVMGetFirstInstruction.argtypes = [BasicBlock]
465 library.LLVMGetFirstInstruction.restype = c_object_p
467 library.LLVMGetLastInstruction.argtypes = [BasicBlock]
468 library.LLVMGetLastInstruction.restype = c_object_p
470 library.LLVMBasicBlockAsValue.argtypes = [BasicBlock]
471 library.LLVMBasicBlockAsValue.restype = c_object_p
473 library.LLVMCountBasicBlocks.argtypes = [Function]
474 library.LLVMCountBasicBlocks.restype = c_uint
476 # Instruction Declarations.
477 library.LLVMGetNextInstruction.argtypes = [Instruction]
478 library.LLVMGetNextInstruction.restype = c_object_p
480 library.LLVMGetPreviousInstruction.argtypes = [Instruction]
481 library.LLVMGetPreviousInstruction.restype = c_object_p
483 library.LLVMGetInstructionOpcode.argtypes = [Instruction]
484 library.LLVMGetInstructionOpcode.restype = c_uint
486 def register_enumerations():
487 for name, value in enumerations.OpCodes:
488 OpCode.register(name, value)
490 def initialize_llvm():
491 c = Context.GetGlobalContext()
493 lib.LLVMInitializeCore(p)
494 lib.LLVMInitializeTransformUtils(p)
495 lib.LLVMInitializeScalarOpts(p)
496 lib.LLVMInitializeObjCARCOpts(p)
497 lib.LLVMInitializeVectorization(p)
498 lib.LLVMInitializeInstCombine(p)
499 lib.LLVMInitializeIPO(p)
500 lib.LLVMInitializeInstrumentation(p)
501 lib.LLVMInitializeAnalysis(p)
502 lib.LLVMInitializeIPA(p)
503 lib.LLVMInitializeCodeGen(p)
504 lib.LLVMInitializeTarget(p)
506 register_library(lib)
507 register_enumerations()