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.LLVMInitializeIPA.argtypes = [PassRegistry]
469
library.LLVMInitializeIPA.restype = None
471
library.LLVMInitializeCodeGen.argtypes = [PassRegistry]
472
library.LLVMInitializeCodeGen.restype = None
474
library.LLVMInitializeTarget.argtypes = [PassRegistry]
475
library.LLVMInitializeTarget.restype = None
477
library.LLVMShutdown.argtypes = []
478
library.LLVMShutdown.restype = None
480
# Pass Registry declarations.
481
library.LLVMGetGlobalPassRegistry.argtypes = []
482
library.LLVMGetGlobalPassRegistry.restype = c_object_p
484
# Context declarations.
485
library.LLVMContextCreate.argtypes = []
486
library.LLVMContextCreate.restype = c_object_p
488
library.LLVMContextDispose.argtypes = [Context]
489
library.LLVMContextDispose.restype = None
491
library.LLVMGetGlobalContext.argtypes = []
492
library.LLVMGetGlobalContext.restype = c_object_p
494
# Memory buffer declarations
495
library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p,
496
POINTER(c_object_p), POINTER(c_char_p)]
497
library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool
499
library.LLVMGetBufferSize.argtypes = [MemoryBuffer]
501
library.LLVMDisposeMemoryBuffer.argtypes = [MemoryBuffer]
503
# Module declarations
504
library.LLVMModuleCreateWithName.argtypes = [c_char_p]
505
library.LLVMModuleCreateWithName.restype = c_object_p
507
library.LLVMDisposeModule.argtypes = [Module]
508
library.LLVMDisposeModule.restype = None
510
library.LLVMGetDataLayout.argtypes = [Module]
511
library.LLVMGetDataLayout.restype = c_char_p
513
library.LLVMSetDataLayout.argtypes = [Module, c_char_p]
514
library.LLVMSetDataLayout.restype = None
516
library.LLVMGetTarget.argtypes = [Module]
517
library.LLVMGetTarget.restype = c_char_p
519
library.LLVMSetTarget.argtypes = [Module, c_char_p]
520
library.LLVMSetTarget.restype = None
522
library.LLVMDumpModule.argtypes = [Module]
523
library.LLVMDumpModule.restype = None
525
library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p,
527
library.LLVMPrintModuleToFile.restype = bool
529
library.LLVMGetFirstFunction.argtypes = [Module]
530
library.LLVMGetFirstFunction.restype = c_object_p
532
library.LLVMGetLastFunction.argtypes = [Module]
533
library.LLVMGetLastFunction.restype = c_object_p
535
library.LLVMGetNextFunction.argtypes = [Function]
536
library.LLVMGetNextFunction.restype = c_object_p
538
library.LLVMGetPreviousFunction.argtypes = [Function]
539
library.LLVMGetPreviousFunction.restype = c_object_p
541
# Value declarations.
542
library.LLVMGetValueName.argtypes = [Value]
543
library.LLVMGetValueName.restype = c_char_p
545
library.LLVMDumpValue.argtypes = [Value]
546
library.LLVMDumpValue.restype = None
548
library.LLVMGetOperand.argtypes = [Value, c_uint]
549
library.LLVMGetOperand.restype = c_object_p
551
library.LLVMSetOperand.argtypes = [Value, Value, c_uint]
552
library.LLVMSetOperand.restype = None
554
library.LLVMGetNumOperands.argtypes = [Value]
555
library.LLVMGetNumOperands.restype = c_uint
557
# Basic Block Declarations.
558
library.LLVMGetFirstBasicBlock.argtypes = [Function]
559
library.LLVMGetFirstBasicBlock.restype = c_object_p
561
library.LLVMGetLastBasicBlock.argtypes = [Function]
562
library.LLVMGetLastBasicBlock.restype = c_object_p
564
library.LLVMGetNextBasicBlock.argtypes = [BasicBlock]
565
library.LLVMGetNextBasicBlock.restype = c_object_p
567
library.LLVMGetPreviousBasicBlock.argtypes = [BasicBlock]
568
library.LLVMGetPreviousBasicBlock.restype = c_object_p
570
library.LLVMGetFirstInstruction.argtypes = [BasicBlock]
571
library.LLVMGetFirstInstruction.restype = c_object_p
573
library.LLVMGetLastInstruction.argtypes = [BasicBlock]
574
library.LLVMGetLastInstruction.restype = c_object_p
576
library.LLVMBasicBlockAsValue.argtypes = [BasicBlock]
577
library.LLVMBasicBlockAsValue.restype = c_object_p
579
library.LLVMCountBasicBlocks.argtypes = [Function]
580
library.LLVMCountBasicBlocks.restype = c_uint
582
# Instruction Declarations.
583
library.LLVMGetNextInstruction.argtypes = [Instruction]
584
library.LLVMGetNextInstruction.restype = c_object_p
586
library.LLVMGetPreviousInstruction.argtypes = [Instruction]
587
library.LLVMGetPreviousInstruction.restype = c_object_p
589
library.LLVMGetInstructionOpcode.argtypes = [Instruction]
590
library.LLVMGetInstructionOpcode.restype = c_uint
592
def register_enumerations():
596
(Attribute, enumerations.Attributes),
597
(OpCode, enumerations.OpCodes),
598
(TypeKind, enumerations.TypeKinds),
599
(Linkage, enumerations.Linkages),
600
(Visibility, enumerations.Visibility),
601
(CallConv, enumerations.CallConv),
602
(IntPredicate, enumerations.IntPredicate),
603
(RealPredicate, enumerations.RealPredicate),
604
(LandingPadClauseTy, enumerations.LandingPadClauseTy),
606
for enum_class, enum_spec in enums:
607
for name, value in enum_spec:
609
enum_class.register(name, value)
612
def initialize_llvm():
613
Context.GetGlobalContext()
615
lib.LLVMInitializeCore(p)
616
lib.LLVMInitializeTransformUtils(p)
617
lib.LLVMInitializeScalarOpts(p)
618
lib.LLVMInitializeObjCARCOpts(p)
619
lib.LLVMInitializeVectorization(p)
620
lib.LLVMInitializeInstCombine(p)
621
lib.LLVMInitializeIPO(p)
622
lib.LLVMInitializeInstrumentation(p)
623
lib.LLVMInitializeAnalysis(p)
624
lib.LLVMInitializeIPA(p)
625
lib.LLVMInitializeCodeGen(p)
626
lib.LLVMInitializeTarget(p)
628
register_library(lib)
629
Enums = register_enumerations()