Set default namespace to top-level C++ namespace.

This commit is contained in:
Siu Kwan Lam 2013-02-08 18:10:52 -06:00
commit 6eae24bcf3
3 changed files with 124 additions and 120 deletions

View file

@ -83,19 +83,19 @@ class SubModule(object):
writer.println('};')
writer.println()
def generate_downcasts(self, println):
for ((fromty, toty), fn) in self.downcastlist:
name = fn.name
fmt = '''
static
%(toty)s* %(name)s(%(fromty)s* arg)
{
return typecast<%(toty)s>::from(arg);
}
'''
println(fmt % locals())
fn.generate_cpp(println)
# def generate_downcasts(self, println):
# for ((fromty, toty), fn) in self.downcastlist:
# name = fn.name
# fmt = '''
#static
#%(toty)s* %(name)s(%(fromty)s* arg)
#{
# return typecast< %(toty)s >::from(arg);
#}
# '''
# println(fmt % locals())
#
# fn.generate_cpp(println)
def generate_cpp(self, println, extras=()):
for unit in self.iter_all():
@ -151,7 +151,7 @@ static
class Namespace(SubModule):
def __init__(self, name):
SubModule.__init__(self)
self.name = name
self.name = name = name.lstrip(':')
namespaces[name] = self
def Class(self, *bases):
@ -187,6 +187,10 @@ class Namespace(SubModule):
def fullname(self):
return self.name
@property
def py_name(self):
return self.name.replace('::', '.')
@property
def localname(self):
return self.name.rsplit('::', 1)[-1]
@ -313,6 +317,11 @@ class Class(SubModule, _Type):
name = self.name
return '::'.join([self.ns.fullname, name])
@property
def py_name(self):
ns = self.ns.name.split('::')
return '.'.join(ns + [self.name])
def __str__(self):
return self.fullname
@ -323,7 +332,7 @@ class Class(SubModule, _Type):
writer.die_if_false(raw)
ptrty = ptr(self).fullname
ty = self.fullname
fmt = 'typecast<%(ty)s >::from(%(raw)s)'
fmt = 'typecast< %(ty)s >::from(%(raw)s)'
casted = writer.declare(ptrty, fmt % locals())
writer.die_if_false(casted)
return casted
@ -385,7 +394,7 @@ class Enum(object):
else:
k = v
fmt = '%(k)s = %(p)s.%(v)s()'
p = '.'.join(['_api'] + self.parent.fullname.split('::')[1:])
p = '.'.join(['_api'] + self.parent.fullname.split('::'))
writer.println(fmt % locals())
writer.println()
@ -415,7 +424,7 @@ class Method(object):
@property
def fullname(self):
return '::'.join([self.parent.fullname, self.realname])
return '::'.join([self.parent.fullname, self.realname]).lstrip(':')
@property
def realname(self):
@ -472,8 +481,7 @@ class Method(object):
writer.release_ownership(unwrap_this)
unwrapped = writer.unwrap_many(varargs)
self.process_ownedptr_args(writer, unwrapped)
func = '.'.join([self.parent.name, self.name])
func = '.'.join([self.parent.py_name, self.name])
ret = writer.call('_api.%s' % func,
args=(unwrap_this,), varargs=unwrapped)
@ -537,7 +545,7 @@ class StaticMethod(Method):
unwrapped = writer.unwrap_many(varargs)
self.process_ownedptr_args(writer, unwrapped)
func = '.'.join([self.parent.name, self.name])
func = '.'.join([self.parent.py_name, self.name])
ret = writer.call('_api.%s' % func, varargs=unwrapped)
wrapped = writer.wrap(ret, self.is_return_ownedptr())
writer.return_value(wrapped)
@ -570,11 +578,7 @@ class Function(Method):
with writer.function(self.name, varargs='args') as varargs:
unwrapped = writer.unwrap_many(varargs)
self.process_ownedptr_args(writer, unwrapped)
if '::' in self.parent.name:
ns = self.parent.name.split('::', 1)[-1].replace('::', '.')
func = '.'.join([ns, self.name])
else:
func = self.name
func = '.'.join([self.parent.py_name, self.name])
ret = writer.call('_api.%s' % func, varargs=unwrapped)
wrapped = writer.wrap(ret, self.is_return_ownedptr())
writer.return_value(wrapped)
@ -603,7 +607,7 @@ class Destructor(Method):
writer.return_value(None)
def compile_py(self, writer):
func = '.'.join([self.parent.name, self.name])
func = '.'.join([self.parent.py_name, self.name])
writer.println('_delete_ = _api.%s' % func)
@ -799,7 +803,7 @@ class Attr(object):
def compile_py(self, writer):
name = self.name
parent = '.'.join(self.parent.fullname.split('::')[1:])
parent = '.'.join(self.parent.fullname.split('::'))
getter = '.'.join([parent, self.getter_name])
setter = '.'.join([parent, self.setter_name])
writer.println('@property')

