| 1 |
__copyright__ = "Copyright (C) 2009 Andreas Kloeckner" |
| 2 |
|
| 3 |
__license__ = """ |
| 4 |
Permission is hereby granted, free of charge, to any person obtaining a copy |
| 5 |
of this software and associated documentation files (the "Software"), to deal |
| 6 |
in the Software without restriction, including without limitation the rights |
| 7 |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 8 |
copies of the Software, and to permit persons to whom the Software is |
| 9 |
furnished to do so, subject to the following conditions: |
| 10 |
|
| 11 |
The above copyright notice and this permission notice shall be included in |
| 12 |
all copies or substantial portions of the Software. |
| 13 |
|
| 14 |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 19 |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 20 |
THE SOFTWARE. |
| 21 |
""" |
| 22 |
|
| 23 |
import re |
| 24 |
from sys import intern |
| 25 |
from typing import ClassVar, Dict, List, Tuple |
| 26 |
from warnings import warn |
| 27 |
|
| 28 |
import numpy as np |
| 29 |
|
| 30 |
import cgen |
| 31 |
import pymbolic.primitives as p |
| 32 |
import pytools.lex |
| 33 |
from pymbolic.mapper import CombineMapper |
| 34 |
from pymbolic.mapper.c_code import CCodeMapper as CCodeMapperBase |
| 35 |
from pymbolic.parser import Parser as ExpressionParserBase |
| 36 |
|
| 37 |
|
| 38 |
class TranslatorWarning(UserWarning): |
| 39 |
pass |
| 40 |
|
| 41 |
|
| 42 |
class TranslationError(RuntimeError): |
| 43 |
pass |
| 44 |
|
| 45 |
|
| 46 |
def complex_type_name(dtype): |
| 47 |
if dtype == np.complex64: |
| 48 |
return "cfloat" |
| 49 |
if dtype == np.complex128: |
| 50 |
return "cdouble" |
| 51 |
else: |
| 52 |
raise RuntimeError |
| 53 |
|
| 54 |
|
| 55 |
# {{{ AST components |
| 56 |
|
| 57 |
def dtype_to_ctype(dtype): |
| 58 |
if dtype is None: |
| 59 |
raise ValueError("dtype may not be None") |
| 60 |
|
| 61 |
dtype = np.dtype(dtype) |
| 62 |
if dtype == np.int64: |
| 63 |
return "long" |
| 64 |
elif dtype == np.uint64: |
| 65 |
return "unsigned long" |
| 66 |
elif dtype == np.int32: |
| 67 |
return "int" |
| 68 |
elif dtype == np.uint32: |
| 69 |
return "unsigned int" |
| 70 |
elif dtype == np.int16: |
| 71 |
return "short int" |
| 72 |
elif dtype == np.uint16: |
| 73 |
return "short unsigned int" |
| 74 |
elif dtype == np.int8: |
| 75 |
return "signed char" |
| 76 |
elif dtype == np.uint8: |
| 77 |
return "unsigned char" |
| 78 |
elif dtype == np.float32: |
| 79 |
return "float" |
| 80 |
elif dtype == np.float64: |
| 81 |
return "double" |
| 82 |
elif dtype == np.complex64: |
| 83 |
return "cfloat_t" |
| 84 |
elif dtype == np.complex128: |
| 85 |
return "cdouble_t" |
| 86 |
else: |
| 87 |
raise ValueError("unable to map dtype '%s'" % dtype) |
| 88 |
|
| 89 |
|
| 90 |
class POD(cgen.POD): |
| 91 |
def get_decl_pair(self): |
| 92 |
return [dtype_to_ctype(self.dtype)], self.name |
| 93 |
|
| 94 |
# }}} |
| 95 |
|
| 96 |
|
| 97 |
# {{{ expression parser |
| 98 |
|
| 99 |
_less_than = intern("less_than") |
| 100 |
_greater_than = intern("greater_than") |
| 101 |
_less_equal = intern("less_equal") |
| 102 |
_greater_equal = intern("greater_equal") |
| 103 |
_equal = intern("equal") |
| 104 |
_not_equal = intern("not_equal") |
| 105 |
|
| 106 |
_not = intern("not") |
| 107 |
_and = intern("and") |
| 108 |
_or = intern("or") |
| 109 |
|
| 110 |
|
| 111 |
class TypedLiteral(p.Leaf): |
| 112 |
def __init__(self, value, dtype): |
| 113 |
self.value = value |
| 114 |
self.dtype = np.dtype(dtype) |
| 115 |
|
| 116 |
def __getinitargs__(self): |
| 117 |
return self.value, self.dtype |
| 118 |
|
| 119 |
mapper_method = intern("map_literal") |
| 120 |
|
| 121 |
|
| 122 |
def simplify_typed_literal(expr): |
| 123 |
if (isinstance(expr, p.Product) |
| 124 |
and len(expr.children) == 2 |
| 125 |
and isinstance(expr.children[1], TypedLiteral) |
| 126 |
and p.is_constant(expr.children[0]) |
| 127 |
and expr.children[0] == -1): |
| 128 |
tl = expr.children[1] |
| 129 |
return TypedLiteral("-"+tl.value, tl.dtype) |
| 130 |
else: |
| 131 |
return expr |
| 132 |
|
| 133 |
|
| 134 |
class FortranExpressionParser(ExpressionParserBase): |
| 135 |
# FIXME double/single prec literals |
| 136 |
|
| 137 |
lex_table: ClassVar[List[Tuple[str, str]]] = [ |
| 138 |
(_less_than, pytools.lex.RE(r"\.lt\.", re.I)), |
| 139 |
(_greater_than, pytools.lex.RE(r"\.gt\.", re.I)), |
| 140 |
(_less_equal, pytools.lex.RE(r"\.le\.", re.I)), |
| 141 |
(_greater_equal, pytools.lex.RE(r"\.ge\.", re.I)), |
| 142 |
(_equal, pytools.lex.RE(r"\.eq\.", re.I)), |
| 143 |
(_not_equal, pytools.lex.RE(r"\.ne\.", re.I)), |
| 144 |
|
| 145 |
(_not, pytools.lex.RE(r"\.not\.", re.I)), |
| 146 |
(_and, pytools.lex.RE(r"\.and\.", re.I)), |
| 147 |
(_or, pytools.lex.RE(r"\.or\.", re.I)), |
| 148 |
*ExpressionParserBase.lex_table] |
| 149 |
|
| 150 |
def __init__(self, tree_walker): |
| 151 |
self.tree_walker = tree_walker |
| 152 |
|
| 153 |
_PREC_FUNC_ARGS = 1 |
| 154 |
|
| 155 |
def parse_terminal(self, pstate): |
| 156 |
scope = self.tree_walker.scope_stack[-1] |
| 157 |
|
| 158 |
from pymbolic.parser import _closepar, _float, _identifier, _openpar |
| 159 |
|
| 160 |
next_tag = pstate.next_tag() |
| 161 |
if next_tag is _float: |
| 162 |
value = pstate.next_str_and_advance().lower() |
| 163 |
if "d" in value: |
| 164 |
dtype = np.float64 |
| 165 |
else: |
| 166 |
dtype = np.float32 |
| 167 |
|
| 168 |
value = value.replace("d", "e") |
| 169 |
if value.startswith("."): |
| 170 |
prev_value = value |
| 171 |
value = "0"+value |
| 172 |
print(value, prev_value) |
| 173 |
elif value.startswith("-."): |
| 174 |
prev_value = value |
| 175 |
value = "-0"+value[1:] |
| 176 |
print(value, prev_value) |
| 177 |
return TypedLiteral(value, dtype) |
| 178 |
|
| 179 |
elif next_tag is _identifier: |
| 180 |
name = pstate.next_str_and_advance() |
| 181 |
|
| 182 |
if pstate.is_at_end() or pstate.next_tag() is not _openpar: |
| 183 |
# not a subscript |
| 184 |
scope.use_name(name) |
| 185 |
|
| 186 |
return p.Variable(name) |
| 187 |
|
| 188 |
left_exp = p.Variable(name) |
| 189 |
|
| 190 |
pstate.advance() |
| 191 |
pstate.expect_not_end() |
| 192 |
|
| 193 |
if scope.is_known(name): |
| 194 |
cls = p.Subscript |
| 195 |
else: |
| 196 |
cls = p.Call |
| 197 |
|
| 198 |
if pstate.next_tag is _closepar: |
| 199 |
pstate.advance() |
| 200 |
left_exp = cls(left_exp, ()) |
| 201 |
else: |
| 202 |
args = self.parse_expression(pstate, self._PREC_FUNC_ARGS) |
| 203 |
if not isinstance(args, tuple): |
| 204 |
args = (args,) |
| 205 |
left_exp = cls(left_exp, args) |
| 206 |
pstate.expect(_closepar) |
| 207 |
pstate.advance() |
| 208 |
|
| 209 |
return left_exp |
| 210 |
else: |
| 211 |
return ExpressionParserBase.parse_terminal( |
| 212 |
self, pstate) |
| 213 |
|
| 214 |
COMP_MAP: ClassVar[Dict[str, str]] = { |
| 215 |
_less_than: "<", |
| 216 |
_less_equal: "<=", |
| 217 |
_greater_than: ">", |
| 218 |
_greater_equal: ">=", |
| 219 |
_equal: "==", |
| 220 |
_not_equal: "!=", |
| 221 |
} |
| 222 |
|
| 223 |
def parse_prefix(self, pstate, min_precedence=0): |
| 224 |
import pymbolic.primitives as primitives |
| 225 |
from pymbolic.parser import _PREC_UNARY |
| 226 |
|
| 227 |
pstate.expect_not_end() |
| 228 |
|
| 229 |
if pstate.is_next(_not): |
| 230 |
pstate.advance() |
| 231 |
return primitives.LogicalNot( |
| 232 |
self.parse_expression(pstate, _PREC_UNARY)) |
| 233 |
else: |
| 234 |
return ExpressionParserBase.parse_prefix(self, pstate) |
| 235 |
|
| 236 |
def parse_postfix(self, pstate, min_precedence, left_exp): |
| 237 |
from pymbolic.parser import ( |
| 238 |
_PREC_CALL, |
| 239 |
_PREC_COMPARISON, |
| 240 |
_PREC_LOGICAL_AND, |
| 241 |
_PREC_LOGICAL_OR, |
| 242 |
_openpar, |
| 243 |
) |
| 244 |
from pymbolic.primitives import Comparison, LogicalAnd, LogicalOr |
| 245 |
|
| 246 |
next_tag = pstate.next_tag() |
| 247 |
if next_tag is _openpar and _PREC_CALL > min_precedence: |
| 248 |
raise TranslationError("parenthesis operator only works on names") |
| 249 |
elif next_tag in self.COMP_MAP and _PREC_COMPARISON > min_precedence: |
| 250 |
pstate.advance() |
| 251 |
left_exp = Comparison( |
| 252 |
left_exp, |
| 253 |
self.COMP_MAP[next_tag], |
| 254 |
self.parse_expression(pstate, _PREC_COMPARISON)) |
| 255 |
did_something = True |
| 256 |
elif next_tag is _and and _PREC_LOGICAL_AND > min_precedence: |
| 257 |
pstate.advance() |
| 258 |
left_exp = LogicalAnd((left_exp, |
| 259 |
self.parse_expression(pstate, _PREC_LOGICAL_AND))) |
| 260 |
did_something = True |
| 261 |
elif next_tag is _or and _PREC_LOGICAL_OR > min_precedence: |
| 262 |
pstate.advance() |
| 263 |
left_exp = LogicalOr((left_exp, |
| 264 |
self.parse_expression(pstate, _PREC_LOGICAL_OR))) |
| 265 |
did_something = True |
| 266 |
else: |
| 267 |
left_exp, did_something = ExpressionParserBase.parse_postfix( |
| 268 |
self, pstate, min_precedence, left_exp) |
| 269 |
|
| 270 |
if isinstance(left_exp, tuple) and min_precedence < self._PREC_FUNC_ARGS: |
| 271 |
# this must be a complex literal |
| 272 |
assert len(left_exp) == 2 |
| 273 |
r, i = left_exp |
| 274 |
|
| 275 |
r = simplify_typed_literal(r) |
| 276 |
i = simplify_typed_literal(i) |
| 277 |
|
| 278 |
dtype = (r.dtype.type(0) + i.dtype.type(0)).dtype |
| 279 |
if dtype == np.float32: |
| 280 |
dtype = np.complex64 |
| 281 |
else: |
| 282 |
dtype = np.complex128 |
| 283 |
|
| 284 |
left_exp = TypedLiteral(left_exp, dtype) |
| 285 |
|
| 286 |
return left_exp, did_something |
| 287 |
|
| 288 |
# }}} |
| 289 |
|
| 290 |
|
| 291 |
# {{{ expression generator |
| 292 |
|
| 293 |
class TypeInferenceMapper(CombineMapper): |
| 294 |
def __init__(self, scope): |
| 295 |
self.scope = scope |
| 296 |
|
| 297 |
def combine(self, dtypes): |
| 298 |
return sum(dtype.type(1) for dtype in dtypes).dtype |
| 299 |
|
| 300 |
def map_literal(self, expr): |
| 301 |
return expr.dtype |
| 302 |
|
| 303 |
def map_constant(self, expr): |
| 304 |
return np.asarray(expr).dtype |
| 305 |
|
| 306 |
def map_variable(self, expr): |
| 307 |
return self.scope.get_type(expr.name) |
| 308 |
|
| 309 |
def map_call(self, expr): |
| 310 |
name = expr.function.name |
| 311 |
if name == "fromreal": |
| 312 |
arg, = expr.parameters |
| 313 |
base_dtype = self.rec(arg) |
| 314 |
tgt_real_dtype = (np.float32(0)+base_dtype.type(0)).dtype |
| 315 |
assert tgt_real_dtype.kind == "f" |
| 316 |
if tgt_real_dtype == np.float32: |
| 317 |
return np.dtype(np.complex64) |
| 318 |
elif tgt_real_dtype == np.float64: |
| 319 |
return np.dtype(np.complex128) |
| 320 |
else: |
| 321 |
raise RuntimeError("unexpected complex type") |
| 322 |
|
| 323 |
elif name in ["imag", "real", "abs", "dble"]: |
| 324 |
arg, = expr.parameters |
| 325 |
base_dtype = self.rec(arg) |
| 326 |
|
| 327 |
if base_dtype == np.complex128: |
| 328 |
return np.dtype(np.float64) |
| 329 |
elif base_dtype == np.complex64: |
| 330 |
return np.dtype(np.float32) |
| 331 |
else: |
| 332 |
return base_dtype |
| 333 |
|
| 334 |
else: |
| 335 |
return CombineMapper.map_call(self, expr) |
| 336 |
|
| 337 |
|
| 338 |
class ComplexCCodeMapper(CCodeMapperBase): |
| 339 |
def __init__(self, infer_type): |
| 340 |
CCodeMapperBase.__init__(self) |
| 341 |
self.infer_type = infer_type |
| 342 |
|
| 343 |
def map_sum(self, expr, enclosing_prec): |
| 344 |
tgt_dtype = self.infer_type(expr) |
| 345 |
is_complex = tgt_dtype.kind == "c" |
| 346 |
|
| 347 |
if not is_complex: |
| 348 |
return CCodeMapperBase.map_sum(self, expr, enclosing_prec) |
| 349 |
else: |
| 350 |
tgt_name = complex_type_name(tgt_dtype) |
| 351 |
|
| 352 |
reals = [child for child in expr.children |
| 353 |
if "c" != self.infer_type(child).kind] |
| 354 |
complexes = [child for child in expr.children |
| 355 |
if "c" == self.infer_type(child).kind] |
| 356 |
|
| 357 |
from pymbolic.mapper.stringifier import PREC_NONE, PREC_SUM |
| 358 |
real_sum = self.join_rec(" + ", reals, PREC_SUM) |
| 359 |
|
| 360 |
if len(complexes) == 1: |
| 361 |
myprec = PREC_SUM |
| 362 |
else: |
| 363 |
myprec = PREC_NONE |
| 364 |
|
| 365 |
complex_sum = self.rec(complexes[0], myprec) |
| 366 |
for child in complexes[1:]: |
| 367 |
complex_sum = "{}_add({}, {})".format( |
| 368 |
tgt_name, complex_sum, |
| 369 |
self.rec(child, PREC_NONE)) |
| 370 |
|
| 371 |
if real_sum: |
| 372 |
result = "{}_add({}_fromreal({}), {})".format( |
| 373 |
tgt_name, tgt_name, real_sum, complex_sum) |
| 374 |
else: |
| 375 |
result = complex_sum |
| 376 |
|
| 377 |
return self.parenthesize_if_needed(result, enclosing_prec, PREC_SUM) |
| 378 |
|
| 379 |
def map_product(self, expr, enclosing_prec): |
| 380 |
tgt_dtype = self.infer_type(expr) |
| 381 |
is_complex = "c" == tgt_dtype.kind |
| 382 |
|
| 383 |
if not is_complex: |
| 384 |
return CCodeMapperBase.map_product(self, expr, enclosing_prec) |
| 385 |
else: |
| 386 |
tgt_name = complex_type_name(tgt_dtype) |
| 387 |
|
| 388 |
reals = [child for child in expr.children |
| 389 |
if "c" != self.infer_type(child).kind] |
| 390 |
complexes = [child for child in expr.children |
| 391 |
if "c" == self.infer_type(child).kind] |
| 392 |
|
| 393 |
from pymbolic.mapper.stringifier import PREC_NONE, PREC_PRODUCT |
| 394 |
real_prd = self.join_rec("*", reals, PREC_PRODUCT) |
| 395 |
|
| 396 |
if len(complexes) == 1: |
| 397 |
myprec = PREC_PRODUCT |
| 398 |
else: |
| 399 |
myprec = PREC_NONE |
| 400 |
|
| 401 |
complex_prd = self.rec(complexes[0], myprec) |
| 402 |
for child in complexes[1:]: |
| 403 |
complex_prd = "{}_mul({}, {})".format( |
| 404 |
tgt_name, complex_prd, |
| 405 |
self.rec(child, PREC_NONE)) |
| 406 |
|
| 407 |
if real_prd: |
| 408 |
result = f"{tgt_name}_rmul({real_prd}, {complex_prd})" |
| 409 |
else: |
| 410 |
result = complex_prd |
| 411 |
|
| 412 |
return self.parenthesize_if_needed(result, enclosing_prec, PREC_PRODUCT) |
| 413 |
|
| 414 |
def map_quotient(self, expr, enclosing_prec): |
| 415 |
from pymbolic.mapper.stringifier import PREC_NONE |
| 416 |
n_complex = "c" == self.infer_type(expr.numerator).kind |
| 417 |
d_complex = "c" == self.infer_type(expr.denominator).kind |
| 418 |
|
| 419 |
tgt_dtype = self.infer_type(expr) |
| 420 |
|
| 421 |
if not (n_complex or d_complex): |
| 422 |
return CCodeMapperBase.map_quotient(self, expr, enclosing_prec) |
| 423 |
elif n_complex and not d_complex: |
| 424 |
return "{}_divider({}, {})".format( |
| 425 |
complex_type_name(tgt_dtype), |
| 426 |
self.rec(expr.numerator, PREC_NONE), |
| 427 |
self.rec(expr.denominator, PREC_NONE)) |
| 428 |
elif not n_complex and d_complex: |
| 429 |
return "{}_rdivide({}, {})".format( |
| 430 |
complex_type_name(tgt_dtype), |
| 431 |
self.rec(expr.numerator, PREC_NONE), |
| 432 |
self.rec(expr.denominator, PREC_NONE)) |
| 433 |
else: |
| 434 |
return "{}_divide({}, {})".format( |
| 435 |
complex_type_name(tgt_dtype), |
| 436 |
self.rec(expr.numerator, PREC_NONE), |
| 437 |
self.rec(expr.denominator, PREC_NONE)) |
| 438 |
|
| 439 |
def map_remainder(self, expr, enclosing_prec): |
| 440 |
tgt_dtype = self.infer_type(expr) |
| 441 |
if "c" == tgt_dtype.kind: |
| 442 |
raise RuntimeError("complex remainder not defined") |
| 443 |
|
| 444 |
return CCodeMapperBase.map_remainder(self, expr, enclosing_prec) |
| 445 |
|
| 446 |
def map_power(self, expr, enclosing_prec): |
| 447 |
from pymbolic.mapper.stringifier import PREC_NONE |
| 448 |
|
| 449 |
tgt_dtype = self.infer_type(expr) |
| 450 |
if "c" == tgt_dtype.kind: |
| 451 |
if expr.exponent in [2, 3, 4]: |
| 452 |
value = expr.base |
| 453 |
for i in range(expr.exponent-1): |
| 454 |
value = value * expr.base |
| 455 |
return self.rec(value, enclosing_prec) |
| 456 |
else: |
| 457 |
b_complex = "c" == self.infer_type(expr.base).kind |
| 458 |
e_complex = "c" == self.infer_type(expr.exponent).kind |
| 459 |
|
| 460 |
if b_complex and not e_complex: |
| 461 |
return "{}_powr({}, {})".format( |
| 462 |
complex_type_name(tgt_dtype), |
| 463 |
self.rec(expr.base, PREC_NONE), |
| 464 |
self.rec(expr.exponent, PREC_NONE)) |
| 465 |
else: |
| 466 |
return "{}_pow({}, {})".format( |
| 467 |
complex_type_name(tgt_dtype), |
| 468 |
self.rec(expr.base, PREC_NONE), |
| 469 |
self.rec(expr.exponent, PREC_NONE)) |
| 470 |
|
| 471 |
return CCodeMapperBase.map_power(self, expr, enclosing_prec) |
| 472 |
|
| 473 |
|
| 474 |
class CCodeMapper(ComplexCCodeMapper): |
| 475 |
# Whatever is needed to mop up after Fortran goes here. |
| 476 |
# Stuff that deals with generating real-valued code |
| 477 |
# from complex code goes above. |
| 478 |
|
| 479 |
def __init__(self, translator, scope): |
| 480 |
ComplexCCodeMapper.__init__(self, scope.get_type_inference_mapper()) |
| 481 |
self.translator = translator |
| 482 |
self.scope = scope |
| 483 |
|
| 484 |
def map_subscript(self, expr, enclosing_prec): |
| 485 |
idx_dtype = self.infer_type(expr.index) |
| 486 |
if not "i" == idx_dtype.kind or "u" == idx_dtype.kind: |
| 487 |
ind_prefix = "(int) " |
| 488 |
else: |
| 489 |
ind_prefix = "" |
| 490 |
|
| 491 |
idx = expr.index |
| 492 |
if isinstance(idx, tuple) and len(idx) == 1: |
| 493 |
idx, = idx |
| 494 |
|
| 495 |
from pymbolic.mapper.stringifier import PREC_CALL, PREC_NONE |
| 496 |
return self.parenthesize_if_needed( |
| 497 |
self.format("%s[%s%s]", |
| 498 |
self.scope.translate_var_name(expr.aggregate.name), |
| 499 |
ind_prefix, |
| 500 |
self.rec(idx, PREC_NONE)), |
| 501 |
enclosing_prec, PREC_CALL) |
| 502 |
|
| 503 |
def map_call(self, expr, enclosing_prec): |
| 504 |
from pymbolic.mapper.stringifier import PREC_NONE |
| 505 |
|
| 506 |
tgt_dtype = self.infer_type(expr) |
| 507 |
arg_dtypes = [self.infer_type(par) for par in expr.parameters] |
| 508 |
|
| 509 |
name = expr.function.name |
| 510 |
if "f" == tgt_dtype.kind and name == "abs": |
| 511 |
name = "fabs" |
| 512 |
|
| 513 |
elif "c" == tgt_dtype.kind: |
| 514 |
if name in ["conjg", "dconjg"]: |
| 515 |
name = "conj" |
| 516 |
|
| 517 |
if name[:2] == "cd" and name[2:] in ["log", "exp", "sqrt"]: |
| 518 |
name = name[2:] |
| 519 |
|
| 520 |
if name == "dble": |
| 521 |
name = "real" |
| 522 |
|
| 523 |
name = "{}_{}".format( |
| 524 |
complex_type_name(tgt_dtype), |
| 525 |
name) |
| 526 |
|
| 527 |
elif name in ["aimag", "real", "imag"] and tgt_dtype.kind == "f": |
| 528 |
arg_dtype, = arg_dtypes |
| 529 |
|
| 530 |
if name == "aimag": |
| 531 |
name = "imag" |
| 532 |
|
| 533 |
name = "{}_{}".format( |
| 534 |
complex_type_name(arg_dtype), |
| 535 |
name) |
| 536 |
|
| 537 |
elif "c" == tgt_dtype.kind and name == "abs": |
| 538 |
arg_dtype, = arg_dtypes |
| 539 |
|
| 540 |
name = "%s_abs" % ( |
| 541 |
complex_type_name(arg_dtype)) |
| 542 |
|
| 543 |
return self.format("%s(%s)", |
| 544 |
name, |
| 545 |
self.join_rec(", ", expr.parameters, PREC_NONE)) |
| 546 |
|
| 547 |
def map_variable(self, expr, enclosing_prec): |
| 548 |
# guaranteed to not be a subscript or a call |
| 549 |
|
| 550 |
name = expr.name |
| 551 |
shape = self.scope.get_shape(name) |
| 552 |
name = self.scope.translate_var_name(name) |
| 553 |
if expr.name in self.scope.arg_names: |
| 554 |
arg_idx = self.scope.arg_names.index(name) |
| 555 |
if self.translator.arg_needs_pointer( |
| 556 |
self.scope.subprogram_name, arg_idx): |
| 557 |
return "*"+name |
| 558 |
else: |
| 559 |
return name |
| 560 |
elif shape not in [(), None]: |
| 561 |
return "*"+name |
| 562 |
else: |
| 563 |
return name |
| 564 |
|
| 565 |
def map_literal(self, expr, enclosing_prec): |
| 566 |
from pymbolic.mapper.stringifier import PREC_NONE |
| 567 |
if expr.dtype.kind == "c": |
| 568 |
r, i = expr.value |
| 569 |
return "{}_new({}, {})".format( |
| 570 |
complex_type_name(expr.dtype), |
| 571 |
self.rec(r, PREC_NONE), |
| 572 |
self.rec(i, PREC_NONE)) |
| 573 |
else: |
| 574 |
return expr.value |
| 575 |
|
| 576 |
def map_wildcard(self, expr, enclosing_prec): |
| 577 |
return ":" |
| 578 |
|
| 579 |
|
| 580 |
# }}} |
| 581 |
|
| 582 |
class Scope: |
| 583 |
def __init__(self, subprogram_name, arg_names=set()): |
| 584 |
self.subprogram_name = subprogram_name |
| 585 |
|
| 586 |
# map name to data |
| 587 |
self.data_statements = {} |
| 588 |
|
| 589 |
# map first letter to type |
| 590 |
self.implicit_types = {} |
| 591 |
|
| 592 |
# map name to dim tuple |
| 593 |
self.dim_map = {} |
| 594 |
|
| 595 |
# map name to dim tuple |
| 596 |
self.type_map = {} |
| 597 |
|
| 598 |
# map name to data |
| 599 |
self.data = {} |
| 600 |
|
| 601 |
self.arg_names = arg_names |
| 602 |
|
| 603 |
self.used_names = set() |
| 604 |
|
| 605 |
self.type_inf_mapper = None |
| 606 |
|
| 607 |
def known_names(self): |
| 608 |
return (self.used_names |
| 609 |
| set(self.dim_map.keys()) |
| 610 |
| set(self.type_map.keys())) |
| 611 |
|
| 612 |
def is_known(self, name): |
| 613 |
return (name in self.used_names |
| 614 |
or name in self.dim_map |
| 615 |
or name in self.type_map) |
| 616 |
|
| 617 |
def use_name(self, name): |
| 618 |
self.used_names.add(name) |
| 619 |
|
| 620 |
def get_type(self, name): |
| 621 |
try: |
| 622 |
return self.type_map[name] |
| 623 |
except KeyError: |
| 624 |
|
| 625 |
if self.implicit_types is None: |
| 626 |
raise TranslationError( |
| 627 |
"no type for '%s' found in implicit none routine" |
| 628 |
% name) |
| 629 |
|
| 630 |
return self.implicit_types.get(name[0], np.dtype(np.int32)) |
| 631 |
|
| 632 |
def get_shape(self, name): |
| 633 |
return self.dim_map.get(name, ()) |
| 634 |
|
| 635 |
def get_type_inference_mapper(self): |
| 636 |
if self.type_inf_mapper is None: |
| 637 |
self.type_inf_mapper = TypeInferenceMapper(self) |
| 638 |
|
| 639 |
return self.type_inf_mapper |
| 640 |
|
| 641 |
def translate_var_name(self, name): |
| 642 |
shape = self.dim_map.get(name) |
| 643 |
if name in self.data and shape is not None: |
| 644 |
return f"{self.subprogram_name}_{name}" |
| 645 |
else: |
| 646 |
return name |
| 647 |
|
| 648 |
|
| 649 |
class FTreeWalkerBase: |
| 650 |
def __init__(self): |
| 651 |
self.scope_stack = [] |
| 652 |
|
| 653 |
self.expr_parser = FortranExpressionParser(self) |
| 654 |
|
| 655 |
def rec(self, expr, *args, **kwargs): |
| 656 |
mro = list(type(expr).__mro__) |
| 657 |
dispatch_class = kwargs.pop("dispatch_class", type(self)) |
| 658 |
|
| 659 |
while mro: |
| 660 |
method_name = "map_"+mro.pop(0).__name__ |
| 661 |
|
| 662 |
try: |
| 663 |
method = getattr(dispatch_class, method_name) |
| 664 |
except AttributeError: |
| 665 |
pass |
| 666 |
else: |
| 667 |
return method(self, expr, *args, **kwargs) |
| 668 |
|
| 669 |
raise NotImplementedError( |
| 670 |
"%s does not know how to map type '%s'" |
| 671 |
% (type(self).__name__, |
| 672 |
type(expr))) |
| 673 |
|
| 674 |
ENTITY_RE = re.compile( |
| 675 |
r"^(?P<name>[_0-9a-zA-Z]+)" |
| 676 |
r"(\((?P<shape>[-+*0-9:a-zA-Z,]+)\))?$") |
| 677 |
|
| 678 |
def parse_dimension_specs(self, dim_decls): |
| 679 |
def parse_bounds(bounds_str): |
| 680 |
start_end = bounds_str.split(":") |
| 681 |
|
| 682 |
assert 1 <= len(start_end) <= 2 |
| 683 |
|
| 684 |
return tuple(self.parse_expr(s) for s in start_end) |
| 685 |
|
| 686 |
for decl in dim_decls: |
| 687 |
entity_match = self.ENTITY_RE.match(decl) |
| 688 |
assert entity_match |
| 689 |
|
| 690 |
groups = entity_match.groupdict() |
| 691 |
name = groups["name"] |
| 692 |
assert name |
| 693 |
|
| 694 |
if groups["shape"]: |
| 695 |
shape = [parse_bounds(s) for s in groups["shape"].split(",")] |
| 696 |
else: |
| 697 |
shape = None |
| 698 |
|
| 699 |
yield name, shape |
| 700 |
|
| 701 |
def __call__(self, expr, *args, **kwargs): |
| 702 |
return self.rec(expr, *args, **kwargs) |
| 703 |
|
| 704 |
# {{{ expressions |
| 705 |
|
| 706 |
def parse_expr(self, expr_str): |
| 707 |
return self.expr_parser(expr_str) |
| 708 |
|
| 709 |
# }}} |
| 710 |
|
| 711 |
|
| 712 |
class ArgumentAnalayzer(FTreeWalkerBase): |
| 713 |
def __init__(self): |
| 714 |
FTreeWalkerBase.__init__(self) |
| 715 |
|
| 716 |
# map (func, arg_nr) to |
| 717 |
# "w" for "needs pointer" |
| 718 |
# [] for no obstacle to de-pointerification known |
| 719 |
# [(func_name, arg_nr), ...] # depends on how this arg is used |
| 720 |
|
| 721 |
self.arg_usage_info = {} |
| 722 |
|
| 723 |
def arg_needs_pointer(self, func, arg_nr): |
| 724 |
data = self.arg_usage_info.get((func, arg_nr), []) |
| 725 |
|
| 726 |
if isinstance(data, list): |
| 727 |
return any( |
| 728 |
self.arg_needs_pointer(sub_func, sub_arg_nr) |
| 729 |
for sub_func, sub_arg_nr in data) |
| 730 |
|
| 731 |
return True |
| 732 |
|
| 733 |
# {{{ map_XXX functions |
| 734 |
|
| 735 |
def map_BeginSource(self, node): |
| 736 |
scope = Scope(None) |
| 737 |
self.scope_stack.append(scope) |
| 738 |
|
| 739 |
for c in node.content: |
| 740 |
self.rec(c) |
| 741 |
|
| 742 |
def map_Subroutine(self, node): |
| 743 |
scope = Scope(node.name, list(node.args)) |
| 744 |
self.scope_stack.append(scope) |
| 745 |
|
| 746 |
for c in node.content: |
| 747 |
self.rec(c) |
| 748 |
|
| 749 |
self.scope_stack.pop() |
| 750 |
|
| 751 |
def map_EndSubroutine(self, node): |
| 752 |
pass |
| 753 |
|
| 754 |
def map_Implicit(self, node): |
| 755 |
pass |
| 756 |
|
| 757 |
# {{{ types, declarations |
| 758 |
|
| 759 |
def map_Equivalence(self, node): |
| 760 |
raise NotImplementedError("equivalence") |
| 761 |
|
| 762 |
def map_Dimension(self, node): |
| 763 |
scope = self.scope_stack[-1] |
| 764 |
|
| 765 |
for name, shape in self.parse_dimension_specs(node.items): |
| 766 |
if name in scope.arg_names: |
| 767 |
arg_idx = scope.arg_names.index(name) |
| 768 |
self.arg_usage_info[scope.subprogram_name, arg_idx] = "w" |
| 769 |
|
| 770 |
def map_External(self, node): |
| 771 |
pass |
| 772 |
|
| 773 |
def map_type_decl(self, node): |
| 774 |
scope = self.scope_stack[-1] |
| 775 |
|
| 776 |
for name, shape in self.parse_dimension_specs(node.entity_decls): |
| 777 |
if shape is not None and name in scope.arg_names: |
| 778 |
arg_idx = scope.arg_names.index(name) |
| 779 |
self.arg_usage_info[scope.subprogram_name, arg_idx] = "w" |
| 780 |
|
| 781 |
map_Logical = map_type_decl |
| 782 |
map_Integer = map_type_decl |
| 783 |
map_Real = map_type_decl |
| 784 |
map_Complex = map_type_decl |
| 785 |
|
| 786 |
# }}} |
| 787 |
|
| 788 |
def map_Data(self, node): |
| 789 |
pass |
| 790 |
|
| 791 |
def map_Parameter(self, node): |
| 792 |
raise NotImplementedError("parameter") |
| 793 |
|
| 794 |
# {{{ I/O |
| 795 |
|
| 796 |
def map_Open(self, node): |
| 797 |
pass |
| 798 |
|
| 799 |
def map_Format(self, node): |
| 800 |
pass |
| 801 |
|
| 802 |
def map_Write(self, node): |
| 803 |
pass |
| 804 |
|
| 805 |
def map_Print(self, node): |
| 806 |
pass |
| 807 |
|
| 808 |
def map_Read1(self, node): |
| 809 |
pass |
| 810 |
|
| 811 |
# }}} |
| 812 |
|
| 813 |
def map_Assignment(self, node): |
| 814 |
scope = self.scope_stack[-1] |
| 815 |
|
| 816 |
lhs = self.parse_expr(node.variable) |
| 817 |
|
| 818 |
if isinstance(lhs, p.Subscript): |
| 819 |
lhs_name = lhs.aggregate.name |
| 820 |
elif isinstance(lhs, p.Call): |
| 821 |
# in absence of dim info, subscripts get parsed as calls |
| 822 |
lhs_name = lhs.function.name |
| 823 |
else: |
| 824 |
lhs_name = lhs.name |
| 825 |
|
| 826 |
if lhs_name in scope.arg_names: |
| 827 |
arg_idx = scope.arg_names.index(lhs_name) |
| 828 |
self.arg_usage_info[scope.subprogram_name, arg_idx] = "w" |
| 829 |
|
| 830 |
def map_Allocate(self, node): |
| 831 |
raise NotImplementedError("allocate") |
| 832 |
|
| 833 |
def map_Deallocate(self, node): |
| 834 |
raise NotImplementedError("deallocate") |
| 835 |
|
| 836 |
def map_Save(self, node): |
| 837 |
raise NotImplementedError("save") |
| 838 |
|
| 839 |
def map_Line(self, node): |
| 840 |
raise NotImplementedError |
| 841 |
|
| 842 |
def map_Program(self, node): |
| 843 |
raise NotImplementedError |
| 844 |
|
| 845 |
def map_Entry(self, node): |
| 846 |
raise NotImplementedError |
| 847 |
|
| 848 |
# {{{ control flow |
| 849 |
|
| 850 |
def map_Goto(self, node): |
| 851 |
pass |
| 852 |
|
| 853 |
def map_Call(self, node): |
| 854 |
scope = self.scope_stack[-1] |
| 855 |
|
| 856 |
for i, arg_str in enumerate(node.items): |
| 857 |
arg = self.parse_expr(arg_str) |
| 858 |
if isinstance(arg, (p.Variable, p.Subscript)): |
| 859 |
if isinstance(arg, p.Subscript): |
| 860 |
arg_name = arg.aggregate.name |
| 861 |
else: |
| 862 |
arg_name = arg.name |
| 863 |
|
| 864 |
if arg_name in scope.arg_names: |
| 865 |
arg_idx = scope.arg_names.index(arg_name) |
| 866 |
arg_usage = self.arg_usage_info.setdefault( |
| 867 |
(scope.subprogram_name, arg_idx), |
| 868 |
[]) |
| 869 |
if isinstance(arg_usage, list): |
| 870 |
arg_usage.append((node.designator, i)) |
| 871 |
|
| 872 |
def map_Return(self, node): |
| 873 |
pass |
| 874 |
|
| 875 |
def map_ArithmeticIf(self, node): |
| 876 |
pass |
| 877 |
|
| 878 |
def map_If(self, node): |
| 879 |
for c in node.content: |
| 880 |
self.rec(c) |
| 881 |
|
| 882 |
def map_IfThen(self, node): |
| 883 |
for c in node.content: |
| 884 |
self.rec(c) |
| 885 |
|
| 886 |
def map_ElseIf(self, node): |
| 887 |
pass |
| 888 |
|
| 889 |
def map_Else(self, node): |
| 890 |
pass |
| 891 |
|
| 892 |
def map_EndIfThen(self, node): |
| 893 |
pass |
| 894 |
|
| 895 |
def map_Do(self, node): |
| 896 |
for c in node.content: |
| 897 |
self.rec(c) |
| 898 |
|
| 899 |
def map_EndDo(self, node): |
| 900 |
pass |
| 901 |
|
| 902 |
def map_Continue(self, node): |
| 903 |
pass |
| 904 |
|
| 905 |
def map_Stop(self, node): |
| 906 |
pass |
| 907 |
|
| 908 |
def map_Comment(self, node): |
| 909 |
pass |
| 910 |
|
| 911 |
# }}} |
| 912 |
|
| 913 |
# }}} |
| 914 |
|
| 915 |
|
| 916 |
# {{{ translator |
| 917 |
|
| 918 |
class F2CLTranslator(FTreeWalkerBase): |
| 919 |
def __init__(self, addr_space_hints, force_casts, arg_info, |
| 920 |
use_restrict_pointers): |
| 921 |
FTreeWalkerBase.__init__(self) |
| 922 |
self.addr_space_hints = addr_space_hints |
| 923 |
self.force_casts = force_casts |
| 924 |
self.arg_info = arg_info |
| 925 |
self.use_restrict_pointers = use_restrict_pointers |
| 926 |
|
| 927 |
def arg_needs_pointer(self, subprogram_name, arg_index): |
| 928 |
return self.arg_info.arg_needs_pointer(subprogram_name, arg_index) |
| 929 |
|
| 930 |
# {{{ declaration helpers |
| 931 |
|
| 932 |
def get_declarator(self, name): |
| 933 |
scope = self.scope_stack[-1] |
| 934 |
return POD(scope.get_type(name), name) |
| 935 |
|
| 936 |
def get_declarations(self): |
| 937 |
scope = self.scope_stack[-1] |
| 938 |
|
| 939 |
result = [] |
| 940 |
pre_func_decl = [] |
| 941 |
|
| 942 |
def gen_shape(start_end): |
| 943 |
return ":".join(self.gen_expr(s) for s in start_end) |
| 944 |
|
| 945 |
for name in sorted(scope.known_names()): |
| 946 |
shape = scope.dim_map.get(name) |
| 947 |
|
| 948 |
if shape is not None: |
| 949 |
dim_stmt = cgen.Statement( |
| 950 |
'dimension "fortran" {}[{}]'.format( |
| 951 |
scope.translate_var_name(name), |
| 952 |
", ".join(gen_shape(s) for s in shape) |
| 953 |
)) |
| 954 |
|
| 955 |
# cannot omit "dimension" decl even for rank-1 args: |
| 956 |
result.append(dim_stmt) |
| 957 |
|
| 958 |
if name in scope.data: |
| 959 |
assert name not in scope.arg_names |
| 960 |
|
| 961 |
data = scope.data[name] |
| 962 |
|
| 963 |
if shape is None: |
| 964 |
assert len(data) == 1 |
| 965 |
result.append( |
| 966 |
cgen.Initializer( |
| 967 |
self.get_declarator(name), |
| 968 |
self.gen_expr(data[0]) |
| 969 |
)) |
| 970 |
else: |
| 971 |
from cgen.opencl import CLConstant |
| 972 |
pre_func_decl.append( |
| 973 |
cgen.Initializer( |
| 974 |
CLConstant( |
| 975 |
cgen.ArrayOf(self.get_declarator( |
| 976 |
f"{scope.subprogram_name}_{name}"))), |
| 977 |
"{ %s }" % ",\n".join(self.gen_expr(x) for x in data) |
| 978 |
)) |
| 979 |
else: |
| 980 |
if name not in scope.arg_names: |
| 981 |
if shape is not None: |
| 982 |
result.append(cgen.Statement( |
| 983 |
"%s %s[nitemsof(%s)]" |
| 984 |
% ( |
| 985 |
dtype_to_ctype(scope.get_type(name)), |
| 986 |
name, name))) |
| 987 |
else: |
| 988 |
result.append(self.get_declarator(name)) |
| 989 |
|
| 990 |
return pre_func_decl, result |
| 991 |
|
| 992 |
def map_statement_list(self, content): |
| 993 |
body = [] |
| 994 |
|
| 995 |
for c in content: |
| 996 |
mapped = self.rec(c) |
| 997 |
if mapped is None: |
| 998 |
warn("mapping '%s' returned None" % type(c)) |
| 999 |
elif isinstance(mapped, list): |
| 1000 |
body.extend(mapped) |
| 1001 |
else: |
| 1002 |
body.append(mapped) |
| 1003 |
|
| 1004 |
return body |
| 1005 |
|
| 1006 |
# }}} |
| 1007 |
|
| 1008 |
# {{{ map_XXX functions |
| 1009 |
|
| 1010 |
def map_BeginSource(self, node): |
| 1011 |
scope = Scope(None) |
| 1012 |
self.scope_stack.append(scope) |
| 1013 |
|
| 1014 |
return self.map_statement_list(node.content) |
| 1015 |
|
| 1016 |
def map_Subroutine(self, node): |
| 1017 |
assert not node.prefix |
| 1018 |
assert not hasattr(node, "suffix") |
| 1019 |
|
| 1020 |
scope = Scope(node.name, list(node.args)) |
| 1021 |
self.scope_stack.append(scope) |
| 1022 |
|
| 1023 |
body = self.map_statement_list(node.content) |
| 1024 |
|
| 1025 |
pre_func_decl, in_func_decl = self.get_declarations() |
| 1026 |
body = [*in_func_decl, cgen.Line(), *body] |
| 1027 |
|
| 1028 |
if isinstance(body[-1], cgen.Statement) and body[-1].text == "return": |
| 1029 |
body.pop() |
| 1030 |
|
| 1031 |
def get_arg_decl(arg_idx, arg_name): |
| 1032 |
decl = self.get_declarator(arg_name) |
| 1033 |
|
| 1034 |
if self.arg_needs_pointer(node.name, arg_idx): |
| 1035 |
hint = self.addr_space_hints.get((node.name, arg_name)) |
| 1036 |
if hint: |
| 1037 |
decl = hint(cgen.Pointer(decl)) |
| 1038 |
else: |
| 1039 |
if self.use_restrict_pointers: |
| 1040 |
decl = cgen.RestrictPointer(decl) |
| 1041 |
else: |
| 1042 |
decl = cgen.Pointer(decl) |
| 1043 |
|
| 1044 |
return decl |
| 1045 |
|
| 1046 |
result = cgen.FunctionBody( |
| 1047 |
cgen.FunctionDeclaration( |
| 1048 |
cgen.Value("void", node.name), |
| 1049 |
[get_arg_decl(i, arg) for i, arg in enumerate(node.args)] |
| 1050 |
), |
| 1051 |
cgen.Block(body)) |
| 1052 |
|
| 1053 |
self.scope_stack.pop() |
| 1054 |
if pre_func_decl: |
| 1055 |
return [*pre_func_decl, cgen.Line(), result] |
| 1056 |
else: |
| 1057 |
return result |
| 1058 |
|
| 1059 |
def map_EndSubroutine(self, node): |
| 1060 |
return [] |
| 1061 |
|
| 1062 |
def map_Implicit(self, node): |
| 1063 |
scope = self.scope_stack[-1] |
| 1064 |
|
| 1065 |
if not node.items: |
| 1066 |
assert not scope.implicit_types |
| 1067 |
scope.implicit_types = None |
| 1068 |
|
| 1069 |
for stmt, specs in node.items: |
| 1070 |
tp = self.dtype_from_stmt(stmt) |
| 1071 |
for start, end in specs: |
| 1072 |
for char_code in range(ord(start), ord(end)+1): |
| 1073 |
scope.implicit_types[chr(char_code)] = tp |
| 1074 |
|
| 1075 |
return [] |
| 1076 |
|
| 1077 |
# {{{ types, declarations |
| 1078 |
|
| 1079 |
def map_Equivalence(self, node): |
| 1080 |
raise NotImplementedError("equivalence") |
| 1081 |
|
| 1082 |
TYPE_MAP: ClassVar[Dict[Tuple[str, str], np.generic]] = { |
| 1083 |
("real", "4"): np.float32, |
| 1084 |
("real", "8"): np.float64, |
| 1085 |
("real", "16"): np.float128, |
| 1086 |
|
| 1087 |
("complex", "8"): np.complex64, |
| 1088 |
("complex", "16"): np.complex128, |
| 1089 |
("complex", "32"): np.complex256, |
| 1090 |
|
| 1091 |
("integer", ""): np.int32, |
| 1092 |
("integer", "4"): np.int32, |
| 1093 |
("integer", "8"): np.int64, |
| 1094 |
} |
| 1095 |
|
| 1096 |
def dtype_from_stmt(self, stmt): |
| 1097 |
length, kind = stmt.selector |
| 1098 |
assert not kind |
| 1099 |
return np.dtype(self.TYPE_MAP[type(stmt).__name__.lower(), length]) |
| 1100 |
|
| 1101 |
def map_type_decl(self, node): |
| 1102 |
scope = self.scope_stack[-1] |
| 1103 |
|
| 1104 |
tp = self.dtype_from_stmt(node) |
| 1105 |
|
| 1106 |
for name, shape in self.parse_dimension_specs(node.entity_decls): |
| 1107 |
if shape is not None: |
| 1108 |
assert name not in scope.dim_map |
| 1109 |
scope.dim_map[name] = shape |
| 1110 |
scope.use_name(name) |
| 1111 |
|
| 1112 |
assert name not in scope.type_map |
| 1113 |
scope.type_map[name] = tp |
| 1114 |
|
| 1115 |
return [] |
| 1116 |
|
| 1117 |
map_Logical = map_type_decl |
| 1118 |
map_Integer = map_type_decl |
| 1119 |
map_Real = map_type_decl |
| 1120 |
map_Complex = map_type_decl |
| 1121 |
|
| 1122 |
def map_Dimension(self, node): |
| 1123 |
scope = self.scope_stack[-1] |
| 1124 |
|
| 1125 |
for name, shape in self.parse_dimension_specs(node.items): |
| 1126 |
if shape is not None: |
| 1127 |
assert name not in scope.dim_map |
| 1128 |
scope.dim_map[name] = shape |
| 1129 |
scope.use_name(name) |
| 1130 |
|
| 1131 |
return [] |
| 1132 |
|
| 1133 |
def map_External(self, node): |
| 1134 |
raise NotImplementedError("external") |
| 1135 |
|
| 1136 |
# }}} |
| 1137 |
|
| 1138 |
def map_Data(self, node): |
| 1139 |
scope = self.scope_stack[-1] |
| 1140 |
|
| 1141 |
for name, data in node.stmts: |
| 1142 |
name, = name |
| 1143 |
assert name not in scope.data |
| 1144 |
scope.data[name] = [self.parse_expr(i) for i in data] |
| 1145 |
|
| 1146 |
return [] |
| 1147 |
|
| 1148 |
def map_Parameter(self, node): |
| 1149 |
raise NotImplementedError("parameter") |
| 1150 |
|
| 1151 |
# {{{ I/O |
| 1152 |
|
| 1153 |
def map_Open(self, node): |
| 1154 |
raise NotImplementedError |
| 1155 |
|
| 1156 |
def map_Format(self, node): |
| 1157 |
warn("'format' unsupported", TranslatorWarning) |
| 1158 |
|
| 1159 |
def map_Write(self, node): |
| 1160 |
warn("'write' unsupported", TranslatorWarning) |
| 1161 |
|
| 1162 |
def map_Print(self, node): |
| 1163 |
warn("'print' unsupported", TranslatorWarning) |
| 1164 |
|
| 1165 |
def map_Read1(self, node): |
| 1166 |
warn("'read' unsupported", TranslatorWarning) |
| 1167 |
|
| 1168 |
# }}} |
| 1169 |
|
| 1170 |
def map_Assignment(self, node): |
| 1171 |
lhs = self.parse_expr(node.variable) |
| 1172 |
from pymbolic.primitives import Subscript |
| 1173 |
if isinstance(lhs, Subscript): |
| 1174 |
lhs_name = lhs.aggregate.name |
| 1175 |
else: |
| 1176 |
lhs_name = lhs.name |
| 1177 |
|
| 1178 |
scope = self.scope_stack[-1] |
| 1179 |
scope.use_name(lhs_name) |
| 1180 |
infer_type = scope.get_type_inference_mapper() |
| 1181 |
|
| 1182 |
rhs = self.parse_expr(node.expr) |
| 1183 |
lhs_dtype = infer_type(lhs) |
| 1184 |
rhs_dtype = infer_type(rhs) |
| 1185 |
|
| 1186 |
# check for silent truncation of complex |
| 1187 |
if lhs_dtype.kind != "c" and rhs_dtype.kind == "c": |
| 1188 |
from pymbolic import var |
| 1189 |
rhs = var("real")(rhs) |
| 1190 |
# check for silent widening of real |
| 1191 |
if lhs_dtype.kind == "c" and rhs_dtype.kind != "c": |
| 1192 |
from pymbolic import var |
| 1193 |
rhs = var("fromreal")(rhs) |
| 1194 |
|
| 1195 |
return cgen.Assign(self.gen_expr(lhs), self.gen_expr(rhs)) |
| 1196 |
|
| 1197 |
def map_Allocate(self, node): |
| 1198 |
raise NotImplementedError("allocate") |
| 1199 |
|
| 1200 |
def map_Deallocate(self, node): |
| 1201 |
raise NotImplementedError("deallocate") |
| 1202 |
|
| 1203 |
def map_Save(self, node): |
| 1204 |
raise NotImplementedError("save") |
| 1205 |
|
| 1206 |
def map_Line(self, node): |
| 1207 |
# from warnings import warn |
| 1208 |
# warn("Encountered a 'line': %s" % node) |
| 1209 |
raise NotImplementedError |
| 1210 |
|
| 1211 |
def map_Program(self, node): |
| 1212 |
raise NotImplementedError |
| 1213 |
|
| 1214 |
def map_Entry(self, node): |
| 1215 |
raise NotImplementedError |
| 1216 |
|
| 1217 |
# {{{ control flow |
| 1218 |
|
| 1219 |
def map_Goto(self, node): |
| 1220 |
return cgen.Statement("goto label_%s" % node.label) |
| 1221 |
|
| 1222 |
def map_Call(self, node): |
| 1223 |
def transform_arg(i, arg_str): |
| 1224 |
expr = self.parse_expr(arg_str) |
| 1225 |
result = self.gen_expr(expr) |
| 1226 |
if self.arg_needs_pointer(node.designator, i): |
| 1227 |
result = "&"+result |
| 1228 |
|
| 1229 |
cast = self.force_casts.get( |
| 1230 |
(node.designator, i)) |
| 1231 |
if cast is not None: |
| 1232 |
result = f"({cast}) ({result})" |
| 1233 |
|
| 1234 |
return result |
| 1235 |
|
| 1236 |
return cgen.Statement("{}({})".format( |
| 1237 |
node.designator, |
| 1238 |
", ".join(transform_arg(i, arg_str) |
| 1239 |
for i, arg_str in enumerate(node.items)))) |
| 1240 |
|
| 1241 |
def map_Return(self, node): |
| 1242 |
return cgen.Statement("return") |
| 1243 |
|
| 1244 |
def map_ArithmeticIf(self, node): |
| 1245 |
raise NotImplementedError |
| 1246 |
|
| 1247 |
def map_If(self, node): |
| 1248 |
return cgen.If(self.transform_expr(node.expr), |
| 1249 |
self.rec(node.content[0])) |
| 1250 |
|
| 1251 |
def map_IfThen(self, node): |
| 1252 |
current_cond = self.transform_expr(node.expr) |
| 1253 |
|
| 1254 |
blocks_and_conds = [] |
| 1255 |
else_block = [] |
| 1256 |
|
| 1257 |
def end_block(): |
| 1258 |
if current_body: |
| 1259 |
if current_cond is None: |
| 1260 |
else_block[:] = self.map_statement_list(current_body) |
| 1261 |
else: |
| 1262 |
blocks_and_conds.append( |
| 1263 |
(current_cond, cgen.block_if_necessary( |
| 1264 |
self.map_statement_list(current_body)))) |
| 1265 |
|
| 1266 |
del current_body[:] |
| 1267 |
|
| 1268 |
from fparser.statements import Else, ElseIf |
| 1269 |
i = 0 |
| 1270 |
current_body = [] |
| 1271 |
while i < len(node.content): |
| 1272 |
c = node.content[i] |
| 1273 |
if isinstance(c, ElseIf): |
| 1274 |
end_block() |
| 1275 |
current_cond = self.transform_expr(c.expr) |
| 1276 |
elif isinstance(c, Else): |
| 1277 |
end_block() |
| 1278 |
current_cond = None |
| 1279 |
else: |
| 1280 |
current_body.append(c) |
| 1281 |
|
| 1282 |
i += 1 |
| 1283 |
end_block() |
| 1284 |
|
| 1285 |
def block_or_none(body): |
| 1286 |
if not body: |
| 1287 |
return None |
| 1288 |
else: |
| 1289 |
return cgen.block_if_necessary(body) |
| 1290 |
|
| 1291 |
return cgen.make_multiple_ifs( |
| 1292 |
blocks_and_conds, |
| 1293 |
block_or_none(else_block)) |
| 1294 |
|
| 1295 |
def map_EndIfThen(self, node): |
| 1296 |
return [] |
| 1297 |
|
| 1298 |
def map_Do(self, node): |
| 1299 |
scope = self.scope_stack[-1] |
| 1300 |
|
| 1301 |
body = self.map_statement_list(node.content) |
| 1302 |
|
| 1303 |
if node.loopcontrol: |
| 1304 |
loop_var, loop_bounds = node.loopcontrol.split("=") |
| 1305 |
loop_var = loop_var.strip() |
| 1306 |
scope.use_name(loop_var) |
| 1307 |
loop_bounds = [self.parse_expr(s) for s in loop_bounds.split(",")] |
| 1308 |
|
| 1309 |
if len(loop_bounds) == 2: |
| 1310 |
start, stop = loop_bounds |
| 1311 |
step = 1 |
| 1312 |
elif len(loop_bounds) == 3: |
| 1313 |
start, stop, step = loop_bounds |
| 1314 |
else: |
| 1315 |
raise RuntimeError("loop bounds not understood: %s" |
| 1316 |
% node.loopcontrol) |
| 1317 |
|
| 1318 |
if not isinstance(step, int): |
| 1319 |
print(type(step)) |
| 1320 |
raise TranslationError( |
| 1321 |
"non-constant steps not yet supported: %s" % step) |
| 1322 |
|
| 1323 |
if step < 0: |
| 1324 |
comp_op = ">=" |
| 1325 |
else: |
| 1326 |
comp_op = "<=" |
| 1327 |
|
| 1328 |
return cgen.For( |
| 1329 |
"{} = {}".format(loop_var, self.gen_expr(start)), |
| 1330 |
"{} {} {}".format(loop_var, comp_op, self.gen_expr(stop)), |
| 1331 |
"{} += {}".format(loop_var, self.gen_expr(step)), |
| 1332 |
cgen.block_if_necessary(body)) |
| 1333 |
|
| 1334 |
else: |
| 1335 |
raise NotImplementedError("unbounded do loop") |
| 1336 |
|
| 1337 |
def map_EndDo(self, node): |
| 1338 |
return [] |
| 1339 |
|
| 1340 |
def map_Continue(self, node): |
| 1341 |
return cgen.Statement("label_%s:" % node.label) |
| 1342 |
|
| 1343 |
def map_Stop(self, node): |
| 1344 |
raise NotImplementedError("stop") |
| 1345 |
|
| 1346 |
def map_Comment(self, node): |
| 1347 |
if node.content: |
| 1348 |
return cgen.LineComment(node.content.strip()) |
| 1349 |
else: |
| 1350 |
return [] |
| 1351 |
|
| 1352 |
# }}} |
| 1353 |
|
| 1354 |
# }}} |
| 1355 |
|
| 1356 |
# {{{ expressions |
| 1357 |
|
| 1358 |
def gen_expr(self, expr): |
| 1359 |
scope = self.scope_stack[-1] |
| 1360 |
return CCodeMapper(self, scope)(expr) |
| 1361 |
|
| 1362 |
def transform_expr(self, expr_str): |
| 1363 |
return self.gen_expr(self.expr_parser(expr_str)) |
| 1364 |
|
| 1365 |
# }}} |
| 1366 |
|
| 1367 |
# }}} |
| 1368 |
|
| 1369 |
|
| 1370 |
def f2cl(source, free_form=False, strict=True, |
| 1371 |
addr_space_hints={}, force_casts={}, |
| 1372 |
do_arg_analysis=True, |
| 1373 |
use_restrict_pointers=False, |
| 1374 |
try_compile=False): |
| 1375 |
from fparser import api |
| 1376 |
tree = api.parse(source, isfree=free_form, isstrict=strict, |
| 1377 |
analyze=False, ignore_comments=False) |
| 1378 |
|
| 1379 |
arg_info = ArgumentAnalayzer() |
| 1380 |
if do_arg_analysis: |
| 1381 |
arg_info(tree) |
| 1382 |
|
| 1383 |
source = F2CLTranslator(addr_space_hints, force_casts, |
| 1384 |
arg_info, use_restrict_pointers=use_restrict_pointers)(tree) |
| 1385 |
|
| 1386 |
func_decls = [] |
| 1387 |
for entry in source: |
| 1388 |
if isinstance(entry, cgen.FunctionBody): |
| 1389 |
func_decls.append(entry.fdecl) |
| 1390 |
|
| 1391 |
mod = cgen.Module([*func_decls, cgen.Line(), *source]) |
| 1392 |
|
| 1393 |
# open("pre-cnd.cl", "w").write(str(mod)) |
| 1394 |
|
| 1395 |
from cnd import transform_cl |
| 1396 |
str_mod = transform_cl(str(mod)) |
| 1397 |
|
| 1398 |
if try_compile: |
| 1399 |
import pyopencl as cl |
| 1400 |
ctx = cl.create_some_context() |
| 1401 |
cl.Program(ctx, """ |
| 1402 |
#if __OPENCL_VERSION__ <= CL_VERSION_1_1 |
| 1403 |
#pragma OPENCL EXTENSION cl_khr_fp64: enable |
| 1404 |
#endif |
| 1405 |
#include <pyopencl-complex.h> |
| 1406 |
""").build() |
| 1407 |
return str_mod |
| 1408 |
|
| 1409 |
|
| 1410 |
def f2cl_files(source_file, target_file, **kwargs): |
| 1411 |
mod = f2cl(open(source_file).read(), **kwargs) |
| 1412 |
open(target_file, "w").write(mod) |
| 1413 |
|
| 1414 |
|
| 1415 |
if __name__ == "__main__": |
| 1416 |
import logging |
| 1417 |
console = logging.StreamHandler() |
| 1418 |
console.setLevel(logging.DEBUG) |
| 1419 |
formatter = logging.Formatter("%(name)-12s: %(levelname)-8s %(message)s") |
| 1420 |
console.setFormatter(formatter) |
| 1421 |
logging.getLogger("fparser").addHandler(console) |
| 1422 |
|
| 1423 |
from cgen.opencl import CLConstant |
| 1424 |
|
| 1425 |
if 0: |
| 1426 |
f2cl_files("hank107.f", "hank107.cl", |
| 1427 |
addr_space_hints={ |
| 1428 |
("hank107p", "p"): CLConstant, |
| 1429 |
("hank107pc", "p"): CLConstant, |
| 1430 |
}, |
| 1431 |
force_casts={ |
| 1432 |
("hank107p", 0): "__constant cdouble_t *", |
| 1433 |
}) |
| 1434 |
|
| 1435 |
f2cl_files("cdjseval2d.f", "cdjseval2d.cl") |
| 1436 |
|
| 1437 |
f2cl_files("hank103.f", "hank103.cl", |
| 1438 |
addr_space_hints={ |
| 1439 |
("hank103p", "p"): CLConstant, |
| 1440 |
("hank103pc", "p"): CLConstant, |
| 1441 |
}, |
| 1442 |
force_casts={ |
| 1443 |
("hank103p", 0): "__constant cdouble_t *", |
| 1444 |
}, |
| 1445 |
try_compile=True) |
| 1446 |
|
| 1447 |
# vim: foldmethod=marker |