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