source: src/Concurrency/Keywords.cc @ 8d7bef2

new-envwith_gc
Last change on this file since 8d7bef2 was 8d7bef2, checked in by Aaron Moss <a3moss@…>, 6 years ago

First compiling build of CFA-CC with GC

  • Property mode set to 100644
File size: 19.8 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2016 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// Keywords.cc --
8//
9// Author           : Thierry Delisle
10// Created On       : Mon Mar 13 12:41:22 2017
11// Last Modified By :
12// Last Modified On :
13// Update Count     : 5
14//
15
16#include "Concurrency/Keywords.h"
17
18#include <cassert>                 // for assert
19#include <string>                  // for string, operator==
20
21#include "Common/PassVisitor.h"    // for PassVisitor
22#include "Common/SemanticError.h"  // for SemanticError
23#include "Common/utility.h"        // for deleteAll, map_range
24#include "CodeGen/OperatorTable.h" // for isConstructor
25#include "InitTweak/InitTweak.h"   // for getPointerBase
26#include "Parser/LinkageSpec.h"    // for Cforall
27#include "SynTree/Constant.h"      // for Constant
28#include "SynTree/Declaration.h"   // for StructDecl, FunctionDecl, ObjectDecl
29#include "SynTree/Expression.h"    // for VariableExpr, ConstantExpr, Untype...
30#include "SynTree/Initializer.h"   // for SingleInit, ListInit, Initializer ...
31#include "SynTree/Label.h"         // for Label
32#include "SynTree/Statement.h"     // for CompoundStmt, DeclStmt, ExprStmt
33#include "SynTree/Type.h"          // for StructInstType, Type, PointerType
34#include "SynTree/Visitor.h"       // for Visitor, acceptAll
35
36class Attribute;
37
38namespace Concurrency {
39        //=============================================================================================
40        // Pass declarations
41        //=============================================================================================
42
43        //-----------------------------------------------------------------------------
44        //Handles sue type declarations :
45        // sue MyType {                             struct MyType {
46        //      int data;                                  int data;
47        //      a_struct_t more_data;                      a_struct_t more_data;
48        //                                =>             NewField_t newField;
49        // };                                        };
50        //                                           static inline NewField_t * getter_name( MyType * this ) { return &this->newField; }
51        //
52        class ConcurrentSueKeyword : public WithDeclsToAdd {
53          public:
54
55                ConcurrentSueKeyword( std::string&& type_name, std::string&& field_name, std::string&& getter_name, std::string&& context_error, bool needs_main ) :
56                  type_name( type_name ), field_name( field_name ), getter_name( getter_name ), context_error( context_error ), needs_main( needs_main ) {}
57
58                virtual ~ConcurrentSueKeyword() {}
59
60                void postvisit( StructDecl * decl );
61
62                void handle( StructDecl * );
63                FunctionDecl * forwardDeclare( StructDecl * );
64                ObjectDecl * addField( StructDecl * );
65                void addRoutines( ObjectDecl *, FunctionDecl * );
66
67                virtual bool is_target( StructDecl * decl ) = 0;
68
69          private:
70                const std::string type_name;
71                const std::string field_name;
72                const std::string getter_name;
73                const std::string context_error;
74                bool needs_main;
75
76                StructDecl* type_decl = nullptr;
77        };
78
79
80        //-----------------------------------------------------------------------------
81        //Handles thread type declarations :
82        // thread Mythread {                         struct MyThread {
83        //      int data;                                  int data;
84        //      a_struct_t more_data;                      a_struct_t more_data;
85        //                                =>             thread_desc __thrd_d;
86        // };                                        };
87        //                                           static inline thread_desc * get_thread( MyThread * this ) { return &this->__thrd_d; }
88        //
89        class ThreadKeyword final : public ConcurrentSueKeyword {
90          public:
91
92                ThreadKeyword() : ConcurrentSueKeyword(
93                        "thread_desc",
94                        "__thrd",
95                        "get_thread",
96                        "thread keyword requires threads to be in scope, add #include <thread>",
97                        true
98                )
99                {}
100
101                virtual ~ThreadKeyword() {}
102
103                virtual bool is_target( StructDecl * decl ) override final { return decl->is_thread(); }
104
105                static void implement( std::list< Declaration * > & translationUnit ) {
106                        PassVisitor< ThreadKeyword > impl;
107                        acceptAll( translationUnit, impl );
108                }
109        };
110
111        //-----------------------------------------------------------------------------
112        //Handles coroutine type declarations :
113        // coroutine MyCoroutine {                   struct MyCoroutine {
114        //      int data;                                  int data;
115        //      a_struct_t more_data;                      a_struct_t more_data;
116        //                                =>             coroutine_desc __cor_d;
117        // };                                        };
118        //                                           static inline coroutine_desc * get_coroutine( MyCoroutine * this ) { return &this->__cor_d; }
119        //
120        class CoroutineKeyword final : public ConcurrentSueKeyword {
121          public:
122
123                CoroutineKeyword() : ConcurrentSueKeyword(
124                        "coroutine_desc",
125                        "__cor",
126                        "get_coroutine",
127                        "coroutine keyword requires coroutines to be in scope, add #include <coroutine>",
128                        true
129                )
130                {}
131
132                virtual ~CoroutineKeyword() {}
133
134                virtual bool is_target( StructDecl * decl ) override final { return decl->is_coroutine(); }
135
136                static void implement( std::list< Declaration * > & translationUnit ) {
137                        PassVisitor< CoroutineKeyword > impl;
138                        acceptAll( translationUnit, impl );
139                }
140        };
141
142        //-----------------------------------------------------------------------------
143        //Handles monitor type declarations :
144        // monitor MyMonitor {                       struct MyMonitor {
145        //      int data;                                  int data;
146        //      a_struct_t more_data;                      a_struct_t more_data;
147        //                                =>             monitor_desc __mon_d;
148        // };                                        };
149        //                                           static inline monitor_desc * get_coroutine( MyMonitor * this ) { return &this->__cor_d; }
150        //
151        class MonitorKeyword final : public ConcurrentSueKeyword {
152          public:
153
154                MonitorKeyword() : ConcurrentSueKeyword(
155                        "monitor_desc",
156                        "__mon",
157                        "get_monitor",
158                        "monitor keyword requires monitors to be in scope, add #include <monitor>",
159                        false
160                )
161                {}
162
163                virtual ~MonitorKeyword() {}
164
165                virtual bool is_target( StructDecl * decl ) override final { return decl->is_monitor(); }
166
167                static void implement( std::list< Declaration * > & translationUnit ) {
168                        PassVisitor< MonitorKeyword > impl;
169                        acceptAll( translationUnit, impl );
170                }
171        };
172
173        //-----------------------------------------------------------------------------
174        //Handles mutex routines definitions :
175        // void foo( A * mutex a, B * mutex b,  int i ) {                  void foo( A * a, B * b,  int i ) {
176        //                                                                       monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
177        //                                                                       monitor_guard_t __guard = { __monitors, 2 };
178        //    /*Some code*/                                       =>           /*Some code*/
179        // }                                                               }
180        //
181        class MutexKeyword final {
182          public:
183
184                void postvisit( FunctionDecl * decl );
185                void postvisit(   StructDecl * decl );
186
187                std::list<DeclarationWithType*> findMutexArgs( FunctionDecl* );
188                void validate( DeclarationWithType * );
189                void addDtorStatments( FunctionDecl* func, CompoundStmt *, const std::list<DeclarationWithType * > &);
190                void addStatments( FunctionDecl* func, CompoundStmt *, const std::list<DeclarationWithType * > &);
191
192                static void implement( std::list< Declaration * > & translationUnit ) {
193                        PassVisitor< MutexKeyword > impl;
194                        acceptAll( translationUnit, impl );
195                }
196
197          private:
198                StructDecl* monitor_decl = nullptr;
199                StructDecl* guard_decl = nullptr;
200                StructDecl* dtor_guard_decl = nullptr;
201
202                static Type* generic_func;
203        };
204
205        Type* MutexKeyword::generic_func = new FunctionType{ noQualifiers, true };
206
207        //-----------------------------------------------------------------------------
208        //Handles mutex routines definitions :
209        // void foo( A * mutex a, B * mutex b,  int i ) {                  void foo( A * a, B * b,  int i ) {
210        //                                                                       monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
211        //                                                                       monitor_guard_t __guard = { __monitors, 2 };
212        //    /*Some code*/                                       =>           /*Some code*/
213        // }                                                               }
214        //
215        class ThreadStarter final {
216          public:
217
218                void postvisit( FunctionDecl * decl );
219                void previsit ( StructDecl   * decl );
220
221                void addStartStatement( FunctionDecl * decl, DeclarationWithType * param );
222
223                static void implement( std::list< Declaration * > & translationUnit ) {
224                        PassVisitor< ThreadStarter > impl;
225                        acceptAll( translationUnit, impl );
226                }
227
228          private :
229                bool thread_ctor_seen = false;
230                StructDecl * thread_decl = nullptr;
231        };
232
233        //=============================================================================================
234        // General entry routine
235        //=============================================================================================
236        void applyKeywords( std::list< Declaration * > & translationUnit ) {
237                ThreadKeyword   ::implement( translationUnit );
238                CoroutineKeyword        ::implement( translationUnit );
239                MonitorKeyword  ::implement( translationUnit );
240        }
241
242        void implementMutexFuncs( std::list< Declaration * > & translationUnit ) {
243                MutexKeyword    ::implement( translationUnit );
244        }
245
246        void implementThreadStarter( std::list< Declaration * > & translationUnit ) {
247                ThreadStarter   ::implement( translationUnit );
248        }
249
250        //=============================================================================================
251        // Generic keyword implementation
252        //=============================================================================================
253        void fixupGenerics(FunctionType * func, StructDecl * decl) {
254                cloneAll(decl->parameters, func->forall);
255                for ( TypeDecl * td : func->forall ) {
256                        strict_dynamic_cast<StructInstType*>(
257                                func->parameters.front()->get_type()->stripReferences()
258                        )->parameters.push_back(
259                                new TypeExpr( new TypeInstType( noQualifiers, td->name, td ) )
260                        );
261                }
262        }
263
264        void ConcurrentSueKeyword::postvisit(StructDecl * decl) {
265                if( decl->name == type_name && decl->body ) {
266                        assert( !type_decl );
267                        type_decl = decl;
268                }
269                else if ( is_target(decl) ) {
270                        handle( decl );
271                }
272        }
273
274        void ConcurrentSueKeyword::handle( StructDecl * decl ) {
275                if( ! decl->body ) return;
276
277                if( !type_decl ) SemanticError( decl, context_error );
278
279                FunctionDecl * func = forwardDeclare( decl );
280                ObjectDecl * field = addField( decl );
281                addRoutines( field, func );
282        }
283
284        FunctionDecl * ConcurrentSueKeyword::forwardDeclare( StructDecl * decl ) {
285
286                StructDecl * forward = decl->clone();
287                forward->set_body( false );
288                forward->get_members().clear();
289
290                FunctionType * get_type = new FunctionType( noQualifiers, false );
291                ObjectDecl * this_decl = new ObjectDecl(
292                        "this",
293                        noStorageClasses,
294                        LinkageSpec::Cforall,
295                        nullptr,
296                        new ReferenceType(
297                                noQualifiers,
298                                new StructInstType(
299                                        noQualifiers,
300                                        decl
301                                )
302                        ),
303                        nullptr
304                );
305
306                get_type->get_parameters().push_back( this_decl->clone() );
307                get_type->get_returnVals().push_back(
308                        new ObjectDecl(
309                                "ret",
310                                noStorageClasses,
311                                LinkageSpec::Cforall,
312                                nullptr,
313                                new PointerType(
314                                        noQualifiers,
315                                        new StructInstType(
316                                                noQualifiers,
317                                                type_decl
318                                        )
319                                ),
320                                nullptr
321                        )
322                );
323                fixupGenerics(get_type, decl);
324
325                FunctionDecl * get_decl = new FunctionDecl(
326                        getter_name,
327                        Type::Static,
328                        LinkageSpec::Cforall,
329                        get_type,
330                        nullptr,
331                        noAttributes,
332                        Type::Inline
333                );
334
335                FunctionDecl * main_decl = nullptr;
336
337                if( needs_main ) {
338                        FunctionType * main_type = new FunctionType( noQualifiers, false );
339
340                        main_type->get_parameters().push_back( this_decl->clone() );
341
342                        main_decl = new FunctionDecl(
343                                "main",
344                                noStorageClasses,
345                                LinkageSpec::Cforall,
346                                main_type,
347                                nullptr
348                        );
349                        fixupGenerics(main_type, decl);
350                }
351
352                declsToAddBefore.push_back( forward );
353                if( needs_main ) declsToAddBefore.push_back( main_decl );
354                declsToAddBefore.push_back( get_decl );
355
356                return get_decl;
357        }
358
359        ObjectDecl * ConcurrentSueKeyword::addField( StructDecl * decl ) {
360                ObjectDecl * field = new ObjectDecl(
361                        field_name,
362                        noStorageClasses,
363                        LinkageSpec::Cforall,
364                        nullptr,
365                        new StructInstType(
366                                noQualifiers,
367                                type_decl
368                        ),
369                        nullptr
370                );
371
372                decl->get_members().push_back( field );
373
374                return field;
375        }
376
377        void ConcurrentSueKeyword::addRoutines( ObjectDecl * field, FunctionDecl * func ) {
378                CompoundStmt * statement = new CompoundStmt();
379                statement->push_back(
380                        new ReturnStmt(
381                                new AddressExpr(
382                                        new MemberExpr(
383                                                field,
384                                                new CastExpr(
385                                                        new VariableExpr( func->get_functionType()->get_parameters().front() ),
386                                                        func->get_functionType()->get_parameters().front()->get_type()->stripReferences()->clone()
387                                                )
388                                        )
389                                )
390                        )
391                );
392
393                FunctionDecl * get_decl = func->clone();
394
395                get_decl->set_statements( statement );
396
397                declsToAddAfter.push_back( get_decl );
398
399                // get_decl->fixUniqueId();
400        }
401
402        //=============================================================================================
403        // Mutex keyword implementation
404        //=============================================================================================
405
406        void MutexKeyword::postvisit(FunctionDecl* decl) {
407
408                std::list<DeclarationWithType*> mutexArgs = findMutexArgs( decl );
409                if( mutexArgs.empty() ) return;
410
411                if( CodeGen::isConstructor(decl->name) ) SemanticError( decl, "constructors cannot have mutex parameters" );
412
413                bool isDtor = CodeGen::isDestructor( decl->name );
414
415                if( isDtor && mutexArgs.size() != 1 ) SemanticError( decl, "destructors can only have 1 mutex argument" );
416
417                for(auto arg : mutexArgs) {
418                        validate( arg );
419                }
420
421                CompoundStmt* body = decl->get_statements();
422                if( ! body ) return;
423
424                if( !monitor_decl || !guard_decl || !dtor_guard_decl )
425                        SemanticError( decl, "mutex keyword requires monitors to be in scope, add #include <monitor>" );
426
427                if( isDtor ) {
428                        addDtorStatments( decl, body, mutexArgs );
429                }
430                else {
431                        addStatments( decl, body, mutexArgs );
432                }
433        }
434
435        void MutexKeyword::postvisit(StructDecl* decl) {
436
437                if( decl->name == "monitor_desc" ) {
438                        assert( !monitor_decl );
439                        monitor_decl = decl;
440                }
441                else if( decl->name == "monitor_guard_t" ) {
442                        assert( !guard_decl );
443                        guard_decl = decl;
444                }
445                else if( decl->name == "monitor_dtor_guard_t" ) {
446                        assert( !dtor_guard_decl );
447                        dtor_guard_decl = decl;
448                }
449        }
450
451        std::list<DeclarationWithType*> MutexKeyword::findMutexArgs( FunctionDecl* decl ) {
452                std::list<DeclarationWithType*> mutexArgs;
453
454                for( auto arg : decl->get_functionType()->get_parameters()) {
455                        //Find mutex arguments
456                        Type* ty = arg->get_type();
457                        if( ! ty->get_mutex() ) continue;
458
459                        //Append it to the list
460                        mutexArgs.push_back( arg );
461                }
462
463                return mutexArgs;
464        }
465
466        void MutexKeyword::validate( DeclarationWithType * arg ) {
467                Type* ty = arg->get_type();
468
469                //Makes sure it's not a copy
470                ReferenceType* rty = dynamic_cast< ReferenceType * >( ty );
471                if( ! rty ) SemanticError( arg, "Mutex argument must be of reference type " );
472
473                //Make sure the we are pointing directly to a type
474                Type* base = rty->get_base();
475                if( dynamic_cast< ReferenceType * >( base ) ) SemanticError( arg, "Mutex argument have exactly one level of indirection " );
476                if( dynamic_cast< PointerType * >( base ) ) SemanticError( arg, "Mutex argument have exactly one level of indirection " );
477
478                //Make sure that typed isn't mutex
479                if( base->get_mutex() ) SemanticError( arg, "mutex keyword may only appear once per argument " );
480        }
481
482        void MutexKeyword::addDtorStatments( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args ) {
483                Type * arg_type = args.front()->get_type()->clone();
484                arg_type->set_mutex( false );
485
486                ObjectDecl * monitors = new ObjectDecl(
487                        "__monitor",
488                        noStorageClasses,
489                        LinkageSpec::Cforall,
490                        nullptr,
491                        new PointerType(
492                                noQualifiers,
493                                new StructInstType(
494                                        noQualifiers,
495                                        monitor_decl
496                                )
497                        ),
498                        new SingleInit( new UntypedExpr(
499                                new NameExpr( "get_monitor" ),
500                                {  new CastExpr( new VariableExpr( args.front() ), arg_type ) }
501                        ))
502                );
503
504                assert(generic_func);
505
506                //in reverse order :
507                // monitor_guard_t __guard = { __monitors, #, func };
508                body->push_front(
509                        new DeclStmt( new ObjectDecl(
510                                "__guard",
511                                noStorageClasses,
512                                LinkageSpec::Cforall,
513                                nullptr,
514                                new StructInstType(
515                                        noQualifiers,
516                                        dtor_guard_decl
517                                ),
518                                new ListInit(
519                                        {
520                                                new SingleInit( new AddressExpr( new VariableExpr( monitors ) ) ),
521                                                new SingleInit( new CastExpr( new VariableExpr( func ), generic_func->clone() ) )
522                                        },
523                                        noDesignators,
524                                        true
525                                )
526                        ))
527                );
528
529                //monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
530                body->push_front( new DeclStmt( monitors) );
531        }
532
533        void MutexKeyword::addStatments( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args ) {
534                ObjectDecl * monitors = new ObjectDecl(
535                        "__monitors",
536                        noStorageClasses,
537                        LinkageSpec::Cforall,
538                        nullptr,
539                        new ArrayType(
540                                noQualifiers,
541                                new PointerType(
542                                        noQualifiers,
543                                        new StructInstType(
544                                                noQualifiers,
545                                                monitor_decl
546                                        )
547                                ),
548                                new ConstantExpr( Constant::from_ulong( args.size() ) ),
549                                false,
550                                false
551                        ),
552                        new ListInit(
553                                map_range < std::list<Initializer*> > ( args, [](DeclarationWithType * var ){
554                                        Type * type = var->get_type()->clone();
555                                        type->set_mutex( false );
556                                        return new SingleInit( new UntypedExpr(
557                                                new NameExpr( "get_monitor" ),
558                                                {  new CastExpr( new VariableExpr( var ), type ) }
559                                        ) );
560                                })
561                        )
562                );
563
564                assert(generic_func);
565
566                //in reverse order :
567                // monitor_guard_t __guard = { __monitors, #, func };
568                body->push_front(
569                        new DeclStmt( new ObjectDecl(
570                                "__guard",
571                                noStorageClasses,
572                                LinkageSpec::Cforall,
573                                nullptr,
574                                new StructInstType(
575                                        noQualifiers,
576                                        guard_decl
577                                ),
578                                new ListInit(
579                                        {
580                                                new SingleInit( new VariableExpr( monitors ) ),
581                                                new SingleInit( new ConstantExpr( Constant::from_ulong( args.size() ) ) ),
582                                                new SingleInit( new CastExpr( new VariableExpr( func ), generic_func->clone() ) )
583                                        },
584                                        noDesignators,
585                                        true
586                                )
587                        ))
588                );
589
590                //monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
591                body->push_front( new DeclStmt( monitors) );
592        }
593
594        //=============================================================================================
595        // General entry routine
596        //=============================================================================================
597        void ThreadStarter::previsit( StructDecl * decl ) {
598                if( decl->name == "thread_desc" && decl->body ) {
599                        assert( !thread_decl );
600                        thread_decl = decl;
601                }
602        }
603
604        void ThreadStarter::postvisit(FunctionDecl * decl) {
605                if( ! CodeGen::isConstructor(decl->name) ) return;
606
607                Type * typeof_this = InitTweak::getTypeofThis(decl->type);
608                StructInstType * ctored_type = dynamic_cast< StructInstType * >( typeof_this );
609                if( ctored_type && ctored_type->baseStruct == thread_decl ) {
610                        thread_ctor_seen = true;
611                }
612
613                DeclarationWithType * param = decl->get_functionType()->get_parameters().front();
614                auto type  = dynamic_cast< StructInstType * >( InitTweak::getPointerBase( param->get_type() ) );
615                if( type && type->get_baseStruct()->is_thread() ) {
616                        if( !thread_decl || !thread_ctor_seen ) {
617                                SemanticError( type->get_baseStruct()->location, "thread keyword requires threads to be in scope, add #include <thread>");
618                        }
619
620                        addStartStatement( decl, param );
621                }
622        }
623
624        void ThreadStarter::addStartStatement( FunctionDecl * decl, DeclarationWithType * param ) {
625                CompoundStmt * stmt = decl->get_statements();
626
627                if( ! stmt ) return;
628
629                stmt->push_back(
630                        new ExprStmt(
631                                new UntypedExpr(
632                                        new NameExpr( "__thrd_start" ),
633                                        { new VariableExpr( param ) }
634                                )
635                        )
636                );
637        }
638};
639
640// Local Variables: //
641// mode: c //
642// tab-width: 4 //
643// End: //
Note: See TracBrowser for help on using the repository browser.