-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfortran_gpu_analyzer.py
More file actions
953 lines (813 loc) · 34.4 KB
/
fortran_gpu_analyzer.py
File metadata and controls
953 lines (813 loc) · 34.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
#!/usr/bin/env python3
"""
Fortran GPU Porting Assistant - 補助情報自動生成スクリプト
Phase 1: 静的解析(AST、配列アクセス、ループ構造)
Phase 2: 依存関係解析(依存ベクトル計算)
Phase 3: パターン認識(wavefront等の検出、戦略推奨)
"""
import json
import re
import sys
from dataclasses import dataclass, field, asdict
from typing import List, Dict, Optional, Tuple, Set
from pathlib import Path
# fparser2のインポート
try:
from fparser.two.parser import ParserFactory
from fparser.two.utils import walk
from fparser.two import Fortran2003 as f2003
from fparser.common.readfortran import FortranFileReader
FPARSER_AVAILABLE = True
except ImportError:
FPARSER_AVAILABLE = False
print("Warning: fparser not available, using regex-based fallback", file=sys.stderr)
# =============================================================================
# Data Classes
# =============================================================================
@dataclass
class IndexExpr:
"""配列添字の解析結果"""
raw: str # 元の式 (e.g., "k-1")
base_var: Optional[str] # 基本変数 (e.g., "k")
offset: int # オフセット (e.g., -1)
is_constant: bool # 定数かどうか
is_loop_var: bool = False # ループ変数かどうか
@dataclass
class ArrayAccess:
"""配列アクセス情報"""
array_name: str
indices: List[IndexExpr]
is_write: bool
line_number: int
context: str # 所属するループのコンテキスト
@dataclass
class LoopInfo:
"""ループ情報"""
line_number: int
variable: str
start: str
end: str
step: str
depth: int
parent_loops: List[str] # 外側ループの変数名
@dataclass
class DependencyVector:
"""依存ベクトル"""
array: str
write_access: ArrayAccess
read_access: ArrayAccess
vector: List[int] # 各次元の依存距離
loop_vars: List[str] # 対応するループ変数
direction: str # "forward", "backward", "independent"
@dataclass
class DependencyPattern:
"""依存パターンの分類"""
pattern_type: str # "wavefront", "stencil", "reduction", "sequential", "independent"
affected_dimensions: List[str]
description: str
parallelizable: bool
transformation_needed: Optional[str]
# =============================================================================
# Known Algorithm Patterns Database
# =============================================================================
KNOWN_PATTERNS = {
"forward_substitution": {
"signature": {
"dep_directions": ["k-1", "j-1", "i-1"],
"array_pattern": "same_array_read_write",
"operation": "triangular_solve"
},
"strategy": {
"recommended": "diagonal_wavefront",
"description": "対角線並列化: i+j+k=const の点を同時に処理",
"auxiliary_arrays": ["np", "indxp", "jndxp"],
"kernel_separation": True,
"acc_directives": [
"!$acc parallel loop gang vector",
"!$acc data present(...)"
]
}
},
"backward_substitution": {
"signature": {
"dep_directions": ["k+1", "j+1", "i+1"],
"array_pattern": "same_array_read_write"
},
"strategy": {
"recommended": "reverse_diagonal_wavefront",
"description": "逆対角線並列化",
"auxiliary_arrays": ["np", "indxp", "jndxp"]
}
},
"jacobi_stencil": {
"signature": {
"dep_directions": [],
"array_pattern": "double_buffer"
},
"strategy": {
"recommended": "direct_parallel",
"description": "全点独立並列化可能(ダブルバッファ使用時)",
"auxiliary_arrays": None
}
},
"gauss_seidel": {
"signature": {
"dep_directions": ["j-1", "i-1"],
"array_pattern": "same_array_read_write"
},
"strategy": {
"recommended": "red_black_ordering",
"alternative": "diagonal_wavefront",
"description": "Red-Black順序または対角線並列化"
}
}
}
# =============================================================================
# Phase 1: Static Analysis
# =============================================================================
class FortranStaticAnalyzer:
"""Fortranソースの静的解析"""
def __init__(self, source_code: str, filename: str = ""):
self.source = source_code
self.filename = filename
self.lines = source_code.split('\n')
self.loops: List[LoopInfo] = []
self.array_accesses: List[ArrayAccess] = []
self.array_declarations: Dict[str, Dict] = {}
self.subroutines: List[Dict] = []
def analyze(self) -> Dict:
"""全体解析を実行"""
self._parse_subroutines()
self._parse_array_declarations()
self._parse_loops()
self._parse_array_accesses()
return {
"file": self.filename,
"subroutines": self.subroutines,
"arrays": self.array_declarations,
"loops": [self._loop_to_dict(l) for l in self.loops],
"accesses": [self._access_to_dict(a) for a in self.array_accesses]
}
def _parse_subroutines(self):
"""サブルーチン定義を解析"""
# subroutine name ( args )
pattern = r'subroutine\s+(\w+)\s*\(([^)]*)\)'
for i, line in enumerate(self.lines):
line_lower = line.lower()
match = re.search(pattern, line_lower)
if match:
name = match.group(1)
args_str = match.group(2)
args = [a.strip() for a in args_str.split(',') if a.strip()]
self.subroutines.append({
"name": name,
"line": i + 1,
"arguments": args
})
def _parse_array_declarations(self):
"""配列宣言を解析"""
# double precision v( 5, ldmx/2*2+1, ldmy/2*2+1, ldmz )
pattern = r'(integer|real|double\s+precision)\s+(\w+)\s*\(([^)]+)\)'
for i, line in enumerate(self.lines):
line_clean = self._remove_continuation(line)
matches = re.finditer(pattern, line_clean.lower())
for match in matches:
dtype = match.group(1).replace(' ', '_')
name = match.group(2)
dims_str = match.group(3)
dims = [d.strip() for d in dims_str.split(',')]
self.array_declarations[name] = {
"type": dtype,
"dimensions": dims,
"ndim": len(dims),
"line": i + 1
}
def _parse_loops(self):
"""DOループを解析"""
# do j = jst, jend または do j = 1, 5
pattern = r'do\s+(\w+)\s*=\s*([^,]+)\s*,\s*([^,\s]+)(?:\s*,\s*(\S+))?'
loop_stack = [] # 現在のループネストを追跡
for i, line in enumerate(self.lines):
line_lower = line.lower().strip()
# 継続行を処理
if line_lower.startswith('&') or (len(line) > 5 and line[5] not in ' 0'):
continue
match = re.search(pattern, line_lower)
if match:
var = match.group(1)
start = match.group(2).strip()
end = match.group(3).strip()
step = match.group(4).strip() if match.group(4) else "1"
loop = LoopInfo(
line_number=i + 1,
variable=var,
start=start,
end=end,
step=step,
depth=len(loop_stack),
parent_loops=list(loop_stack)
)
self.loops.append(loop)
loop_stack.append(var)
# enddo または end do を検出
if re.match(r'end\s*do', line_lower):
if loop_stack:
loop_stack.pop()
def _parse_array_accesses(self):
"""配列アクセスを解析"""
# まず継続行を結合したソースを作成
joined_lines = self._join_continuation_lines()
# 配列アクセスパターン: name( idx1, idx2, ... )
pattern = r'(\w+)\s*\(\s*([^)]+)\s*\)'
# 現在のループコンテキストを追跡
current_loops = []
loop_vars = set()
for line_info in joined_lines:
line_num = line_info["start_line"]
line_content = line_info["content"]
# ループの開始/終了を追跡
line_lower = line_content.lower()
do_match = re.search(r'do\s+(\w+)\s*=', line_lower)
if do_match:
var = do_match.group(1)
current_loops.append(var)
loop_vars.add(var)
if re.match(r'\s*end\s*do', line_lower):
if current_loops:
current_loops.pop()
# 代入文かどうかを判定
is_assignment = '=' in line_content and not any(
op in line_content for op in ['==', '/=', '<=', '>=']
)
if is_assignment:
# 左辺(書き込み)と右辺(読み込み)を分離
parts = line_content.split('=', 1)
lhs = parts[0]
rhs = parts[1] if len(parts) > 1 else ""
# 左辺の配列アクセス(書き込み)
for match in re.finditer(pattern, lhs):
if self._is_array(match.group(1)):
access = self._parse_single_access(
match, line_num, True, current_loops, loop_vars
)
if access:
self.array_accesses.append(access)
# 右辺の配列アクセス(読み込み)
for match in re.finditer(pattern, rhs):
if self._is_array(match.group(1)):
access = self._parse_single_access(
match, line_num, False, current_loops, loop_vars
)
if access:
self.array_accesses.append(access)
def _join_continuation_lines(self) -> List[Dict]:
"""Fortran継続行を結合"""
result = []
current_statement = ""
start_line = 1
for i, line in enumerate(self.lines):
line_num = i + 1
# コメント行をスキップ
if line and line[0].lower() in 'c*!':
continue
# 行末コメントを除去
if '!' in line:
line = line.split('!')[0]
# 固定形式の継続行判定(6列目が空白または0以外)
is_continuation = len(line) > 5 and line[5] not in ' 0\t'
if is_continuation:
# 継続行の内容を追加(7列目以降)
current_statement += " " + line[6:].strip()
else:
# 前のステートメントを保存
if current_statement.strip():
result.append({
"start_line": start_line,
"content": current_statement.strip()
})
# 新しいステートメントを開始
if len(line) > 6:
current_statement = line[6:].strip() if len(line) > 6 else line.strip()
else:
current_statement = line.strip()
start_line = line_num
# 最後のステートメント
if current_statement.strip():
result.append({
"start_line": start_line,
"content": current_statement.strip()
})
return result
def _parse_single_access(self, match, line_num: int, is_write: bool,
current_loops: List[str], loop_vars: Set[str]) -> Optional[ArrayAccess]:
"""単一の配列アクセスを解析"""
name = match.group(1).lower()
indices_str = match.group(2)
# 添字を解析
indices = []
for idx_str in self._split_indices(indices_str):
idx_str = idx_str.strip()
idx_expr = self._parse_index_expr(idx_str, loop_vars)
indices.append(idx_expr)
return ArrayAccess(
array_name=name,
indices=indices,
is_write=is_write,
line_number=line_num,
context=','.join(current_loops)
)
def _parse_index_expr(self, expr: str, loop_vars: Set[str]) -> IndexExpr:
"""添字式を解析"""
expr = expr.strip().lower()
# 定数チェック
if expr.isdigit():
return IndexExpr(
raw=expr,
base_var=None,
offset=int(expr),
is_constant=True
)
# 変数 + オフセット形式を解析 (e.g., k-1, j+2)
match = re.match(r'(\w+)\s*([+-])\s*(\d+)', expr)
if match:
var = match.group(1)
sign = 1 if match.group(2) == '+' else -1
offset = sign * int(match.group(3))
return IndexExpr(
raw=expr,
base_var=var,
offset=offset,
is_constant=False,
is_loop_var=var in loop_vars
)
# 単純変数
if re.match(r'^\w+$', expr):
return IndexExpr(
raw=expr,
base_var=expr,
offset=0,
is_constant=False,
is_loop_var=expr in loop_vars
)
# 複雑な式
return IndexExpr(
raw=expr,
base_var=None,
offset=0,
is_constant=False
)
def _split_indices(self, indices_str: str) -> List[str]:
"""カンマで添字を分割(括弧のネストを考慮)"""
indices = []
depth = 0
current = ""
for char in indices_str:
if char == '(':
depth += 1
current += char
elif char == ')':
depth -= 1
current += char
elif char == ',' and depth == 0:
indices.append(current.strip())
current = ""
else:
current += char
if current.strip():
indices.append(current.strip())
return indices
def _is_array(self, name: str) -> bool:
"""配列かどうかを判定"""
name_lower = name.lower()
# 宣言済み配列
if name_lower in self.array_declarations:
return True
# 組み込み関数は除外
builtins = {'sin', 'cos', 'exp', 'log', 'sqrt', 'abs', 'max', 'min',
'mod', 'real', 'dble', 'int', 'nint'}
if name_lower in builtins:
return False
return True
def _preprocess_line(self, line: str) -> str:
"""行を前処理(コメント除去、継続行処理)"""
# Fortran 77形式のコメント
if line and line[0].lower() in 'c*!':
return ""
# 行末コメント
if '!' in line:
line = line.split('!')[0]
return line
def _remove_continuation(self, line: str) -> str:
"""継続行マーカーを除去"""
if len(line) > 5 and line[5] not in ' 0':
return line[6:]
return line
def _loop_to_dict(self, loop: LoopInfo) -> Dict:
return {
"line": loop.line_number,
"variable": loop.variable,
"range": f"{loop.start}:{loop.end}",
"step": loop.step,
"depth": loop.depth,
"parent_loops": loop.parent_loops
}
def _access_to_dict(self, access: ArrayAccess) -> Dict:
return {
"array": access.array_name,
"indices": [{"raw": idx.raw, "base_var": idx.base_var,
"offset": idx.offset, "is_loop_var": idx.is_loop_var}
for idx in access.indices],
"is_write": access.is_write,
"line": access.line_number,
"context": access.context
}
# =============================================================================
# Phase 2: Dependency Analysis
# =============================================================================
class DependencyAnalyzer:
"""依存関係を解析"""
def __init__(self, static_info: Dict):
self.static_info = static_info
self.dependencies: List[DependencyVector] = []
self.patterns: List[DependencyPattern] = []
def analyze(self) -> Dict:
"""依存関係解析を実行"""
self._compute_dependency_vectors()
self._classify_patterns()
return {
"dependencies": [self._dep_to_dict(d) for d in self.dependencies],
"patterns": [self._pattern_to_dict(p) for p in self.patterns],
"summary": self._create_summary()
}
def _compute_dependency_vectors(self):
"""依存ベクトルを計算"""
accesses = self.static_info.get("accesses", [])
# 配列ごとにグループ化
by_array: Dict[str, List[Dict]] = {}
for access in accesses:
arr = access["array"]
if arr not in by_array:
by_array[arr] = []
by_array[arr].append(access)
# 各配列についてwrite→read依存を解析
for arr, arr_accesses in by_array.items():
writes = [a for a in arr_accesses if a["is_write"]]
reads = [a for a in arr_accesses if not a["is_write"]]
for write in writes:
for read in reads:
# 同じループコンテキスト内のみ解析
if write["context"] != read["context"]:
continue
dep_vec = self._compute_single_dependency(write, read)
if dep_vec:
self.dependencies.append(dep_vec)
def _compute_single_dependency(self, write: Dict, read: Dict) -> Optional[DependencyVector]:
"""単一の依存ベクトルを計算"""
w_indices = write["indices"]
r_indices = read["indices"]
if len(w_indices) != len(r_indices):
return None
vector = []
loop_vars = []
has_dependency = False
for wi, ri in zip(w_indices, r_indices):
# 同じ変数かチェック
if wi["base_var"] and ri["base_var"]:
if wi["base_var"] == ri["base_var"]:
diff = wi["offset"] - ri["offset"]
vector.append(diff)
loop_vars.append(wi["base_var"])
if diff != 0:
has_dependency = True
else:
# 異なる変数 - 依存なしとみなす
vector.append(0)
loop_vars.append(wi["base_var"] or ri["base_var"])
else:
vector.append(0)
loop_vars.append("")
if not has_dependency:
return None
# 方向を判定
direction = "forward" if all(v >= 0 for v in vector if v != 0) else \
"backward" if all(v <= 0 for v in vector if v != 0) else "mixed"
return DependencyVector(
array=write["array"],
write_access=write,
read_access=read,
vector=vector,
loop_vars=loop_vars,
direction=direction
)
def _classify_patterns(self):
"""依存パターンを分類"""
# 依存を配列ごとに集約
by_array: Dict[str, List[DependencyVector]] = {}
for dep in self.dependencies:
if dep.array not in by_array:
by_array[dep.array] = []
by_array[dep.array].append(dep)
for arr, deps in by_array.items():
pattern = self._identify_pattern(arr, deps)
self.patterns.append(pattern)
def _identify_pattern(self, array: str, deps: List[DependencyVector]) -> DependencyPattern:
"""パターンを識別"""
# 依存方向を集約
dep_dims = set()
for dep in deps:
for i, (v, lv) in enumerate(zip(dep.vector, dep.loop_vars)):
if v != 0:
dep_dims.add((lv, v))
# パターン判定
if not dep_dims:
return DependencyPattern(
pattern_type="independent",
affected_dimensions=[],
description="依存なし - 完全並列化可能",
parallelizable=True,
transformation_needed=None
)
# 複数次元に依存がある場合
affected_vars = list(set(d[0] for d in dep_dims))
if len(affected_vars) >= 2:
# 全て同じ符号かチェック
signs = [d[1] > 0 for d in dep_dims]
if len(set(signs)) == 1:
return DependencyPattern(
pattern_type="wavefront",
affected_dimensions=affected_vars,
description=f"Wavefront依存: {affected_vars} 方向に依存あり → 対角線並列化可能",
parallelizable=True,
transformation_needed="diagonal_wavefront"
)
else:
return DependencyPattern(
pattern_type="complex",
affected_dimensions=affected_vars,
description="複雑な依存パターン - 詳細解析が必要",
parallelizable=False,
transformation_needed="manual_analysis"
)
# 単一次元の依存
return DependencyPattern(
pattern_type="sequential",
affected_dimensions=affected_vars,
description=f"{affected_vars[0]} 方向にシーケンシャル依存",
parallelizable=False,
transformation_needed="loop_carried_dependency"
)
def _create_summary(self) -> Dict:
"""サマリーを作成"""
wavefront_patterns = [p for p in self.patterns if p.pattern_type == "wavefront"]
independent_patterns = [p for p in self.patterns if p.pattern_type == "independent"]
sequential_patterns = [p for p in self.patterns if p.pattern_type == "sequential"]
return {
"total_dependencies": len(self.dependencies),
"wavefront_candidates": len(wavefront_patterns),
"independent_arrays": len(independent_patterns),
"sequential_constraints": len(sequential_patterns),
"recommended_strategy": self._recommend_strategy()
}
def _recommend_strategy(self) -> str:
"""推奨戦略を決定"""
if any(p.pattern_type == "wavefront" for p in self.patterns):
return "diagonal_wavefront"
if all(p.pattern_type == "independent" for p in self.patterns):
return "direct_parallel"
return "needs_analysis"
def _dep_to_dict(self, dep: DependencyVector) -> Dict:
return {
"array": dep.array,
"vector": dep.vector,
"loop_vars": dep.loop_vars,
"direction": dep.direction,
"write_line": dep.write_access["line"],
"read_line": dep.read_access["line"]
}
def _pattern_to_dict(self, pattern: DependencyPattern) -> Dict:
return {
"type": pattern.pattern_type,
"dimensions": pattern.affected_dimensions,
"description": pattern.description,
"parallelizable": pattern.parallelizable,
"transformation": pattern.transformation_needed
}
# =============================================================================
# Phase 3: Pattern Matching & Strategy Generation
# =============================================================================
class StrategyGenerator:
"""GPU移植戦略を生成"""
def __init__(self, static_info: Dict, dep_info: Dict):
self.static_info = static_info
self.dep_info = dep_info
def generate(self) -> Dict:
"""戦略を生成"""
strategy = self._match_known_patterns()
transformations = self._generate_transformations()
acc_directives = self._generate_acc_directives()
auxiliary_arrays = self._determine_auxiliary_arrays()
return {
"algorithm_classification": strategy,
"required_transformations": transformations,
"recommended_acc_directives": acc_directives,
"auxiliary_arrays_needed": auxiliary_arrays,
"implementation_guide": self._generate_implementation_guide()
}
def _match_known_patterns(self) -> Dict:
"""既知パターンとマッチング"""
summary = self.dep_info.get("summary", {})
patterns = self.dep_info.get("patterns", [])
# Wavefrontパターンがある場合
wavefront_patterns = [p for p in patterns if p.get("type") == "wavefront"]
if wavefront_patterns:
dims = wavefront_patterns[0].get("dimensions", [])
if "k" in dims or len(dims) >= 2:
return {
"matched_pattern": "forward_substitution",
"confidence": "high",
"description": "下三角行列求解パターン - Wavefront並列化が有効",
"reference_implementation": "NPB LU blts.c (OpenACC版)"
}
# 独立パターンのみ
if summary.get("recommended_strategy") == "direct_parallel":
return {
"matched_pattern": "jacobi_stencil",
"confidence": "medium",
"description": "独立並列化可能 - 直接GPU化"
}
return {
"matched_pattern": "unknown",
"confidence": "low",
"description": "既知パターンにマッチせず - 詳細解析が必要"
}
def _generate_transformations(self) -> List[Dict]:
"""必要な変換を生成"""
transformations = []
summary = self.dep_info.get("summary", {})
if summary.get("recommended_strategy") == "diagonal_wavefront":
transformations.extend([
{
"step": 1,
"action": "create_diagonal_index_arrays",
"description": "対角線インデックス配列 np[l], indxp[l][n], jndxp[l][n] を事前計算",
"code_snippet": """
! 対角線インデックスの事前計算
do l = 1, nx + ny + nz - 2
np(l) = 0
do j = max(1, l - nx - nz + 2), min(ny, l - 1)
do i = max(1, l - j - nz + 1), min(nx, l - j)
np(l) = np(l) + 1
indxp(l, np(l)) = i
jndxp(l, np(l)) = j
end do
end do
end do
"""
},
{
"step": 2,
"action": "restructure_loops",
"description": "ループ構造を変換: DO j; DO i → DO l (sequential); DO n (parallel)",
"before": "DO j = jst, jend; DO i = ist, iend",
"after": "DO l = ...; DO n = 1, np(l) ! n方向が並列化可能"
},
{
"step": 3,
"action": "separate_kernels",
"description": "依存方向ごとにカーネルを分離(k-1依存とi-1,j-1依存を別カーネルに)"
},
{
"step": 4,
"action": "transform_coefficient_arrays",
"description": "係数配列を対角線インデックスで再構成: d(5,5,i,j) → d(5,5,n)"
}
])
return transformations
def _generate_acc_directives(self) -> Dict:
"""OpenACCディレクティブを生成"""
summary = self.dep_info.get("summary", {})
arrays = list(self.static_info.get("arrays", {}).keys())
if summary.get("recommended_strategy") == "diagonal_wavefront":
return {
"data_region": {
"directive": "!$acc data present(...)",
"arrays": arrays + ["indxp", "jndxp", "np", "tmat", "tv"],
"note": "データはデバイスに常駐させる"
},
"kernel_1": {
"purpose": "k-1方向の依存を処理",
"directive": "!$acc parallel loop gang vector",
"clause": "num_gangs((npl+127)/128) vector_length(128)",
"loop_var": "n",
"note": "各対角線上の点を並列処理"
},
"kernel_2": {
"purpose": "i-1, j-1方向の依存を処理 + 対角ブロック反転",
"directive": "!$acc parallel loop gang vector",
"clause": "同上",
"loop_var": "n"
}
}
return {
"note": "パターンに基づくディレクティブ生成ができませんでした"
}
def _determine_auxiliary_arrays(self) -> Dict:
"""必要な補助配列を決定"""
summary = self.dep_info.get("summary", {})
if summary.get("recommended_strategy") == "diagonal_wavefront":
return {
"np": {
"type": "integer, dimension(ISIZ1+ISIZ2+ISIZ3)",
"purpose": "各対角線 l 上の点数"
},
"indxp": {
"type": "integer, dimension(ISIZ1+ISIZ2+ISIZ3, ISIZ1*ISIZ2)",
"purpose": "対角線 l 上の n 番目の点の i インデックス"
},
"jndxp": {
"type": "integer, dimension(ISIZ1+ISIZ2+ISIZ3, ISIZ1*ISIZ2)",
"purpose": "対角線 l 上の n 番目の点の j インデックス"
},
"a": {
"type": "double precision, dimension(5, 5, ISIZ1*ISIZ2)",
"purpose": "k-1方向の係数(対角線インデックスで再構成)"
},
"b": {
"type": "double precision, dimension(5, 5, ISIZ1*ISIZ2)",
"purpose": "j-1方向の係数(対角線インデックスで再構成)"
},
"c": {
"type": "double precision, dimension(5, 5, ISIZ1*ISIZ2)",
"purpose": "i-1方向の係数(対角線インデックスで再構成)"
}
}
return {}
def _generate_implementation_guide(self) -> Dict:
"""実装ガイドを生成"""
return {
"overview": "Wavefront並列化によるGPU移植",
"steps": [
"1. 補助配列(np, indxp, jndxp)を計算するセットアップルーチンを作成",
"2. 係数配列(a, b, c, d)を対角線インデックスで事前計算",
"3. メインループを対角線ループに変換",
"4. 各対角線内のポイントを並列処理するOpenACCディレクティブを追加",
"5. 依存方向ごとにカーネルを分離(同期ポイントを最小化)"
],
"critical_points": [
"対角線 l の処理は l-1 の完了後に行う必要がある(これがシーケンシャル)",
"同一対角線内の点は相互依存がないため並列化可能",
"tmat, tv は各点ごとに独立なので並列化に影響しない"
],
"reference": "NPB LU OpenACC実装 (blts.c) を参照"
}
# =============================================================================
# Main Interface
# =============================================================================
def analyze_fortran_for_gpu(source_file: str) -> Dict:
"""
Fortranソースを解析してGPU移植用の補助情報を生成
Args:
source_file: Fortranソースファイルのパス
Returns:
GPU移植用の補助情報(JSON形式)
"""
# ソースを読み込み
with open(source_file, 'r') as f:
source_code = f.read()
filename = Path(source_file).name
# Phase 1: 静的解析
static_analyzer = FortranStaticAnalyzer(source_code, filename)
static_info = static_analyzer.analyze()
# Phase 2: 依存関係解析
dep_analyzer = DependencyAnalyzer(static_info)
dep_info = dep_analyzer.analyze()
# Phase 3: 戦略生成
strategy_gen = StrategyGenerator(static_info, dep_info)
strategy_info = strategy_gen.generate()
# 結果を統合
result = {
"file": filename,
"analysis_version": "1.0",
"static_analysis": {
"subroutines": static_info["subroutines"],
"arrays": static_info["arrays"],
"loop_structure": static_info["loops"]
},
"dependency_analysis": dep_info,
"gpu_porting_strategy": strategy_info
}
return result
def main():
"""メイン関数"""
if len(sys.argv) < 2:
print("Usage: python fortran_gpu_analyzer.py <source.f>")
sys.exit(1)
source_file = sys.argv[1]
if not Path(source_file).exists():
print(f"Error: File not found: {source_file}")
sys.exit(1)
result = analyze_fortran_for_gpu(source_file)
# JSON出力
print(json.dumps(result, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()