source: src/Concurrency/Keywords.cc @ b4bfa0a

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 b4bfa0a was a843067, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Fixed several errors in monitor.c
Update debug prints
Added proper sched-ext-parse test

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