View file

@ -12,9 +12,9 @@ extern "C" {
PyObject *
PyInit_%(module)s(void)
{
PyObject *module = create_python_module("%(module)s", %(methtable)s);
PyObject *module = create_python_module("%(module)s", meth_%(ns)s);
if (module) {
if (populate_submodules(module, submodule_llvm))
if (populate_submodules(module, submodule_%(ns)s))
return module;
}
return NULL;
@ -25,9 +25,9 @@ return NULL;
PyMODINIT_FUNC
init%(module)s(void)
{
PyObject *module = create_python_module("%(module)s", %(methtable)s);
PyObject *module = create_python_module("%(module)s", meth_%(ns)s);
if (module) {
populate_submodules(module, submodule_llvm);
populate_submodules(module, submodule_%(ns)s);
}
}
#endif
@ -55,7 +55,7 @@ def main():
sys.path += [os.path.dirname(os.curdir)]
entry_module = __import__(entry_modname)
rootns = namespaces['llvm']
rootns = namespaces['']
# Generate C++ source
with open('%s.cpp' % outputfilename, 'w') as cppfile:
@ -73,7 +73,7 @@ def main():
static
%(toty)s* %(name)s(%(fromty)s* arg)
{
return typecast<%(toty)s>::from(arg);
return typecast< %(toty)s >::from(arg);
}
'''
println(fmt % locals())
@ -93,8 +93,8 @@ static
# generate submodule
rootns.generate_cpp(println, extras=[('extra', 'extra_methodtable'),
('downcast', 'downcast_methodtable')])
println(extension_entry % {'module' : '_api',
'methtable': 'meth_llvm'})
println(extension_entry % {'module' : '_api',
'ns' : ''})
# Generate Python source
rootns.generate_py(rootdir='.', name='api')

View file

@ -1,22 +1,22 @@
import api
from api import llvm
import extra
import _capsule
from StringIO import StringIO
api.capsule.set_debug(True)
llvm.capsule.set_debug(True)
def test_basic_jit_use():
api.InitializeNativeTarget()
api.InitializeNativeTargetAsmPrinter()
context = api.getGlobalContext()
llvm.InitializeNativeTarget()
llvm.InitializeNativeTargetAsmPrinter()
context = llvm.getGlobalContext()
m = api.Module.new("modname", context)
m = llvm.Module.new("modname", context)
print m.getModuleIdentifier()
m.setModuleIdentifier('modname2')
print m.getModuleIdentifier()
print 'endianness', m.getEndianness()
assert m.getEndianness() == api.Module.Endianness.AnyEndianness
assert m.getEndianness() == llvm.Module.Endianness.AnyEndianness
print 'pointer-size', m.getPointerSize()
assert m.getPointerSize() == api.Module.PointerSize.AnyPointerSize
assert m.getPointerSize() == llvm.Module.PointerSize.AnyPointerSize
m.dump()
@ -25,21 +25,21 @@ def test_basic_jit_use():
print os.str()
int1ty = api.Type.getInt1Ty(context)
int1ty = llvm.Type.getInt1Ty(context)
int1ty.dump()
assert int1ty.isIntegerTy(1)
fnty = api.FunctionType.get(int1ty, False)
fnty = llvm.FunctionType.get(int1ty, False)
fnty.dump()
types = [api.Type.getIntNTy(context, 8), api.Type.getIntNTy(context, 32)]
fnty = api.FunctionType.get(api.Type.getIntNTy(context, 8), types, False)
types = [llvm.Type.getIntNTy(context, 8), llvm.Type.getIntNTy(context, 32)]
fnty = llvm.FunctionType.get(llvm.Type.getIntNTy(context, 8), types, False)
print fnty
const = m.getOrInsertFunction("foo", fnty)
fn = const._downcast(api.Function)
fn = const._downcast(llvm.Function)
print fn
assert fn.hasName()
assert 'foo' == fn.getName()
@ -58,10 +58,10 @@ def test_basic_jit_use():
assert isinstance(fn_uselist, list)
assert len(fn_uselist) == 0
builder = api.IRBuilder.new(context)
builder = llvm.IRBuilder.new(context)
print builder
bb = api.BasicBlock.Create(context, "entry", fn, None)
bb = llvm.BasicBlock.Create(context, "entry", fn, None)
assert bb.empty()
builder.SetInsertPoint(bb)
@ -83,23 +83,23 @@ def test_basic_jit_use():
print m
# verifier
action = api.VerifierFailureAction.ReturnStatusAction
action = llvm.VerifierFailureAction.ReturnStatusAction
corrupted = api.verifyFunction(fn, action)
corrupted = llvm.verifyFunction(fn, action)
assert not corrupted
corrupted = api.verifyModule(m, action, errio)
corrupted = llvm.verifyModule(m, action, errio)
print corrupted
assert not corrupted, errio.getvalue()
# build pass manager
pmb = api.PassManagerBuilder.new()
pmb = llvm.PassManagerBuilder.new()
pmb.OptLevel = 3
assert pmb.OptLevel == 3
pmb.LibraryInfo = api.TargetLibraryInfo.new()
pmb.Inliner = api.createFunctionInliningPass()
pmb.LibraryInfo = llvm.TargetLibraryInfo.new()
pmb.Inliner = llvm.createFunctionInliningPass()
fpm = api.FunctionPassManager.new(m)
pm = api.PassManager.new()
fpm = llvm.FunctionPassManager.new(m)
pm = llvm.PassManager.new()
pmb.populateFunctionPassManager(fpm)
pmb.populateModulePassManager(pm)
@ -114,14 +114,14 @@ def test_basic_jit_use():
# build engine
ee = api.ExecutionEngine.createJIT(m, errio)
ee = llvm.ExecutionEngine.createJIT(m, errio)
print ee, errio.getvalue()
print ee.getDataLayout().getStringRepresentation()
datalayout_str = 'e-p:64:64:64-S128-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f16:16:16-f32:32:32-f64:64:64-f128:128:128-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64'
assert datalayout_str == str(api.DataLayout.new(datalayout_str))
assert datalayout_str == str(api.DataLayout.new(str(api.DataLayout.new(datalayout_str))))
assert datalayout_str == str(llvm.DataLayout.new(datalayout_str))
assert datalayout_str == str(llvm.DataLayout.new(str(llvm.DataLayout.new(datalayout_str))))
fn2 = ee.FindFunctionNamed(fn.getName())
assert fn2 is fn
@ -129,8 +129,8 @@ def test_basic_jit_use():
assert ee.getPointerToFunction(fn)
assert ee.getPointerToNamedFunction('printf')
gv0 = api.GenericValue.CreateInt(arg0.getType(), 12, False)
gv1 = api.GenericValue.CreateInt(arg1.getType(), -32, True)
gv0 = llvm.GenericValue.CreateInt(arg0.getType(), 12, False)
gv1 = llvm.GenericValue.CreateInt(arg1.getType(), -32, True)
assert gv0.valueIntWidth() == arg0.getType().getIntegerBitWidth()
assert gv1.valueIntWidth() == arg1.getType().getIntegerBitWidth()
@ -138,7 +138,7 @@ def test_basic_jit_use():
assert gv0.toUnsignedInt() == 12
assert gv1.toSignedInt() == -32
gv1 = api.GenericValue.CreateInt(arg1.getType(), 32, False)
gv1 = llvm.GenericValue.CreateInt(arg1.getType(), 32, False)
gvR = ee.runFunction(fn, (gv0, gv1))
@ -146,13 +146,13 @@ def test_basic_jit_use():
# write bitcode
bc_buffer = StringIO()
api.WriteBitcodeToFile(m, bc_buffer)
llvm.WriteBitcodeToFile(m, bc_buffer)
bc = bc_buffer.getvalue()
bc_buffer.close()
# read bitcode
errbuf = StringIO()
m2 = api.ParseBitCodeFile(bc, context, errbuf)
m2 = llvm.ParseBitCodeFile(bc, context, errbuf)
if not m2:
raise Exception(errbuf.getvalue())
else:
@ -160,35 +160,35 @@ def test_basic_jit_use():
assert str(m2) == str(m)
# parse llvm ir
m3 = api.ParseAssemblyString(str(m), None, api.SMDiagnostic.new(), context)
m3 = llvm.ParseAssemblyString(str(m), None, llvm.SMDiagnostic.new(), context)
m3.setModuleIdentifier(m.getModuleIdentifier())
assert str(m3) == str(m)
# test clone
m4 = api.CloneModule(m)
m4 = llvm.CloneModule(m)
assert m4 is not m
assert str(m4) == str(m)
def test_engine_builder():
api.InitializeNativeTarget()
context = api.getGlobalContext()
llvm.InitializeNativeTarget()
context = llvm.getGlobalContext()
m = api.Module.new("modname", context)
m = llvm.Module.new("modname", context)
int32ty = api.Type.getIntNTy(context, 32)
fnty = api.FunctionType.get(int32ty, [int32ty], False)
fn = m.getOrInsertFunction("foo", fnty)._downcast(api.Function)
bb = api.BasicBlock.Create(context, "entry", fn, None)
builder = api.IRBuilder.new(context)
int32ty = llvm.Type.getIntNTy(context, 32)
fnty = llvm.FunctionType.get(int32ty, [int32ty], False)
fn = m.getOrInsertFunction("foo", fnty)._downcast(llvm.Function)
bb = llvm.BasicBlock.Create(context, "entry", fn, None)
builder = llvm.IRBuilder.new(context)
builder.SetInsertPoint(bb)
builder.CreateRet(fn.getArgumentList()[0])
print fn
eb = api.EngineBuilder.new(m)
eb2 = eb.setEngineKind(api.EngineKind.Kind.JIT)
eb = llvm.EngineBuilder.new(m)
eb2 = eb.setEngineKind(llvm.EngineKind.Kind.JIT)
assert eb is eb2
eb.setOptLevel(api.CodeGenOpt.Level.Aggressive).setUseMCJIT(False)
eb.setOptLevel(llvm.CodeGenOpt.Level.Aggressive).setUseMCJIT(False)
tm = eb.selectTarget()
@ -205,7 +205,7 @@ def test_engine_builder():
ee = eb.create(tm)
triple = api.Triple.new('x86_64-unknown-linux')
triple = llvm.Triple.new('x86_64-unknown-linux')
assert triple.getArchName() == 'x86_64'
assert triple.getVendorName() == 'unknown'
assert triple.getOSName() == 'linux'
@ -216,18 +216,18 @@ def test_engine_builder():
print tm.getDataLayout()
pm = api.PassManager.new()
pm.add(api.DataLayout.new(str(tm.getDataLayout())))
pm.add(api.TargetLibraryInfo.new())
pm = llvm.PassManager.new()
pm.add(llvm.DataLayout.new(str(tm.getDataLayout())))
pm.add(llvm.TargetLibraryInfo.new())
# write assembly
pm = api.PassManager.new()
pm.add(api.DataLayout.new(str(tm.getDataLayout())))
pm = llvm.PassManager.new()
pm.add(llvm.DataLayout.new(str(tm.getDataLayout())))
raw = extra.make_raw_ostream_for_printing()
formatted = api.formatted_raw_ostream.new(raw, False)
formatted = llvm.formatted_raw_ostream.new(raw, False)
cgft = api.TargetMachine.CodeGenFileType.CGFT_AssemblyFile
cgft = llvm.TargetMachine.CodeGenFileType.CGFT_AssemblyFile
failed = tm.addPassesToEmitFile(pm, formatted, cgft, False)
assert not failed
@ -241,17 +241,17 @@ def test_engine_builder():
def test_linker():
context = api.getGlobalContext()
context = llvm.getGlobalContext()
mA = api.Module.new("modA", context)
mB = api.Module.new("modB", context)
mA = llvm.Module.new("modA", context)
mB = llvm.Module.new("modB", context)
def create_function(m, name):
int32ty = api.Type.getIntNTy(context, 32)
fnty = api.FunctionType.get(int32ty, [int32ty], False)
fn = m.getOrInsertFunction(name, fnty)._downcast(api.Function)
bb = api.BasicBlock.Create(context, "entry", fn, None)
builder = api.IRBuilder.new(context)
int32ty = llvm.Type.getIntNTy(context, 32)
fnty = llvm.FunctionType.get(int32ty, [int32ty], False)
fn = m.getOrInsertFunction(name, fnty)._downcast(llvm.Function)
bb = llvm.BasicBlock.Create(context, "entry", fn, None)
builder = llvm.IRBuilder.new(context)
builder.SetInsertPoint(bb)
builder.CreateRet(fn.getArgumentList()[0])
@ -259,8 +259,8 @@ def test_linker():
create_function(mB, 'bar')
errmsg = StringIO()
linkermode = api.Linker.LinkerMode.PreserveSource
failed = api.Linker.LinkModules(mA, mB, linkermode, errmsg)
linkermode = llvm.Linker.LinkerMode.PreserveSource
failed = llvm.Linker.LinkModules(mA, mB, linkermode, errmsg)
assert not failed, errmsg.getvalue()
assert mA.getFunction('foo')
assert mA.getFunction('bar')
@ -269,14 +269,14 @@ def test_linker():
mA.getFunction('bar')])
def test_structtype():
context = api.getGlobalContext()
m = api.Module.new("modname", context)
context = llvm.getGlobalContext()
m = llvm.Module.new("modname", context)
assert m.getTypeByName("truck") is None
truck = api.StructType.create(context, "truck")
truck = llvm.StructType.create(context, "truck")
assert 'type opaque' in str(truck)
elemtys = [api.Type.getInt32Ty(context), api.Type.getDoubleTy(context)]
elemtys = [llvm.Type.getInt32Ty(context), llvm.Type.getDoubleTy(context)]
truck.setBody(elemtys)
assert 'i32' in str(truck)
@ -285,13 +285,13 @@ def test_structtype():
assert m.getTypeByName("truck") is truck
def test_globalvariable():
context = api.getGlobalContext()
m = api.Module.new("modname", context)
context = llvm.getGlobalContext()
m = llvm.Module.new("modname", context)
ty = api.Type.getInt32Ty(context)
LinkageTypes = api.GlobalVariable.LinkageTypes
ty = llvm.Type.getInt32Ty(context)
LinkageTypes = llvm.GlobalVariable.LinkageTypes
linkage = LinkageTypes.ExternalLinkage
gvar = api.GlobalVariable.new(m, ty, False, linkage, None, "apple")
gvar = llvm.GlobalVariable.new(m, ty, False, linkage, None, "apple")
assert '@apple = external global i32' in str(m)
gvar2 = m.getNamedGlobal('apple')
@ -301,30 +301,30 @@ def test_globalvariable():
def test_sequentialtypes():
context = api.getGlobalContext()
int32ty = api.Type.getInt32Ty(context)
ary_int32x4 = api.ArrayType.get(int32ty, 4)
context = llvm.getGlobalContext()
int32ty = llvm.Type.getInt32Ty(context)
ary_int32x4 = llvm.ArrayType.get(int32ty, 4)
assert '[4 x i32]' == str(ary_int32x4)
ptr_int32 = api.PointerType.get(int32ty, 1)
ptr_int32 = llvm.PointerType.get(int32ty, 1)
assert 'i32 addrspace(1)*' == str(ptr_int32)
vec_int32x4 = api.VectorType.get(int32ty, 4)
vec_int32x4 = llvm.VectorType.get(int32ty, 4)
assert '<4 x i32>' == str(vec_int32x4)
def test_constants():
context = api.getGlobalContext()
int32ty = api.Type.getInt32Ty(context)
ary_int32x4 = api.ArrayType.get(int32ty, 4)
intconst = api.ConstantInt.get(int32ty, 123)
aryconst = api.ConstantArray.get(ary_int32x4, [intconst] * 4)
context = llvm.getGlobalContext()
int32ty = llvm.Type.getInt32Ty(context)
ary_int32x4 = llvm.ArrayType.get(int32ty, 4)
intconst = llvm.ConstantInt.get(int32ty, 123)
aryconst = llvm.ConstantArray.get(ary_int32x4, [intconst] * 4)
assert str(aryconst.getAggregateElement(0)) == str(intconst)
def test_intrinsic():
context = api.getGlobalContext()
m = api.Module.new("modname", context)
context = llvm.getGlobalContext()
m = llvm.Module.new("modname", context)
INTR_SIN = 1652
floatty = api.Type.getFloatTy(context)
fn = api.Intrinsic.getDeclaration(m, INTR_SIN, [floatty])
floatty = llvm.Type.getFloatTy(context)
fn = llvm.Intrinsic.getDeclaration(m, INTR_SIN, [floatty])
assert 'llvm.sin.f32' in str(fn)
fn.eraseFromParent()
assert 'llvm.sin.f32' not in str(m)