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
38 class LLVMEnumeration(object):
39 """Represents an individual LLVM enumeration."""
41 def __init__(self, name, value):
46 return '%s.%s' % (self.__class__.__name__,
50 def from_value(cls, value):
51 """Obtain an enumeration instance from a numeric value."""
52 result = cls._value_map.get(value, None)
55 raise ValueError('Unknown %s: %d' % (cls.__name__,
61 def register(cls, name, value):
62 """Registers a new enumeration.
64 This is called by this module for each enumeration defined in
65 enumerations. You should not need to call this outside this module.
67 if value in cls._value_map:
68 raise ValueError('%s value already registered: %d' % (cls.__name__,
70 enum = cls(name, value)
71 cls._value_map[value] = enum
72 setattr(cls, name, enum)
74 class Attribute(LLVMEnumeration):
75 """Represents an individual Attribute enumeration."""
79 def __init__(self, name, value):
80 super(Attribute, self).__init__(name, value)
82 class OpCode(LLVMEnumeration):
83 """Represents an individual OpCode enumeration."""
87 def __init__(self, name, value):
88 super(OpCode, self).__init__(name, value)
90 class TypeKind(LLVMEnumeration):
91 """Represents an individual TypeKind enumeration."""
95 def __init__(self, name, value):
96 super(TypeKind, self).__init__(name, value)
98 class Linkage(LLVMEnumeration):
99 """Represents an individual Linkage enumeration."""
103 def __init__(self, name, value):
104 super(Linkage, self).__init__(name, value)
106 class Visibility(LLVMEnumeration):
107 """Represents an individual visibility enumeration."""
111 def __init__(self, name, value):
112 super(Visibility, self).__init__(name, value)
114 class CallConv(LLVMEnumeration):
115 """Represents an individual calling convention enumeration."""
119 def __init__(self, name, value):
120 super(CallConv, self).__init__(name, value)
122 class IntPredicate(LLVMEnumeration):
123 """Represents an individual IntPredicate enumeration."""
127 def __init__(self, name, value):
128 super(IntPredicate, self).__init__(name, value)
130 class RealPredicate(LLVMEnumeration):
131 """Represents an individual RealPredicate enumeration."""
135 def __init__(self, name, value):
136 super(RealPredicate, self).__init__(name, value)
138 class LandingPadClauseTy(LLVMEnumeration):
139 """Represents an individual LandingPadClauseTy enumeration."""
143 def __init__(self, name, value):
144 super(LandingPadClauseTy, self).__init__(name, value)
146 class MemoryBuffer(LLVMObject):
147 """Represents an opaque memory buffer."""
149 def __init__(self, filename=None):
150 """Create a new memory buffer.
152 Currently, we support creating from the contents of a file at the
156 raise Exception("filename argument must be defined")
158 memory = c_object_p()
161 result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename,
162 byref(memory), byref(out))
165 raise Exception("Could not create memory buffer: %s" % out.value)
167 LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer)
170 return lib.LLVMGetBufferSize(self)
172 class Value(LLVMObject):
174 def __init__(self, value):
175 LLVMObject.__init__(self, value)
179 return lib.LLVMGetValueName(self)
182 lib.LLVMDumpValue(self)
184 def get_operand(self, i):
185 return Value(lib.LLVMGetOperand(self, i))
187 def set_operand(self, i, v):
188 return lib.LLVMSetOperand(self, i, v)
191 return lib.LLVMGetNumOperands(self)
193 class Module(LLVMObject):
194 """Represents the top-level structure of an llvm program in an opaque object."""
196 def __init__(self, module, name=None, context=None):
197 LLVMObject.__init__(self, module, disposer=lib.LLVMDisposeModule)
200 def CreateWithName(cls, module_id):
201 m = Module(lib.LLVMModuleCreateWithName(module_id))
202 Context.GetGlobalContext().take_ownership(m)
206 def datalayout(self):
207 return lib.LLVMGetDataLayout(self)
210 def datalayout(self, new_data_layout):
211 """new_data_layout is a string."""
212 lib.LLVMSetDataLayout(self, new_data_layout)
216 return lib.LLVMGetTarget(self)
219 def target(self, new_target):
220 """new_target is a string."""
221 lib.LLVMSetTarget(self, new_target)
224 lib.LLVMDumpModule(self)
226 class __function_iterator(object):
227 def __init__(self, module, reverse=False):
229 self.reverse = reverse
231 self.function = self.module.last
233 self.function = self.module.first
239 if not isinstance(self.function, Function):
240 raise StopIteration("")
241 result = self.function
243 self.function = self.function.prev
245 self.function = self.function.next
249 return Module.__function_iterator(self)
251 def __reversed__(self):
252 return Module.__function_iterator(self, reverse=True)
256 return Function(lib.LLVMGetFirstFunction(self))
260 return Function(lib.LLVMGetLastFunction(self))
262 def print_module_to_file(self, filename):
264 # Result is inverted so 0 means everything was ok.
265 result = lib.LLVMPrintModuleToFile(self, filename, byref(out))
267 raise RuntimeError("LLVM Error: %s" % out.value)
269 class Function(Value):
271 def __init__(self, value):
272 Value.__init__(self, value)
276 f = lib.LLVMGetNextFunction(self)
277 return f and Function(f)
281 f = lib.LLVMGetPreviousFunction(self)
282 return f and Function(f)
286 b = lib.LLVMGetFirstBasicBlock(self)
287 return b and BasicBlock(b)
291 b = lib.LLVMGetLastBasicBlock(self)
292 return b and BasicBlock(b)
294 class __bb_iterator(object):
295 def __init__(self, function, reverse=False):
296 self.function = function
297 self.reverse = reverse
299 self.bb = function.last
301 self.bb = function.first
307 if not isinstance(self.bb, BasicBlock):
308 raise StopIteration("")
311 self.bb = self.bb.prev
313 self.bb = self.bb.next
317 return Function.__bb_iterator(self)
319 def __reversed__(self):
320 return Function.__bb_iterator(self, reverse=True)
323 return lib.LLVMCountBasicBlocks(self)
325 class BasicBlock(LLVMObject):
327 def __init__(self, value):
328 LLVMObject.__init__(self, value)
332 b = lib.LLVMGetNextBasicBlock(self)
333 return b and BasicBlock(b)
337 b = lib.LLVMGetPreviousBasicBlock(self)
338 return b and BasicBlock(b)
342 i = lib.LLVMGetFirstInstruction(self)
343 return i and Instruction(i)
347 i = lib.LLVMGetLastInstruction(self)
348 return i and Instruction(i)
350 def __as_value(self):
351 return Value(lib.LLVMBasicBlockAsValue(self))
355 return lib.LLVMGetValueName(self.__as_value())
358 lib.LLVMDumpValue(self.__as_value())
360 def get_operand(self, i):
361 return Value(lib.LLVMGetOperand(self.__as_value(),
364 def set_operand(self, i, v):
365 return lib.LLVMSetOperand(self.__as_value(),
369 return lib.LLVMGetNumOperands(self.__as_value())
371 class __inst_iterator(object):
372 def __init__(self, bb, reverse=False):
374 self.reverse = reverse
376 self.inst = self.bb.last
378 self.inst = self.bb.first
384 if not isinstance(self.inst, Instruction):
385 raise StopIteration("")
388 self.inst = self.inst.prev
390 self.inst = self.inst.next
394 return BasicBlock.__inst_iterator(self)
396 def __reversed__(self):
397 return BasicBlock.__inst_iterator(self, reverse=True)
400 class Instruction(Value):
402 def __init__(self, value):
403 Value.__init__(self, value)
407 i = lib.LLVMGetNextInstruction(self)
408 return i and Instruction(i)
412 i = lib.LLVMGetPreviousInstruction(self)
413 return i and Instruction(i)
417 return OpCode.from_value(lib.LLVMGetInstructionOpcode(self))
419 class Context(LLVMObject):
421 def __init__(self, context=None):
423 context = lib.LLVMContextCreate()
424 LLVMObject.__init__(self, context, disposer=lib.LLVMContextDispose)
426 LLVMObject.__init__(self, context)
429 def GetGlobalContext(cls):
430 return Context(lib.LLVMGetGlobalContext())
432 class PassRegistry(LLVMObject):
433 """Represents an opaque pass registry object."""
436 LLVMObject.__init__(self,
437 lib.LLVMGetGlobalPassRegistry())
439 def register_library(library):
440 # Initialization/Shutdown declarations.
441 library.LLVMInitializeCore.argtypes = [PassRegistry]
442 library.LLVMInitializeCore.restype = None
444 library.LLVMInitializeTransformUtils.argtypes = [PassRegistry]
445 library.LLVMInitializeTransformUtils.restype = None
447 library.LLVMInitializeScalarOpts.argtypes = [PassRegistry]
448 library.LLVMInitializeScalarOpts.restype = None
450 library.LLVMInitializeObjCARCOpts.argtypes = [PassRegistry]
451 library.LLVMInitializeObjCARCOpts.restype = None
453 library.LLVMInitializeVectorization.argtypes = [PassRegistry]
454 library.LLVMInitializeVectorization.restype = None
456 library.LLVMInitializeInstCombine.argtypes = [PassRegistry]
457 library.LLVMInitializeInstCombine.restype = None
459 library.LLVMInitializeIPO.argtypes = [PassRegistry]
460 library.LLVMInitializeIPO.restype = None
462 library.LLVMInitializeInstrumentation.argtypes = [PassRegistry]
463 library.LLVMInitializeInstrumentation.restype = None
465 library.LLVMInitializeAnalysis.argtypes = [PassRegistry]
466 library.LLVMInitializeAnalysis.restype = None
468 library.LLVMInitializeCodeGen.argtypes = [PassRegistry]
469 library.LLVMInitializeCodeGen.restype = None
471 library.LLVMInitializeTarget.argtypes = [PassRegistry]
472 library.LLVMInitializeTarget.restype = None
474 library.LLVMShutdown.argtypes = []
475 library.LLVMShutdown.restype = None
477 # Pass Registry declarations.
478 library.LLVMGetGlobalPassRegistry.argtypes = []
479 library.LLVMGetGlobalPassRegistry.restype = c_object_p
481 # Context declarations.
482 library.LLVMContextCreate.argtypes = []
483 library.LLVMContextCreate.restype = c_object_p
485 library.LLVMContextDispose.argtypes = [Context]
486 library.LLVMContextDispose.restype = None
488 library.LLVMGetGlobalContext.argtypes = []
489 library.LLVMGetGlobalContext.restype = c_object_p
491 # Memory buffer declarations
492 library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p,
493 POINTER(c_object_p), POINTER(c_char_p)]
494 library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool
496 library.LLVMGetBufferSize.argtypes = [MemoryBuffer]
498 library.LLVMDisposeMemoryBuffer.argtypes = [MemoryBuffer]
500 # Module declarations
501 library.LLVMModuleCreateWithName.argtypes = [c_char_p]
502 library.LLVMModuleCreateWithName.restype = c_object_p
504 library.LLVMDisposeModule.argtypes = [Module]
505 library.LLVMDisposeModule.restype = None
507 library.LLVMGetDataLayout.argtypes = [Module]
508 library.LLVMGetDataLayout.restype = c_char_p
510 library.LLVMSetDataLayout.argtypes = [Module, c_char_p]
511 library.LLVMSetDataLayout.restype = None
513 library.LLVMGetTarget.argtypes = [Module]
514 library.LLVMGetTarget.restype = c_char_p
516 library.LLVMSetTarget.argtypes = [Module, c_char_p]
517 library.LLVMSetTarget.restype = None
519 library.LLVMDumpModule.argtypes = [Module]
520 library.LLVMDumpModule.restype = None
522 library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p,
524 library.LLVMPrintModuleToFile.restype = bool
526 library.LLVMGetFirstFunction.argtypes = [Module]
527 library.LLVMGetFirstFunction.restype = c_object_p
529 library.LLVMGetLastFunction.argtypes = [Module]
530 library.LLVMGetLastFunction.restype = c_object_p
532 library.LLVMGetNextFunction.argtypes = [Function]
533 library.LLVMGetNextFunction.restype = c_object_p
535 library.LLVMGetPreviousFunction.argtypes = [Function]
536 library.LLVMGetPreviousFunction.restype = c_object_p
538 # Value declarations.
539 library.LLVMGetValueName.argtypes = [Value]
540 library.LLVMGetValueName.restype = c_char_p
542 library.LLVMDumpValue.argtypes = [Value]
543 library.LLVMDumpValue.restype = None
545 library.LLVMGetOperand.argtypes = [Value, c_uint]
546 library.LLVMGetOperand.restype = c_object_p
548 library.LLVMSetOperand.argtypes = [Value, Value, c_uint]
549 library.LLVMSetOperand.restype = None
551 library.LLVMGetNumOperands.argtypes = [Value]
552 library.LLVMGetNumOperands.restype = c_uint
554 # Basic Block Declarations.
555 library.LLVMGetFirstBasicBlock.argtypes = [Function]
556 library.LLVMGetFirstBasicBlock.restype = c_object_p
558 library.LLVMGetLastBasicBlock.argtypes = [Function]
559 library.LLVMGetLastBasicBlock.restype = c_object_p
561 library.LLVMGetNextBasicBlock.argtypes = [BasicBlock]
562 library.LLVMGetNextBasicBlock.restype = c_object_p
564 library.LLVMGetPreviousBasicBlock.argtypes = [BasicBlock]
565 library.LLVMGetPreviousBasicBlock.restype = c_object_p
567 library.LLVMGetFirstInstruction.argtypes = [BasicBlock]
568 library.LLVMGetFirstInstruction.restype = c_object_p
570 library.LLVMGetLastInstruction.argtypes = [BasicBlock]
571 library.LLVMGetLastInstruction.restype = c_object_p
573 library.LLVMBasicBlockAsValue.argtypes = [BasicBlock]
574 library.LLVMBasicBlockAsValue.restype = c_object_p
576 library.LLVMCountBasicBlocks.argtypes = [Function]
577 library.LLVMCountBasicBlocks.restype = c_uint
579 # Instruction Declarations.
580 library.LLVMGetNextInstruction.argtypes = [Instruction]
581 library.LLVMGetNextInstruction.restype = c_object_p
583 library.LLVMGetPreviousInstruction.argtypes = [Instruction]
584 library.LLVMGetPreviousInstruction.restype = c_object_p
586 library.LLVMGetInstructionOpcode.argtypes = [Instruction]
587 library.LLVMGetInstructionOpcode.restype = c_uint
589 def register_enumerations():
593 (Attribute, enumerations.Attributes),
594 (OpCode, enumerations.OpCodes),
595 (TypeKind, enumerations.TypeKinds),
596 (Linkage, enumerations.Linkages),
597 (Visibility, enumerations.Visibility),
598 (CallConv, enumerations.CallConv),
599 (IntPredicate, enumerations.IntPredicate),
600 (RealPredicate, enumerations.RealPredicate),
601 (LandingPadClauseTy, enumerations.LandingPadClauseTy),
603 for enum_class, enum_spec in enums:
604 for name, value in enum_spec:
606 enum_class.register(name, value)
609 def initialize_llvm():
610 Context.GetGlobalContext()
612 lib.LLVMInitializeCore(p)
613 lib.LLVMInitializeTransformUtils(p)
614 lib.LLVMInitializeScalarOpts(p)
615 lib.LLVMInitializeObjCARCOpts(p)
616 lib.LLVMInitializeVectorization(p)
617 lib.LLVMInitializeInstCombine(p)
618 lib.LLVMInitializeIPO(p)
619 lib.LLVMInitializeInstrumentation(p)
620 lib.LLVMInitializeAnalysis(p)
621 lib.LLVMInitializeCodeGen(p)
622 lib.LLVMInitializeTarget(p)
624 register_library(lib)
625 Enums = register_enumerations()