source: src/Concurrency/Keywords.cc @ 08fc48f

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

Big header cleaning pass - commit 1

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