source: src/ControlStruct/ExceptTranslate.cc @ 44f44617

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 44f44617 was 307a732, checked in by Andrew Beach <ajbeach@…>, 7 years ago

The exception handling code compilers and translates, but the translation crashes.

  • Property mode set to 100644
File size: 17.2 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// ExceptVisitor.cc --
8//
9// Author           : Andrew Beach
10// Created On       : Wed Jun 14 16:49:00 2017
11// Last Modified By : Andrew Beach
12// Last Modified On : Fri Jun 30 13:30:00 2017
13// Update Count     : 1
14//
15
16#include "ExceptTranslate.h"
17#include "Common/PassVisitor.h"
18#include "SynTree/Statement.h"
19#include "SynTree/Declaration.h"
20#include "SynTree/Expression.h"
21#include "SynTree/Type.h"
22#include "SynTree/Attribute.h"
23
24namespace ControlStruct {
25
26        // This (large) section could probably be moved out of the class
27        // and be static helpers instead.
28
29        // Type(Qualifiers &, false, std::list<Attribute *> &)
30
31        // void (*function)();
32        static FunctionType try_func_t(Type::Qualifiers(), false);
33        // void (*function)(int, exception);
34        static FunctionType catch_func_t(Type::Qualifiers(), false);
35        // int (*function)(exception);
36        static FunctionType match_func_t(Type::Qualifiers(), false);
37        // bool (*function)(exception);
38        static FunctionType handle_func_t(Type::Qualifiers(), false);
39        // void (*function)(__attribute__((unused)) void *);
40        static FunctionType finally_func_t(Type::Qualifiers(), false);
41
42        static void init_func_types() {
43                static bool init_complete = false;
44                if (init_complete) {
45                        return;
46                }
47                ObjectDecl index_obj(
48                        "__handler_index",
49                        Type::StorageClasses(),
50                        LinkageSpec::Cforall,
51                        /*bitfieldWidth*/ NULL,
52                        new BasicType( emptyQualifiers, BasicType::SignedInt ),
53                        /*init*/ NULL
54                        );
55                ObjectDecl exception_obj(
56                        "__exception_inst",
57                        Type::StorageClasses(),
58                        LinkageSpec::Cforall,
59                        /*bitfieldWidth*/ NULL,
60                        new PointerType(
61                                emptyQualifiers,
62                                new BasicType( emptyQualifiers, BasicType::SignedInt )
63                                ),
64                        /*init*/ NULL
65                        );
66                ObjectDecl bool_obj(
67                        "__ret_bool",
68                        Type::StorageClasses(),
69                        LinkageSpec::Cforall,
70                        /*bitfieldWidth*/ NULL,
71                        new BasicType(emptyQualifiers, BasicType::Bool),
72                        /*init*/ NULL
73                        );
74                ObjectDecl voidptr_obj(
75                        "__hook",
76                        Type::StorageClasses(),
77                        LinkageSpec::Cforall,
78                        NULL,
79                        new PointerType(
80                                emptyQualifiers,
81                                new VoidType(
82                                        emptyQualifiers
83                                        ),
84                                std::list<Attribute *>{new Attribute("unused")}
85                                ),
86                        NULL
87                        );
88
89                catch_func_t.get_parameters().push_back( index_obj.clone() );
90                catch_func_t.get_parameters().push_back( exception_obj.clone() );
91                match_func_t.get_returnVals().push_back( index_obj.clone() );
92                match_func_t.get_parameters().push_back( exception_obj.clone() );
93                handle_func_t.get_returnVals().push_back( bool_obj.clone() );
94                handle_func_t.get_parameters().push_back( exception_obj.clone() );
95                finally_func_t.get_parameters().push_back( voidptr_obj.clone() );
96
97                init_complete = true;
98        }
99
100        // Buricratic Helpers (Not having to do with the paritular operation.)
101
102        typedef std::list<CatchStmt*> CatchList;
103
104        void split( CatchList& allHandlers, CatchList& terHandlers,
105                                CatchList& resHandlers ) {
106                while ( !allHandlers.empty() ) {
107                        CatchStmt * stmt = allHandlers.front();
108                        allHandlers.pop_front();
109                        if (CatchStmt::Terminate == stmt->get_kind()) {
110                                terHandlers.push_back(stmt);
111                        } else {
112                                resHandlers.push_back(stmt);
113                        }
114                }
115        }
116
117        template<typename T>
118        void free_all( std::list<T *> &list ) {
119                typename std::list<T *>::iterator it;
120                for ( it = list.begin() ; it != list.end() ; ++it ) {
121                        delete *it;
122                }
123                list.clear();
124        }
125
126        void appendDeclStmt( CompoundStmt * block, Declaration * item ) {
127                block->push_back(new DeclStmt(noLabels, item));
128        }
129
130        Expression * nameOf( DeclarationWithType * decl ) {
131                return new VariableExpr( decl );
132        }
133
134        // ThrowStmt Mutation Helpers
135
136        Statement * create_given_throw(
137                        const char * throwFunc, ThrowStmt * throwStmt ) {
138                // { int NAME = EXPR; throwFunc( &NAME ); }
139                CompoundStmt * result = new CompoundStmt( noLabels );
140                ObjectDecl * local = new ObjectDecl(
141                        "__local_exception_copy",
142                        Type::StorageClasses(),
143                        LinkageSpec::Cforall,
144                        NULL,
145                        new BasicType( emptyQualifiers, BasicType::SignedInt ),
146                        new SingleInit( throwStmt->get_expr() )
147                        );
148                appendDeclStmt( result, local );
149                UntypedExpr * call = new UntypedExpr( new NameExpr( throwFunc ) );
150                call->get_args().push_back( new AddressExpr( nameOf( local ) ) );
151                result->push_back( new ExprStmt( throwStmt->get_labels(), call ) );
152                throwStmt->set_expr( nullptr );
153                delete throwStmt;
154                return result;
155        }
156
157        Statement * create_terminate_throw( ThrowStmt *throwStmt ) {
158                // { int NAME = EXPR; __throw_terminate( &NAME ); }
159                return create_given_throw( "__cfaehm__throw_termination", throwStmt );
160        }
161        Statement * create_terminate_rethrow( ThrowStmt *throwStmt ) {
162                // __rethrow_terminate();
163                assert( nullptr == throwStmt->get_expr() );
164                Statement * result = new ExprStmt(
165                        throwStmt->get_labels(),
166                        new UntypedExpr( new NameExpr( "__cfaehm__rethrow_termination" ) )
167                        );
168                delete throwStmt;
169                return result;
170        }
171        Statement * create_resume_throw( ThrowStmt *throwStmt ) {
172                // __throw_resume( EXPR );
173                return create_given_throw( "__cfaehm__throw_resumption", throwStmt );
174        }
175        Statement * create_resume_rethrow( ThrowStmt *throwStmt ) {
176                // return false;
177                Statement * result = new ReturnStmt(
178                        throwStmt->get_labels(),
179                        new ConstantExpr( Constant::from_bool( false ) )
180                        );
181                delete throwStmt;
182                return result;
183        }
184
185        // TryStmt Mutation Helpers
186
187        CompoundStmt * take_try_block( TryStmt *tryStmt ) {
188                CompoundStmt * block = tryStmt->get_block();
189                tryStmt->set_block( nullptr );
190                return block;
191        }
192        FunctionDecl * create_try_wrapper( CompoundStmt *body ) {
193
194                return new FunctionDecl( "try", Type::StorageClasses(),
195                        LinkageSpec::Cforall, try_func_t.clone(), body );
196        }
197
198        FunctionDecl * create_terminate_catch( CatchList &handlers ) {
199                std::list<CaseStmt *> handler_wrappers;
200
201                FunctionType *func_type = catch_func_t.clone();
202                DeclarationWithType * index_obj = func_type->get_parameters().front();
203        //      DeclarationWithType * except_obj = func_type->get_parameters().back();
204
205                // Index 1..{number of handlers}
206                int index = 0;
207                CatchList::iterator it = handlers.begin();
208                for ( ; it != handlers.end() ; ++it ) {
209                        ++index;
210                        CatchStmt * handler = *it;
211
212                        // INTEGERconstant Version
213                        // case `index`:
214                        // {
215                        //     `handler.body`
216                        // }
217                        // return;
218                        std::list<Statement *> caseBody;
219                        caseBody.push_back( handler->get_body() );
220                        handler->set_body( nullptr );
221                        caseBody.push_back( new ReturnStmt( noLabels, nullptr ) );
222
223                        handler_wrappers.push_back( new CaseStmt(
224                                noLabels,
225                                new ConstantExpr( Constant::from_int( index ) ),
226                                caseBody
227                                ) );
228                }
229                // TODO: Some sort of meaningful error on default perhaps?
230
231                std::list<Statement*> stmt_handlers;
232                while ( !handler_wrappers.empty() ) {
233                        stmt_handlers.push_back( handler_wrappers.front() );
234                        handler_wrappers.pop_front();
235                }
236
237                SwitchStmt * handler_lookup = new SwitchStmt(
238                        noLabels,
239                        nameOf( index_obj ),
240                        stmt_handlers
241                        );
242                CompoundStmt * body = new CompoundStmt( noLabels );
243                body->push_back( handler_lookup );
244
245                return new FunctionDecl("catch", Type::StorageClasses(),
246                        LinkageSpec::Cforall, func_type, body);
247        }
248
249        // Create a single check from a moddified handler.
250        // except_obj is referenced, modded_handler will be freed.
251        CompoundStmt *create_single_matcher(
252                        DeclarationWithType * except_obj, CatchStmt * modded_handler ) {
253                CompoundStmt * block = new CompoundStmt( noLabels );
254
255                // INTEGERconstant Version
256                assert( nullptr == modded_handler->get_decl() );
257                ConstantExpr * number =
258                        dynamic_cast<ConstantExpr*>( modded_handler->get_cond() );
259                assert( number );
260                modded_handler->set_cond( nullptr );
261
262                Expression * cond;
263                {
264                        std::list<Expression *> args;
265                        args.push_back( number );
266
267                        std::list<Expression *> rhs_args;
268                        rhs_args.push_back( nameOf( except_obj ) );
269                        Expression * rhs = new UntypedExpr(
270                                new NameExpr( "*?" ), rhs_args );
271                        args.push_back( rhs );
272
273                        cond = new UntypedExpr( new NameExpr( "?==?" /*???*/), args );
274                }
275
276                if ( modded_handler->get_cond() ) {
277                        cond = new LogicalExpr( cond, modded_handler->get_cond() );
278                }
279                block->push_back( new IfStmt( noLabels,
280                        cond, modded_handler->get_body(), nullptr ) );
281
282                modded_handler->set_decl( nullptr );
283                modded_handler->set_cond( nullptr );
284                modded_handler->set_body( nullptr );
285                delete modded_handler;
286                return block;
287        }
288
289        FunctionDecl * create_terminate_match( CatchList &handlers ) {
290                CompoundStmt * body = new CompoundStmt( noLabels );
291
292                FunctionType * func_type = match_func_t.clone();
293                DeclarationWithType * except_obj = func_type->get_parameters().back();
294
295                // Index 1..{number of handlers}
296                int index = 0;
297                CatchList::iterator it;
298                for ( it = handlers.begin() ; it != handlers.end() ; ++it ) {
299                        ++index;
300                        CatchStmt * handler = *it;
301
302                        // Body should have been taken by create_terminate_catch.
303                        assert( nullptr == handler->get_body() );
304
305                        // Create new body.
306                        handler->set_body( new ReturnStmt( noLabels,
307                                new ConstantExpr( Constant::from_int( index ) ) ) );
308
309                        // Create the handler.
310                        body->push_back( create_single_matcher( except_obj, handler ) );
311                        *it = nullptr;
312                }
313
314                body->push_back( new ReturnStmt( noLabels, new ConstantExpr(
315                        Constant::from_int( 0 ) ) ) );
316
317                return new FunctionDecl("match", Type::StorageClasses(),
318                        LinkageSpec::Cforall, func_type, body);
319        }
320
321        CompoundStmt * create_terminate_caller(
322                        FunctionDecl * try_wrapper,
323                        FunctionDecl * terminate_catch,
324                        FunctionDecl * terminate_match) {
325
326                UntypedExpr * caller = new UntypedExpr( new NameExpr(
327                        "__cfaehm__try_terminate" ) );
328                std::list<Expression *>& args = caller->get_args();
329                args.push_back( nameOf( try_wrapper ) );
330                args.push_back( nameOf( terminate_catch ) );
331                args.push_back( nameOf( terminate_match ) );
332
333                CompoundStmt * callStmt = new CompoundStmt( noLabels );
334                callStmt->push_back( new ExprStmt( noLabels, caller ) );
335                return callStmt;
336        }
337
338        FunctionDecl * create_resume_handler( CatchList &handlers ) {
339                CompoundStmt * body = new CompoundStmt( noLabels );
340
341                FunctionType * func_type = match_func_t.clone();
342                DeclarationWithType * except_obj = func_type->get_parameters().back();
343
344                CatchList::iterator it;
345                for ( it = handlers.begin() ; it != handlers.end() ; ++it ) {
346                        CatchStmt * handler = *it;
347
348                        // Modifiy body.
349                        CompoundStmt * handling_code =
350                                dynamic_cast<CompoundStmt*>( handler->get_body() );
351                        if ( ! handling_code ) {
352                                handling_code = new CompoundStmt( noLabels );
353                                handling_code->push_back( handler->get_body() );
354                        }
355                        handling_code->push_back( new ReturnStmt( noLabels,
356                                new ConstantExpr( Constant::from_bool( false ) ) ) );
357                        handler->set_body( handling_code );
358
359                        // Create the handler.
360                        body->push_back( create_single_matcher( except_obj, handler ) );
361                        *it = nullptr;
362                }
363
364                return new FunctionDecl("handle", Type::StorageClasses(),
365                        LinkageSpec::Cforall, func_type, body);
366        }
367
368        CompoundStmt * create_resume_wrapper(
369                        StructDecl * node_decl,
370                        Statement * wraps,
371                        FunctionDecl * resume_handler ) {
372                CompoundStmt * body = new CompoundStmt( noLabels );
373
374                // struct __try_resume_node __resume_node
375                //      __attribute__((cleanup( __cfaehm__try_resume_cleanup )));
376                // ** unwinding of the stack here could cause problems **
377                // ** however I don't think that can happen currently **
378                // __cfaehm__try_resume_setup( &__resume_node, resume_handler );
379
380                std::list< Attribute * > attributes;
381                {
382                        std::list< Expression * > attr_params;
383                        attr_params.push_back( new NameExpr(
384                                "__cfaehm__try_resume_cleanup" ) );
385                        attributes.push_back( new Attribute( "cleanup", attr_params ) );
386                }
387
388                ObjectDecl * obj = new ObjectDecl(
389                        "__resume_node",
390                        Type::StorageClasses(),
391                        LinkageSpec::Cforall,
392                        nullptr,
393                        new StructInstType(
394                                Type::Qualifiers(),
395                                node_decl
396                                ),
397                        nullptr,
398                        attributes
399                        );
400                appendDeclStmt( body, obj );
401
402                UntypedExpr *setup = new UntypedExpr( new NameExpr(
403                        "__cfaehm__try_resume_setup" ) );
404                setup->get_args().push_back( new AddressExpr( nameOf( obj ) ) );
405                setup->get_args().push_back( nameOf( resume_handler ) );
406
407                body->push_back( new ExprStmt( noLabels, setup ) );
408
409                body->push_back( wraps );
410                return body;
411        }
412
413        FunctionDecl * create_finally_wrapper( TryStmt * tryStmt ) {
414                FinallyStmt * finally = tryStmt->get_finally();
415                CompoundStmt * body = finally->get_block();
416                finally->set_block( nullptr );
417                delete finally;
418                tryStmt->set_finally( nullptr );
419
420                return new FunctionDecl("finally", Type::StorageClasses(),
421                        LinkageSpec::Cforall, finally_func_t.clone(), body);
422        }
423
424        ObjectDecl * create_finally_hook(
425                        StructDecl * hook_decl, FunctionDecl * finally_wrapper ) {
426                // struct __cfaehm__cleanup_hook __finally_hook
427                //      __attribute__((cleanup( finally_wrapper )));
428
429                // Make Cleanup Attribute.
430                std::list< Attribute * > attributes;
431                {
432                        std::list< Expression * > attr_params;
433                        attr_params.push_back( nameOf( finally_wrapper ) );
434                        attributes.push_back( new Attribute( "cleanup", attr_params ) );
435                }
436
437                return new ObjectDecl(
438                        "__finally_hook",
439                        Type::StorageClasses(),
440                        LinkageSpec::Cforall,
441                        nullptr,
442                        new StructInstType(
443                                emptyQualifiers,
444                                hook_decl
445                                ),
446                        nullptr,
447                        attributes
448                        );
449        }
450
451
452        class ExceptionMutatorCore : public WithGuards {
453                enum Context { NoHandler, TerHandler, ResHandler };
454
455                // Also need to handle goto, break & continue.
456                // They need to be cut off in a ResHandler, until we enter another
457                // loop, switch or the goto stays within the function.
458
459                Context cur_context;
460
461                // We might not need this, but a unique base for each try block's
462                // generated functions might be nice.
463                //std::string curFunctionName;
464                //unsigned int try_count = 0;
465
466                StructDecl *node_decl;
467                StructDecl *hook_decl;
468
469        public:
470                ExceptionMutatorCore() :
471                        cur_context(NoHandler),
472                        node_decl(nullptr), hook_decl(nullptr)
473                {}
474
475                void premutate( CatchStmt *catchStmt );
476                void premutate( StructDecl *structDecl );
477                Statement * postmutate( ThrowStmt *throwStmt );
478                Statement * postmutate( TryStmt *tryStmt );
479        };
480
481        Statement * ExceptionMutatorCore::postmutate( ThrowStmt *throwStmt ) {
482                // Ignoring throwStmt->get_target() for now.
483                if ( ThrowStmt::Terminate == throwStmt->get_kind() ) {
484                        if ( throwStmt->get_expr() ) {
485                                return create_terminate_throw( throwStmt );
486                        } else if ( TerHandler == cur_context ) {
487                                return create_terminate_rethrow( throwStmt );
488                        } else {
489                                assertf(false, "Invalid throw in %s at %i\n",
490                                        throwStmt->location.filename.c_str(),
491                                        throwStmt->location.linenumber);
492                                return nullptr;
493                        }
494                } else {
495                        if ( throwStmt->get_expr() ) {
496                                return create_resume_throw( throwStmt );
497                        } else if ( ResHandler == cur_context ) {
498                                return create_resume_rethrow( throwStmt );
499                        } else {
500                                assertf(false, "Invalid throwResume in %s at %i\n",
501                                        throwStmt->location.filename.c_str(),
502                                        throwStmt->location.linenumber);
503                                return nullptr;
504                        }
505                }
506        }
507
508        Statement * ExceptionMutatorCore::postmutate( TryStmt *tryStmt ) {
509                assert( node_decl );
510                assert( hook_decl );
511
512                // Generate a prefix for the function names?
513
514                CompoundStmt * block = new CompoundStmt( noLabels );
515                CompoundStmt * inner = take_try_block( tryStmt );
516
517                if ( tryStmt->get_finally() ) {
518                        // Define the helper function.
519                        FunctionDecl * finally_block =
520                                create_finally_wrapper( tryStmt );
521                        appendDeclStmt( block, finally_block );
522                        // Create and add the finally cleanup hook.
523                        appendDeclStmt( block,
524                                create_finally_hook( hook_decl, finally_block ) );
525                }
526
527                CatchList termination_handlers;
528                CatchList resumption_handlers;
529                split( tryStmt->get_catchers(),
530                           termination_handlers, resumption_handlers );
531
532                if ( resumption_handlers.size() ) {
533                        // Define the helper function.
534                        FunctionDecl * resume_handler =
535                                create_resume_handler( resumption_handlers );
536                        appendDeclStmt( block, resume_handler );
537                        // Prepare hooks
538                        inner = create_resume_wrapper( node_decl, inner, resume_handler );
539                }
540
541                if ( termination_handlers.size() ) {
542                        // Define the three helper functions.
543                        FunctionDecl * try_wrapper = create_try_wrapper( inner );
544                        appendDeclStmt( block, try_wrapper );
545                        FunctionDecl * terminate_catch =
546                                create_terminate_catch( termination_handlers );
547                        appendDeclStmt( block, terminate_catch );
548                        FunctionDecl * terminate_match =
549                                create_terminate_match( termination_handlers );
550                        appendDeclStmt( block, terminate_match );
551                        // Build the call to the try wrapper.
552                        inner = create_terminate_caller(
553                                try_wrapper, terminate_catch, terminate_match );
554                }
555
556                // Embed the try block.
557                block->push_back( inner );
558
559                //free_all( termination_handlers );
560                //free_all( resumption_handlers );
561
562                return block;
563        }
564
565        void ExceptionMutatorCore::premutate( CatchStmt *catchStmt ) {
566                GuardValue( cur_context );
567                if ( CatchStmt::Terminate == catchStmt->get_kind() ) {
568                        cur_context = TerHandler;
569                } else {
570                        cur_context = ResHandler;
571                }
572        }
573
574        void ExceptionMutatorCore::premutate( StructDecl *structDecl ) {
575                if ( !structDecl->has_body() ) {
576                        // Skip children?
577                        return;
578                } else if ( structDecl->get_name() == "__cfaehm__try_resume_node" ) {
579                        assert( nullptr == node_decl );
580                        node_decl = structDecl;
581                } else if ( structDecl->get_name() == "__cfaehm__cleanup_hook" ) {
582                        assert( nullptr == hook_decl );
583                        hook_decl = structDecl;
584                }
585                // Later we might get the exception type as well.
586        }
587
588        void translateEHM( std::list< Declaration *> & translationUnit ) {
589                init_func_types();
590
591                PassVisitor<ExceptionMutatorCore> translator;
592                for ( Declaration * decl : translationUnit ) {
593                        decl->acceptMutator( translator );
594                }
595        }
596}
Note: See TracBrowser for help on using the repository browser.