source: src/ControlStruct/MultiLevelExit.cpp@ 6804f38

Last change on this file since 6804f38 was 88bc876, checked in by Andrew Beach <ajbeach@…>, 15 months ago

Breaks (and some other control flow) in a loop else clause now work. I also implemented else clauses in printing and code generation.

  • Property mode set to 100644
File size: 23.5 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// MultiLevelExit.cpp -- Replaces CFA's local control flow with C's versions.
8//
9// Author : Andrew Beach
10// Created On : Mon Nov 1 13:48:00 2021
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Dec 14 17:34:12 2023
13// Update Count : 39
14//
15
16#include "MultiLevelExit.hpp"
17
18#include <set>
19
20#include "AST/Pass.hpp"
21#include "AST/Stmt.hpp"
22#include "LabelGenerator.hpp"
23
24using namespace std;
25using namespace ast;
26
27namespace ControlStruct {
28
29namespace {
30
31/// The return context is used to remember if returns are allowed and if
32/// not, why not. It is the nearest local control flow blocking construct.
33enum ReturnContext {
34 MayReturn,
35 InTryWithHandler,
36 InResumeHandler,
37 InFinally,
38};
39
40class Entry {
41 public:
42 const Stmt * stmt;
43 private:
44 // Organized like a manual ADT. Avoids creating a bunch of dead data.
45 struct Target {
46 Label label;
47 bool used = false;
48 Target( const Label & label ) : label( label ) {}
49 Target() : label( CodeLocation(), "" ) {}
50 };
51 Target firstTarget;
52 Target secondTarget;
53
54 enum Kind {
55 ForStmtK, WhileDoStmtK, CompoundStmtK, IfStmtK, CaseClauseK, SwitchStmtK, TryStmtK
56 } kind;
57
58 bool fallDefaultValid = true;
59
60 static Label & useTarget( Target & target ) {
61 target.used = true;
62 return target.label;
63 }
64 public:
65 Entry( const ForStmt * stmt, Label breakExit, Label contExit ) :
66 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( ForStmtK ) {}
67 Entry( const WhileDoStmt * stmt, Label breakExit, Label contExit ) :
68 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileDoStmtK ) {}
69 Entry( const CompoundStmt *stmt, Label breakExit ) :
70 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( CompoundStmtK ) {}
71 Entry( const IfStmt *stmt, Label breakExit ) :
72 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( IfStmtK ) {}
73 Entry( const CaseClause *, const CompoundStmt *stmt, Label fallExit ) :
74 stmt( stmt ), firstTarget( fallExit ), secondTarget(), kind( CaseClauseK ) {}
75 Entry( const SwitchStmt *stmt, Label breakExit, Label fallDefaultExit ) :
76 stmt( stmt ), firstTarget( breakExit ), secondTarget( fallDefaultExit ), kind( SwitchStmtK ) {}
77 Entry( const TryStmt *stmt, Label breakExit ) :
78 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( TryStmtK ) {}
79
80 // Check if this entry can be the target of the given type of control flow.
81 bool isContTarget() const { return kind <= WhileDoStmtK; }
82 bool isBreakTarget() const { return kind != CaseClauseK; }
83 bool isFallTarget() const { return kind == CaseClauseK; }
84 bool isFallDefaultTarget() const { return kind == SwitchStmtK; }
85
86 // These routines set a target as being "used" by a BranchStmt
87 Label useContExit() { assert( kind <= WhileDoStmtK ); return useTarget(secondTarget); }
88 Label useBreakExit() { assert( kind != CaseClauseK ); return useTarget(firstTarget); }
89 Label useFallExit() { assert( kind == CaseClauseK ); return useTarget(firstTarget); }
90 Label useFallDefaultExit() { assert( kind == SwitchStmtK ); return useTarget(secondTarget); }
91
92 // These routines check if a specific label for a statement is used by a BranchStmt
93 bool isContUsed() const { assert( kind <= WhileDoStmtK ); return secondTarget.used; }
94 bool isBreakUsed() const { assert( kind != CaseClauseK ); return firstTarget.used; }
95 bool isFallUsed() const { assert( kind == CaseClauseK ); return firstTarget.used; }
96 bool isFallDefaultUsed() const { assert( kind == SwitchStmtK ); return secondTarget.used; }
97 void seenDefault() { fallDefaultValid = false; }
98 bool isFallDefaultValid() const { return fallDefaultValid; }
99};
100
101// Helper predicates used in find_if calls (it doesn't take methods):
102bool isBreakTarget( const Entry & entry ) {
103 return entry.isBreakTarget();
104}
105
106bool isContinueTarget( const Entry & entry ) {
107 return entry.isContTarget();
108}
109
110bool isFallthroughTarget( const Entry & entry ) {
111 return entry.isFallTarget();
112}
113
114bool isFallthroughDefaultTarget( const Entry & entry ) {
115 return entry.isFallDefaultTarget();
116}
117
118struct MultiLevelExitCore final :
119 public WithVisitorRef<MultiLevelExitCore>,
120 public WithShortCircuiting, public WithGuards {
121 MultiLevelExitCore( const LabelToStmt & lt );
122
123 void previsit( const FunctionDecl * );
124
125 const CompoundStmt * previsit( const CompoundStmt * );
126 const BranchStmt * postvisit( const BranchStmt * );
127 void previsit( const WhileDoStmt * );
128 const WhileDoStmt * postvisit( const WhileDoStmt * );
129 void previsit( const ForStmt * );
130 const ForStmt * postvisit( const ForStmt * );
131 const CaseClause * previsit( const CaseClause * );
132 void previsit( const IfStmt * );
133 const IfStmt * postvisit( const IfStmt * );
134 void previsit( const SwitchStmt * );
135 const SwitchStmt * postvisit( const SwitchStmt * );
136 void previsit( const ReturnStmt * );
137 void previsit( const TryStmt * );
138 void postvisit( const TryStmt * );
139 void previsit( const CatchClause * );
140 void previsit( const FinallyClause * );
141
142 const Stmt * mutateLoop( const Stmt * body, Entry& );
143
144 const LabelToStmt & target_table;
145 set<Label> fallthrough_labels;
146 vector<Entry> enclosing_control_structures;
147 Label break_label;
148 ReturnContext ret_context;
149
150 template<typename LoopNode>
151 void prehandleLoopStmt( const LoopNode * loopStmt );
152 template<typename LoopNode>
153 const LoopNode * posthandleLoopStmt( const LoopNode * loopStmt );
154
155 list<ptr<Stmt>> fixBlock(
156 const list<ptr<Stmt>> & kids, bool caseClause );
157
158 void enterSealedContext( ReturnContext );
159
160 template<typename UnaryPredicate>
161 auto findEnclosingControlStructure( UnaryPredicate pred ) {
162 return find_if( enclosing_control_structures.rbegin(),
163 enclosing_control_structures.rend(), pred );
164 }
165};
166
167NullStmt * labelledNullStmt( const CodeLocation & cl, const Label & label ) {
168 return new NullStmt( cl, vector<Label>{ label } );
169}
170
171MultiLevelExitCore::MultiLevelExitCore( const LabelToStmt & lt ) :
172 target_table( lt ), break_label( CodeLocation(), "" ),
173 ret_context( ReturnContext::MayReturn )
174{}
175
176void MultiLevelExitCore::previsit( const FunctionDecl * ) {
177 visit_children = false;
178}
179
180const CompoundStmt * MultiLevelExitCore::previsit(
181 const CompoundStmt * stmt ) {
182 visit_children = false;
183
184 // if the stmt is labelled then generate a label to check in postvisit if the label is used
185 bool isLabeled = ! stmt->labels.empty();
186 if ( isLabeled ) {
187 Label breakLabel = newLabel( "blockBreak", stmt );
188 enclosing_control_structures.emplace_back( stmt, breakLabel );
189 GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
190 }
191
192 auto mutStmt = mutate( stmt );
193 // A child statement may set the break label.
194 mutStmt->kids = fixBlock( stmt->kids, false );
195
196 if ( isLabeled ) {
197 assert( ! enclosing_control_structures.empty() );
198 Entry & entry = enclosing_control_structures.back();
199 if ( ! entry.useBreakExit().empty() ) {
200 break_label = entry.useBreakExit();
201 }
202 }
203 return mutStmt;
204}
205
206size_t getUnusedIndex( const Stmt * stmt, const Label & originalTarget ) {
207 const size_t size = stmt->labels.size();
208
209 // If the label is empty, do not add unused attribute.
210 if ( originalTarget.empty() ) return size;
211
212 // Search for a label that matches the originalTarget.
213 for ( size_t i = 0 ; i < size ; ++i ) {
214 const Label & label = stmt->labels[i];
215 if ( label == originalTarget ) {
216 for ( const Attribute * attr : label.attributes ) {
217 if ( attr->name == "unused" ) return size;
218 }
219 return i;
220 }
221 }
222 assertf( false, "CFA internal error: could not find label '%s' on statement %s",
223 originalTarget.name.c_str(), toString( stmt ).c_str() );
224}
225
226const Stmt * addUnused( const Stmt * stmt, const Label & originalTarget ) {
227 size_t i = getUnusedIndex( stmt, originalTarget );
228 if ( i == stmt->labels.size() ) {
229 return stmt;
230 }
231 Stmt * mutStmt = mutate( stmt );
232 mutStmt->labels[i].attributes.push_back( new Attribute( "unused" ) );
233 return mutStmt;
234}
235
236// This routine updates targets on enclosing control structures to indicate which
237// label is used by the BranchStmt that is passed
238const BranchStmt * MultiLevelExitCore::postvisit( const BranchStmt * stmt ) {
239 vector<Entry>::reverse_iterator targetEntry =
240 enclosing_control_structures.rend();
241
242 // Labels on different stmts require different approaches to access
243 switch ( stmt->kind ) {
244 case BranchStmt::Goto:
245 return stmt;
246 case BranchStmt::Continue:
247 case BranchStmt::Break: {
248 bool isContinue = stmt->kind == BranchStmt::Continue;
249 // Handle unlabeled break and continue.
250 if ( stmt->target.empty() ) {
251 if ( isContinue ) {
252 targetEntry = findEnclosingControlStructure( isContinueTarget );
253 } else {
254 if ( enclosing_control_structures.empty() ) {
255 SemanticError( stmt->location,
256 "\"break\" outside a loop, \"switch\", or labelled block" );
257 }
258 targetEntry = findEnclosingControlStructure( isBreakTarget );
259 }
260 // Handle labeled break and continue.
261 } else {
262 // Lookup label in table to find attached control structure.
263 targetEntry = findEnclosingControlStructure(
264 [ targetStmt = target_table.at(stmt->target) ](auto entry){
265 return entry.stmt == targetStmt;
266 } );
267 }
268 // Ensure that selected target is valid.
269 if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && ! isContinueTarget( *targetEntry ) ) ) {
270 SemanticError( stmt->location, toString( (isContinue ? "\"continue\"" : "\"break\""),
271 " target must be an enclosing ", (isContinue ? "loop: " : "control structure: "),
272 stmt->originalTarget ) );
273 }
274 break;
275 }
276 // handle fallthrough in case/switch stmts
277 case BranchStmt::FallThrough: {
278 targetEntry = findEnclosingControlStructure( isFallthroughTarget );
279 // Check that target is valid.
280 if ( targetEntry == enclosing_control_structures.rend() ) {
281 SemanticError( stmt->location, "\"fallthrough\" must be enclosed in a \"switch\" or \"choose\"" );
282 }
283 if ( ! stmt->target.empty() ) {
284 // Labelled fallthrough: target must be a valid fallthough label.
285 if ( ! fallthrough_labels.count( stmt->target ) ) {
286 SemanticError( stmt->location, toString( "\"fallthrough\" target must be a later case statement: ",
287 stmt->originalTarget ) );
288 }
289 return new BranchStmt( stmt->location, BranchStmt::Goto, stmt->originalTarget );
290 }
291 break;
292 }
293 case BranchStmt::FallThroughDefault: {
294 targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
295
296 // Check if in switch or choose statement.
297 if ( targetEntry == enclosing_control_structures.rend() ) {
298 SemanticError( stmt->location, "\"fallthrough\" must be enclosed in a \"switch\" or \"choose\"" );
299 }
300
301 // Check if switch or choose has default clause.
302 auto switchStmt = strict_dynamic_cast< const SwitchStmt * >( targetEntry->stmt );
303 bool foundDefault = false;
304 for ( auto caseStmt : switchStmt->cases ) {
305 if ( caseStmt->isDefault() ) {
306 foundDefault = true;
307 break;
308 }
309 }
310 if ( ! foundDefault ) {
311 SemanticError( stmt->location, "\"fallthrough default\" must be enclosed in a \"switch\" or \"choose\""
312 "control structure with a \"default\" clause" );
313 }
314 break;
315 }
316 default:
317 assert( false );
318 }
319
320 // Branch error checks: get the appropriate label name, which is always replaced.
321 Label exitLabel( CodeLocation(), "" );
322 switch ( stmt->kind ) {
323 case BranchStmt::Break:
324 assert( ! targetEntry->useBreakExit().empty() );
325 exitLabel = targetEntry->useBreakExit();
326 break;
327 case BranchStmt::Continue:
328 assert( ! targetEntry->useContExit().empty() );
329 exitLabel = targetEntry->useContExit();
330 break;
331 case BranchStmt::FallThrough:
332 assert( ! targetEntry->useFallExit().empty() );
333 exitLabel = targetEntry->useFallExit();
334 break;
335 case BranchStmt::FallThroughDefault:
336 assert( ! targetEntry->useFallDefaultExit().empty() );
337 exitLabel = targetEntry->useFallDefaultExit();
338 // Check that fallthrough default comes before the default clause.
339 if ( ! targetEntry->isFallDefaultValid() ) {
340 SemanticError( stmt->location, "\"fallthrough default\" must precede the \"default\" clause" );
341 }
342 break;
343 default:
344 assert(0);
345 }
346 assert( !exitLabel.empty() );
347
348 // Add unused attribute to silence warnings.
349 targetEntry->stmt = addUnused( targetEntry->stmt, stmt->originalTarget );
350
351 // Replace with goto to make later passes more uniform.
352 return new BranchStmt( stmt->location, BranchStmt::Goto, exitLabel );
353}
354
355void MultiLevelExitCore::previsit( const WhileDoStmt * stmt ) {
356 return prehandleLoopStmt( stmt );
357}
358
359const WhileDoStmt * MultiLevelExitCore::postvisit( const WhileDoStmt * stmt ) {
360 return posthandleLoopStmt( stmt );
361}
362
363void MultiLevelExitCore::previsit( const ForStmt * stmt ) {
364 return prehandleLoopStmt( stmt );
365}
366
367const ForStmt * MultiLevelExitCore::postvisit( const ForStmt * stmt ) {
368 return posthandleLoopStmt( stmt );
369}
370
371// Mimic what the built-in push_front would do anyways. It is O(n).
372void push_front( vector<ptr<Stmt>> & vec, const Stmt * element ) {
373 vec.emplace_back( nullptr );
374 for ( size_t i = vec.size() - 1 ; 0 < i ; --i ) {
375 vec[ i ] = std::move( vec[ i - 1 ] );
376 }
377 vec[ 0 ] = element;
378}
379
380const CaseClause * MultiLevelExitCore::previsit( const CaseClause * stmt ) {
381 visit_children = false;
382
383 // If default, mark seen.
384 if ( stmt->isDefault() ) {
385 assert( ! enclosing_control_structures.empty() );
386 enclosing_control_structures.back().seenDefault();
387 }
388
389 // The cond may not exist, but if it does update it now.
390 visitor->maybe_accept( stmt, &CaseClause::cond );
391
392 // Just save the mutated node for simplicity.
393 CaseClause * mutStmt = mutate( stmt );
394
395 Label fallLabel = newLabel( "fallThrough", stmt->location );
396 if ( ! mutStmt->stmts.empty() ) {
397 // These should already be in a block.
398 auto first = mutStmt->stmts.front().get_and_mutate();
399 auto block = strict_dynamic_cast<CompoundStmt *>( first );
400
401 // Ensure that the stack isn't corrupted by exceptions in fixBlock.
402 auto guard = makeFuncGuard(
403 [&](){ enclosing_control_structures.emplace_back( mutStmt, block, fallLabel ); },
404 [this](){ enclosing_control_structures.pop_back(); }
405 );
406
407 block->kids = fixBlock( block->kids, true );
408
409 // Add fallthrough label if necessary.
410 assert( ! enclosing_control_structures.empty() );
411 Entry & entry = enclosing_control_structures.back();
412 if ( entry.isFallUsed() ) {
413 mutStmt->stmts.push_back( labelledNullStmt( block->location, entry.useFallExit() ) );
414 }
415 }
416 assert( ! enclosing_control_structures.empty() );
417 Entry & entry = enclosing_control_structures.back();
418 assertf( dynamic_cast< const SwitchStmt * >( entry.stmt ),
419 "CFA internal error: control structure enclosing a case clause must be a switch, but is: %s",
420 toString( entry.stmt ).c_str() );
421 if ( mutStmt->isDefault() ) {
422 if ( entry.isFallDefaultUsed() ) {
423 // Add fallthrough default label if necessary.
424 push_front( mutStmt->stmts, labelledNullStmt( stmt->location, entry.useFallDefaultExit() ) );
425 }
426 }
427 return mutStmt;
428}
429
430void MultiLevelExitCore::previsit( const IfStmt * stmt ) {
431 bool labeledBlock = ! stmt->labels.empty();
432 if ( labeledBlock ) {
433 Label breakLabel = newLabel( "blockBreak", stmt );
434 enclosing_control_structures.emplace_back( stmt, breakLabel );
435 GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
436 }
437}
438
439const IfStmt * MultiLevelExitCore::postvisit( const IfStmt * stmt ) {
440 bool labeledBlock = ! stmt->labels.empty();
441 if ( labeledBlock ) {
442 auto this_label = enclosing_control_structures.back().useBreakExit();
443 if ( ! this_label.empty() ) {
444 break_label = this_label;
445 }
446 }
447 return stmt;
448}
449
450static bool isDefaultCase( const ptr<CaseClause> & caseClause ) {
451 return caseClause->isDefault();
452}
453
454void MultiLevelExitCore::previsit( const SwitchStmt * stmt ) {
455 Label label = newLabel( "switchBreak", stmt );
456 auto it = find_if( stmt->cases.rbegin(), stmt->cases.rend(), isDefaultCase );
457
458 const CaseClause * defaultCase = it != stmt->cases.rend() ? (*it) : nullptr;
459 Label defaultLabel = defaultCase ? newLabel( "fallThroughDefault", defaultCase->location ) : Label( stmt->location, "" );
460 enclosing_control_structures.emplace_back( stmt, label, defaultLabel );
461 GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
462
463 // Collect valid labels for fallthrough. It starts with all labels at this level, then remove as each is seen during
464 // traversal.
465 for ( const CaseClause * caseStmt : stmt->cases ) {
466 if ( caseStmt->stmts.empty() ) continue;
467 auto block = caseStmt->stmts.front().strict_as<CompoundStmt>();
468 for ( const Stmt * stmt : block->kids ) {
469 for ( const Label & l : stmt->labels ) {
470 fallthrough_labels.insert( l );
471 }
472 }
473 }
474}
475
476const SwitchStmt * MultiLevelExitCore::postvisit( const SwitchStmt * stmt ) {
477 assert( ! enclosing_control_structures.empty() );
478 Entry & entry = enclosing_control_structures.back();
479 assert( entry.stmt == stmt );
480
481 // Only run to generate the break label.
482 if ( entry.isBreakUsed() ) {
483 // To keep the switch statements uniform (all direct children of a SwitchStmt should be CastStmts), append the
484 // exit label and break to the last case, create a default case if no cases.
485 SwitchStmt * mutStmt = mutate( stmt );
486 if ( mutStmt->cases.empty() ) {
487 mutStmt->cases.push_back( new CaseClause( mutStmt->location, nullptr, {} ) );
488 }
489
490 auto mutCase = mutStmt->cases.back().get_and_mutate();
491
492 Label label( mutCase->location, "breakLabel" );
493 auto branch = new BranchStmt( mutCase->location, BranchStmt::Break, label );
494 branch->labels.push_back( entry.useBreakExit() );
495 mutCase->stmts.push_back( branch );
496
497 return mutStmt;
498 }
499 return stmt;
500}
501
502void MultiLevelExitCore::previsit( const ReturnStmt * stmt ) {
503 char const * context;
504 switch ( ret_context ) {
505 case ReturnContext::MayReturn:
506 return;
507 case ReturnContext::InTryWithHandler:
508 context = "try statement with a catch clause";
509 break;
510 case ReturnContext::InResumeHandler:
511 context = "catchResume clause";
512 break;
513 case ReturnContext::InFinally:
514 context = "finally clause";
515 break;
516 default:
517 assert(0);
518 }
519 SemanticError( stmt->location, "\"return\" may not appear in a %s", context );
520}
521
522bool hasTerminate( const TryStmt * stmt ) {
523 for ( auto clause : stmt->handlers ) {
524 if ( ast::Terminate == clause->kind ) return true;
525 }
526 return false;
527}
528
529void MultiLevelExitCore::previsit( const TryStmt * stmt ) {
530 visit_children = false;
531
532 bool isLabeled = ! stmt->labels.empty();
533 if ( isLabeled ) {
534 Label breakLabel = newLabel( "blockBreak", stmt );
535 enclosing_control_structures.emplace_back( stmt, breakLabel );
536 GuardAction([this](){ enclosing_control_structures.pop_back(); } );
537 }
538
539 // Try statements/try blocks are only sealed with a termination handler.
540 if ( hasTerminate( stmt ) ) {
541 // This is just enterSealedContext except scoped to the block.
542 // And that is because the state must change for a single field.
543 ValueGuard< ReturnContext > guard0( ret_context );
544 ret_context = ReturnContext::InTryWithHandler;
545 auto guard = makeFuncGuard( [](){}, [this, old = std::move(enclosing_control_structures)](){ enclosing_control_structures = std::move(old); });
546 enclosing_control_structures = vector<Entry>();
547 visitor->maybe_accept( stmt, &TryStmt::body );
548 } else {
549 visitor->maybe_accept( stmt, &TryStmt::body );
550 }
551
552 visitor->maybe_accept( stmt, &TryStmt::handlers );
553 visitor->maybe_accept( stmt, &TryStmt::finally );
554}
555
556void MultiLevelExitCore::postvisit( const TryStmt * stmt ) {
557 bool isLabeled = ! stmt->labels.empty();
558 if ( isLabeled ) {
559 auto this_label = enclosing_control_structures.back().useBreakExit();
560 if ( ! this_label.empty() ) {
561 break_label = this_label;
562 }
563 }
564}
565
566void MultiLevelExitCore::previsit( const CatchClause * clause ) {
567 if ( ast::Resume == clause->kind ) {
568 enterSealedContext( ReturnContext::InResumeHandler );
569 }
570}
571
572void MultiLevelExitCore::previsit( const FinallyClause * ) {
573 enterSealedContext( ReturnContext::InFinally );
574}
575
576const Stmt * MultiLevelExitCore::mutateLoop(
577 const Stmt * body, Entry & entry ) {
578 if ( entry.isBreakUsed() ) {
579 break_label = entry.useBreakExit();
580 }
581
582 // if continue is used insert a continue label into the back of the body of the loop
583 if ( entry.isContUsed() ) {
584 // {
585 // body
586 // ContinueLabel: ;
587 // }
588 return new CompoundStmt( body->location, {
589 body,
590 labelledNullStmt( body->location, entry.useContExit() ),
591 } );
592 }
593
594 return body;
595}
596
597template<typename LoopNode>
598void MultiLevelExitCore::prehandleLoopStmt( const LoopNode * loopStmt ) {
599 // Create temporary labels and mark the enclosing loop before traversal.
600 // The labels will be folded in if they are used.
601 Label breakLabel = newLabel( "loopBreak", loopStmt );
602 Label contLabel = newLabel( "loopContinue", loopStmt );
603 enclosing_control_structures.emplace_back( loopStmt, breakLabel, contLabel );
604
605 GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
606
607 // Because of fixBlock, this should be empty now (and must be).
608 assert( nullptr == loopStmt->else_ );
609}
610
611template<typename LoopNode>
612const LoopNode * MultiLevelExitCore::posthandleLoopStmt( const LoopNode * loopStmt ) {
613 assert( ! enclosing_control_structures.empty() );
614 Entry & entry = enclosing_control_structures.back();
615 assert( entry.stmt == loopStmt );
616
617 // Now check if the labels are used and add them if so.
618 return mutate_field( loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
619}
620
621list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
622 const list<ptr<Stmt>> & kids, bool is_case_clause ) {
623 // Unfortunately cannot use automatic error collection.
624 SemanticErrorException errors;
625
626 list<ptr<Stmt>> ret;
627
628 // Manually visit each child.
629 for ( const ptr<Stmt> & kid : kids ) {
630 if ( is_case_clause ) {
631 // Once a label is seen, it's no longer a valid for fallthrough.
632 for ( const Label & l : kid->labels ) {
633 fallthrough_labels.erase( l );
634 }
635 }
636
637 ptr<Stmt> else_stmt = nullptr;
638 const Stmt * to_visit;
639 // check if loop node and if so add else clause if it exists
640 if ( auto ptr = kid.as<WhileDoStmt>() ; ptr && ptr->else_ ) {
641 else_stmt = ptr->else_;
642 to_visit = mutate_field( ptr, &WhileDoStmt::else_, nullptr );
643 } else if ( auto ptr = kid.as<ForStmt>() ; ptr && ptr->else_ ) {
644 else_stmt = ptr->else_;
645 to_visit = mutate_field( ptr, &ForStmt::else_, nullptr );
646 } else {
647 to_visit = kid.get();
648 }
649
650 // This is the main (safe) visit of the child node.
651 try {
652 ret.push_back( to_visit->accept( *visitor ) );
653 } catch ( SemanticErrorException & e ) {
654 errors.append( e );
655 }
656
657 // The following sections handle visiting loop else clause and makes
658 // sure breaking from a loop body does not execute that clause.
659 Label local_break_label = std::move( break_label );
660 break_label = Label( CodeLocation(), "" );
661
662 if ( else_stmt ) try {
663 ret.push_back( else_stmt->accept( *visitor ) );
664 } catch ( SemanticErrorException & e ) {
665 errors.append( e );
666 }
667
668 if ( !break_label.empty() ) {
669 ret.push_back( labelledNullStmt( ret.back()->location, break_label ) );
670 break_label = Label( CodeLocation(), "" );
671 }
672
673 // This handles a break from the body or non-loop statement.
674 if ( !local_break_label.empty() ) {
675 ret.push_back( labelledNullStmt( ret.back()->location, local_break_label ) );
676 }
677 }
678
679 if ( !errors.isEmpty() ) {
680 throw errors;
681 }
682 return ret;
683}
684
685void MultiLevelExitCore::enterSealedContext( ReturnContext enter_context ) {
686 GuardAction([this, old = std::move(enclosing_control_structures)](){ enclosing_control_structures = std::move(old); });
687 enclosing_control_structures = vector<Entry>();
688 GuardValue( ret_context ) = enter_context;
689}
690
691} // namespace
692
693const CompoundStmt * multiLevelExitUpdate(
694 const CompoundStmt * stmt, const LabelToStmt & labelTable ) {
695 // Must start in the body, so FunctionDecls can be a stopping point.
696 Pass<MultiLevelExitCore> visitor( labelTable );
697 return stmt->accept( visitor );
698}
699
700} // namespace ControlStruct
701
702// Local Variables: //
703// tab-width: 4 //
704// mode: c++ //
705// compile-command: "make install" //
706// End: //
Note: See TracBrowser for help on using the repository browser.