plcopen 0.22.0
载入中...
搜索中...
未找到
codegen.h
浏览该文件的文档.
1#pragma once
2
3#include <cstdint>
4#include <limits>
5#include <map>
6#include <vector>
7
8#include "st/ast.h"
9#include "st/bytecode.h"
10#include "st/conv.h"
11#include "st/diag.h"
12#include "st/sema.h"
13
14// L0 code generation (approved st-l0-semantics 2.4/3.1/3.3): deterministic
15// AST-to-bytecode emission -- the byte stream depends only on the AST walk
16// order and a value-keyed constant pool, never on addresses or iteration
17// order of unordered containers. Evaluation-stack depth is computed here at
18// compile time and capped; hidden temporaries (FOR bounds, CASE selectors)
19// use scoped slots above the declared variables. Constant subtrees folded by
20// sema are emitted as single pushes, so runtime and fold semantics agree by
21// construction. Load domain only.
22
23namespace plcopen::core::st
24{
25
27{
28 std::uint32_t max_code_bytes = 65536;
29 std::uint32_t max_vars_bytes = 16384;
30 std::uint16_t max_stack_slots = 64;
31 std::size_t max_diagnostics = 256;
32 std::string source_name = "source.st";
34 std::int32_t debug_line_offset = 0;
35 std::string debug_pou;
36 std::uint16_t debug_call_depth = 1;
38};
39
41{
42public:
43 Codegen(const Ast &ast, const SemaResult &sema,
44 std::vector<Diagnostic> &diagnostics, const CodegenLimits &limits)
45 : ast_(ast)
46 , sema_(sema)
47 , diagnostics_(diagnostics)
48 , limits_(limits)
49 {
50 }
51
53 {
54 temp_top_ = (sema_.vars_bytes + 7U) & ~7U;
55 temp_high_ = temp_top_;
56 for(const StmtIndex index : ast_.body) {
57 emit_stmt(index);
58 }
59 emit_op(Op::halt);
60 if(failed_) {
61 return false;
62 }
63 analyze_worst_case(program);
64 program.code = static_cast<std::vector<std::uint8_t> &&>(code_);
65 program.instruction_offsets =
66 static_cast<std::vector<std::uint32_t> &&>(instruction_offsets_);
67 program.constants =
68 static_cast<std::vector<std::uint64_t> &&>(constants_);
69 program.string_constants =
70 static_cast<std::vector<std::uint8_t> &&>(string_constants_);
71 program.vars = sema_.vars;
72 program.process_image = sema_.process_image;
73 program.fbs = sema_.fbs;
74 program.types = sema_.types;
75 program.initial_data = sema_.initial_data;
76 program.stack_slots = static_cast<std::uint16_t>(max_depth_);
77 program.vars_bytes = temp_high_;
78 program.fb_bytes = sema_.fb_bytes;
79 program.max_string_operation_cost = sema_.max_string_operation_cost;
80 program.max_standard_function_cost = sema_.max_standard_function_cost;
81 program.debug_mode = limits_.debug_mode;
82 program.source_map.entries =
83 static_cast<std::vector<SourceMapEntry> &&>(source_map_);
84 program.debug_report.breakpoint_probe_count =
85 program.source_map.entries.size();
86 program.debug_report.source_map_entries =
87 program.source_map.entries.size();
88 if(program.vars_bytes > limits_.max_vars_bytes) {
90 return false;
91 }
92 return true;
93 }
94
95private:
96 void fail(DiagCode code)
97 {
98 if(!failed_ && diagnostics_.size() < limits_.max_diagnostics) {
100 d.code = code;
101 d.message = to_string(code);
102 diagnostics_.push_back(static_cast<Diagnostic &&>(d));
103 }
104 failed_ = true;
105 }
106
107 // --- emission ----------------------------------------------------------
108
109 void emit_op(Op op)
110 {
111 if(code_.size() + 16 > limits_.max_code_bytes) {
113 return;
114 }
115 instruction_offsets_.push_back(static_cast<std::uint32_t>(code_.size()));
116 instruction_costs_.push_back(1U);
117 code_.push_back(static_cast<std::uint8_t>(op));
118 }
119
120 void set_last_cost(std::uint32_t cost)
121 {
122 if(!instruction_costs_.empty()) {
123 instruction_costs_.back() = std::max(1U, cost);
124 }
125 }
126
127 std::uint32_t read_u32(std::size_t at) const
128 {
129 if(at + 4U > code_.size()) return 0;
130 return static_cast<std::uint32_t>(code_[at]) |
131 (static_cast<std::uint32_t>(code_[at + 1U]) << 8U) |
132 (static_cast<std::uint32_t>(code_[at + 2U]) << 16U) |
133 (static_cast<std::uint32_t>(code_[at + 3U]) << 24U);
134 }
135
136 std::size_t instruction_at(std::uint32_t byte_offset) const
137 {
138 const auto found = std::lower_bound(instruction_offsets_.begin(),
139 instruction_offsets_.end(),
140 byte_offset);
141 if(found == instruction_offsets_.end() || *found != byte_offset) {
142 return instruction_offsets_.size();
143 }
144 return static_cast<std::size_t>(found - instruction_offsets_.begin());
145 }
146
147 static std::uint64_t add_cost(std::uint64_t left, std::uint64_t right)
148 {
149 return right > std::numeric_limits<std::uint64_t>::max() - left
150 ? std::numeric_limits<std::uint64_t>::max()
151 : left + right;
152 }
153
154 void analyze_worst_case(Program &program) const
155 {
156 program.worst_case_bounded = true;
157 program.worst_case_instructions = 0;
158 const std::size_t count = instruction_offsets_.size();
159 if(count == 0 || instruction_costs_.size() != count) return;
160
161 for(std::size_t index = 0; index < count; ++index) {
162 const Op op = static_cast<Op>(code_[instruction_offsets_[index]]);
163 if(op != Op::jmp && op != Op::jmp_if_false) continue;
164 const std::uint32_t target = read_u32(
165 static_cast<std::size_t>(instruction_offsets_[index]) + 1U);
166 if(instruction_at(target) == count ||
167 target <= instruction_offsets_[index]) {
168 program.worst_case_bounded = false;
169 return;
170 }
171 }
172
173 std::vector<std::uint64_t> longest(count, 0);
174 for(std::size_t reverse = count; reverse-- > 0;) {
175 const Op op = static_cast<Op>(code_[instruction_offsets_[reverse]]);
176 std::uint64_t tail = 0;
177 if(op == Op::jmp || op == Op::jmp_if_false) {
178 const std::uint32_t target = read_u32(
179 static_cast<std::size_t>(instruction_offsets_[reverse]) + 1U);
180 const std::size_t target_index = instruction_at(target);
181 if(target_index == count) {
182 program.worst_case_bounded = false;
183 program.worst_case_instructions = 0;
184 return;
185 }
186 tail = longest[target_index];
187 if(op == Op::jmp_if_false && reverse + 1U < count) {
188 tail = std::max(tail, longest[reverse + 1U]);
189 }
190 } else if(op != Op::halt && reverse + 1U < count) {
191 tail = longest[reverse + 1U];
192 }
193 longest[reverse] = add_cost(instruction_costs_[reverse], tail);
194 }
195 program.worst_case_instructions = longest[0];
196 }
197
198 void emit_u8(std::uint8_t value)
199 {
200 code_.push_back(value);
201 }
202
203 void emit_u16(std::uint16_t value)
204 {
205 code_.push_back(static_cast<std::uint8_t>(value & 0xFF));
206 code_.push_back(static_cast<std::uint8_t>((value >> 8) & 0xFF));
207 }
208
209 std::size_t emit_u32(std::uint32_t value)
210 {
211 const std::size_t at = code_.size();
212 code_.push_back(static_cast<std::uint8_t>(value & 0xFF));
213 code_.push_back(static_cast<std::uint8_t>((value >> 8) & 0xFF));
214 code_.push_back(static_cast<std::uint8_t>((value >> 16) & 0xFF));
215 code_.push_back(static_cast<std::uint8_t>((value >> 24) & 0xFF));
216 return at;
217 }
218
219 void emit_u64(std::uint64_t value)
220 {
221 emit_u32(static_cast<std::uint32_t>(value));
222 emit_u32(static_cast<std::uint32_t>(value >> 32U));
223 }
224
225 void patch_u32(std::size_t at, std::uint32_t value)
226 {
227 if(at + 4 > code_.size()) {
228 return;
229 }
230 code_[at] = static_cast<std::uint8_t>(value & 0xFF);
231 code_[at + 1] = static_cast<std::uint8_t>((value >> 8) & 0xFF);
232 code_[at + 2] = static_cast<std::uint8_t>((value >> 16) & 0xFF);
233 code_[at + 3] = static_cast<std::uint8_t>((value >> 24) & 0xFF);
234 }
235
236 std::uint32_t here() const
237 {
238 return static_cast<std::uint32_t>(code_.size());
239 }
240
241 void push(int slots = 1)
242 {
243 depth_ += slots;
244 if(depth_ > max_depth_) {
245 max_depth_ = depth_;
246 if(max_depth_ > limits_.max_stack_slots) {
248 }
249 }
250 }
251
252 void pop(int slots = 1)
253 {
254 depth_ -= slots;
255 }
256
257 void push_const(std::uint64_t bits)
258 {
259 const auto found = const_index_.find(bits);
260 std::uint16_t index = 0;
261 if(found != const_index_.end()) {
262 index = found->second;
263 } else {
264 if(constants_.size() >= 65535) {
266 return;
267 }
268 index = static_cast<std::uint16_t>(constants_.size());
269 constants_.push_back(bits);
270 const_index_.emplace(bits, index);
271 }
272 emit_op(Op::push_const);
273 emit_u16(index);
274 push();
275 }
276
277 std::uint32_t add_string_constant(const ExprInfo &note)
278 {
279 if(note.object_bytes.size() < 4U) {
281 return 0;
282 }
283 const TypeDesc *desc = sema_.types.get(note.type_id);
284 if(desc == nullptr ||
285 (desc->kind != TypeKind::string &&
286 desc->kind != TypeKind::wstring)) {
288 return 0;
289 }
290 const std::uint32_t length =
291 static_cast<std::uint32_t>(note.object_bytes[0]) |
292 (static_cast<std::uint32_t>(note.object_bytes[1]) << 8U) |
293 (static_cast<std::uint32_t>(note.object_bytes[2]) << 16U) |
294 (static_cast<std::uint32_t>(note.object_bytes[3]) << 24U);
295 const std::size_t object_size = 4U +
296 static_cast<std::size_t>(length) *
297 (desc->kind == TypeKind::wstring ? 4U : 1U);
298 if(object_size > note.object_bytes.size() ||
300 std::numeric_limits<std::uint32_t>::max() -
301 string_constants_.size()) {
303 return 0;
304 }
305 const std::uint32_t offset =
306 static_cast<std::uint32_t>(string_constants_.size());
307 string_constants_.insert(string_constants_.end(),
308 note.object_bytes.begin(),
309 note.object_bytes.begin() +
310 static_cast<std::ptrdiff_t>(object_size));
311 return offset;
312 }
313
314 std::uint32_t alloc_temp()
315 {
316 const std::uint32_t offset = (temp_top_ + 7U) & ~7U;
317 temp_top_ = offset + 8U;
318 if(temp_top_ > temp_high_) {
319 temp_high_ = temp_top_;
320 }
321 if(temp_high_ > limits_.max_vars_bytes) {
323 }
324 return offset;
325 }
326
327 void release_temps(std::uint32_t watermark)
328 {
329 temp_top_ = watermark;
330 }
331
332 // --- expressions --------------------------------------------------------
333
334 const ExprInfo &info(ExprIndex index) const
335 {
336 return sema_.exprs[static_cast<std::size_t>(index)];
337 }
338
339 void emit_expr(ExprIndex index)
340 {
341 if(failed_ || index == kNoExpr) {
342 return;
343 }
344 const Expr &expr = ast_.exprs[static_cast<std::size_t>(index)];
345 const ExprInfo &note = info(index);
346 if(note.is_const) {
347 push_const(note.bits);
348 return;
349 }
350 switch(expr.kind) {
352 if(note.string_index != kNoExpr) {
353 emit_expr(note.string_index);
354 emit_op(Op::string_index);
355 emit_u32(note.offset);
356 emit_u32(note.storage_type_id);
357 const TypeDesc *desc = sema_.types.get(note.storage_type_id);
358 if(desc != nullptr) {
359 set_last_cost(static_cast<std::uint32_t>(
360 desc->string.capacity));
361 }
362 return;
363 }
364 emit_access(note, false);
365 return;
367 if(note.memory_access) {
368 emit_access(note, false);
369 } else {
370 emit_op(Op::fb_load_out);
371 emit_u16(note.fb_index);
372 emit_u8(note.pin_id);
373 push();
374 }
375 return;
376 case ExprKind::unary:
377 emit_expr(expr.lhs);
378 if(expr.unary_op == UnaryOp::logical_not) {
379 if(is_bitstring(note.type)) {
380 emit_op(Op::bit_not);
381 emit_u8(static_cast<std::uint8_t>(note.type));
382 } else {
383 emit_op(Op::not_bool);
384 }
385 } else {
386 switch(note.type) {
387 case Type::int_: emit_op(Op::neg_int); break;
388 case Type::dint: emit_op(Op::neg_dint); break;
389 case Type::real: emit_op(Op::neg_real); break;
390 case Type::lreal: emit_op(Op::neg_lreal); break;
391 default:
392 emit_op(Op::iarith);
393 emit_u8(5); // neg
394 emit_u8(static_cast<std::uint8_t>(note.type));
395 break;
396 }
397 }
398 return;
399 case ExprKind::binary: {
400 if(info(expr.lhs).type == Type::string_ ||
401 info(expr.lhs).type == Type::wstring ||
402 info(expr.rhs).type == Type::string_ ||
403 info(expr.rhs).type == Type::wstring) {
404 emit_op(Op::string_compare);
405 emit_u8(static_cast<std::uint8_t>(expr.binary_op));
406 emit_string_operand(info(expr.lhs));
407 emit_string_operand(info(expr.rhs));
408 const ExprInfo &left = info(expr.lhs);
409 const ExprInfo &right = info(expr.rhs);
410 const TypeDesc *left_desc = sema_.types.get(
411 left.storage_type_id == invalid_type_id
412 ? left.type_id : left.storage_type_id);
413 const TypeDesc *right_desc = sema_.types.get(
414 right.storage_type_id == invalid_type_id
415 ? right.type_id : right.storage_type_id);
416 if(left_desc != nullptr && right_desc != nullptr) {
417 set_last_cost(static_cast<std::uint32_t>(std::max(
418 left_desc->string.capacity,
419 right_desc->string.capacity)));
420 }
421 push();
422 return;
423 }
424 emit_expr(expr.lhs);
425 emit_expr(expr.rhs);
426 if(expr.binary_op == BinaryOp::power) {
427 // integer exponents widen to double first (L1a 5.2)
428 const Type exp_type = info(expr.rhs).type;
429 if(is_integer(exp_type)) {
430 emit_op(is_unsigned_int(exp_type) ? Op::conv_u2d
431 : Op::conv_i2d);
432 }
433 emit_op(Op::power);
434 emit_u8(static_cast<std::uint8_t>(note.type));
435 } else if(note.type == Type::time &&
436 (expr.binary_op == BinaryOp::multiply ||
437 expr.binary_op == BinaryOp::divide)) {
438 const bool floaty = is_real_family(info(expr.rhs).type);
439 const std::uint8_t sub =
440 expr.binary_op == BinaryOp::multiply
441 ? (floaty ? 2 : 0)
442 : (floaty ? 3 : 1);
443 emit_op(Op::time_scale);
444 emit_u8(sub);
445 } else if(note.type == Type::date || note.type == Type::tod ||
446 note.type == Type::dt) {
447 emit_op(Op::date_arith);
448 const std::uint8_t base = note.type == Type::date ? 0
449 : note.type == Type::tod ? 2
450 : 4;
451 emit_u8(static_cast<std::uint8_t>(
452 base + (expr.binary_op == BinaryOp::subtract ? 1 : 0)));
453 } else {
454 emit_binary_op(expr.binary_op, info(expr.lhs).type);
455 }
456 pop(); // two operands popped, one result pushed
457 return;
458 }
459 case ExprKind::call: {
460 if(note.standard_function != StandardFunction::count) {
461 if(note.standard_function >= StandardFunction::len &&
462 note.standard_function <= StandardFunction::find) {
463 int scalar_count = 0;
464 for(const ExprIndex argument : expr.arguments) {
465 const ExprInfo &argument_info = info(argument);
466 if(argument_info.type == Type::string_ ||
467 argument_info.type == Type::wstring) {
468 const Expr &argument_expr =
469 ast_.exprs[static_cast<std::size_t>(argument)];
470 if(argument_expr.kind == ExprKind::call &&
471 argument_info.standard_function != StandardFunction::count)
472 emit_expr(argument);
473 } else {
474 emit_expr(argument);
475 ++scalar_count;
476 }
477 }
478 emit_op(Op::standard_string);
479 emit_u8(static_cast<std::uint8_t>(note.standard_function));
480 emit_u8(note.standard_argc);
481 const bool string_result = note.type == Type::string_ ||
482 note.type == Type::wstring;
483 emit_u32(string_result ? note.offset
484 : std::numeric_limits<std::uint32_t>::max());
485 emit_u32(string_result ? note.storage_type_id : note.type_id);
486 for(const ExprIndex argument : expr.arguments) {
487 const ExprInfo &argument_info = info(argument);
488 const bool string_argument =
489 argument_info.type == Type::string_ ||
490 argument_info.type == Type::wstring;
491 emit_u8(string_argument ? 1U : 0U);
492 if(string_argument) emit_string_operand(argument_info);
493 }
494 set_last_cost(note.standard_cost);
495 if(string_result) {
496 pop(scalar_count);
497 } else {
498 pop(scalar_count);
499 push();
500 }
501 return;
502 }
503 for(const ExprIndex argument : expr.arguments) {
504 emit_expr(argument);
505 }
506 emit_op(Op::standard_scalar);
507 emit_u8(static_cast<std::uint8_t>(note.standard_function));
508 emit_u8(note.standard_argc);
509 emit_u8(static_cast<std::uint8_t>(note.type));
510 set_last_cost(note.standard_cost);
511 if(note.standard_argc > 0) pop(note.standard_argc - 1);
512 return;
513 }
514 // Conversion function (L1a 4.x): argument then lowering ops.
515 const std::string call_name = lower_name(expr.name);
516 if(call_name == "len") {
517 emit_op(Op::string_length);
518 emit_string_operand(info(expr.lhs));
519 const TypeDesc *desc = sema_.types.get(
520 info(expr.lhs).storage_type_id == invalid_type_id
521 ? info(expr.lhs).type_id
522 : info(expr.lhs).storage_type_id);
523 if(desc != nullptr) {
524 set_last_cost(static_cast<std::uint32_t>(
525 desc->string.capacity));
526 }
527 push();
528 return;
529 }
530 emit_expr(expr.lhs);
531 if(call_name == "l2b_alias_guard") {
532 emit_op(Op::alias_guard);
533 return;
534 }
535 if(call_name == "usint_to_char" ||
536 call_name == "char_to_usint" ||
537 call_name == "wchar_to_udint") {
538 return;
539 }
540 if(call_name == "udint_to_wchar") {
541 emit_op(Op::check_unicode);
542 return;
543 }
544 ConvDesc desc;
545 if(!resolve_conversion(lower_name(expr.name), desc)) {
546 const ExprInfo &arg = info(expr.lhs);
547 if(arg.type != note.type) {
548 emit_op(Op::conv_wrap);
549 emit_u8(static_cast<std::uint8_t>(note.type));
550 }
551 if(note.type_id >= first_load_type_id) {
552 emit_op(Op::check_range);
553 emit_u32(note.type_id);
554 }
555 return;
556 }
557 emit_conversion(desc);
558 return;
559 }
560 default:
561 // Constant literals always fold; reaching here is a compiler
562 // defect surfaced as an explicit failure, never silent output.
564 return;
565 }
566 }
567
568 void emit_string_operand(const ExprInfo &note)
569 {
570 if(note.object_constant) {
571 emit_u8(1);
572 emit_u32(add_string_constant(note));
573 emit_u32(note.type_id);
574 } else {
575 emit_u8(0);
576 emit_u32(note.offset);
577 emit_u32(note.storage_type_id == invalid_type_id
578 ? note.type_id
579 : note.storage_type_id);
580 }
581 }
582
583 void emit_access(const ExprInfo &note, bool store)
584 {
585 for(const ExprInfo::DynamicIndex &index : note.dynamic_indices) {
586 emit_expr(index.expr);
587 }
588 emit_op(store ? Op::store_access : Op::load_access);
589 emit_u32(note.offset);
590 emit_u32(note.storage_type_id == invalid_type_id
591 ? note.type_id
592 : note.storage_type_id);
593 emit_u8(static_cast<std::uint8_t>(note.dynamic_indices.size()));
594 for(const ExprInfo::DynamicIndex &index : note.dynamic_indices) {
595 emit_u64(static_cast<std::uint64_t>(index.lower));
596 emit_u64(static_cast<std::uint64_t>(index.upper));
597 emit_u64(index.stride);
598 }
599 if(store) {
600 pop(static_cast<int>(note.dynamic_indices.size()) + 1);
601 } else {
602 pop(static_cast<int>(note.dynamic_indices.size()));
603 push();
604 }
605 }
606
607 static std::string lower_name(const std::string &text)
608 {
609 std::string lower;
610 lower.reserve(text.size());
611 for(char c : text) {
612 lower.push_back(
613 static_cast<char>(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c));
614 }
615 return lower;
616 }
617
618 void emit_conversion(const ConvDesc &desc)
619 {
620 switch(desc.kind) {
623 return; // canonical form already matches
624 case ConvKind::wrap:
625 emit_op(Op::conv_wrap);
626 emit_u8(static_cast<std::uint8_t>(desc.to));
627 return;
630 emit_op(desc.kind == ConvKind::int_to_float ? Op::conv_i2d
631 : Op::conv_u2d);
632 if(desc.to == Type::real) {
633 emit_op(Op::f_narrow);
634 }
635 return;
637 emit_op(desc.trunc ? Op::conv_trunc : Op::conv_round);
638 emit_u8(static_cast<std::uint8_t>(desc.to));
639 return;
641 emit_op(Op::f_narrow);
642 return;
644 emit_op(Op::conv_to_bool);
645 return;
647 emit_op(Op::conv_f_to_bool);
648 return;
649 default:
651 return;
652 }
653 }
654
655 // Legacy L0 types keep their dedicated opcodes so L0 bytecode stays
656 // byte-identical (determinism anchor); the L1a breadth goes through the
657 // parametrized iarith/cmp_u/bit_* extensions.
658 static bool legacy_arith_type(Type type)
659 {
660 return type == Type::int_ || type == Type::dint ||
661 type == Type::real || type == Type::lreal ||
662 type == Type::time;
663 }
664
665 void emit_iarith(std::uint8_t sub, Type type)
666 {
667 emit_op(Op::iarith);
668 emit_u8(sub);
669 emit_u8(static_cast<std::uint8_t>(type));
670 }
671
672 void emit_binary_op(BinaryOp op, Type operand)
673 {
674 const bool floaty = operand == Type::real || operand == Type::lreal;
675 switch(op) {
676 case BinaryOp::add:
677 if(!legacy_arith_type(operand)) {
678 emit_iarith(0, operand);
679 return;
680 }
681 switch(operand) {
682 case Type::int_: emit_op(Op::add_int); return;
683 case Type::dint: emit_op(Op::add_dint); return;
684 case Type::real: emit_op(Op::add_real); return;
685 case Type::lreal: emit_op(Op::add_lreal); return;
686 default: emit_op(Op::add_time); return;
687 }
689 if(!legacy_arith_type(operand)) {
690 emit_iarith(1, operand);
691 return;
692 }
693 switch(operand) {
694 case Type::int_: emit_op(Op::sub_int); return;
695 case Type::dint: emit_op(Op::sub_dint); return;
696 case Type::real: emit_op(Op::sub_real); return;
697 case Type::lreal: emit_op(Op::sub_lreal); return;
698 default: emit_op(Op::sub_time); return;
699 }
701 if(!legacy_arith_type(operand)) {
702 emit_iarith(2, operand);
703 return;
704 }
705 switch(operand) {
706 case Type::int_: emit_op(Op::mul_int); return;
707 case Type::dint: emit_op(Op::mul_dint); return;
708 case Type::real: emit_op(Op::mul_real); return;
709 default: emit_op(Op::mul_lreal); return;
710 }
711 case BinaryOp::divide:
712 if(!legacy_arith_type(operand)) {
713 emit_iarith(3, operand);
714 return;
715 }
716 switch(operand) {
717 case Type::int_: emit_op(Op::div_int); return;
718 case Type::dint: emit_op(Op::div_dint); return;
719 case Type::real: emit_op(Op::div_real); return;
720 default: emit_op(Op::div_lreal); return;
721 }
722 case BinaryOp::modulo:
723 if(operand != Type::int_ && operand != Type::dint) {
724 emit_iarith(4, operand);
725 return;
726 }
727 emit_op(operand == Type::int_ ? Op::mod_int : Op::mod_dint);
728 return;
730 if(is_bitstring(operand)) {
731 emit_op(Op::bit_and);
732 return;
733 }
734 emit_op(Op::and_bool);
735 return;
737 if(is_bitstring(operand)) {
738 emit_op(Op::bit_or);
739 return;
740 }
741 emit_op(Op::or_bool);
742 return;
744 if(is_bitstring(operand)) {
745 emit_op(Op::bit_xor);
746 return;
747 }
748 emit_op(Op::xor_bool);
749 return;
750 case BinaryOp::cmp_eq:
751 emit_op(floaty ? Op::cmp_eq_f : Op::cmp_eq_i);
752 return;
753 case BinaryOp::cmp_ne:
754 emit_op(floaty ? Op::cmp_ne_f : Op::cmp_ne_i);
755 return;
756 case BinaryOp::cmp_lt:
757 if(is_unsigned_int(operand)) {
758 emit_op(Op::cmp_u);
759 emit_u8(0);
760 return;
761 }
762 emit_op(floaty ? Op::cmp_lt_f : Op::cmp_lt_i);
763 return;
764 case BinaryOp::cmp_gt:
765 if(is_unsigned_int(operand)) {
766 emit_op(Op::cmp_u);
767 emit_u8(1);
768 return;
769 }
770 emit_op(floaty ? Op::cmp_gt_f : Op::cmp_gt_i);
771 return;
772 case BinaryOp::cmp_le:
773 if(is_unsigned_int(operand)) {
774 emit_op(Op::cmp_u);
775 emit_u8(2);
776 return;
777 }
778 emit_op(floaty ? Op::cmp_le_f : Op::cmp_le_i);
779 return;
780 default:
781 if(is_unsigned_int(operand)) {
782 emit_op(Op::cmp_u);
783 emit_u8(3);
784 return;
785 }
786 emit_op(floaty ? Op::cmp_ge_f : Op::cmp_ge_i);
787 return;
788 }
789 }
790
791 // --- statements ---------------------------------------------------------
792
793 const StmtInfo &stmt_info(StmtIndex index) const
794 {
795 return sema_.stmts[static_cast<std::size_t>(index)];
796 }
797
798 void emit_stmt(StmtIndex index)
799 {
800 if(failed_ || index < 0 ||
801 static_cast<std::size_t>(index) >= ast_.stmts.size()) {
802 return;
803 }
804 const Stmt &stmt = ast_.stmts[static_cast<std::size_t>(index)];
805 const std::int32_t source_line =
806 debug_statement_line_ == stmt.line ? debug_statement_line_
807 : stmt.line;
808 const std::int32_t source_column =
809 debug_statement_line_ == stmt.line ? debug_statement_column_
810 : stmt.column;
811 struct DebugStatementScope
812 {
813 std::int32_t &line;
814 std::int32_t &column;
815 std::int32_t previous_line;
816 std::int32_t previous_column;
817 DebugStatementScope(std::int32_t &target_line,
818 std::int32_t &target_column,
819 std::int32_t next_line,
820 std::int32_t next_column)
821 : line(target_line), column(target_column),
822 previous_line(target_line),
823 previous_column(target_column)
824 {
825 line = next_line;
826 column = next_column;
827 }
828 ~DebugStatementScope()
829 {
830 line = previous_line;
831 column = previous_column;
832 }
833 } debug_scope(debug_statement_line_, debug_statement_column_,
834 source_line, source_column);
835 if(stmt.kind != StmtKind::empty &&
836 (!limits_.debug_require_provenance || stmt.debug_provenance) &&
837 limits_.debug_mode == DebugMode::enabled) {
838 SourceMapEntry entry;
839 entry.source_name = limits_.source_name;
840 entry.pou = stmt.debug_provenance
841 ? stmt.debug_pou
842 : limits_.debug_pou.empty()
843 ? ast_.program_name
844 : limits_.debug_pou;
845 for(char &value : entry.pou)
846 if(value >= 'A' && value <= 'Z')
847 value = static_cast<char>(value - 'A' + 'a');
848 entry.pou_id = stable_symbol_id(entry.pou).value;
849 entry.line = static_cast<std::uint32_t>(std::max(
850 0, stmt.debug_provenance
851 ? stmt.debug_line
852 : source_line + limits_.debug_line_offset));
853 entry.column = static_cast<std::uint32_t>(std::max(
854 0, stmt.debug_provenance ? stmt.debug_column
855 : source_column));
856 entry.call_path = stmt.debug_call_path;
857 entry.instruction = static_cast<std::uint32_t>(code_.size());
858 entry.instruction_id.offset = entry.instruction;
859 entry.probe_index = static_cast<std::uint32_t>(source_map_.size());
860 entry.breakpoint_key = entry.probe_index;
861 entry.event_kind = stmt.kind == StmtKind::fb_call
864 entry.call_depth = stmt.debug_provenance
865 ? stmt.debug_call_depth
866 : limits_.debug_call_depth;
867 source_map_.push_back(entry);
868 emit_op(Op::debug_probe);
869 emit_u32(entry.probe_index);
870 }
871 switch(stmt.kind) {
872 case StmtKind::assign: {
873 const StmtInfo &target = stmt_info(index);
874 const TypeDesc *target_desc = sema_.types.get(target.type_id);
875 if(target_desc != nullptr &&
876 (target_desc->kind == TypeKind::string ||
877 target_desc->kind == TypeKind::wstring)) {
878 const ExprInfo &source = info(stmt.value);
879 if(source.standard_function != StandardFunction::count) {
880 emit_expr(stmt.value);
881 }
882 if(source.object_constant) {
883 emit_op(Op::string_copy_const);
884 emit_u32(target.offset);
885 emit_u32(target.type_id);
886 emit_u32(add_string_constant(source));
887 emit_u32(source.type_id);
888 } else {
889 emit_op(Op::string_copy);
890 emit_u32(target.offset);
891 emit_u32(target.type_id);
892 emit_u32(source.offset);
893 emit_u32(source.storage_type_id == invalid_type_id
894 ? source.type_id
895 : source.storage_type_id);
896 }
897 const TypeDesc *source_desc = sema_.types.get(
898 source.storage_type_id == invalid_type_id
899 ? source.type_id
900 : source.storage_type_id);
901 if(source_desc != nullptr) {
902 set_last_cost(static_cast<std::uint32_t>(std::max(
903 target_desc->string.capacity,
904 source_desc->string.capacity)));
905 }
906 return;
907 }
908 if(target.aggregate_copy) {
909 emit_op(Op::copy_bytes);
910 emit_u32(target.offset);
911 emit_u32(target.source_offset);
912 emit_u32(target.copy_size);
913 return;
914 }
915 if(target.fb_output_copy) {
916 emit_op(Op::fb_load_object);
917 emit_u16(target.fb_index);
918 emit_u8(target.pin_id);
919 emit_u32(target.offset);
920 emit_u32(target.type_id);
921 set_last_cost(target.copy_size);
922 return;
923 }
924 emit_expr(stmt.value);
925 ExprInfo access;
926 access.offset = target.offset;
927 access.type_id = target.type_id;
928 access.storage_type_id = target.type_id;
929 access.dynamic_indices = target.dynamic_indices;
930 emit_access(access, true);
931 return;
932 }
933 case StmtKind::if_: emit_if(stmt); return;
934 case StmtKind::case_: emit_case(stmt, stmt_info(index)); return;
935 case StmtKind::for_: emit_for(stmt, stmt_info(index)); return;
936 case StmtKind::while_: emit_while(stmt); return;
937 case StmtKind::repeat: emit_repeat(stmt); return;
938 case StmtKind::fb_call: emit_fb_call(stmt, stmt_info(index)); return;
939 case StmtKind::output_commit: emit_output_commit(stmt); return;
940 case StmtKind::exit_:
941 if(!loops_.empty()) {
942 emit_op(Op::jmp);
943 loops_.back().exits.push_back(emit_u32(0));
944 }
945 return;
947 if(!loops_.empty()) {
948 emit_op(Op::jmp);
949 if(loops_.back().continue_known) {
950 emit_u32(loops_.back().continue_target);
951 } else {
952 loops_.back().continues.push_back(emit_u32(0));
953 }
954 }
955 return;
957 emit_op(Op::halt);
958 return;
959 case StmtKind::empty:
960 return;
961 }
962 }
963
964 std::vector<SourceMapEntry> source_map_;
965 std::int32_t debug_statement_line_ = -1;
966 std::int32_t debug_statement_column_ = 0;
967
968 void emit_body(const std::vector<StmtIndex> &body)
969 {
970 for(const StmtIndex child : body) {
971 emit_stmt(child);
972 }
973 }
974
975 void emit_if(const Stmt &stmt)
976 {
977 std::vector<std::size_t> end_patches;
978 for(std::size_t i = 0; i < stmt.conditions.size(); ++i) {
979 emit_expr(stmt.conditions[i]);
980 emit_op(Op::jmp_if_false);
981 pop();
982 const std::size_t skip = emit_u32(0);
983 emit_body(stmt.branches[i]);
984 const bool more =
985 i + 1 < stmt.conditions.size() || !stmt.else_body.empty();
986 if(more) {
987 emit_op(Op::jmp);
988 end_patches.push_back(emit_u32(0));
989 }
990 patch_u32(skip, here());
991 }
992 emit_body(stmt.else_body);
993 for(const std::size_t at : end_patches) {
994 patch_u32(at, here());
995 }
996 }
997
998 void emit_case(const Stmt &stmt, const StmtInfo &case_info)
999 {
1000 const std::uint32_t watermark = temp_top_;
1001 const std::uint32_t selector = alloc_temp();
1002 emit_expr(stmt.selector);
1003 emit_op(Op::store_var);
1004 emit_u32(selector);
1005 emit_u32(case_info.type_id);
1006 pop();
1007
1008 std::vector<std::size_t> end_patches;
1009 for(const CaseArm &arm : stmt.arms) {
1010 if(arm.labels.empty()) {
1011 // ELSE arm
1012 emit_body(arm.body);
1013 continue;
1014 }
1015 bool first = true;
1016 for(const CaseLabel &label : arm.labels) {
1017 emit_op(Op::load_var);
1018 emit_u32(selector);
1019 emit_u32(case_info.type_id);
1020 push();
1021 if(label.high == kNoExpr) {
1022 push_const(this->info(label.low).bits);
1023 emit_op(Op::cmp_eq_i);
1024 pop();
1025 } else {
1026 push_const(this->info(label.low).bits);
1027 emit_op(Op::cmp_ge_i);
1028 pop();
1029 emit_op(Op::load_var);
1030 emit_u32(selector);
1031 emit_u32(case_info.type_id);
1032 push();
1033 push_const(this->info(label.high).bits);
1034 emit_op(Op::cmp_le_i);
1035 pop();
1036 emit_op(Op::and_bool);
1037 pop();
1038 }
1039 if(!first) {
1040 emit_op(Op::or_bool);
1041 pop();
1042 }
1043 first = false;
1044 }
1045 emit_op(Op::jmp_if_false);
1046 pop();
1047 const std::size_t next = emit_u32(0);
1048 emit_body(arm.body);
1049 emit_op(Op::jmp);
1050 end_patches.push_back(emit_u32(0));
1051 patch_u32(next, here());
1052 }
1053 for(const std::size_t at : end_patches) {
1054 patch_u32(at, here());
1055 }
1056 release_temps(watermark);
1057 }
1058
1059 void emit_for(const Stmt &stmt, const StmtInfo &info)
1060 {
1061 const std::uint32_t watermark = temp_top_;
1062 const std::uint32_t to_slot = alloc_temp();
1063 const std::uint32_t by_slot = alloc_temp();
1064
1065 emit_expr(stmt.from);
1066 emit_op(Op::store_var);
1067 emit_u32(info.offset);
1068 emit_u32(info.type_id);
1069 pop();
1070 emit_expr(stmt.to);
1071 emit_op(Op::store_var);
1072 emit_u32(to_slot);
1073 emit_u32(info.type_id);
1074 pop();
1075 bool by_needs_guard = false;
1076 if(stmt.by == kNoExpr) {
1077 push_const(1);
1078 } else {
1079 emit_expr(stmt.by);
1080 by_needs_guard = !this->info(stmt.by).is_const;
1081 }
1082 emit_op(Op::store_var);
1083 emit_u32(by_slot);
1084 emit_u32(info.type_id);
1085 pop();
1086 if(by_needs_guard) {
1087 emit_op(Op::for_guard);
1088 emit_u32(by_slot);
1089 }
1090
1091 loops_.emplace_back();
1092 const std::uint32_t loop_start = here();
1093 emit_op(Op::for_test);
1094 emit_u32(info.offset);
1095 emit_u32(to_slot);
1096 emit_u32(by_slot);
1097 emit_u32(info.type_id);
1098 push();
1099 emit_op(Op::jmp_if_false);
1100 pop();
1101 const std::size_t exit_at = emit_u32(0);
1102 emit_body(stmt.body);
1103 const std::uint32_t step_at = here();
1104 emit_op(info.type == Type::int_ ? Op::for_step_int
1106 emit_u32(info.offset);
1107 emit_u32(by_slot);
1108 emit_u32(info.type_id);
1109 emit_op(Op::jmp);
1110 emit_u32(loop_start);
1111 patch_u32(exit_at, here());
1112 for(const std::size_t at : loops_.back().exits) {
1113 patch_u32(at, here());
1114 }
1115 for(const std::size_t at : loops_.back().continues) {
1116 patch_u32(at, step_at);
1117 }
1118 loops_.pop_back();
1119 release_temps(watermark);
1120 }
1121
1122 void emit_while(const Stmt &stmt)
1123 {
1124 loops_.emplace_back();
1125 const std::uint32_t loop_start = here();
1126 loops_.back().continue_target = loop_start;
1127 loops_.back().continue_known = true;
1128 emit_expr(stmt.condition);
1129 emit_op(Op::jmp_if_false);
1130 pop();
1131 const std::size_t exit_at = emit_u32(0);
1132 emit_body(stmt.body);
1133 emit_op(Op::jmp);
1134 emit_u32(loop_start);
1135 patch_u32(exit_at, here());
1136 for(const std::size_t at : loops_.back().exits) {
1137 patch_u32(at, here());
1138 }
1139 loops_.pop_back();
1140 }
1141
1142 void emit_repeat(const Stmt &stmt)
1143 {
1144 loops_.emplace_back();
1145 const std::uint32_t loop_start = here();
1146 emit_body(stmt.body);
1147 const std::uint32_t condition_at = here();
1148 emit_expr(stmt.condition);
1149 emit_op(Op::jmp_if_false);
1150 pop();
1151 emit_u32(loop_start);
1152 for(const std::size_t at : loops_.back().exits) {
1153 patch_u32(at, here());
1154 }
1155 for(const std::size_t at : loops_.back().continues) {
1156 patch_u32(at, condition_at);
1157 }
1158 loops_.pop_back();
1159 }
1160
1161 void emit_fb_call(const Stmt &stmt, const StmtInfo &info)
1162 {
1163 for(std::size_t i = 0; i < stmt.params.size(); ++i) {
1164 const ExprInfo &argument =
1165 this->info(stmt.params[i].value);
1166 const TypeDesc *desc = sema_.types.get(argument.type_id);
1167 const bool object = desc != nullptr &&
1168 (desc->kind == TypeKind::array ||
1169 desc->kind == TypeKind::struct_ ||
1170 desc->kind == TypeKind::string ||
1171 desc->kind == TypeKind::wstring);
1172 if(object) {
1173 emit_op(Op::fb_store_object);
1174 emit_u16(info.fb_index);
1175 emit_u8(info.param_pins[i]);
1176 emit_u32(argument.offset);
1177 emit_u32(argument.type_id);
1178 set_last_cost(static_cast<std::uint32_t>(desc->size));
1179 } else {
1180 emit_expr(stmt.params[i].value);
1181 emit_op(Op::fb_store_in);
1182 emit_u16(info.fb_index);
1183 emit_u8(info.param_pins[i]);
1184 pop();
1185 }
1186 }
1187 emit_op(Op::fb_call);
1188 emit_u16(info.fb_index);
1189 }
1190
1191 void emit_output_commit(const Stmt &stmt)
1192 {
1193 std::uint16_t dynamic_count = 0;
1194 for(std::size_t i = 1; i < stmt.params.size(); i += 2U) {
1195 const ExprInfo &target = info(stmt.params[i].value);
1196 for(const ExprInfo::DynamicIndex &index : target.dynamic_indices) {
1197 emit_expr(index.expr);
1198 ++dynamic_count;
1199 }
1200 }
1201 emit_op(Op::commit_outputs);
1202 emit_u16(static_cast<std::uint16_t>(stmt.params.size() / 2U));
1203 emit_u16(dynamic_count);
1204 set_last_cost(static_cast<std::uint32_t>(stmt.params.size() / 2U));
1205 for(std::size_t i = 0; i < stmt.params.size(); i += 2U) {
1206 const ExprInfo &source = info(stmt.params[i].value);
1207 const ExprInfo &target = info(stmt.params[i + 1U].value);
1208 emit_u32(source.offset);
1209 emit_u32(source.storage_type_id == invalid_type_id
1210 ? source.type_id : source.storage_type_id);
1211 emit_u32(target.offset);
1212 emit_u32(target.storage_type_id == invalid_type_id
1213 ? target.type_id : target.storage_type_id);
1214 emit_u8(static_cast<std::uint8_t>(target.dynamic_indices.size()));
1215 for(const ExprInfo::DynamicIndex &index : target.dynamic_indices) {
1216 emit_u64(static_cast<std::uint64_t>(index.lower));
1217 emit_u64(static_cast<std::uint64_t>(index.upper));
1218 emit_u64(index.stride);
1219 }
1220 }
1221 pop(dynamic_count);
1222 }
1223
1224 const Ast &ast_;
1225 const SemaResult &sema_;
1226 std::vector<Diagnostic> &diagnostics_;
1227 CodegenLimits limits_;
1228
1229 struct LoopCtx
1230 {
1231 std::vector<std::size_t> exits;
1232 std::vector<std::size_t> continues;
1233 std::uint32_t continue_target = 0;
1234 bool continue_known = false; // WHILE knows its target up front
1235 };
1236
1237 std::vector<std::uint8_t> code_;
1238 std::vector<std::uint32_t> instruction_offsets_;
1239 std::vector<std::uint32_t> instruction_costs_;
1240 std::vector<std::uint64_t> constants_;
1241 std::vector<std::uint8_t> string_constants_;
1242 std::map<std::uint64_t, std::uint16_t> const_index_;
1243 std::vector<LoopCtx> loops_;
1244 std::uint32_t temp_top_ = 0;
1245 std::uint32_t temp_high_ = 0;
1246 int depth_ = 0;
1247 int max_depth_ = 0;
1248 bool failed_ = false;
1249};
1250
1251} // namespace plcopen::core::st
Codegen(const Ast &ast, const SemaResult &sema, std::vector< Diagnostic > &diagnostics, const CodegenLimits &limits)
bool run(Program &program)
constexpr bool is_integer(Type type)
constexpr ExprIndex kNoExpr
定义 ast.h:19
constexpr bool is_real_family(Type type)
SymbolId stable_symbol_id(std::string_view qualified_name) noexcept
constexpr const char * to_string(ConvKind kind)
定义 conv.h:90
std::int32_t StmtIndex
定义 ast.h:18
std::int32_t ExprIndex
定义 ast.h:17
constexpr TypeId first_load_type_id
constexpr bool is_unsigned_int(Type type)
bool resolve_conversion(std::string_view lower, ConvDesc &desc)
定义 conv.h:118
constexpr TypeId invalid_type_id
constexpr bool is_bitstring(Type type)