source: src/ControlStruct/MultiLevelExit.cpp

Last change on this file was 0a6d2045, checked in by Andrew Beach <ajbeach@…>, 4 months ago

You can how use local control flow out of 'catch' clauses. Added a test to show that it works.

  • Property mode set to 100644
File size: 23.4 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        bool isContTarget() const { return kind <= WhileDoStmtK; }
81        bool isBreakTarget() const { return kind != CaseClauseK; }
82        bool isFallTarget() const { return kind == CaseClauseK; }
83        bool isFallDefaultTarget() const { return kind == SwitchStmtK; }
84
85        // These routines set a target as being "used" by a BranchStmt
86        Label useContExit() { assert( kind <= WhileDoStmtK ); return useTarget(secondTarget); }
87        Label useBreakExit() { assert( kind != CaseClauseK ); return useTarget(firstTarget); }
88        Label useFallExit() { assert( kind == CaseClauseK );  return useTarget(firstTarget); }
89        Label useFallDefaultExit() { assert( kind == SwitchStmtK ); return useTarget(secondTarget); }
90
91        // These routines check if a specific label for a statement is used by a BranchStmt
92        bool isContUsed() const { assert( kind <= WhileDoStmtK ); return secondTarget.used; }
93        bool isBreakUsed() const { assert( kind != CaseClauseK ); return firstTarget.used; }
94        bool isFallUsed() const { assert( kind == CaseClauseK ); return firstTarget.used; }
95        bool isFallDefaultUsed() const { assert( kind == SwitchStmtK ); return secondTarget.used; }
96        void seenDefault() { fallDefaultValid = false; }
97        bool isFallDefaultValid() const { return fallDefaultValid; }
98};
99
100// Helper predicates used in find_if calls (it doesn't take methods):
101bool isBreakTarget( const Entry & entry ) {
102        return entry.isBreakTarget();
103}
104
105bool isContinueTarget( const Entry & entry ) {
106        return entry.isContTarget();
107}
108
109bool isFallthroughTarget( const Entry & entry ) {
110        return entry.isFallTarget();
111}
112
113bool isFallthroughDefaultTarget( const Entry & entry ) {
114        return entry.isFallDefaultTarget();
115}
116
117struct MultiLevelExitCore final :
118        public WithVisitorRef<MultiLevelExitCore>,
119        public WithShortCircuiting, public WithGuards {
120        MultiLevelExitCore( const LabelToStmt & lt );
121
122        void previsit( const FunctionDecl * );
123
124        const CompoundStmt * previsit( const CompoundStmt * );
125        const BranchStmt * postvisit( const BranchStmt * );
126        void previsit( const WhileDoStmt * );
127        const WhileDoStmt * postvisit( const WhileDoStmt * );
128        void previsit( const ForStmt * );
129        const ForStmt * postvisit( const ForStmt * );
130        const CaseClause * previsit( const CaseClause * );
131        void previsit( const IfStmt * );
132        const IfStmt * postvisit( const IfStmt * );
133        void previsit( const SwitchStmt * );
134        const SwitchStmt * postvisit( const SwitchStmt * );
135        void previsit( const ReturnStmt * );
136        void previsit( const TryStmt * );
137        void postvisit( const TryStmt * );
138        void previsit( const CatchClause * );
139        void previsit( const FinallyClause * );
140
141        const Stmt * mutateLoop( const Stmt * body, Entry& );
142
143        const LabelToStmt & target_table;
144        set<Label> fallthrough_labels;
145        vector<Entry> enclosing_control_structures;
146        Label break_label;
147        ReturnContext ret_context;
148
149        template<typename LoopNode>
150        void prehandleLoopStmt( const LoopNode * loopStmt );
151        template<typename LoopNode>
152        const LoopNode * posthandleLoopStmt( const LoopNode * loopStmt );
153
154        list<ptr<Stmt>> fixBlock(
155                const list<ptr<Stmt>> & kids, bool caseClause );
156
157        void enterSealedContext( ReturnContext );
158
159        template<typename UnaryPredicate>
160        auto findEnclosingControlStructure( UnaryPredicate pred ) {
161                return find_if( enclosing_control_structures.rbegin(),
162                                                enclosing_control_structures.rend(), pred );
163        }
164};
165
166NullStmt * labelledNullStmt( const CodeLocation & cl, const Label & label ) {
167        return new NullStmt( cl, vector<Label>{ label } );
168}
169
170MultiLevelExitCore::MultiLevelExitCore( const LabelToStmt & lt ) :
171        target_table( lt ), break_label( CodeLocation(), "" ),
172        ret_context( ReturnContext::MayReturn )
173{}
174
175void MultiLevelExitCore::previsit( const FunctionDecl * ) {
176        visit_children = false;
177}
178
179const CompoundStmt * MultiLevelExitCore::previsit(
180                const CompoundStmt * stmt ) {
181        visit_children = false;
182
183        // if the stmt is labelled then generate a label to check in postvisit if the label is used
184        bool isLabeled = ! stmt->labels.empty();
185        if ( isLabeled ) {
186                Label breakLabel = newLabel( "blockBreak", stmt );
187                enclosing_control_structures.emplace_back( stmt, breakLabel );
188                GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
189        }
190
191        auto mutStmt = mutate( stmt );
192        // A child statement may set the break label.
193        mutStmt->kids = fixBlock( stmt->kids, false );
194
195        if ( isLabeled ) {
196                assert( ! enclosing_control_structures.empty() );
197                Entry & entry = enclosing_control_structures.back();
198                if ( ! entry.useBreakExit().empty() ) {
199                        break_label = entry.useBreakExit();
200                }
201        }
202        return mutStmt;
203}
204
205size_t getUnusedIndex( const Stmt * stmt, const Label & originalTarget ) {
206        const size_t size = stmt->labels.size();
207
208        // If the label is empty, do not add unused attribute.
209  if ( originalTarget.empty() ) return size;
210
211        // Search for a label that matches the originalTarget.
212        for ( size_t i = 0 ; i < size ; ++i ) {
213                const Label & label = stmt->labels[i];
214                if ( label == originalTarget ) {
215                        for ( const Attribute * attr : label.attributes ) {
216                                if ( attr->name == "unused" ) return size;
217                        }
218                        return i;
219                }
220        }
221        assertf( false, "CFA internal error: could not find label '%s' on statement %s",
222                         originalTarget.name.c_str(), toString( stmt ).c_str() );
223}
224
225const Stmt * addUnused( const Stmt * stmt, const Label & originalTarget ) {
226        size_t i = getUnusedIndex( stmt, originalTarget );
227        if ( i == stmt->labels.size() ) {
228                return stmt;
229        }
230        Stmt * mutStmt = mutate( stmt );
231        mutStmt->labels[i].attributes.push_back( new Attribute( "unused" ) );
232        return mutStmt;
233}
234
235// This routine updates targets on enclosing control structures to indicate which
236//     label is used by the BranchStmt that is passed
237const BranchStmt * MultiLevelExitCore::postvisit( const BranchStmt * stmt ) {
238        vector<Entry>::reverse_iterator targetEntry =
239                enclosing_control_structures.rend();
240
241        // Labels on different stmts require different approaches to access
242        switch ( stmt->kind ) {
243        case BranchStmt::Goto:
244                return stmt;
245        case BranchStmt::Continue:
246        case BranchStmt::Break: {
247                bool isContinue = stmt->kind == BranchStmt::Continue;
248                // Handle unlabeled break and continue.
249                if ( stmt->target.empty() ) {
250                        if ( isContinue ) {
251                                targetEntry = findEnclosingControlStructure( isContinueTarget );
252                        } else {
253                                if ( enclosing_control_structures.empty() ) {
254                                          SemanticError( stmt->location,
255                                                                         "\"break\" outside a loop, \"switch\", or labelled block" );
256                                }
257                                targetEntry = findEnclosingControlStructure( isBreakTarget );
258                        }
259                        // Handle labeled break and continue.
260                } else {
261                        // Lookup label in table to find attached control structure.
262                        targetEntry = findEnclosingControlStructure(
263                                [ targetStmt = target_table.at(stmt->target) ](auto entry){
264                                          return entry.stmt == targetStmt;
265                                } );
266                }
267                // Ensure that selected target is valid.
268                if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && ! isContinueTarget( *targetEntry ) ) ) {
269                        SemanticError( stmt->location, toString( (isContinue ? "\"continue\"" : "\"break\""),
270                                                        " target must be an enclosing ", (isContinue ? "loop: " : "control structure: "),
271                                                        stmt->originalTarget ) );
272                }
273                break;
274        }
275        // handle fallthrough in case/switch stmts
276        case BranchStmt::FallThrough: {
277                targetEntry = findEnclosingControlStructure( isFallthroughTarget );
278                // Check that target is valid.
279                if ( targetEntry == enclosing_control_structures.rend() ) {
280                        SemanticError( stmt->location, "\"fallthrough\" must be enclosed in a \"switch\" or \"choose\"" );
281                }
282                if ( ! stmt->target.empty() ) {
283                        // Labelled fallthrough: target must be a valid fallthough label.
284                        if ( ! fallthrough_labels.count( stmt->target ) ) {
285                                SemanticError( stmt->location, toString( "\"fallthrough\" target must be a later case statement: ",
286                                                                                                                   stmt->originalTarget ) );
287                        }
288                        return new BranchStmt( stmt->location, BranchStmt::Goto, stmt->originalTarget );
289                }
290                break;
291        }
292        case BranchStmt::FallThroughDefault: {
293                targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
294
295                // Check if in switch or choose statement.
296                if ( targetEntry == enclosing_control_structures.rend() ) {
297                        SemanticError( stmt->location, "\"fallthrough\" must be enclosed in a \"switch\" or \"choose\"" );
298                }
299
300                // Check if switch or choose has default clause.
301                auto switchStmt = strict_dynamic_cast< const SwitchStmt * >( targetEntry->stmt );
302                bool foundDefault = false;
303                for ( auto caseStmt : switchStmt->cases ) {
304                        if ( caseStmt->isDefault() ) {
305                                foundDefault = true;
306                                break;
307                        }
308                }
309                if ( ! foundDefault ) {
310                        SemanticError( stmt->location, "\"fallthrough default\" must be enclosed in a \"switch\" or \"choose\""
311                                                   "control structure with a \"default\" clause" );
312                }
313                break;
314        }
315        default:
316                assert( false );
317        }
318
319        // Branch error checks: get the appropriate label name, which is always replaced.
320        Label exitLabel( CodeLocation(), "" );
321        switch ( stmt->kind ) {
322        case BranchStmt::Break:
323                assert( ! targetEntry->useBreakExit().empty() );
324                exitLabel = targetEntry->useBreakExit();
325                break;
326        case BranchStmt::Continue:
327                assert( ! targetEntry->useContExit().empty() );
328                exitLabel = targetEntry->useContExit();
329                break;
330        case BranchStmt::FallThrough:
331                assert( ! targetEntry->useFallExit().empty() );
332                exitLabel = targetEntry->useFallExit();
333                break;
334        case BranchStmt::FallThroughDefault:
335                assert( ! targetEntry->useFallDefaultExit().empty() );
336                exitLabel = targetEntry->useFallDefaultExit();
337                // Check that fallthrough default comes before the default clause.
338                if ( ! targetEntry->isFallDefaultValid() ) {
339                        SemanticError( stmt->location, "\"fallthrough default\" must precede the \"default\" clause" );
340                }
341                break;
342        default:
343                assert(0);
344        }
345
346        // Add unused attribute to silence warnings.
347        targetEntry->stmt = addUnused( targetEntry->stmt, stmt->originalTarget );
348
349        // Replace with goto to make later passes more uniform.
350        return new BranchStmt( stmt->location, BranchStmt::Goto, exitLabel );
351}
352
353void MultiLevelExitCore::previsit( const WhileDoStmt * stmt ) {
354        return prehandleLoopStmt( stmt );
355}
356
357const WhileDoStmt * MultiLevelExitCore::postvisit( const WhileDoStmt * stmt ) {
358        return posthandleLoopStmt( stmt );
359}
360
361void MultiLevelExitCore::previsit( const ForStmt * stmt ) {
362        return prehandleLoopStmt( stmt );
363}
364
365const ForStmt * MultiLevelExitCore::postvisit( const ForStmt * stmt ) {
366        return posthandleLoopStmt( stmt );
367}
368
369// Mimic what the built-in push_front would do anyways. It is O(n).
370void push_front( vector<ptr<Stmt>> & vec, const Stmt * element ) {
371        vec.emplace_back( nullptr );
372        for ( size_t i = vec.size() - 1 ; 0 < i ; --i ) {
373                vec[ i ] = std::move( vec[ i - 1 ] );
374        }
375        vec[ 0 ] = element;
376}
377
378const CaseClause * MultiLevelExitCore::previsit( const CaseClause * stmt ) {
379        visit_children = false;
380
381        // If default, mark seen.
382        if ( stmt->isDefault() ) {
383                assert( ! enclosing_control_structures.empty() );
384                enclosing_control_structures.back().seenDefault();
385        }
386
387        // The cond may not exist, but if it does update it now.
388        visitor->maybe_accept( stmt, &CaseClause::cond );
389
390        // Just save the mutated node for simplicity.
391        CaseClause * mutStmt = mutate( stmt );
392
393        Label fallLabel = newLabel( "fallThrough", stmt->location );
394        if ( ! mutStmt->stmts.empty() ) {
395                // These should already be in a block.
396                auto first = mutStmt->stmts.front().get_and_mutate();
397                auto block = strict_dynamic_cast<CompoundStmt *>( first );
398
399                // Ensure that the stack isn't corrupted by exceptions in fixBlock.
400                auto guard = makeFuncGuard(
401                        [&](){ enclosing_control_structures.emplace_back( mutStmt, block, fallLabel ); },
402                        [this](){ enclosing_control_structures.pop_back(); }
403                        );
404
405                block->kids = fixBlock( block->kids, true );
406
407                // Add fallthrough label if necessary.
408                assert( ! enclosing_control_structures.empty() );
409                Entry & entry = enclosing_control_structures.back();
410                if ( entry.isFallUsed() ) {
411                        mutStmt->stmts.push_back( labelledNullStmt( block->location, entry.useFallExit() ) );
412                }
413        }
414        assert( ! enclosing_control_structures.empty() );
415        Entry & entry = enclosing_control_structures.back();
416        assertf( dynamic_cast< const SwitchStmt * >( entry.stmt ),
417                         "CFA internal error: control structure enclosing a case clause must be a switch, but is: %s",
418                         toString( entry.stmt ).c_str() );
419        if ( mutStmt->isDefault() ) {
420                if ( entry.isFallDefaultUsed() ) {
421                        // Add fallthrough default label if necessary.
422                        push_front( mutStmt->stmts, labelledNullStmt( stmt->location, entry.useFallDefaultExit() ) );
423                }
424        }
425        return mutStmt;
426}
427
428void MultiLevelExitCore::previsit( const IfStmt * stmt ) {
429        bool labeledBlock = ! stmt->labels.empty();
430        if ( labeledBlock ) {
431                Label breakLabel = newLabel( "blockBreak", stmt );
432                enclosing_control_structures.emplace_back( stmt, breakLabel );
433                GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
434        }
435}
436
437const IfStmt * MultiLevelExitCore::postvisit( const IfStmt * stmt ) {
438        bool labeledBlock = ! stmt->labels.empty();
439        if ( labeledBlock ) {
440                auto this_label = enclosing_control_structures.back().useBreakExit();
441                if ( ! this_label.empty() ) {
442                        break_label = this_label;
443                }
444        }
445        return stmt;
446}
447
448static bool isDefaultCase( const ptr<CaseClause> & caseClause ) {
449        return caseClause->isDefault();
450}
451
452void MultiLevelExitCore::previsit( const SwitchStmt * stmt ) {
453        Label label = newLabel( "switchBreak", stmt );
454        auto it = find_if( stmt->cases.rbegin(), stmt->cases.rend(), isDefaultCase );
455
456        const CaseClause * defaultCase = it != stmt->cases.rend() ? (*it) : nullptr;
457        Label defaultLabel = defaultCase ? newLabel( "fallThroughDefault", defaultCase->location ) : Label( stmt->location, "" );
458        enclosing_control_structures.emplace_back( stmt, label, defaultLabel );
459        GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
460
461        // Collect valid labels for fallthrough. It starts with all labels at this level, then remove as each is seen during
462        // traversal.
463        for ( const CaseClause * caseStmt : stmt->cases ) {
464                if ( caseStmt->stmts.empty() ) continue;
465                auto block = caseStmt->stmts.front().strict_as<CompoundStmt>();
466                for ( const Stmt * stmt : block->kids ) {
467                        for ( const Label & l : stmt->labels ) {
468                                fallthrough_labels.insert( l );
469                        }
470                }
471        }
472}
473
474const SwitchStmt * MultiLevelExitCore::postvisit( const SwitchStmt * stmt ) {
475        assert( ! enclosing_control_structures.empty() );
476        Entry & entry = enclosing_control_structures.back();
477        assert( entry.stmt == stmt );
478
479        // Only run to generate the break label.
480        if ( entry.isBreakUsed() ) {
481                // To keep the switch statements uniform (all direct children of a SwitchStmt should be CastStmts), append the
482                // exit label and break to the last case, create a default case if no cases.
483                SwitchStmt * mutStmt = mutate( stmt );
484                if ( mutStmt->cases.empty() ) {
485                        mutStmt->cases.push_back( new CaseClause( mutStmt->location, nullptr, {} ) );
486                }
487
488                auto caseStmt = mutStmt->cases.back().get();
489                auto mutCase = mutate( caseStmt );
490                mutStmt->cases.back() = mutCase;
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        // Remember is loop before going onto mutate the body.
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        // labels are added temporarily to see if they are used and then added permanently in postvisit if ther are used
605        // children will tag labels as being used during their traversal which occurs before postvisit
606
607        // GuardAction calls the lambda after the node is done being visited
608        GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
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        // this call to mutate_field compares loopStmt->body and the result of mutateLoop
620        //              if they are the same the node isn't mutated, if they differ then the new mutated node is returned
621        //              the stmts will only differ if a label is used
622}
623
624list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
625        const list<ptr<Stmt>> & kids, bool is_case_clause ) {
626        // Unfortunately cannot use automatic error collection.
627        SemanticErrorException errors;
628
629        list<ptr<Stmt>> ret;
630
631        // Manually visit each child.
632        for ( const ptr<Stmt> & kid : kids ) {
633                if ( is_case_clause ) {
634                        // Once a label is seen, it's no longer a valid for fallthrough.
635                        for ( const Label & l : kid->labels ) {
636                                fallthrough_labels.erase( l );
637                        }
638                }
639
640                ptr<Stmt> else_stmt = nullptr;
641                const Stmt * loop_kid = nullptr;
642                // check if loop node and if so add else clause if it exists
643                const WhileDoStmt * whilePtr = kid.as<WhileDoStmt>();
644                if ( whilePtr && whilePtr->else_ ) {
645                        else_stmt = whilePtr->else_;
646                        loop_kid = mutate_field( whilePtr, &WhileDoStmt::else_, nullptr );
647                }
648                const ForStmt * forPtr = kid.as<ForStmt>();
649                if ( forPtr && forPtr->else_ ) {
650                        else_stmt = forPtr->else_;
651                        loop_kid = mutate_field( forPtr, &ForStmt::else_, nullptr );
652                }
653
654                try {
655                        if (else_stmt) ret.push_back( loop_kid->accept( *visitor ) );
656                        else ret.push_back( kid->accept( *visitor ) );
657                } catch ( SemanticErrorException & e ) {
658                        errors.append( e );
659                }
660
661                if (else_stmt) ret.push_back(else_stmt);
662
663                if ( ! break_label.empty() ) {
664                        ret.push_back( labelledNullStmt( ret.back()->location, break_label ) );
665                        break_label = Label( CodeLocation(), "" );
666                }
667        }
668
669        if ( ! errors.isEmpty() ) {
670                throw errors;
671        }
672        return ret;
673}
674
675void MultiLevelExitCore::enterSealedContext( ReturnContext enter_context ) {
676        GuardAction([this, old = std::move(enclosing_control_structures)](){ enclosing_control_structures = std::move(old); });
677        enclosing_control_structures = vector<Entry>();
678        GuardValue( ret_context ) = enter_context;
679}
680
681} // namespace
682
683const CompoundStmt * multiLevelExitUpdate(
684                const CompoundStmt * stmt, const LabelToStmt & labelTable ) {
685        // Must start in the body, so FunctionDecls can be a stopping point.
686        Pass<MultiLevelExitCore> visitor( labelTable );
687        return stmt->accept( visitor );
688}
689
690} // namespace ControlStruct
691
692// Local Variables: //
693// tab-width: 4 //
694// mode: c++ //
695// compile-command: "make install" //
696// End: //
Note: See TracBrowser for help on using the repository browser.