source: src/Concurrency/Keywords.cc @ bf2438c

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

Cleaned-up some headers using a tool called 'include-what-you-use'

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