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 : Andrew Beach
|
---|
12 | // Last Modified On : Fri Sep 8 17:04:00 2023
|
---|
13 | // Update Count : 36
|
---|
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 |
|
---|
24 | using namespace std;
|
---|
25 | using namespace ast;
|
---|
26 |
|
---|
27 | namespace ControlStruct {
|
---|
28 |
|
---|
29 | namespace {
|
---|
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.
|
---|
33 | enum ReturnContext {
|
---|
34 | MayReturn,
|
---|
35 | InTryWithHandler,
|
---|
36 | InResumeHandler,
|
---|
37 | InTerminateHandler,
|
---|
38 | InFinally,
|
---|
39 | };
|
---|
40 |
|
---|
41 | class Entry {
|
---|
42 | public:
|
---|
43 | const Stmt * stmt;
|
---|
44 | private:
|
---|
45 | // Organized like a manual ADT. Avoids creating a bunch of dead data.
|
---|
46 | struct Target {
|
---|
47 | Label label;
|
---|
48 | bool used = false;
|
---|
49 | Target( const Label & label ) : label( label ) {}
|
---|
50 | Target() : label( CodeLocation(), "" ) {}
|
---|
51 | };
|
---|
52 | Target firstTarget;
|
---|
53 | Target secondTarget;
|
---|
54 |
|
---|
55 | enum Kind {
|
---|
56 | ForStmtK, WhileDoStmtK, CompoundStmtK, IfStmtK, CaseClauseK, SwitchStmtK, TryStmtK
|
---|
57 | } kind;
|
---|
58 |
|
---|
59 | bool fallDefaultValid = true;
|
---|
60 |
|
---|
61 | static Label & useTarget( Target & target ) {
|
---|
62 | target.used = true;
|
---|
63 | return target.label;
|
---|
64 | }
|
---|
65 | public:
|
---|
66 | Entry( const ForStmt * stmt, Label breakExit, Label contExit ) :
|
---|
67 | stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( ForStmtK ) {}
|
---|
68 | Entry( const WhileDoStmt * stmt, Label breakExit, Label contExit ) :
|
---|
69 | stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileDoStmtK ) {}
|
---|
70 | Entry( const CompoundStmt *stmt, Label breakExit ) :
|
---|
71 | stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( CompoundStmtK ) {}
|
---|
72 | Entry( const IfStmt *stmt, Label breakExit ) :
|
---|
73 | stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( IfStmtK ) {}
|
---|
74 | Entry( const CaseClause *, const CompoundStmt *stmt, Label fallExit ) :
|
---|
75 | stmt( stmt ), firstTarget( fallExit ), secondTarget(), kind( CaseClauseK ) {}
|
---|
76 | Entry( const SwitchStmt *stmt, Label breakExit, Label fallDefaultExit ) :
|
---|
77 | stmt( stmt ), firstTarget( breakExit ), secondTarget( fallDefaultExit ), kind( SwitchStmtK ) {}
|
---|
78 | Entry( const TryStmt *stmt, Label breakExit ) :
|
---|
79 | stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( TryStmtK ) {}
|
---|
80 |
|
---|
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):
|
---|
102 | bool isBreakTarget( const Entry & entry ) {
|
---|
103 | return entry.isBreakTarget();
|
---|
104 | }
|
---|
105 |
|
---|
106 | bool isContinueTarget( const Entry & entry ) {
|
---|
107 | return entry.isContTarget();
|
---|
108 | }
|
---|
109 |
|
---|
110 | bool isFallthroughTarget( const Entry & entry ) {
|
---|
111 | return entry.isFallTarget();
|
---|
112 | }
|
---|
113 |
|
---|
114 | bool isFallthroughDefaultTarget( const Entry & entry ) {
|
---|
115 | return entry.isFallDefaultTarget();
|
---|
116 | }
|
---|
117 |
|
---|
118 | struct 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 |
|
---|
167 | NullStmt * labelledNullStmt( const CodeLocation & cl, const Label & label ) {
|
---|
168 | return new NullStmt( cl, vector<Label>{ label } );
|
---|
169 | }
|
---|
170 |
|
---|
171 | MultiLevelExitCore::MultiLevelExitCore( const LabelToStmt & lt ) :
|
---|
172 | target_table( lt ), break_label( CodeLocation(), "" ),
|
---|
173 | ret_context( ReturnContext::MayReturn )
|
---|
174 | {}
|
---|
175 |
|
---|
176 | void MultiLevelExitCore::previsit( const FunctionDecl * ) {
|
---|
177 | visit_children = false;
|
---|
178 | }
|
---|
179 |
|
---|
180 | const 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 |
|
---|
206 | size_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 |
|
---|
226 | const 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
|
---|
238 | const 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 |
|
---|
347 | // Add unused attribute to silence warnings.
|
---|
348 | targetEntry->stmt = addUnused( targetEntry->stmt, stmt->originalTarget );
|
---|
349 |
|
---|
350 | // Replace with goto to make later passes more uniform.
|
---|
351 | return new BranchStmt( stmt->location, BranchStmt::Goto, exitLabel );
|
---|
352 | }
|
---|
353 |
|
---|
354 | void MultiLevelExitCore::previsit( const WhileDoStmt * stmt ) {
|
---|
355 | return prehandleLoopStmt( stmt );
|
---|
356 | }
|
---|
357 |
|
---|
358 | const WhileDoStmt * MultiLevelExitCore::postvisit( const WhileDoStmt * stmt ) {
|
---|
359 | return posthandleLoopStmt( stmt );
|
---|
360 | }
|
---|
361 |
|
---|
362 | void MultiLevelExitCore::previsit( const ForStmt * stmt ) {
|
---|
363 | return prehandleLoopStmt( stmt );
|
---|
364 | }
|
---|
365 |
|
---|
366 | const ForStmt * MultiLevelExitCore::postvisit( const ForStmt * stmt ) {
|
---|
367 | return posthandleLoopStmt( stmt );
|
---|
368 | }
|
---|
369 |
|
---|
370 | // Mimic what the built-in push_front would do anyways. It is O(n).
|
---|
371 | void push_front( vector<ptr<Stmt>> & vec, const Stmt * element ) {
|
---|
372 | vec.emplace_back( nullptr );
|
---|
373 | for ( size_t i = vec.size() - 1 ; 0 < i ; --i ) {
|
---|
374 | vec[ i ] = std::move( vec[ i - 1 ] );
|
---|
375 | }
|
---|
376 | vec[ 0 ] = element;
|
---|
377 | }
|
---|
378 |
|
---|
379 | const CaseClause * MultiLevelExitCore::previsit( const CaseClause * stmt ) {
|
---|
380 | visit_children = false;
|
---|
381 |
|
---|
382 | // If default, mark seen.
|
---|
383 | if ( stmt->isDefault() ) {
|
---|
384 | assert( ! enclosing_control_structures.empty() );
|
---|
385 | enclosing_control_structures.back().seenDefault();
|
---|
386 | }
|
---|
387 |
|
---|
388 | // The cond may not exist, but if it does update it now.
|
---|
389 | visitor->maybe_accept( stmt, &CaseClause::cond );
|
---|
390 |
|
---|
391 | // Just save the mutated node for simplicity.
|
---|
392 | CaseClause * mutStmt = mutate( stmt );
|
---|
393 |
|
---|
394 | Label fallLabel = newLabel( "fallThrough", stmt->location );
|
---|
395 | if ( ! mutStmt->stmts.empty() ) {
|
---|
396 | // These should already be in a block.
|
---|
397 | auto first = mutStmt->stmts.front().get_and_mutate();
|
---|
398 | auto block = strict_dynamic_cast<CompoundStmt *>( first );
|
---|
399 |
|
---|
400 | // Ensure that the stack isn't corrupted by exceptions in fixBlock.
|
---|
401 | auto guard = makeFuncGuard(
|
---|
402 | [&](){ enclosing_control_structures.emplace_back( mutStmt, block, fallLabel ); },
|
---|
403 | [this](){ enclosing_control_structures.pop_back(); }
|
---|
404 | );
|
---|
405 |
|
---|
406 | block->kids = fixBlock( block->kids, true );
|
---|
407 |
|
---|
408 | // Add fallthrough label if necessary.
|
---|
409 | assert( ! enclosing_control_structures.empty() );
|
---|
410 | Entry & entry = enclosing_control_structures.back();
|
---|
411 | if ( entry.isFallUsed() ) {
|
---|
412 | mutStmt->stmts.push_back( labelledNullStmt( block->location, entry.useFallExit() ) );
|
---|
413 | }
|
---|
414 | }
|
---|
415 | assert( ! enclosing_control_structures.empty() );
|
---|
416 | Entry & entry = enclosing_control_structures.back();
|
---|
417 | assertf( dynamic_cast< const SwitchStmt * >( entry.stmt ),
|
---|
418 | "CFA internal error: control structure enclosing a case clause must be a switch, but is: %s",
|
---|
419 | toString( entry.stmt ).c_str() );
|
---|
420 | if ( mutStmt->isDefault() ) {
|
---|
421 | if ( entry.isFallDefaultUsed() ) {
|
---|
422 | // Add fallthrough default label if necessary.
|
---|
423 | push_front( mutStmt->stmts, labelledNullStmt( stmt->location, entry.useFallDefaultExit() ) );
|
---|
424 | }
|
---|
425 | }
|
---|
426 | return mutStmt;
|
---|
427 | }
|
---|
428 |
|
---|
429 | void MultiLevelExitCore::previsit( const IfStmt * stmt ) {
|
---|
430 | bool labeledBlock = ! stmt->labels.empty();
|
---|
431 | if ( labeledBlock ) {
|
---|
432 | Label breakLabel = newLabel( "blockBreak", stmt );
|
---|
433 | enclosing_control_structures.emplace_back( stmt, breakLabel );
|
---|
434 | GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
|
---|
435 | }
|
---|
436 | }
|
---|
437 |
|
---|
438 | const IfStmt * MultiLevelExitCore::postvisit( const IfStmt * stmt ) {
|
---|
439 | bool labeledBlock = ! stmt->labels.empty();
|
---|
440 | if ( labeledBlock ) {
|
---|
441 | auto this_label = enclosing_control_structures.back().useBreakExit();
|
---|
442 | if ( ! this_label.empty() ) {
|
---|
443 | break_label = this_label;
|
---|
444 | }
|
---|
445 | }
|
---|
446 | return stmt;
|
---|
447 | }
|
---|
448 |
|
---|
449 | static bool isDefaultCase( const ptr<CaseClause> & caseClause ) {
|
---|
450 | return caseClause->isDefault();
|
---|
451 | }
|
---|
452 |
|
---|
453 | void MultiLevelExitCore::previsit( const SwitchStmt * stmt ) {
|
---|
454 | Label label = newLabel( "switchBreak", stmt );
|
---|
455 | auto it = find_if( stmt->cases.rbegin(), stmt->cases.rend(), isDefaultCase );
|
---|
456 |
|
---|
457 | const CaseClause * defaultCase = it != stmt->cases.rend() ? (*it) : nullptr;
|
---|
458 | Label defaultLabel = defaultCase ? newLabel( "fallThroughDefault", defaultCase->location ) : Label( stmt->location, "" );
|
---|
459 | enclosing_control_structures.emplace_back( stmt, label, defaultLabel );
|
---|
460 | GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
|
---|
461 |
|
---|
462 | // Collect valid labels for fallthrough. It starts with all labels at this level, then remove as each is seen during
|
---|
463 | // traversal.
|
---|
464 | for ( const CaseClause * caseStmt : stmt->cases ) {
|
---|
465 | if ( caseStmt->stmts.empty() ) continue;
|
---|
466 | auto block = caseStmt->stmts.front().strict_as<CompoundStmt>();
|
---|
467 | for ( const Stmt * stmt : block->kids ) {
|
---|
468 | for ( const Label & l : stmt->labels ) {
|
---|
469 | fallthrough_labels.insert( l );
|
---|
470 | }
|
---|
471 | }
|
---|
472 | }
|
---|
473 | }
|
---|
474 |
|
---|
475 | const SwitchStmt * MultiLevelExitCore::postvisit( const SwitchStmt * stmt ) {
|
---|
476 | assert( ! enclosing_control_structures.empty() );
|
---|
477 | Entry & entry = enclosing_control_structures.back();
|
---|
478 | assert( entry.stmt == stmt );
|
---|
479 |
|
---|
480 | // Only run to generate the break label.
|
---|
481 | if ( entry.isBreakUsed() ) {
|
---|
482 | // To keep the switch statements uniform (all direct children of a SwitchStmt should be CastStmts), append the
|
---|
483 | // exit label and break to the last case, create a default case if no cases.
|
---|
484 | SwitchStmt * mutStmt = mutate( stmt );
|
---|
485 | if ( mutStmt->cases.empty() ) {
|
---|
486 | mutStmt->cases.push_back( new CaseClause( mutStmt->location, nullptr, {} ) );
|
---|
487 | }
|
---|
488 |
|
---|
489 | auto caseStmt = mutStmt->cases.back().get();
|
---|
490 | auto mutCase = mutate( caseStmt );
|
---|
491 | mutStmt->cases.back() = mutCase;
|
---|
492 |
|
---|
493 | Label label( mutCase->location, "breakLabel" );
|
---|
494 | auto branch = new BranchStmt( mutCase->location, BranchStmt::Break, label );
|
---|
495 | branch->labels.push_back( entry.useBreakExit() );
|
---|
496 | mutCase->stmts.push_back( branch );
|
---|
497 |
|
---|
498 | return mutStmt;
|
---|
499 | }
|
---|
500 | return stmt;
|
---|
501 | }
|
---|
502 |
|
---|
503 | void MultiLevelExitCore::previsit( const ReturnStmt * stmt ) {
|
---|
504 | char const * context;
|
---|
505 | switch ( ret_context ) {
|
---|
506 | case ReturnContext::MayReturn:
|
---|
507 | return;
|
---|
508 | case ReturnContext::InTryWithHandler:
|
---|
509 | context = "try statement with a catch clause";
|
---|
510 | break;
|
---|
511 | case ReturnContext::InResumeHandler:
|
---|
512 | context = "catchResume clause";
|
---|
513 | break;
|
---|
514 | case ReturnContext::InTerminateHandler:
|
---|
515 | context = "catch clause";
|
---|
516 | break;
|
---|
517 | case ReturnContext::InFinally:
|
---|
518 | context = "finally clause";
|
---|
519 | break;
|
---|
520 | default:
|
---|
521 | assert(0);
|
---|
522 | }
|
---|
523 | SemanticError( stmt->location, toString( "'return' may not appear in a ", context ) );
|
---|
524 | }
|
---|
525 |
|
---|
526 | void MultiLevelExitCore::previsit( const TryStmt * stmt ) {
|
---|
527 | bool isLabeled = ! stmt->labels.empty();
|
---|
528 | if ( isLabeled ) {
|
---|
529 | Label breakLabel = newLabel( "blockBreak", stmt );
|
---|
530 | enclosing_control_structures.emplace_back( stmt, breakLabel );
|
---|
531 | GuardAction([this](){ enclosing_control_structures.pop_back(); } );
|
---|
532 | }
|
---|
533 |
|
---|
534 | // Try statements/try blocks are only sealed with a termination handler.
|
---|
535 | for ( auto clause : stmt->handlers ) {
|
---|
536 | if ( ast::Terminate == clause->kind ) {
|
---|
537 | return enterSealedContext( ReturnContext::InTryWithHandler );
|
---|
538 | }
|
---|
539 | }
|
---|
540 | }
|
---|
541 |
|
---|
542 | void MultiLevelExitCore::postvisit( const TryStmt * stmt ) {
|
---|
543 | bool isLabeled = ! stmt->labels.empty();
|
---|
544 | if ( isLabeled ) {
|
---|
545 | auto this_label = enclosing_control_structures.back().useBreakExit();
|
---|
546 | if ( ! this_label.empty() ) {
|
---|
547 | break_label = this_label;
|
---|
548 | }
|
---|
549 | }
|
---|
550 | }
|
---|
551 |
|
---|
552 | void MultiLevelExitCore::previsit( const CatchClause * clause ) {
|
---|
553 | ReturnContext context = ( ast::Terminate == clause->kind )
|
---|
554 | ? ReturnContext::InTerminateHandler : ReturnContext::InResumeHandler;
|
---|
555 | enterSealedContext( context );
|
---|
556 | }
|
---|
557 |
|
---|
558 | void MultiLevelExitCore::previsit( const FinallyClause * ) {
|
---|
559 | enterSealedContext( ReturnContext::InFinally );
|
---|
560 | }
|
---|
561 |
|
---|
562 | const Stmt * MultiLevelExitCore::mutateLoop(
|
---|
563 | const Stmt * body, Entry & entry ) {
|
---|
564 | if ( entry.isBreakUsed() ) {
|
---|
565 | break_label = entry.useBreakExit();
|
---|
566 | }
|
---|
567 |
|
---|
568 | // if continue is used insert a continue label into the back of the body of the loop
|
---|
569 | if ( entry.isContUsed() ) {
|
---|
570 | // {
|
---|
571 | // body
|
---|
572 | // ContinueLabel: ;
|
---|
573 | // }
|
---|
574 | return new CompoundStmt( body->location, {
|
---|
575 | body,
|
---|
576 | labelledNullStmt( body->location, entry.useContExit() ),
|
---|
577 | } );
|
---|
578 | }
|
---|
579 |
|
---|
580 | return body;
|
---|
581 | }
|
---|
582 |
|
---|
583 | template<typename LoopNode>
|
---|
584 | void MultiLevelExitCore::prehandleLoopStmt( const LoopNode * loopStmt ) {
|
---|
585 | // Remember is loop before going onto mutate the body.
|
---|
586 | // The labels will be folded in if they are used.
|
---|
587 | Label breakLabel = newLabel( "loopBreak", loopStmt );
|
---|
588 | Label contLabel = newLabel( "loopContinue", loopStmt );
|
---|
589 | enclosing_control_structures.emplace_back( loopStmt, breakLabel, contLabel );
|
---|
590 | // labels are added temporarily to see if they are used and then added permanently in postvisit if ther are used
|
---|
591 | // children will tag labels as being used during their traversal which occurs before postvisit
|
---|
592 |
|
---|
593 | // GuardAction calls the lambda after the node is done being visited
|
---|
594 | GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
|
---|
595 | }
|
---|
596 |
|
---|
597 | template<typename LoopNode>
|
---|
598 | const LoopNode * MultiLevelExitCore::posthandleLoopStmt( const LoopNode * loopStmt ) {
|
---|
599 | assert( ! enclosing_control_structures.empty() );
|
---|
600 | Entry & entry = enclosing_control_structures.back();
|
---|
601 | assert( entry.stmt == loopStmt );
|
---|
602 |
|
---|
603 | // Now check if the labels are used and add them if so.
|
---|
604 | return mutate_field( loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
|
---|
605 | // this call to mutate_field compares loopStmt->body and the result of mutateLoop
|
---|
606 | // if they are the same the node isn't mutated, if they differ then the new mutated node is returned
|
---|
607 | // the stmts will only differ if a label is used
|
---|
608 | }
|
---|
609 |
|
---|
610 | list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
|
---|
611 | const list<ptr<Stmt>> & kids, bool is_case_clause ) {
|
---|
612 | // Unfortunately cannot use automatic error collection.
|
---|
613 | SemanticErrorException errors;
|
---|
614 |
|
---|
615 | list<ptr<Stmt>> ret;
|
---|
616 |
|
---|
617 | // Manually visit each child.
|
---|
618 | for ( const ptr<Stmt> & kid : kids ) {
|
---|
619 | if ( is_case_clause ) {
|
---|
620 | // Once a label is seen, it's no longer a valid for fallthrough.
|
---|
621 | for ( const Label & l : kid->labels ) {
|
---|
622 | fallthrough_labels.erase( l );
|
---|
623 | }
|
---|
624 | }
|
---|
625 |
|
---|
626 | ptr<Stmt> else_stmt = nullptr;
|
---|
627 | const Stmt * loop_kid = nullptr;
|
---|
628 | // check if loop node and if so add else clause if it exists
|
---|
629 | const WhileDoStmt * whilePtr = kid.as<WhileDoStmt>();
|
---|
630 | if ( whilePtr && whilePtr->else_ ) {
|
---|
631 | else_stmt = whilePtr->else_;
|
---|
632 | loop_kid = mutate_field( whilePtr, &WhileDoStmt::else_, nullptr );
|
---|
633 | }
|
---|
634 | const ForStmt * forPtr = kid.as<ForStmt>();
|
---|
635 | if ( forPtr && forPtr->else_ ) {
|
---|
636 | else_stmt = forPtr->else_;
|
---|
637 | loop_kid = mutate_field( forPtr, &ForStmt::else_, nullptr );
|
---|
638 | }
|
---|
639 |
|
---|
640 | try {
|
---|
641 | if (else_stmt) ret.push_back( loop_kid->accept( *visitor ) );
|
---|
642 | else ret.push_back( kid->accept( *visitor ) );
|
---|
643 | } catch ( SemanticErrorException & e ) {
|
---|
644 | errors.append( e );
|
---|
645 | }
|
---|
646 |
|
---|
647 | if (else_stmt) ret.push_back(else_stmt);
|
---|
648 |
|
---|
649 | if ( ! break_label.empty() ) {
|
---|
650 | ret.push_back( labelledNullStmt( ret.back()->location, break_label ) );
|
---|
651 | break_label = Label( CodeLocation(), "" );
|
---|
652 | }
|
---|
653 | }
|
---|
654 |
|
---|
655 | if ( ! errors.isEmpty() ) {
|
---|
656 | throw errors;
|
---|
657 | }
|
---|
658 | return ret;
|
---|
659 | }
|
---|
660 |
|
---|
661 | void MultiLevelExitCore::enterSealedContext( ReturnContext enter_context ) {
|
---|
662 | GuardAction([this, old = std::move(enclosing_control_structures)](){ enclosing_control_structures = std::move(old); });
|
---|
663 | enclosing_control_structures = vector<Entry>();
|
---|
664 | GuardValue( ret_context ) = enter_context;
|
---|
665 | }
|
---|
666 |
|
---|
667 | } // namespace
|
---|
668 |
|
---|
669 | const CompoundStmt * multiLevelExitUpdate(
|
---|
670 | const CompoundStmt * stmt, const LabelToStmt & labelTable ) {
|
---|
671 | // Must start in the body, so FunctionDecls can be a stopping point.
|
---|
672 | Pass<MultiLevelExitCore> visitor( labelTable );
|
---|
673 | return stmt->accept( visitor );
|
---|
674 | }
|
---|
675 |
|
---|
676 | } // namespace ControlStruct
|
---|
677 |
|
---|
678 | // Local Variables: //
|
---|
679 | // tab-width: 4 //
|
---|
680 | // mode: c++ //
|
---|
681 | // compile-command: "make install" //
|
---|
682 | // End: //
|
---|