LlvmGenerator.py 25.6 KB
Newer Older
Maxime Perrotin's avatar
Maxime Perrotin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    OpenGEODE - A tiny SDL Editor for TASTE

    This module generates LLVM IR code from SDL process models, allowing
    generation of a binary application without an intermediate language.
    LLVM also allows for various code verification, analysis, and optimization.

    The design is based on the Ada code generator. Check it for details.

    Copyright (c) 2012-2013 European Space Agency

    Designed and implemented by Maxime Perrotin

    Contact: maxime.perrotin@esa.int
"""

import logging
Maxime Perrotin's avatar
Maxime Perrotin committed
21
from singledispatch import singledispatch
Maxime Perrotin's avatar
Maxime Perrotin committed
22
23
24
from llvm import core, passes, ee

import ogAST
Maxime Perrotin's avatar
Maxime Perrotin committed
25
import Helper
Maxime Perrotin's avatar
Maxime Perrotin committed
26
27
28

LOG = logging.getLogger(__name__)

Maxime Perrotin's avatar
Maxime Perrotin committed
29
30
__all__ = ['generate']

Maxime Perrotin's avatar
Maxime Perrotin committed
31
32
33
34
35
36
37
38

# LLVM Global variable - Initialized when the generator is invoked
LLVM = {
    # The LLVM module, which holds all the IR code.
    'module': None,
    # Dictionary that keeps track of which values are defined in the current
    # scope and what their LLVM representation is.
    'named_values': {},
39
40
41
    # Dictionary that keeps track of the defined states and its integer
    # constant representation
    'states': {},
42
43
    # The builder used for the current function generation.
    'builder': None,
Maxime Perrotin's avatar
Maxime Perrotin committed
44
45
46
    # The function optimization passes manager.
    'pass_manager': None,
    # The LLVM execution engine.
47
48
49
50
    'executor': None,
    # ASN.1 data view
    'dataview': None,
    # Generated types
51
52
53
    'types': {},
    # Global strings
    'strings': {}
Maxime Perrotin's avatar
Maxime Perrotin committed
54
55
}

dbarbera's avatar
dbarbera committed
56

Maxime Perrotin's avatar
Maxime Perrotin committed
57
58
59
60
@singledispatch
def generate(ast):
    ''' Generate the code for an item of the AST '''
    raise TypeError('[Backend] Unsupported AST construct')
Maxime Perrotin's avatar
Maxime Perrotin committed
61

dbarbera's avatar
dbarbera committed
62

Maxime Perrotin's avatar
Maxime Perrotin committed
63
# Processing of the AST
Maxime Perrotin's avatar
Maxime Perrotin committed
64

Maxime Perrotin's avatar
Maxime Perrotin committed
65
66
@generate.register(ogAST.Process)
def _process(process):
dbarbera's avatar
dbarbera committed
67
    ''' Generate LLVM IR code '''
68

69
    process_name = str(process.processName)
Maxime Perrotin's avatar
Maxime Perrotin committed
70
71
    LOG.info('Generating LLVM IR code for process ' + str(process_name))

72
    # Initialize LLVM global structure
73
    LLVM['module'] = core.Module.new(process_name)
Maxime Perrotin's avatar
Maxime Perrotin committed
74
75
    LLVM['pass_manager'] = passes.FunctionPassManager.new(LLVM['module'])
    LLVM['executor'] = ee.ExecutionEngine.new(LLVM['module'])
76
    LLVM['dataview'] = process.dataview
Maxime Perrotin's avatar
Maxime Perrotin committed
77
78
79
    # Set up the optimizer pipeline.
    # Start with registering info about how the
    # target lays out data structures.
dbarbera's avatar
dbarbera committed
80
81
82
83
84
85
86
87
88
89
90
    #   LLVM['pass_manager'].add(LLVM['executor'].target_data)
    #   # Do simple "peephole" optimizations and bit-twiddling optzns.
    #   LLVM['pass_manager'].add(passes.PASS_INSTRUCTION_COMBINING)
    #   # Reassociate expressions.
    #   LLVM['pass_manager'].add(passes.PASS_REASSOCIATE)
    #   # Eliminate Common SubExpressions.
    #   LLVM['pass_manager'].add(passes.PASS_GVN)
    #   # Simplify the control flow graph (deleting unreachable blocks, etc).
    #   LLVM['pass_manager'].add(passes.PASS_CFG_SIMPLIFICATION)
    #   LLVM['pass_manager'].initialize()

91
92
93
94
95
96
97
    # Initialize built-in functions
    printf_type = core.Type.function(
        core.Type.void(),
        [core.Type.pointer(core.Type.int(8))], True
    )
    LLVM['module'].add_function(printf_type, 'printf')

dbarbera's avatar
dbarbera committed
98
99
100
101
102
103
    # In case model has nested states, flatten everything
    Helper.flatten(process)

    # Make an maping {input: {state: transition...}} in order to easily
    # generate the lookup tables for the state machine runtime
    mapping = Helper.map_input_state(process)
Maxime Perrotin's avatar
Maxime Perrotin committed
104

105
106
107
108
109
110
    # Initialize states enum
    for name in process.mapping.iterkeys():
        if not name.endswith('START'):
            cons = core.Constant.int(core.Type.int(), len(LLVM['states']))
            LLVM['states'][name] = cons

111
    # Generate state var
112
113
    LLVM['module'].add_global_variable(core.Type.int(), 'state')

dbarbera's avatar
dbarbera committed
114
115
116
117
118
119
120
121
122
123
124
125
    # Initialize output signals
    for signal in process.output_signals:
        param_tys = [core.Type.pointer(_generate_type(signal['type']))]
        func_ty = core.Type.function(core.Type.void(), param_tys)
        core.Function.new(LLVM['module'], func_ty, str(signal['name']))

    # Initialize external procedures
    for proc in [proc for proc in process.procedures if proc.external]:
        param_tys = [core.Type.pointer(_generate_type(p['type'])) for p in proc.fpar]
        func_ty = core.Type.function(core.Type.void(), param_tys)
        core.Function.new(LLVM['module'], func_ty, str(proc.inputString))

126
    # Generare process-level vars
dbarbera's avatar
dbarbera committed
127
    for var_name, (var_asn1_type, def_value) in process.variables.viewitems():
128
        var_type = _generate_type(var_asn1_type)
129
        LLVM['module'].add_global_variable(var_type, str(var_name).lower())
130
        if def_value:
dbarbera's avatar
dbarbera committed
131
            raise NotImplementedError
132

133
    # Generate process functions
134
135
136
    runtr_func = _generate_runtr_func(process)
    _generate_startup_func(process, process_name, runtr_func)

137
138
139
140
    # Generate input signals
    for signal in process.input_signals:
        _generate_input_signal(signal, mapping[signal['name']])

141
142
143
144
    print LLVM['module']


def _generate_runtr_func(process):
dbarbera's avatar
dbarbera committed
145
    ''' Generate code for the run_transition function '''
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
    func_name = 'run_transition'
    func_type = core.Type.function(core.Type.void(), [core.Type.int()])
    func = core.Function.new(LLVM['module'], func_type, func_name)

    entry_block = func.append_basic_block('entry')
    cond_block = func.append_basic_block('cond')
    body_block = func.append_basic_block('body')
    exit_block = func.append_basic_block('exit')

    builder = core.Builder.new(entry_block)
    LLVM['builder'] = builder

    # entry
    id_ptr = builder.alloca(core.Type.int(), None, 'id')
    LLVM['named_values']['id'] = id_ptr
    builder.store(func.args[0], id_ptr)
    builder.branch(cond_block)

    # cond
    builder.position_at_end(cond_block)
    id_ptr = func.args[0]
    no_tr_cons = core.Constant.int(core.Type.int(), -1)
    cond_val = builder.icmp(core.ICMP_NE, id_ptr, no_tr_cons, 'cond')
    builder.cbranch(cond_val, body_block, exit_block)

    # body
    builder.position_at_end(body_block)
    switch = builder.switch(func.args[0], exit_block)

    # transitions
    for idx, tr in enumerate(process.transitions):
        tr_block = func.append_basic_block('tr%d' % idx)
        const = core.Constant.int(core.Type.int(), idx)
        switch.add_case(const, tr_block)
        builder.position_at_end(tr_block)
        generate(tr)
        builder.branch(cond_block)

    # exit
    builder.position_at_end(exit_block)
    builder.ret_void()

    func.verify()
Maxime Perrotin's avatar
Maxime Perrotin committed
189
    LLVM['named_values'].clear()
190
191
192
193
    return func


def _generate_startup_func(process, process_name, runtr_func):
dbarbera's avatar
dbarbera committed
194
    ''' Generate code for the startup function '''
195
196
197
198
199
200
201
202
203
204
    func_name = process_name + '_startup'
    func_type = core.Type.function(core.Type.void(), [])
    func = core.Function.new(LLVM['module'], func_type, func_name)

    entry_block = func.append_basic_block('entry')
    builder = core.Builder.new(entry_block)
    LLVM['builder'] = builder

    # entry
    builder.call(runtr_func, [core.Constant.int(core.Type.int(), 0)])
Maxime Perrotin's avatar
Maxime Perrotin committed
205
206
    builder.ret_void()

207
208
    func.verify()
    return func
Maxime Perrotin's avatar
Maxime Perrotin committed
209
210


211
def _generate_input_signal(signal, inputs):
dbarbera's avatar
dbarbera committed
212
    ''' Generate code for an input signal '''
213
    func_name = str(signal['name'])
214
215
216
217
    param_tys = []
    if 'type' in signal:
        param_tys.append(core.Type.pointer(_generate_type(signal['type'])))
    func_type = core.Type.function(core.Type.void(), param_tys)
218
219
220
221
222
    func = core.Function.new(LLVM['module'], func_type, func_name)

    entry_block = func.append_basic_block('entry')
    exit_block = func.append_basic_block('exit')
    builder = core.Builder.new(entry_block)
223
    LLVM['builder'] = builder
224
225
226
227
228
229
230
231
232
233
234
235
236

    runtr_func = LLVM['module'].get_function_named('run_transition')

    g_state_val = builder.load(LLVM['module'].get_global_variable_named('state'))
    switch = builder.switch(g_state_val, exit_block)

    for state_name, state_id in LLVM['states'].iteritems():
        state_block = func.append_basic_block('state_%s' % str(state_name))
        switch.add_case(state_id, state_block)
        builder.position_at_end(state_block)

        # TODO: Nested states

237
238
239
240
241
242
243
        input = inputs.get(state_name)
        if input:
            for var_name in input.parameters:
                var_val = LLVM['module'].get_global_variable_named(str(var_name).lower())
                _generate_assign(var_val, func.args[0])
            if input.transition:
                id_val = core.Constant.int(core.Type.int(), input.transition_id)
244
245
246
247
248
249
250
251
252
253
                builder.call(runtr_func, [id_val])

        builder.ret_void()

    builder.position_at_end(exit_block)
    builder.ret_void()

    func.verify()


Maxime Perrotin's avatar
Maxime Perrotin committed
254
255
256
257
@generate.register(ogAST.Output)
@generate.register(ogAST.ProcedureCall)
def _call_external_function(output):
    ''' Generate the code of a set of output or procedure call statement '''
dbarbera's avatar
dbarbera committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277

    for out in output.output:
        name = out['outputName'].lower()

        if name in ('write', 'writeln'):
            _generate_write(out['params'])
            continue
        elif name == 'reset_timer':
            _generate_reset_timer(out['params'])
            continue
        elif name == 'set_timer':
            _generate_set_timer(out['params'])
            continue

        func = LLVM['module'].get_function_named(str(name))
        LLVM['builder'].call(func, [expression(p) for p in out.get('params', [])])


def _generate_write(params):
    ''' Generate the code for the write operator '''
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    zero = core.Constant.int(core.Type.int(), 0)
    for param in params:
        basic_ty = find_basic_type(param.exprType)
        expr_val = expression(param)
        printf_func = LLVM['module'].get_function_named('printf')
        if basic_ty.kind == 'IntegerType':
            fmt_val = _get_string_cons('%d')
            fmt_ptr = LLVM['builder'].gep(fmt_val, [zero, zero])
            LLVM['builder'].call(printf_func, [fmt_ptr, expr_val])
        elif basic_ty.kind == 'RealType':
            fmt_val = _get_string_cons('%.14E')
            fmt_ptr = LLVM['builder'].gep(fmt_val, [zero, zero])
            LLVM['builder'].call(printf_func, [fmt_ptr, expr_val])
        elif basic_ty.kind == 'BooleanType':
            true_str_val = _get_string_cons('true')
            true_str_ptr = LLVM['builder'].gep(true_str_val, [zero, zero])
            false_str_val = _get_string_cons('false')
            false_str_ptr = LLVM['builder'].gep(false_str_val, [zero, zero])
            str_ptr = LLVM['builder'].select(expr_val, true_str_ptr, false_str_ptr)
            LLVM['builder'].call(printf_func, [str_ptr])
        else:
            raise NotImplementedError


def _generate_writeln(params):
    ''' Generate the code for the writeln operator '''
    _generate_write(params)
    str_cons = _get_string_cons('\n')
    str_ptr = LLVM['builder'].gep(str_cons, [zero, zero])
    LLVM['builder'].call(printf_func, [str_ptr])
dbarbera's avatar
dbarbera committed
308
309
310
311
312
313
314
315
316


def _generate_reset_timer(params):
    ''' Generate the code for the reset timer operator '''
    raise NotImplementedError


def _generate_set_timer(params):
    ''' Generate the code for the set timer operator '''
317
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
318
319
320
321


@generate.register(ogAST.TaskAssign)
def _task_assign(task):
dbarbera's avatar
dbarbera committed
322
    ''' Generate the code of a list of assignments '''
323
324
    for expr in task.elems:
        expression(expr)
Maxime Perrotin's avatar
Maxime Perrotin committed
325
326
327
328
329


@generate.register(ogAST.TaskInformalText)
def _task_informal_text(task):
    ''' Generate comments for informal text '''
330
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
331
332
333
334


@generate.register(ogAST.TaskForLoop)
def _task_forloop(task):
dbarbera's avatar
dbarbera committed
335
    ''' Generate the code for a for loop '''
336
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
337

dbarbera's avatar
dbarbera committed
338

Maxime Perrotin's avatar
Maxime Perrotin committed
339
340
341
342
# ------ expressions --------

@singledispatch
def expression(expr):
dbarbera's avatar
dbarbera committed
343
    ''' Generate the code for Expression-classes '''
Maxime Perrotin's avatar
Maxime Perrotin committed
344
345
346
347
    raise TypeError('Unsupported expression: ' + str(expr))


@expression.register(ogAST.PrimVariable)
Maxime Perrotin's avatar
Maxime Perrotin committed
348
def _primary_variable(prim):
dbarbera's avatar
dbarbera committed
349
    ''' Generate the code for a single variable reference '''
350
    return LLVM['module'].get_global_variable_named(str(prim.value[0]).lower())
Maxime Perrotin's avatar
Maxime Perrotin committed
351
352


Maxime Perrotin's avatar
Maxime Perrotin committed
353
@expression.register(ogAST.PrimPath)
dbarbera's avatar
dbarbera committed
354
def _prim_path(primary_id):
dbarbera's avatar
dbarbera committed
355
    ''' Generate the code for an of an element list (path) '''
356
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
357
358


Maxime Perrotin's avatar
Maxime Perrotin committed
359
360
361
362
363
364
365
366
367
368
369
370
@expression.register(ogAST.ExprPlus)
@expression.register(ogAST.ExprMul)
@expression.register(ogAST.ExprMinus)
@expression.register(ogAST.ExprEq)
@expression.register(ogAST.ExprNeq)
@expression.register(ogAST.ExprGt)
@expression.register(ogAST.ExprGe)
@expression.register(ogAST.ExprLt)
@expression.register(ogAST.ExprLe)
@expression.register(ogAST.ExprDiv)
@expression.register(ogAST.ExprMod)
@expression.register(ogAST.ExprRem)
dbarbera's avatar
dbarbera committed
371
372
def _basic(expr):
    ''' Generate the code for an arithmetic of relational expression '''
373
    builder = LLVM['builder']
374
375
    lefttmp = expression(expr.left)
    righttmp = expression(expr.right)
376
377

    # load the value of the expression if it is a pointer
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
    if lefttmp.type.kind == core.TYPE_POINTER:
        lefttmp = builder.load(lefttmp, 'lefttmp')
    if righttmp.type.kind == core.TYPE_POINTER:
        righttmp = builder.load(righttmp, 'lefttmp')

    if lefttmp.type.kind != righttmp.type.kind:
        raise NotImplementedError

    if lefttmp.type.kind == core.TYPE_INTEGER:
        if expr.operand == '+':
            return builder.add(lefttmp, righttmp, 'addtmp')
        elif expr.operand == '-':
            return builder.sub(lefttmp, righttmp, 'subtmp')
        elif expr.operand == '*':
            return builder.mul(lefttmp, righttmp, 'multmp')
        elif expr.operand == '/':
            return builder.sdiv(lefttmp, righttmp, 'divtmp')
        elif expr.operand == 'mod':
396
397
398
399
400
401
            # l mod r == (((l rem r) + r) rem r)
            remtmp = builder.srem(lefttmp, righttmp)
            addtmp = builder.add(remtmp, righttmp)
            return builder.srem(addtmp, righttmp, 'modtmp')
        elif expr.operand == 'rem':
            return builder.srem(lefttmp, righttmp, 'remtmp')
402
403
404
405
406
407
408
409
410
411
412
413
        elif expr.operand == '<':
            return builder.icmp(core.ICMP_SLT, lefttmp, righttmp, 'lttmp')
        elif expr.operand == '<=':
            return builder.icmp(core.ICMP_SLE, lefttmp, righttmp, 'letmp')
        elif expr.operand == '=':
            return builder.icmp(core.ICMP_EQ, lefttmp, righttmp, 'eqtmp')
        elif expr.operand == '/=':
            return builder.icmp(core.ICMP_NE, lefttmp, righttmp, 'netmp')
        elif expr.operand == '>=':
            return builder.icmp(core.ICMP_SGE, lefttmp, righttmp, 'getmp')
        elif expr.operand == '>':
            return builder.icmp(core.ICMP_SGT, lefttmp, righttmp, 'gttmp')
414
415
416
417
418
419
420
421
422
423
424
425
        else:
            raise NotImplementedError
    elif lefttmp.type.kind == core.TYPE_DOUBLE:
        if expr.operand == '+':
            return builder.fadd(lefttmp, righttmp, 'addtmp')
        elif expr.operand == '-':
            return builder.fsub(lefttmp, righttmp, 'subtmp')
        elif expr.operand == '*':
            return builder.fmul(lefttmp, righttmp, 'multmp')
        elif expr.operand == '/':
            return builder.fdiv(lefttmp, righttmp, 'divtmp')
        elif expr.operand == 'mod':
426
427
428
429
430
431
            # l mod r == (((l rem r) + r) rem r)
            remtmp = builder.frem(lefttmp, righttmp)
            addtmp = builder.fadd(remtmp, righttmp)
            return builder.frem(addtmp, righttmp, 'modtmp')
        elif expr.operand == 'rem':
            return builder.frem(lefttmp, righttmp, 'remtmp')
432
433
434
435
436
437
438
439
440
441
442
443
        elif expr.operand == '<':
            return builder.icmp(core.FCMP_OLT, lefttmp, righttmp, 'lttmp')
        elif expr.operand == '<=':
            return builder.icmp(core.FCMP_OLE, lefttmp, righttmp, 'letmp')
        elif expr.operand == '=':
            return builder.icmp(core.FCMP_OEQ, lefttmp, righttmp, 'eqtmp')
        elif expr.operand == '/=':
            return builder.icmp(core.FCMP_ONE, lefttmp, righttmp, 'netmp')
        elif expr.operand == '>=':
            return builder.icmp(core.FCMP_OGE, lefttmp, righttmp, 'getmp')
        elif expr.operand == '>':
            return builder.icmp(core.FCMP_OGT, lefttmp, righttmp, 'gttmp')
444
445
        else:
            raise NotImplementedError
446
    else:
447
        raise NotImplementedError
448

Maxime Perrotin's avatar
Maxime Perrotin committed
449

450
451
@expression.register(ogAST.ExprAssign)
def _assign(expr):
dbarbera's avatar
dbarbera committed
452
    ''' Generate the code for an assign expression '''
453
454
    left = expression(expr.left)
    right = expression(expr.right)
455
456
    _generate_assign(left, right)
    return left
457

458
459
460
461
462
463

def _generate_assign(left, right):
    ''' Generate code for an assign from two LLVM values'''
    # This is extracted as an standalone function because is used by
    # multiple generation rules
    builder = LLVM['builder']
464
465
466
467
468
469
470
471
472
473
474
475
476
    if left.type.kind == core.TYPE_POINTER and left.type.pointee.kind == core.TYPE_STRUCT:
        memcpy = _get_memcpy_intrinsic()

        size = core.Constant.int(core.Type.int(64), 2)
        align = core.Constant.int(core.Type.int(32), 1)
        volatile = core.Constant.int(core.Type.int(1), 0)

        right_ptr = builder.bitcast(right, core.Type.pointer(core.Type.int(8)))
        left_ptr = builder.bitcast(left, core.Type.pointer(core.Type.int(8)))

        builder.call(memcpy, [left_ptr, right_ptr, size, align, volatile])
    else:
        builder.store(right, left)
dbarbera's avatar
dbarbera committed
477

Maxime Perrotin's avatar
Maxime Perrotin committed
478

Maxime Perrotin's avatar
Maxime Perrotin committed
479
480
481
@expression.register(ogAST.ExprOr)
@expression.register(ogAST.ExprAnd)
@expression.register(ogAST.ExprXor)
dbarbera's avatar
dbarbera committed
482
483
def _logical(expr):
    ''' Generate the code for a logical expression '''
dbarbera's avatar
dbarbera committed
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
    builder = LLVM['builder']

    lefttmp = expression(expr.left)
    righttmp = expression(expr.right)

    ty = find_basic_type(expr.exprType)
    if ty.kind != 'BooleanType':
        raise NotImplementedError

    # load the value of the expression if it is a pointer
    if lefttmp.type.kind == core.TYPE_POINTER:
        lefttmp = builder.load(lefttmp, 'lefttmp')
    if righttmp.type.kind == core.TYPE_POINTER:
        righttmp = builder.load(righttmp, 'lefttmp')

    if expr.operand == '&&':
        return builder.and_(lefttmp, righttmp, 'ortmp')
    elif expr.operand == '||':
        return builder.or_(lefttmp, righttmp, 'ortmp')
    else:
        return builder.xor(lefttmp, righttmp, 'xortmp')

Maxime Perrotin's avatar
Maxime Perrotin committed
506

Maxime Perrotin's avatar
Maxime Perrotin committed
507
@expression.register(ogAST.ExprAppend)
Maxime Perrotin's avatar
Maxime Perrotin committed
508
509
def _append(expr):
    ''' Generate code for the APPEND construct: a // b '''
510
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
511
512


Maxime Perrotin's avatar
Maxime Perrotin committed
513
@expression.register(ogAST.ExprIn)
Maxime Perrotin's avatar
Maxime Perrotin committed
514
def _expr_in(expr):
dbarbera's avatar
dbarbera committed
515
    ''' Generate the code for an in expression '''
516
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
517
518


Maxime Perrotin's avatar
Maxime Perrotin committed
519
@expression.register(ogAST.PrimEnumeratedValue)
Maxime Perrotin's avatar
Maxime Perrotin committed
520
521
def _enumerated_value(primary):
    ''' Generate code for an enumerated value '''
522
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
523
524


Maxime Perrotin's avatar
Maxime Perrotin committed
525
@expression.register(ogAST.PrimChoiceDeterminant)
Maxime Perrotin's avatar
Maxime Perrotin committed
526
527
def _choice_determinant(primary):
    ''' Generate code for a choice determinant (enumerated) '''
528
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
529
530


Maxime Perrotin's avatar
Maxime Perrotin committed
531
@expression.register(ogAST.PrimInteger)
532
533
534
535
536
def _integer(primary):
    ''' Generate code for a raw integer value  '''
    return core.Constant.int(core.Type.int(), primary.value[0])


Maxime Perrotin's avatar
Maxime Perrotin committed
537
@expression.register(ogAST.PrimReal)
538
539
def _real(primary):
    ''' Generate code for a raw real value  '''
dbarbera's avatar
dbarbera committed
540
    return core.Constant.real(core.Type.double(), primary.value[0])
541
542


Maxime Perrotin's avatar
Maxime Perrotin committed
543
@expression.register(ogAST.PrimBoolean)
544
545
def _boolean(primary):
    ''' Generate code for a raw boolean value  '''
dbarbera's avatar
dbarbera committed
546
547
548
549
    if primary.value[0].lower() == 'true':
        return core.Constant.int(core.Type.int(1), 1)
    else:
        return core.Constant.int(core.Type.int(1), 0)
Maxime Perrotin's avatar
Maxime Perrotin committed
550
551


Maxime Perrotin's avatar
Maxime Perrotin committed
552
@expression.register(ogAST.PrimEmptyString)
Maxime Perrotin's avatar
Maxime Perrotin committed
553
554
def _empty_string(primary):
    ''' Generate code for an empty SEQUENCE OF: {} '''
555
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
556
557


Maxime Perrotin's avatar
Maxime Perrotin committed
558
@expression.register(ogAST.PrimStringLiteral)
Maxime Perrotin's avatar
Maxime Perrotin committed
559
560
def _string_literal(primary):
    ''' Generate code for a string (Octet String) '''
561
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
562
563


Maxime Perrotin's avatar
Maxime Perrotin committed
564
@expression.register(ogAST.PrimConstant)
Maxime Perrotin's avatar
Maxime Perrotin committed
565
566
def _constant(primary):
    ''' Generate code for a reference to an ASN.1 constant '''
567
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
568
569


Maxime Perrotin's avatar
Maxime Perrotin committed
570
@expression.register(ogAST.PrimMantissaBaseExp)
Maxime Perrotin's avatar
Maxime Perrotin committed
571
572
def _mantissa_base_exp(primary):
    ''' Generate code for a Real with Mantissa-base-Exponent representation '''
573
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
574
575


Maxime Perrotin's avatar
Maxime Perrotin committed
576
@expression.register(ogAST.PrimIfThenElse)
dbarbera's avatar
dbarbera committed
577
def _if_then_else(ifthen):
dbarbera's avatar
dbarbera committed
578
    ''' Generate the code for ternary operator '''
579
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
580
581


Maxime Perrotin's avatar
Maxime Perrotin committed
582
@expression.register(ogAST.PrimSequence)
Maxime Perrotin's avatar
Maxime Perrotin committed
583
def _sequence(seq):
dbarbera's avatar
dbarbera committed
584
    ''' Generate the code for an ASN.1 SEQUENCE '''
585
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
586
587


Maxime Perrotin's avatar
Maxime Perrotin committed
588
@expression.register(ogAST.PrimSequenceOf)
Maxime Perrotin's avatar
Maxime Perrotin committed
589
def _sequence_of(seqof):
dbarbera's avatar
dbarbera committed
590
    ''' Generate the code for an ASN.1 SEQUENCE OF '''
591
592
593
594
595
596
597
598
599
600
601
602
603
604
    builder = LLVM['builder']

    ty = _generate_type(seqof.exprType)
    struct_ptr = builder.alloca(ty)
    zero_cons = core.Constant.int(core.Type.int(), 0)
    array_ptr = builder.gep(struct_ptr, [zero_cons, zero_cons])

    for idx, expr in enumerate(seqof.value):
        idx_cons = core.Constant.int(core.Type.int(), idx)
        expr_val = expression(expr)
        pos_ptr = builder.gep(array_ptr, [zero_cons, idx_cons])
        builder.store(expr_val, pos_ptr)

    return struct_ptr
Maxime Perrotin's avatar
Maxime Perrotin committed
605
606


Maxime Perrotin's avatar
Maxime Perrotin committed
607
@expression.register(ogAST.PrimChoiceItem)
Maxime Perrotin's avatar
Maxime Perrotin committed
608
def _choiceitem(choice):
dbarbera's avatar
dbarbera committed
609
    ''' Generate the code for a CHOICE expression '''
610
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
611
612
613
614


@generate.register(ogAST.Decision)
def _decision(dec):
dbarbera's avatar
dbarbera committed
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    ''' Generate the code for a decision '''
    builder = LLVM['builder']
    func = builder.basic_block.function

    ans_cond_blocks = [func.append_basic_block('ans_cond') for ans in dec.answers]
    end_block = func.append_basic_block('end')

    builder.branch(ans_cond_blocks[0])

    for idx, ans in enumerate(dec.answers):
        ans_cond_block = ans_cond_blocks[idx]
        if ans.transition:
            ans_tr_block = func.append_basic_block('ans_tr')
        builder.position_at_end(ans_cond_block)

        if ans.kind == 'constant':
            next_block = ans_cond_blocks[idx+1] if idx < len(ans_cond_blocks) else end_block

            expr = ans.openRangeOp()
            expr.left = dec.question
            expr.right = ans.constant
            expr_val = expression(expr)

            true_cons = core.Constant.int(core.Type.int(1), 1)
            cond_val = builder.icmp(core.ICMP_EQ, expr_val, true_cons)
            builder.cbranch(cond_val, ans_tr_block if ans.transition else end_block, next_block)
        elif ans.kind == 'else':
            if ans.transition:
                builder.branch(ans_tr_block)
            else:
                builder.branch(end_block)
        else:
            raise NotImplementedError

        if ans.transition:
            builder.position_at_end(ans_tr_block)
            generate(ans.transition)
            builder.branch(end_block)

    builder.position_at_end(end_block)
Maxime Perrotin's avatar
Maxime Perrotin committed
655
656
657
658


@generate.register(ogAST.Label)
def _label(tr):
dbarbera's avatar
dbarbera committed
659
    ''' TGenerate the code for a Label '''
660
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
661
662
663
664


@generate.register(ogAST.Transition)
def _transition(tr):
dbarbera's avatar
dbarbera committed
665
    ''' Generate the code for a transition '''
666
667
668
669
670
671
    for action in tr.actions:
        generate(action)
        if isinstance(action, ogAST.Label):
            return
    if tr.terminator:
        _generate_terminator(tr.terminator)
672
673


674
def _generate_terminator(term):
dbarbera's avatar
dbarbera committed
675
    ''' Generate the code for a transition termiantor '''
676
677
678
    builder = LLVM['builder']
    id_ptr = LLVM['named_values']['id']
    if term.label:
679
        raise NotImplementedError
680
681
682
683
684
685
686
687
688
689
    if term.kind == 'next_state':
        state = term.inputString.lower()
        if state.strip() != '-':
            next_id_cons = core.Constant.int(core.Type.int(), term.next_id)
            builder.store(next_id_cons, id_ptr)
            if term.next_id == -1:
                state_ptr = LLVM['module'].get_global_variable_named('state')
                state_id_cons = LLVM['states'][state]
                builder.store(state_id_cons, state_ptr)
        else:
690
            raise NotImplementedError
691
    elif term.kind == 'join':
692
        raise NotImplementedError
693
    elif term.kind == 'stop':
694
        raise NotImplementedError
695
    elif term.kind == 'return':
696
        raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
697
698
699
700


@generate.register(ogAST.Floating_label)
def _floating_label(label):
dbarbera's avatar
dbarbera committed
701
    ''' Generate the code for a floating label '''
702
    raise NotImplementedError
Maxime Perrotin's avatar
Maxime Perrotin committed
703
704
705
706
707


@generate.register(ogAST.Procedure)
def _inner_procedure(proc):
    ''' Generate the code for a procedure '''
708
    raise NotImplementedError
dbarbera's avatar
dbarbera committed
709
710
711


def _generate_type(ty):
712
    ''' Generate the equivalent LLVM type of a ASN.1 type '''
dbarbera's avatar
dbarbera committed
713
714
715
716
717
718
    basic_ty = find_basic_type(ty)
    if basic_ty.kind == 'IntegerType':
        return core.Type.int()
    elif basic_ty.kind == 'BooleanType':
        return core.Type.int(1)
    elif basic_ty.kind == 'RealType':
dbarbera's avatar
dbarbera committed
719
        return core.Type.double()
720
721
722
723
724
725
726
727
728
729
730
731
732
733
    elif basic_ty.kind == 'SequenceOfType':
        if ty.ReferencedTypeName in LLVM['types']:
            return LLVM['types'][ty.ReferencedTypeName]

        min_size = int(basic_ty.Max)
        max_size = int(basic_ty.Min)
        if min_size != max_size:
            raise NotImplementedError

        elem_ty = _generate_type(basic_ty.type)
        array_ty = core.Type.array(elem_ty, max_size)
        struct_ty = core.Type.struct([array_ty], ty.ReferencedTypeName)
        LLVM['types'][ty.ReferencedTypeName] = struct_ty
        return struct_ty
dbarbera's avatar
dbarbera committed
734
735
736
737
    else:
        raise NotImplementedError


738
739
740
741
742
743
744
745
746
747
748
749
750
751
def _get_string_cons(str):
    ''' Returns a reference to a global string constant with the given value '''
    if str in LLVM['strings']:
        return LLVM['strings'][str]

    str_val = core.Constant.stringz(str)
    # TODO: This names can cause conflicts with user defined variables
    gvar_name = 'str_%s' % len(LLVM['strings'])
    gvar_val = LLVM['module'].add_global_variable(str_val.type, gvar_name)
    gvar_val.initializer = str_val
    LLVM['strings'][str] = gvar_val
    return gvar_val


752
def _get_memcpy_intrinsic():
dbarbera's avatar
dbarbera committed
753
    ''' Return the LLVM Memcpy Intrinsic '''
754
755
756
757
758
759
760
761
    arg_tys = [
        core.Type.pointer(core.Type.int(8)),
        core.Type.pointer(core.Type.int(8)),
        core.Type.int(64)
    ]
    return core.Function.intrinsic(LLVM['module'], core.INTR_MEMCPY, arg_tys)


dbarbera's avatar
dbarbera committed
762
763
764
765
766
767
# TODO: Refactor this into the helper module
def find_basic_type(a_type):
    ''' Return the ASN.1 basic type of a_type '''
    basic_type = a_type
    while basic_type.kind == 'ReferenceType':
        # Find type with proper case in the data view
768
        for typename in LLVM['dataview'].viewkeys():
dbarbera's avatar
dbarbera committed
769
            if typename.lower() == basic_type.ReferencedTypeName.lower():
770
                basic_type = LLVM['dataview'][typename].type
dbarbera's avatar
dbarbera committed
771
772
                break
    return basic_type