source: src/ControlStruct/MultiLevelExit.cpp@ a758169

Last change on this file since a758169 was 88bc876, checked in by Andrew Beach <ajbeach@…>, 16 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
RevLine 
[b8ab91a]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//
[817bb3c]7// MultiLevelExit.cpp -- Replaces CFA's local control flow with C's versions.
[b8ab91a]8//
9// Author : Andrew Beach
10// Created On : Mon Nov 1 13:48:00 2021
[b1f2007d]11// Last Modified By : Peter A. Buhr
[ca9d65e]12// Last Modified On : Thu Dec 14 17:34:12 2023
13// Update Count : 39
[b8ab91a]14//
15
16#include "MultiLevelExit.hpp"
17
[83fd57d]18#include <set>
19
[b8ab91a]20#include "AST/Pass.hpp"
21#include "AST/Stmt.hpp"
[83fd57d]22#include "LabelGenerator.hpp"
[b8ab91a]23
[66daee4]24using namespace std;
25using namespace ast;
[b8ab91a]26
27namespace ControlStruct {
[4a40fca7]28
29namespace {
30
[553f032f]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
[b8ab91a]40class Entry {
[66daee4]41 public:
42 const Stmt * stmt;
43 private:
[b8ab91a]44 // Organized like a manual ADT. Avoids creating a bunch of dead data.
45 struct Target {
[66daee4]46 Label label;
[b8ab91a]47 bool used = false;
[66daee4]48 Target( const Label & label ) : label( label ) {}
[4a40fca7]49 Target() : label( CodeLocation(), "" ) {}
[b8ab91a]50 };
51 Target firstTarget;
52 Target secondTarget;
53
54 enum Kind {
[400b8be]55 ForStmtK, WhileDoStmtK, CompoundStmtK, IfStmtK, CaseClauseK, SwitchStmtK, TryStmtK
[b8ab91a]56 } kind;
57
58 bool fallDefaultValid = true;
59
[66daee4]60 static Label & useTarget( Target & target ) {
[b8ab91a]61 target.used = true;
62 return target.label;
63 }
[66daee4]64 public:
65 Entry( const ForStmt * stmt, Label breakExit, Label contExit ) :
66 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( ForStmtK ) {}
[3b0bc16]67 Entry( const WhileDoStmt * stmt, Label breakExit, Label contExit ) :
68 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileDoStmtK ) {}
[66daee4]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 ) {}
[400b8be]73 Entry( const CaseClause *, const CompoundStmt *stmt, Label fallExit ) :
74 stmt( stmt ), firstTarget( fallExit ), secondTarget(), kind( CaseClauseK ) {}
[66daee4]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
[88bc876]80 // Check if this entry can be the target of the given type of control flow.
[3b0bc16]81 bool isContTarget() const { return kind <= WhileDoStmtK; }
[400b8be]82 bool isBreakTarget() const { return kind != CaseClauseK; }
83 bool isFallTarget() const { return kind == CaseClauseK; }
[66daee4]84 bool isFallDefaultTarget() const { return kind == SwitchStmtK; }
[b8ab91a]85
[3e5db5b4]86 // These routines set a target as being "used" by a BranchStmt
[3b0bc16]87 Label useContExit() { assert( kind <= WhileDoStmtK ); return useTarget(secondTarget); }
[400b8be]88 Label useBreakExit() { assert( kind != CaseClauseK ); return useTarget(firstTarget); }
89 Label useFallExit() { assert( kind == CaseClauseK ); return useTarget(firstTarget); }
[66daee4]90 Label useFallDefaultExit() { assert( kind == SwitchStmtK ); return useTarget(secondTarget); }
[b8ab91a]91
[3e5db5b4]92 // These routines check if a specific label for a statement is used by a BranchStmt
[3b0bc16]93 bool isContUsed() const { assert( kind <= WhileDoStmtK ); return secondTarget.used; }
[400b8be]94 bool isBreakUsed() const { assert( kind != CaseClauseK ); return firstTarget.used; }
95 bool isFallUsed() const { assert( kind == CaseClauseK ); return firstTarget.used; }
[66daee4]96 bool isFallDefaultUsed() const { assert( kind == SwitchStmtK ); return secondTarget.used; }
[b8ab91a]97 void seenDefault() { fallDefaultValid = false; }
98 bool isFallDefaultValid() const { return fallDefaultValid; }
99};
100
[66daee4]101// Helper predicates used in find_if calls (it doesn't take methods):
[b8ab91a]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
[817bb3c]118struct MultiLevelExitCore final :
[66daee4]119 public WithVisitorRef<MultiLevelExitCore>,
120 public WithShortCircuiting, public WithGuards {
[cb921d4]121 MultiLevelExitCore( const LabelToStmt & lt );
[b8ab91a]122
[66daee4]123 void previsit( const FunctionDecl * );
124
125 const CompoundStmt * previsit( const CompoundStmt * );
126 const BranchStmt * postvisit( const BranchStmt * );
[3b0bc16]127 void previsit( const WhileDoStmt * );
128 const WhileDoStmt * postvisit( const WhileDoStmt * );
[66daee4]129 void previsit( const ForStmt * );
130 const ForStmt * postvisit( const ForStmt * );
[400b8be]131 const CaseClause * previsit( const CaseClause * );
[66daee4]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 * );
[553f032f]139 void previsit( const CatchClause * );
[400b8be]140 void previsit( const FinallyClause * );
[66daee4]141
142 const Stmt * mutateLoop( const Stmt * body, Entry& );
[b8ab91a]143
[817bb3c]144 const LabelToStmt & target_table;
[66daee4]145 set<Label> fallthrough_labels;
146 vector<Entry> enclosing_control_structures;
147 Label break_label;
[553f032f]148 ReturnContext ret_context;
[b8ab91a]149
150 template<typename LoopNode>
151 void prehandleLoopStmt( const LoopNode * loopStmt );
152 template<typename LoopNode>
153 const LoopNode * posthandleLoopStmt( const LoopNode * loopStmt );
154
[66daee4]155 list<ptr<Stmt>> fixBlock(
156 const list<ptr<Stmt>> & kids, bool caseClause );
[b8ab91a]157
[553f032f]158 void enterSealedContext( ReturnContext );
159
[817bb3c]160 template<typename UnaryPredicate>
161 auto findEnclosingControlStructure( UnaryPredicate pred ) {
[66daee4]162 return find_if( enclosing_control_structures.rbegin(),
163 enclosing_control_structures.rend(), pred );
[817bb3c]164 }
165};
[b8ab91a]166
[0577df2]167NullStmt * labelledNullStmt( const CodeLocation & cl, const Label & label ) {
[66daee4]168 return new NullStmt( cl, vector<Label>{ label } );
[b8ab91a]169}
170
[cb921d4]171MultiLevelExitCore::MultiLevelExitCore( const LabelToStmt & lt ) :
172 target_table( lt ), break_label( CodeLocation(), "" ),
[553f032f]173 ret_context( ReturnContext::MayReturn )
[b8ab91a]174{}
175
[66daee4]176void MultiLevelExitCore::previsit( const FunctionDecl * ) {
[b8ab91a]177 visit_children = false;
178}
179
[66daee4]180const CompoundStmt * MultiLevelExitCore::previsit(
[0577df2]181 const CompoundStmt * stmt ) {
[b8ab91a]182 visit_children = false;
[3e5db5b4]183
184 // if the stmt is labelled then generate a label to check in postvisit if the label is used
[2f52b18]185 bool isLabeled = ! stmt->labels.empty();
[b8ab91a]186 if ( isLabeled ) {
[66daee4]187 Label breakLabel = newLabel( "blockBreak", stmt );
[b8ab91a]188 enclosing_control_structures.emplace_back( stmt, breakLabel );
189 GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
190 }
191
[66daee4]192 auto mutStmt = mutate( stmt );
[b8ab91a]193 // A child statement may set the break label.
[891f707]194 mutStmt->kids = fixBlock( stmt->kids, false );
[b8ab91a]195
196 if ( isLabeled ) {
[2f52b18]197 assert( ! enclosing_control_structures.empty() );
[b8ab91a]198 Entry & entry = enclosing_control_structures.back();
[2f52b18]199 if ( ! entry.useBreakExit().empty() ) {
[b8ab91a]200 break_label = entry.useBreakExit();
201 }
202 }
203 return mutStmt;
204}
205
[0577df2]206size_t getUnusedIndex( const Stmt * stmt, const Label & originalTarget ) {
[b8ab91a]207 const size_t size = stmt->labels.size();
208
[66daee4]209 // If the label is empty, do not add unused attribute.
[88bc876]210 if ( originalTarget.empty() ) return size;
[b8ab91a]211
212 // Search for a label that matches the originalTarget.
213 for ( size_t i = 0 ; i < size ; ++i ) {
[66daee4]214 const Label & label = stmt->labels[i];
[b8ab91a]215 if ( label == originalTarget ) {
[66daee4]216 for ( const Attribute * attr : label.attributes ) {
[b8ab91a]217 if ( attr->name == "unused" ) return size;
218 }
219 return i;
220 }
221 }
[6180274]222 assertf( false, "CFA internal error: could not find label '%s' on statement %s",
[66daee4]223 originalTarget.name.c_str(), toString( stmt ).c_str() );
[b8ab91a]224}
225
[0577df2]226const Stmt * addUnused( const Stmt * stmt, const Label & originalTarget ) {
[b8ab91a]227 size_t i = getUnusedIndex( stmt, originalTarget );
228 if ( i == stmt->labels.size() ) {
229 return stmt;
230 }
[66daee4]231 Stmt * mutStmt = mutate( stmt );
232 mutStmt->labels[i].attributes.push_back( new Attribute( "unused" ) );
[b8ab91a]233 return mutStmt;
234}
235
[3e5db5b4]236// This routine updates targets on enclosing control structures to indicate which
237// label is used by the BranchStmt that is passed
[66daee4]238const BranchStmt * MultiLevelExitCore::postvisit( const BranchStmt * stmt ) {
239 vector<Entry>::reverse_iterator targetEntry =
[b8ab91a]240 enclosing_control_structures.rend();
[3e5db5b4]241
242 // Labels on different stmts require different approaches to access
[b8ab91a]243 switch ( stmt->kind ) {
[491bb81]244 case BranchStmt::Goto:
[b8ab91a]245 return stmt;
[491bb81]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() ) {
[66daee4]255 SemanticError( stmt->location,
[ca9d65e]256 "\"break\" outside a loop, \"switch\", or labelled block" );
[491bb81]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){
[66daee4]265 return entry.stmt == targetStmt;
[491bb81]266 } );
267 }
268 // Ensure that selected target is valid.
269 if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && ! isContinueTarget( *targetEntry ) ) ) {
[ca9d65e]270 SemanticError( stmt->location, toString( (isContinue ? "\"continue\"" : "\"break\""),
[66daee4]271 " target must be an enclosing ", (isContinue ? "loop: " : "control structure: "),
272 stmt->originalTarget ) );
[491bb81]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() ) {
[ca9d65e]281 SemanticError( stmt->location, "\"fallthrough\" must be enclosed in a \"switch\" or \"choose\"" );
[491bb81]282 }
283 if ( ! stmt->target.empty() ) {
284 // Labelled fallthrough: target must be a valid fallthough label.
285 if ( ! fallthrough_labels.count( stmt->target ) ) {
[ca9d65e]286 SemanticError( stmt->location, toString( "\"fallthrough\" target must be a later case statement: ",
[66daee4]287 stmt->originalTarget ) );
[491bb81]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() ) {
[ca9d65e]298 SemanticError( stmt->location, "\"fallthrough\" must be enclosed in a \"switch\" or \"choose\"" );
[491bb81]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 ) {
[ca9d65e]311 SemanticError( stmt->location, "\"fallthrough default\" must be enclosed in a \"switch\" or \"choose\""
312 "control structure with a \"default\" clause" );
[491bb81]313 }
314 break;
315 }
316 default:
[b8ab91a]317 assert( false );
318 }
319
[2f52b18]320 // Branch error checks: get the appropriate label name, which is always replaced.
[66daee4]321 Label exitLabel( CodeLocation(), "" );
[b8ab91a]322 switch ( stmt->kind ) {
[491bb81]323 case BranchStmt::Break:
[2f52b18]324 assert( ! targetEntry->useBreakExit().empty() );
[b8ab91a]325 exitLabel = targetEntry->useBreakExit();
326 break;
[491bb81]327 case BranchStmt::Continue:
[2f52b18]328 assert( ! targetEntry->useContExit().empty() );
[b8ab91a]329 exitLabel = targetEntry->useContExit();
330 break;
[491bb81]331 case BranchStmt::FallThrough:
[2f52b18]332 assert( ! targetEntry->useFallExit().empty() );
[b8ab91a]333 exitLabel = targetEntry->useFallExit();
334 break;
[491bb81]335 case BranchStmt::FallThroughDefault:
[2f52b18]336 assert( ! targetEntry->useFallDefaultExit().empty() );
[b8ab91a]337 exitLabel = targetEntry->useFallDefaultExit();
338 // Check that fallthrough default comes before the default clause.
[2f52b18]339 if ( ! targetEntry->isFallDefaultValid() ) {
[ca9d65e]340 SemanticError( stmt->location, "\"fallthrough default\" must precede the \"default\" clause" );
[b8ab91a]341 }
342 break;
[491bb81]343 default:
[b8ab91a]344 assert(0);
345 }
[88bc876]346 assert( !exitLabel.empty() );
[b8ab91a]347
348 // Add unused attribute to silence warnings.
349 targetEntry->stmt = addUnused( targetEntry->stmt, stmt->originalTarget );
350
[66daee4]351 // Replace with goto to make later passes more uniform.
352 return new BranchStmt( stmt->location, BranchStmt::Goto, exitLabel );
[b8ab91a]353}
354
[3b0bc16]355void MultiLevelExitCore::previsit( const WhileDoStmt * stmt ) {
[b8ab91a]356 return prehandleLoopStmt( stmt );
357}
358
[3b0bc16]359const WhileDoStmt * MultiLevelExitCore::postvisit( const WhileDoStmt * stmt ) {
[b8ab91a]360 return posthandleLoopStmt( stmt );
361}
362
[66daee4]363void MultiLevelExitCore::previsit( const ForStmt * stmt ) {
[b8ab91a]364 return prehandleLoopStmt( stmt );
365}
366
[66daee4]367const ForStmt * MultiLevelExitCore::postvisit( const ForStmt * stmt ) {
[b8ab91a]368 return posthandleLoopStmt( stmt );
369}
370
371// Mimic what the built-in push_front would do anyways. It is O(n).
[0577df2]372void push_front( vector<ptr<Stmt>> & vec, const Stmt * element ) {
[b8ab91a]373 vec.emplace_back( nullptr );
374 for ( size_t i = vec.size() - 1 ; 0 < i ; --i ) {
[0bd46fd]375 vec[ i ] = std::move( vec[ i - 1 ] );
[b8ab91a]376 }
377 vec[ 0 ] = element;
378}
379
[400b8be]380const CaseClause * MultiLevelExitCore::previsit( const CaseClause * stmt ) {
[b8ab91a]381 visit_children = false;
382
[66daee4]383 // If default, mark seen.
[b8ab91a]384 if ( stmt->isDefault() ) {
[2f52b18]385 assert( ! enclosing_control_structures.empty() );
[b8ab91a]386 enclosing_control_structures.back().seenDefault();
387 }
388
389 // The cond may not exist, but if it does update it now.
[400b8be]390 visitor->maybe_accept( stmt, &CaseClause::cond );
[b8ab91a]391
392 // Just save the mutated node for simplicity.
[400b8be]393 CaseClause * mutStmt = mutate( stmt );
[b8ab91a]394
[400b8be]395 Label fallLabel = newLabel( "fallThrough", stmt->location );
[66daee4]396 if ( ! mutStmt->stmts.empty() ) {
[400b8be]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
[b8ab91a]401 // Ensure that the stack isn't corrupted by exceptions in fixBlock.
402 auto guard = makeFuncGuard(
[400b8be]403 [&](){ enclosing_control_structures.emplace_back( mutStmt, block, fallLabel ); },
[b8ab91a]404 [this](){ enclosing_control_structures.pop_back(); }
[66daee4]405 );
[b8ab91a]406
407 block->kids = fixBlock( block->kids, true );
408
409 // Add fallthrough label if necessary.
[66daee4]410 assert( ! enclosing_control_structures.empty() );
[b8ab91a]411 Entry & entry = enclosing_control_structures.back();
412 if ( entry.isFallUsed() ) {
[400b8be]413 mutStmt->stmts.push_back( labelledNullStmt( block->location, entry.useFallExit() ) );
[b8ab91a]414 }
415 }
[66daee4]416 assert( ! enclosing_control_structures.empty() );
[b8ab91a]417 Entry & entry = enclosing_control_structures.back();
[66daee4]418 assertf( dynamic_cast< const SwitchStmt * >( entry.stmt ),
[6180274]419 "CFA internal error: control structure enclosing a case clause must be a switch, but is: %s",
[66daee4]420 toString( entry.stmt ).c_str() );
[b8ab91a]421 if ( mutStmt->isDefault() ) {
422 if ( entry.isFallDefaultUsed() ) {
423 // Add fallthrough default label if necessary.
[2f52b18]424 push_front( mutStmt->stmts, labelledNullStmt( stmt->location, entry.useFallDefaultExit() ) );
[b8ab91a]425 }
426 }
427 return mutStmt;
428}
429
[66daee4]430void MultiLevelExitCore::previsit( const IfStmt * stmt ) {
[2f52b18]431 bool labeledBlock = ! stmt->labels.empty();
[b8ab91a]432 if ( labeledBlock ) {
[66daee4]433 Label breakLabel = newLabel( "blockBreak", stmt );
[b8ab91a]434 enclosing_control_structures.emplace_back( stmt, breakLabel );
435 GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
436 }
437}
438
[66daee4]439const IfStmt * MultiLevelExitCore::postvisit( const IfStmt * stmt ) {
[2f52b18]440 bool labeledBlock = ! stmt->labels.empty();
[b8ab91a]441 if ( labeledBlock ) {
442 auto this_label = enclosing_control_structures.back().useBreakExit();
[2f52b18]443 if ( ! this_label.empty() ) {
[b8ab91a]444 break_label = this_label;
445 }
446 }
447 return stmt;
448}
449
[400b8be]450static bool isDefaultCase( const ptr<CaseClause> & caseClause ) {
451 return caseClause->isDefault();
[b8ab91a]452}
453
[66daee4]454void MultiLevelExitCore::previsit( const SwitchStmt * stmt ) {
455 Label label = newLabel( "switchBreak", stmt );
[400b8be]456 auto it = find_if( stmt->cases.rbegin(), stmt->cases.rend(), isDefaultCase );
[b8ab91a]457
[400b8be]458 const CaseClause * defaultCase = it != stmt->cases.rend() ? (*it) : nullptr;
459 Label defaultLabel = defaultCase ? newLabel( "fallThroughDefault", defaultCase->location ) : Label( stmt->location, "" );
[b8ab91a]460 enclosing_control_structures.emplace_back( stmt, label, defaultLabel );
461 GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
462
[2f52b18]463 // Collect valid labels for fallthrough. It starts with all labels at this level, then remove as each is seen during
464 // traversal.
[400b8be]465 for ( const CaseClause * caseStmt : stmt->cases ) {
[b8ab91a]466 if ( caseStmt->stmts.empty() ) continue;
[66daee4]467 auto block = caseStmt->stmts.front().strict_as<CompoundStmt>();
468 for ( const Stmt * stmt : block->kids ) {
469 for ( const Label & l : stmt->labels ) {
[b8ab91a]470 fallthrough_labels.insert( l );
471 }
472 }
473 }
474}
475
[66daee4]476const SwitchStmt * MultiLevelExitCore::postvisit( const SwitchStmt * stmt ) {
[2f52b18]477 assert( ! enclosing_control_structures.empty() );
[b8ab91a]478 Entry & entry = enclosing_control_structures.back();
479 assert( entry.stmt == stmt );
480
[66daee4]481 // Only run to generate the break label.
[b8ab91a]482 if ( entry.isBreakUsed() ) {
[2f52b18]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.
[66daee4]485 SwitchStmt * mutStmt = mutate( stmt );
[400b8be]486 if ( mutStmt->cases.empty() ) {
487 mutStmt->cases.push_back( new CaseClause( mutStmt->location, nullptr, {} ) );
[b8ab91a]488 }
489
[88bc876]490 auto mutCase = mutStmt->cases.back().get_and_mutate();
[b8ab91a]491
[66daee4]492 Label label( mutCase->location, "breakLabel" );
493 auto branch = new BranchStmt( mutCase->location, BranchStmt::Break, label );
[b8ab91a]494 branch->labels.push_back( entry.useBreakExit() );
495 mutCase->stmts.push_back( branch );
496
497 return mutStmt;
498 }
499 return stmt;
500}
501
[66daee4]502void MultiLevelExitCore::previsit( const ReturnStmt * stmt ) {
[553f032f]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);
[b8ab91a]518 }
[ca9d65e]519 SemanticError( stmt->location, "\"return\" may not appear in a %s", context );
[b8ab91a]520}
521
[0a6d2045]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
[66daee4]529void MultiLevelExitCore::previsit( const TryStmt * stmt ) {
[0a6d2045]530 visit_children = false;
531
[2f52b18]532 bool isLabeled = ! stmt->labels.empty();
[b8ab91a]533 if ( isLabeled ) {
[66daee4]534 Label breakLabel = newLabel( "blockBreak", stmt );
[b8ab91a]535 enclosing_control_structures.emplace_back( stmt, breakLabel );
536 GuardAction([this](){ enclosing_control_structures.pop_back(); } );
537 }
[553f032f]538
539 // Try statements/try blocks are only sealed with a termination handler.
[0a6d2045]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 );
[553f032f]550 }
[0a6d2045]551
552 visitor->maybe_accept( stmt, &TryStmt::handlers );
553 visitor->maybe_accept( stmt, &TryStmt::finally );
[b8ab91a]554}
555
[66daee4]556void MultiLevelExitCore::postvisit( const TryStmt * stmt ) {
[2f52b18]557 bool isLabeled = ! stmt->labels.empty();
[b8ab91a]558 if ( isLabeled ) {
559 auto this_label = enclosing_control_structures.back().useBreakExit();
[2f52b18]560 if ( ! this_label.empty() ) {
[b8ab91a]561 break_label = this_label;
562 }
563 }
564}
565
[553f032f]566void MultiLevelExitCore::previsit( const CatchClause * clause ) {
[0a6d2045]567 if ( ast::Resume == clause->kind ) {
568 enterSealedContext( ReturnContext::InResumeHandler );
569 }
[553f032f]570}
571
[400b8be]572void MultiLevelExitCore::previsit( const FinallyClause * ) {
[553f032f]573 enterSealedContext( ReturnContext::InFinally );
[b8ab91a]574}
575
[66daee4]576const Stmt * MultiLevelExitCore::mutateLoop(
577 const Stmt * body, Entry & entry ) {
[b8ab91a]578 if ( entry.isBreakUsed() ) {
579 break_label = entry.useBreakExit();
580 }
581
[3e5db5b4]582 // if continue is used insert a continue label into the back of the body of the loop
[b8ab91a]583 if ( entry.isContUsed() ) {
[3e5db5b4]584 // {
585 // body
[4a40fca7]586 // ContinueLabel: ;
[3e5db5b4]587 // }
[4a40fca7]588 return new CompoundStmt( body->location, {
589 body,
590 labelledNullStmt( body->location, entry.useContExit() ),
591 } );
[b8ab91a]592 }
593
594 return body;
595}
596
597template<typename LoopNode>
598void MultiLevelExitCore::prehandleLoopStmt( const LoopNode * loopStmt ) {
[88bc876]599 // Create temporary labels and mark the enclosing loop before traversal.
[b8ab91a]600 // The labels will be folded in if they are used.
[66daee4]601 Label breakLabel = newLabel( "loopBreak", loopStmt );
602 Label contLabel = newLabel( "loopContinue", loopStmt );
[b8ab91a]603 enclosing_control_structures.emplace_back( loopStmt, breakLabel, contLabel );
[3e5db5b4]604
[b8ab91a]605 GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
[88bc876]606
607 // Because of fixBlock, this should be empty now (and must be).
608 assert( nullptr == loopStmt->else_ );
[b8ab91a]609}
610
611template<typename LoopNode>
612const LoopNode * MultiLevelExitCore::posthandleLoopStmt( const LoopNode * loopStmt ) {
[2f52b18]613 assert( ! enclosing_control_structures.empty() );
[b8ab91a]614 Entry & entry = enclosing_control_structures.back();
615 assert( entry.stmt == loopStmt );
616
[66daee4]617 // Now check if the labels are used and add them if so.
[2f52b18]618 return mutate_field( loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
[b8ab91a]619}
620
[66daee4]621list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
622 const list<ptr<Stmt>> & kids, bool is_case_clause ) {
623 // Unfortunately cannot use automatic error collection.
[b8ab91a]624 SemanticErrorException errors;
625
[66daee4]626 list<ptr<Stmt>> ret;
[b8ab91a]627
628 // Manually visit each child.
[66daee4]629 for ( const ptr<Stmt> & kid : kids ) {
[b8ab91a]630 if ( is_case_clause ) {
631 // Once a label is seen, it's no longer a valid for fallthrough.
[66daee4]632 for ( const Label & l : kid->labels ) {
[b8ab91a]633 fallthrough_labels.erase( l );
634 }
635 }
636
[f75e25b]637 ptr<Stmt> else_stmt = nullptr;
[88bc876]638 const Stmt * to_visit;
[f75e25b]639 // check if loop node and if so add else clause if it exists
[88bc876]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();
[f75e25b]648 }
649
[88bc876]650 // This is the main (safe) visit of the child node.
[b8ab91a]651 try {
[88bc876]652 ret.push_back( to_visit->accept( *visitor ) );
[b8ab91a]653 } catch ( SemanticErrorException & e ) {
654 errors.append( e );
655 }
656
[88bc876]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(), "" );
[7ad47df]661
[88bc876]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() ) {
[2f52b18]669 ret.push_back( labelledNullStmt( ret.back()->location, break_label ) );
[66daee4]670 break_label = Label( CodeLocation(), "" );
[b8ab91a]671 }
[88bc876]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 }
[b8ab91a]677 }
678
[88bc876]679 if ( !errors.isEmpty() ) {
[b8ab91a]680 throw errors;
681 }
682 return ret;
683}
684
[553f032f]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
[4a40fca7]691} // namespace
692
[66daee4]693const CompoundStmt * multiLevelExitUpdate(
[4a40fca7]694 const CompoundStmt * stmt, const LabelToStmt & labelTable ) {
[b8ab91a]695 // Must start in the body, so FunctionDecls can be a stopping point.
[66daee4]696 Pass<MultiLevelExitCore> visitor( labelTable );
[4a40fca7]697 return stmt->accept( visitor );
[b8ab91a]698}
[4a40fca7]699
[b8ab91a]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.