source: src/Concurrency/Keywords.cc @ eb211bf

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since eb211bf was 3cc1111, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Small fix in Decl.hpp and a new-ast function added in InitTweak?.

  • Property mode set to 100644
File size: 41.8 KB
RevLine 
[64adb03]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 :
[07de76b]13// Update Count     : 10
[64adb03]14//
15
16#include "Concurrency/Keywords.h"
17
[427854b]18#include <cassert>                        // for assert
19#include <string>                         // for string, operator==
20
[1c01c58]21#include <iostream>
22
23#include "Common/Examine.h"               // for isMainFor
[427854b]24#include "Common/PassVisitor.h"           // for PassVisitor
25#include "Common/SemanticError.h"         // for SemanticError
26#include "Common/utility.h"               // for deleteAll, map_range
27#include "CodeGen/OperatorTable.h"        // for isConstructor
28#include "ControlStruct/LabelGenerator.h" // for LebelGenerator
29#include "InitTweak/InitTweak.h"          // for getPointerBase
30#include "SynTree/LinkageSpec.h"          // for Cforall
31#include "SynTree/Constant.h"             // for Constant
32#include "SynTree/Declaration.h"          // for StructDecl, FunctionDecl, ObjectDecl
33#include "SynTree/Expression.h"           // for VariableExpr, ConstantExpr, Untype...
34#include "SynTree/Initializer.h"          // for SingleInit, ListInit, Initializer ...
35#include "SynTree/Label.h"                // for Label
36#include "SynTree/Statement.h"            // for CompoundStmt, DeclStmt, ExprStmt
37#include "SynTree/Type.h"                 // for StructInstType, Type, PointerType
38#include "SynTree/Visitor.h"              // for Visitor, acceptAll
[1c01c58]39#include "Virtual/Tables.h"
[bf2438c]40
41class Attribute;
[64adb03]42
43namespace Concurrency {
[ecfd758]44        inline static std::string getTypeIdName( std::string const & exception_name ) {
45                return exception_name.empty() ? std::string() : Virtual::typeIdType( exception_name );
46        }
[1c01c58]47        inline static std::string getVTableName( std::string const & exception_name ) {
[ecfd758]48                return exception_name.empty() ? std::string() : Virtual::vtableTypeName( exception_name );
[1c01c58]49        }
50
[ab8c6a6]51        // Only detects threads constructed with the keyword thread.
52        inline static bool isThread( DeclarationWithType * decl ) {
53                Type * baseType = decl->get_type()->stripDeclarator();
54                StructInstType * instType = dynamic_cast<StructInstType *>( baseType );
55                if ( nullptr == instType ) { return false; }
56                return instType->baseStruct->is_thread();
57        }
58
[64adb03]59        //=============================================================================================
[2065609]60        // Pass declarations
[64adb03]61        //=============================================================================================
62
[bcda04c]63        //-----------------------------------------------------------------------------
64        //Handles sue type declarations :
65        // sue MyType {                             struct MyType {
66        //      int data;                                  int data;
67        //      a_struct_t more_data;                      a_struct_t more_data;
68        //                                =>             NewField_t newField;
69        // };                                        };
70        //                                           static inline NewField_t * getter_name( MyType * this ) { return &this->newField; }
71        //
[2065609]72        class ConcurrentSueKeyword : public WithDeclsToAdd {
[bcda04c]73          public:
74
[1c01c58]75                ConcurrentSueKeyword( std::string&& type_name, std::string&& field_name,
76                        std::string&& getter_name, std::string&& context_error, std::string&& exception_name,
77                        bool needs_main, AggregateDecl::Aggregate cast_target ) :
78                  type_name( type_name ), field_name( field_name ), getter_name( getter_name ),
[69c5c00]79                  context_error( context_error ), exception_name( exception_name ),
[ecfd758]80                  typeid_name( getTypeIdName( exception_name ) ),
[69c5c00]81                  vtable_name( getVTableName( exception_name ) ),
[1c01c58]82                  needs_main( needs_main ), cast_target( cast_target ) {}
[bcda04c]83
84                virtual ~ConcurrentSueKeyword() {}
85
[9a705dc8]86                Declaration * postmutate( StructDecl * decl );
[6c3a5ac1]87                DeclarationWithType * postmutate( FunctionDecl * decl );
[bcda04c]88
89                void handle( StructDecl * );
[ecfd758]90                void addTypeId( StructDecl * );
[1c01c58]91                void addVtableForward( StructDecl * );
[bcda04c]92                FunctionDecl * forwardDeclare( StructDecl * );
93                ObjectDecl * addField( StructDecl * );
[2f9a722]94                void addRoutines( ObjectDecl *, FunctionDecl * );
[af67ee1]95                void addLockUnlockRoutines( StructDecl * );
[bcda04c]96
97                virtual bool is_target( StructDecl * decl ) = 0;
98
[9a705dc8]99                Expression * postmutate( KeywordCastExpr * cast );
100
[bcda04c]101          private:
102                const std::string type_name;
103                const std::string field_name;
104                const std::string getter_name;
105                const std::string context_error;
[69c5c00]106                const std::string exception_name;
[ecfd758]107                const std::string typeid_name;
[1c01c58]108                const std::string vtable_name;
[bd4d011]109                bool needs_main;
[312029a]110                AggregateDecl::Aggregate cast_target;
[bcda04c]111
[6c3a5ac1]112                StructDecl   * type_decl = nullptr;
113                FunctionDecl * dtor_decl = nullptr;
[69c5c00]114                StructDecl * except_decl = nullptr;
[ecfd758]115                StructDecl * typeid_decl = nullptr;
[1c01c58]116                StructDecl * vtable_decl = nullptr;
[bcda04c]117        };
118
119
[64adb03]120        //-----------------------------------------------------------------------------
121        //Handles thread type declarations :
122        // thread Mythread {                         struct MyThread {
123        //      int data;                                  int data;
124        //      a_struct_t more_data;                      a_struct_t more_data;
[e84ab3d]125        //                                =>             thread$ __thrd_d;
[64adb03]126        // };                                        };
[e84ab3d]127        //                                           static inline thread$ * get_thread( MyThread * this ) { return &this->__thrd_d; }
[64adb03]128        //
[bcda04c]129        class ThreadKeyword final : public ConcurrentSueKeyword {
[64adb03]130          public:
131
[bcda04c]132                ThreadKeyword() : ConcurrentSueKeyword(
[e84ab3d]133                        "thread$",
[bcda04c]134                        "__thrd",
135                        "get_thread",
[6c3a5ac1]136                        "thread keyword requires threads to be in scope, add #include <thread.hfa>\n",
[ab8c6a6]137                        "ThreadCancelled",
[9a705dc8]138                        true,
[312029a]139                        AggregateDecl::Thread
[bcda04c]140                )
141                {}
142
143                virtual ~ThreadKeyword() {}
144
145                virtual bool is_target( StructDecl * decl ) override final { return decl->is_thread(); }
146
147                static void implement( std::list< Declaration * > & translationUnit ) {
[2065609]148                        PassVisitor< ThreadKeyword > impl;
[9a705dc8]149                        mutateAll( translationUnit, impl );
[bcda04c]150                }
[64adb03]151        };
152
153        //-----------------------------------------------------------------------------
154        //Handles coroutine type declarations :
155        // coroutine MyCoroutine {                   struct MyCoroutine {
156        //      int data;                                  int data;
157        //      a_struct_t more_data;                      a_struct_t more_data;
[e84ab3d]158        //                                =>             coroutine$ __cor_d;
[64adb03]159        // };                                        };
[e84ab3d]160        //                                           static inline coroutine$ * get_coroutine( MyCoroutine * this ) { return &this->__cor_d; }
[64adb03]161        //
[bcda04c]162        class CoroutineKeyword final : public ConcurrentSueKeyword {
[64adb03]163          public:
164
[bcda04c]165                CoroutineKeyword() : ConcurrentSueKeyword(
[e84ab3d]166                        "coroutine$",
[bcda04c]167                        "__cor",
168                        "get_coroutine",
[6c3a5ac1]169                        "coroutine keyword requires coroutines to be in scope, add #include <coroutine.hfa>\n",
[1c01c58]170                        "CoroutineCancelled",
[9a705dc8]171                        true,
[312029a]172                        AggregateDecl::Coroutine
[bcda04c]173                )
174                {}
[b32ada31]175
[bcda04c]176                virtual ~CoroutineKeyword() {}
177
178                virtual bool is_target( StructDecl * decl ) override final { return decl->is_coroutine(); }
[b32ada31]179
180                static void implement( std::list< Declaration * > & translationUnit ) {
[2065609]181                        PassVisitor< CoroutineKeyword > impl;
[9a705dc8]182                        mutateAll( translationUnit, impl );
[b32ada31]183                }
[64adb03]184        };
185
[427854b]186
187
[64adb03]188        //-----------------------------------------------------------------------------
189        //Handles monitor type declarations :
190        // monitor MyMonitor {                       struct MyMonitor {
191        //      int data;                                  int data;
192        //      a_struct_t more_data;                      a_struct_t more_data;
[e84ab3d]193        //                                =>             monitor$ __mon_d;
[64adb03]194        // };                                        };
[e84ab3d]195        //                                           static inline monitor$ * get_coroutine( MyMonitor * this ) { return &this->__cor_d; }
[64adb03]196        //
[bcda04c]197        class MonitorKeyword final : public ConcurrentSueKeyword {
[64adb03]198          public:
199
[bcda04c]200                MonitorKeyword() : ConcurrentSueKeyword(
[e84ab3d]201                        "monitor$",
[bcda04c]202                        "__mon",
203                        "get_monitor",
[6c3a5ac1]204                        "monitor keyword requires monitors to be in scope, add #include <monitor.hfa>\n",
[1c01c58]205                        "",
[9a705dc8]206                        false,
[312029a]207                        AggregateDecl::Monitor
[bcda04c]208                )
209                {}
210
211                virtual ~MonitorKeyword() {}
212
213                virtual bool is_target( StructDecl * decl ) override final { return decl->is_monitor(); }
214
215                static void implement( std::list< Declaration * > & translationUnit ) {
[2065609]216                        PassVisitor< MonitorKeyword > impl;
[9a705dc8]217                        mutateAll( translationUnit, impl );
[bcda04c]218                }
[64adb03]219        };
220
[427854b]221        //-----------------------------------------------------------------------------
222        //Handles generator type declarations :
223        // generator MyGenerator {                   struct MyGenerator {
224        //      int data;                                  int data;
225        //      a_struct_t more_data;                      a_struct_t more_data;
226        //                                =>             int __gen_next;
227        // };                                        };
228        //
229        class GeneratorKeyword final : public ConcurrentSueKeyword {
230          public:
231
232                GeneratorKeyword() : ConcurrentSueKeyword(
[e84ab3d]233                        "generator$",
[427854b]234                        "__generator_state",
235                        "get_generator",
[e84ab3d]236                        "Unable to find builtin type generator$\n",
[1c01c58]237                        "",
[427854b]238                        true,
239                        AggregateDecl::Generator
240                )
241                {}
242
243                virtual ~GeneratorKeyword() {}
244
245                virtual bool is_target( StructDecl * decl ) override final { return decl->is_generator(); }
246
247                static void implement( std::list< Declaration * > & translationUnit ) {
248                        PassVisitor< GeneratorKeyword > impl;
249                        mutateAll( translationUnit, impl );
250                }
251        };
252
253
254        //-----------------------------------------------------------------------------
255        class SuspendKeyword final : public WithStmtsToAdd, public WithGuards {
256        public:
257                SuspendKeyword() = default;
258                virtual ~SuspendKeyword() = default;
259
260                void  premutate( FunctionDecl * );
261                DeclarationWithType * postmutate( FunctionDecl * );
262
263                Statement * postmutate( SuspendStmt * );
264
265                static void implement( std::list< Declaration * > & translationUnit ) {
266                        PassVisitor< SuspendKeyword > impl;
267                        mutateAll( translationUnit, impl );
268                }
269
270        private:
271                bool is_real_suspend( FunctionDecl * );
272
273                Statement * make_generator_suspend( SuspendStmt * );
274                Statement * make_coroutine_suspend( SuspendStmt * );
275
276                struct LabelPair {
277                        Label obj;
278                        int   idx;
279                };
280
281                LabelPair make_label() {
282                        labels.push_back( gen.newLabel("generator") );
283                        return { labels.back(), int(labels.size()) };
284                }
285
286                DeclarationWithType * in_generator = nullptr;
287                FunctionDecl * decl_suspend = nullptr;
288                std::vector<Label> labels;
289                ControlStruct::LabelGenerator & gen = *ControlStruct::LabelGenerator::getGenerator();
290        };
291
[64adb03]292        //-----------------------------------------------------------------------------
293        //Handles mutex routines definitions :
294        // void foo( A * mutex a, B * mutex b,  int i ) {                  void foo( A * a, B * b,  int i ) {
[e84ab3d]295        //                                                                       monitor$ * __monitors[] = { get_monitor(a), get_monitor(b) };
[64adb03]296        //                                                                       monitor_guard_t __guard = { __monitors, 2 };
297        //    /*Some code*/                                       =>           /*Some code*/
298        // }                                                               }
299        //
[2065609]300        class MutexKeyword final {
[64adb03]301          public:
302
[2065609]303                void postvisit( FunctionDecl * decl );
304                void postvisit(   StructDecl * decl );
[6cebfef]305                Statement * postmutate( MutexStmt * stmt );
[64adb03]306
[db4d8e3]307                std::list<DeclarationWithType*> findMutexArgs( FunctionDecl*, bool & first );
[64adb03]308                void validate( DeclarationWithType * );
[ab8c6a6]309                void addDtorStatements( FunctionDecl* func, CompoundStmt *, const std::list<DeclarationWithType * > &);
310                void addStatements( FunctionDecl* func, CompoundStmt *, const std::list<DeclarationWithType * > &);
[6cebfef]311                void addStatements( CompoundStmt * body, const std::list<Expression * > & args );
[ab8c6a6]312                void addThreadDtorStatements( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args );
[64adb03]313
314                static void implement( std::list< Declaration * > & translationUnit ) {
[2065609]315                        PassVisitor< MutexKeyword > impl;
[64adb03]316                        acceptAll( translationUnit, impl );
[6cebfef]317                        mutateAll( translationUnit, impl );
[64adb03]318                }
[9243cc91]319
320          private:
321                StructDecl* monitor_decl = nullptr;
[ef42b143]322                StructDecl* guard_decl = nullptr;
[549c006]323                StructDecl* dtor_guard_decl = nullptr;
[ab8c6a6]324                StructDecl* thread_guard_decl = nullptr;
[af67ee1]325                StructDecl* lock_guard_decl = nullptr;
[97e3296]326
327                static std::unique_ptr< Type > generic_func;
[64adb03]328        };
329
[97e3296]330        std::unique_ptr< Type > MutexKeyword::generic_func = std::unique_ptr< Type >(
331                new FunctionType(
332                        noQualifiers,
333                        true
334                )
335        );
336
[bd4d011]337        //-----------------------------------------------------------------------------
338        //Handles mutex routines definitions :
339        // void foo( A * mutex a, B * mutex b,  int i ) {                  void foo( A * a, B * b,  int i ) {
[e84ab3d]340        //                                                                       monitor$ * __monitors[] = { get_monitor(a), get_monitor(b) };
[bd4d011]341        //                                                                       monitor_guard_t __guard = { __monitors, 2 };
342        //    /*Some code*/                                       =>           /*Some code*/
343        // }                                                               }
344        //
[2065609]345        class ThreadStarter final {
[bd4d011]346          public:
347
[2065609]348                void postvisit( FunctionDecl * decl );
[549c006]349                void previsit ( StructDecl   * decl );
[bd4d011]350
351                void addStartStatement( FunctionDecl * decl, DeclarationWithType * param );
352
353                static void implement( std::list< Declaration * > & translationUnit ) {
[2065609]354                        PassVisitor< ThreadStarter > impl;
[bd4d011]355                        acceptAll( translationUnit, impl );
356                }
[549c006]357
358          private :
359                bool thread_ctor_seen = false;
360                StructDecl * thread_decl = nullptr;
[bd4d011]361        };
362
[64adb03]363        //=============================================================================================
364        // General entry routine
365        //=============================================================================================
366        void applyKeywords( std::list< Declaration * > & translationUnit ) {
367                ThreadKeyword   ::implement( translationUnit );
368                CoroutineKeyword        ::implement( translationUnit );
369                MonitorKeyword  ::implement( translationUnit );
[427854b]370                GeneratorKeyword  ::implement( translationUnit );
371                SuspendKeyword    ::implement( translationUnit );
[bcda04c]372        }
373
374        void implementMutexFuncs( std::list< Declaration * > & translationUnit ) {
[64adb03]375                MutexKeyword    ::implement( translationUnit );
376        }
377
[bcda04c]378        void implementThreadStarter( std::list< Declaration * > & translationUnit ) {
[bd4d011]379                ThreadStarter   ::implement( translationUnit );
[bcda04c]380        }
381
[b32ada31]382        //=============================================================================================
[bcda04c]383        // Generic keyword implementation
[b32ada31]384        //=============================================================================================
[2db79e5]385        void fixupGenerics(FunctionType * func, StructDecl * decl) {
386                cloneAll(decl->parameters, func->forall);
387                for ( TypeDecl * td : func->forall ) {
388                        strict_dynamic_cast<StructInstType*>(
389                                func->parameters.front()->get_type()->stripReferences()
390                        )->parameters.push_back(
391                                new TypeExpr( new TypeInstType( noQualifiers, td->name, td ) )
392                        );
393                }
394        }
395
[9a705dc8]396        Declaration * ConcurrentSueKeyword::postmutate(StructDecl * decl) {
[9f5ecf5]397                if( decl->name == type_name && decl->body ) {
[bcda04c]398                        assert( !type_decl );
399                        type_decl = decl;
[b32ada31]400                }
[bcda04c]401                else if ( is_target(decl) ) {
[b32ada31]402                        handle( decl );
403                }
[69c5c00]404                else if ( !except_decl && exception_name == decl->name && decl->body ) {
405                        except_decl = decl;
406                }
[ecfd758]407                else if ( !typeid_decl && typeid_name == decl->name && decl->body ) {
408                        typeid_decl = decl;
409                }
[1c01c58]410                else if ( !vtable_decl && vtable_name == decl->name && decl->body ) {
411                        vtable_decl = decl;
412                }
413                // Might be able to get ride of is target.
414                assert( is_target(decl) == (cast_target == decl->kind) );
[9a705dc8]415                return decl;
[b32ada31]416        }
417
[6c3a5ac1]418        DeclarationWithType * ConcurrentSueKeyword::postmutate( FunctionDecl * decl ) {
[1c01c58]419                if ( type_decl && isDestructorFor( decl, type_decl ) )
420                        dtor_decl = decl;
[b583113]421                else if ( vtable_name.empty() || !decl->has_body() )
[43cedfb1]422                        ;
[1c01c58]423                else if ( auto param = isMainFor( decl, cast_target ) ) {
424                        // This should never trigger.
425                        assert( vtable_decl );
426                        // Should be safe because of isMainFor.
427                        StructInstType * struct_type = static_cast<StructInstType *>(
428                                static_cast<ReferenceType *>( param->get_type() )->base );
429                        assert( struct_type );
430
[69c5c00]431                        std::list< Expression * > poly_args = { new TypeExpr( struct_type->clone() ) };
432                        ObjectDecl * vtable_object = Virtual::makeVtableInstance(
[b583113]433                                "_default_vtable_object_declaration",
[69c5c00]434                                vtable_decl->makeInst( poly_args ), struct_type, nullptr );
435                        declsToAddAfter.push_back( vtable_object );
[b583113]436                        declsToAddAfter.push_back(
437                                new ObjectDecl(
438                                        Virtual::concurrentDefaultVTableName(),
[67b421c]439                                        noStorageClasses,
[b583113]440                                        LinkageSpec::Cforall,
441                                        /* bitfieldWidth */ nullptr,
442                                        new ReferenceType( Type::Const, vtable_object->type->clone() ),
443                                        new SingleInit( new VariableExpr( vtable_object ) )
444                                )
445                        );
[69c5c00]446                        declsToAddAfter.push_back( Virtual::makeGetExceptionFunction(
447                                vtable_object, except_decl->makeInst( std::move( poly_args ) )
448                        ) );
[1c01c58]449                }
[6c3a5ac1]450
451                return decl;
452        }
453
[9a705dc8]454        Expression * ConcurrentSueKeyword::postmutate( KeywordCastExpr * cast ) {
455                if ( cast_target == cast->target ) {
[e84ab3d]456                        // convert (thread &)t to (thread$ &)*get_thread(t), etc.
[9a705dc8]457                        if( !type_decl ) SemanticError( cast, context_error );
[6c3a5ac1]458                        if( !dtor_decl ) SemanticError( cast, context_error );
[3b0c8cb]459                        assert( cast->result == nullptr );
460                        cast->set_result( new ReferenceType( noQualifiers, new StructInstType( noQualifiers, type_decl ) ) );
461                        cast->concrete_target.field  = field_name;
462                        cast->concrete_target.getter = getter_name;
[9a705dc8]463                }
464                return cast;
465        }
466
[bcda04c]467        void ConcurrentSueKeyword::handle( StructDecl * decl ) {
[9f5ecf5]468                if( ! decl->body ) return;
[b32ada31]469
[a16764a6]470                if( !type_decl ) SemanticError( decl, context_error );
[6c3a5ac1]471                if( !dtor_decl ) SemanticError( decl, context_error );
[b32ada31]472
[ecfd758]473                if ( !exception_name.empty() ) {
474                        if( !typeid_decl ) SemanticError( decl, context_error );
475                        if( !vtable_decl ) SemanticError( decl, context_error );
476
477                        addTypeId( decl );
478                        addVtableForward( decl );
479                }
[bcda04c]480                FunctionDecl * func = forwardDeclare( decl );
481                ObjectDecl * field = addField( decl );
[af67ee1]482
483                // add get_.* routine
[2f9a722]484                addRoutines( field, func );
[af67ee1]485                // add lock/unlock routines to monitors for use by mutex stmt
486                addLockUnlockRoutines( decl );
[b32ada31]487        }
488
[ecfd758]489        void ConcurrentSueKeyword::addTypeId( StructDecl * decl ) {
490                assert( typeid_decl );
491                StructInstType typeid_type( Type::Const, typeid_decl );
492                typeid_type.parameters.push_back( new TypeExpr(
493                        new StructInstType( noQualifiers, decl )
[69c5c00]494                        ) );
[ecfd758]495                declsToAddBefore.push_back( Virtual::makeTypeIdInstance( &typeid_type ) );
496        }
497
498        void ConcurrentSueKeyword::addVtableForward( StructDecl * decl ) {
499                assert( vtable_decl );
500                std::list< Expression * > poly_args = {
501                        new TypeExpr( new StructInstType( noQualifiers, decl ) ),
502                };
503                declsToAddBefore.push_back( Virtual::makeGetExceptionForward(
504                        vtable_decl->makeInst( poly_args ),
505                        except_decl->makeInst( poly_args )
506                ) );
[b583113]507                ObjectDecl * vtable_object = Virtual::makeVtableForward(
508                        "_default_vtable_object_declaration",
509                        vtable_decl->makeInst( move( poly_args ) ) );
510                declsToAddBefore.push_back( vtable_object );
[8edbe40]511                declsToAddBefore.push_back(
[b583113]512                        new ObjectDecl(
513                                Virtual::concurrentDefaultVTableName(),
[67b421c]514                                Type::StorageClasses( Type::Extern ),
[b583113]515                                LinkageSpec::Cforall,
516                                /* bitfieldWidth */ nullptr,
517                                new ReferenceType( Type::Const, vtable_object->type->clone() ),
518                                /* init */ nullptr
519                        )
520                );
[1c01c58]521        }
522
[bcda04c]523        FunctionDecl * ConcurrentSueKeyword::forwardDeclare( StructDecl * decl ) {
524
525                StructDecl * forward = decl->clone();
526                forward->set_body( false );
527                deleteAll( forward->get_members() );
528                forward->get_members().clear();
529
[bd4d011]530                FunctionType * get_type = new FunctionType( noQualifiers, false );
[bcda04c]531                ObjectDecl * this_decl = new ObjectDecl(
532                        "this",
[ba3706f]533                        noStorageClasses,
[b32ada31]534                        LinkageSpec::Cforall,
535                        nullptr,
[83a071f9]536                        new ReferenceType(
[b32ada31]537                                noQualifiers,
[bcda04c]538                                new StructInstType(
539                                        noQualifiers,
540                                        decl
541                                )
[b32ada31]542                        ),
543                        nullptr
544                );
545
[2db79e5]546                get_type->get_parameters().push_back( this_decl->clone() );
[bd4d011]547                get_type->get_returnVals().push_back(
[e04b636]548                        new ObjectDecl(
549                                "ret",
[ba3706f]550                                noStorageClasses,
[e04b636]551                                LinkageSpec::Cforall,
552                                nullptr,
553                                new PointerType(
554                                        noQualifiers,
555                                        new StructInstType(
556                                                noQualifiers,
[bcda04c]557                                                type_decl
[e04b636]558                                        )
559                                ),
560                                nullptr
561                        )
562                );
[2db79e5]563                fixupGenerics(get_type, decl);
[b32ada31]564
[bcda04c]565                FunctionDecl * get_decl = new FunctionDecl(
566                        getter_name,
567                        Type::Static,
568                        LinkageSpec::Cforall,
[bd4d011]569                        get_type,
[bcda04c]570                        nullptr,
[a8078ee]571                        { new Attribute("const") },
[bcda04c]572                        Type::Inline
573                );
574
[bd4d011]575                FunctionDecl * main_decl = nullptr;
576
577                if( needs_main ) {
578                        FunctionType * main_type = new FunctionType( noQualifiers, false );
[bf2438c]579
[bd4d011]580                        main_type->get_parameters().push_back( this_decl->clone() );
581
582                        main_decl = new FunctionDecl(
583                                "main",
[ba3706f]584                                noStorageClasses,
[bd4d011]585                                LinkageSpec::Cforall,
586                                main_type,
587                                nullptr
588                        );
[2db79e5]589                        fixupGenerics(main_type, decl);
[bd4d011]590                }
591
[2db79e5]592                delete this_decl;
593
[2065609]594                declsToAddBefore.push_back( forward );
595                if( needs_main ) declsToAddBefore.push_back( main_decl );
596                declsToAddBefore.push_back( get_decl );
[bcda04c]597
598                return get_decl;
599        }
600
601        ObjectDecl * ConcurrentSueKeyword::addField( StructDecl * decl ) {
602                ObjectDecl * field = new ObjectDecl(
603                        field_name,
[ba3706f]604                        noStorageClasses,
[bcda04c]605                        LinkageSpec::Cforall,
606                        nullptr,
607                        new StructInstType(
608                                noQualifiers,
609                                type_decl
610                        ),
611                        nullptr
612                );
613
614                decl->get_members().push_back( field );
615
616                return field;
617        }
618
[af67ee1]619        // This function adds the get_.* routine body for coroutines, monitors etc
620        //              after their corresponding struct has been made
[2f9a722]621        void ConcurrentSueKeyword::addRoutines( ObjectDecl * field, FunctionDecl * func ) {
[ba3706f]622                CompoundStmt * statement = new CompoundStmt();
[bf2438c]623                statement->push_back(
[b32ada31]624                        new ReturnStmt(
[e04b636]625                                new AddressExpr(
[bcda04c]626                                        new MemberExpr(
627                                                field,
[2db79e5]628                                                new CastExpr(
629                                                        new VariableExpr( func->get_functionType()->get_parameters().front() ),
[b81fd95]630                                                        func->get_functionType()->get_parameters().front()->get_type()->stripReferences()->clone(),
631                                                        false
[2db79e5]632                                                )
[e04b636]633                                        )
[b32ada31]634                                )
635                        )
636                );
637
[bcda04c]638                FunctionDecl * get_decl = func->clone();
639
640                get_decl->set_statements( statement );
[e04b636]641
642                declsToAddAfter.push_back( get_decl );
[427854b]643        }
644
[af67ee1]645        // Generates lock/unlock routines for monitors to be used by mutex stmts
646        void ConcurrentSueKeyword::addLockUnlockRoutines( StructDecl * decl ) {
647                // this routine will be called for all ConcurrentSueKeyword children so only continue if we are a monitor
648                if ( !decl->is_monitor() ) return;
649
650                FunctionType * lock_fn_type = new FunctionType( noQualifiers, false );
651                FunctionType * unlock_fn_type = new FunctionType( noQualifiers, false );
652
653                // create this ptr parameter for both routines
654                ObjectDecl * this_decl = new ObjectDecl(
655                        "this",
656                        noStorageClasses,
657                        LinkageSpec::Cforall,
658                        nullptr,
659                        new ReferenceType(
660                                noQualifiers,
661                                new StructInstType(
662                                        noQualifiers,
663                                        decl
664                                )
665                        ),
666                        nullptr
667                );
668
669                lock_fn_type->get_parameters().push_back( this_decl->clone() );
670                unlock_fn_type->get_parameters().push_back( this_decl->clone() );
[5b7c8b5]671                fixupGenerics(lock_fn_type, decl);
672                fixupGenerics(unlock_fn_type, decl);
[af67ee1]673
674                delete this_decl;
675
676
677                //////////////////////////////////////////////////////////////////////
678                // The following generates this lock routine for all monitors
679                /*
680                        void lock (monitor_t & this) {
681                                lock(get_monitor(this));
682                        }       
683                */
684                FunctionDecl * lock_decl = new FunctionDecl(
685                        "lock",
686                        Type::Static,
687                        LinkageSpec::Cforall,
688                        lock_fn_type,
689                        nullptr,
690                        { },
691                        Type::Inline
692                );
693
694                UntypedExpr * get_monitor_lock =  new UntypedExpr (
695                        new NameExpr( "get_monitor" ),
696                        { new VariableExpr( lock_fn_type->get_parameters().front() ) }
697                );
698
699                CompoundStmt * lock_statement = new CompoundStmt();
700                lock_statement->push_back(
701                        new ExprStmt( 
702                                new UntypedExpr (
703                                        new NameExpr( "lock" ),
704                                        {
705                                                get_monitor_lock
706                                        }
707                                )
708                        )
709                );
710                lock_decl->set_statements( lock_statement );
711
712                //////////////////////////////////////////////////////////////////
713                // The following generates this routine for all monitors
714                /*
715                        void unlock (monitor_t & this) {
716                                unlock(get_monitor(this));
717                        }       
718                */
719                FunctionDecl * unlock_decl = new FunctionDecl(
720                        "unlock",
721                        Type::Static,
722                        LinkageSpec::Cforall,
723                        unlock_fn_type,
724                        nullptr,
725                        { },
726                        Type::Inline
727                );
728
729                CompoundStmt * unlock_statement = new CompoundStmt();
730
731                UntypedExpr * get_monitor_unlock =  new UntypedExpr (
732                        new NameExpr( "get_monitor" ),
733                        { new VariableExpr( unlock_fn_type->get_parameters().front() ) }
734                );
735
736                unlock_statement->push_back(
737                        new ExprStmt( 
738                                new UntypedExpr(
739                                        new NameExpr( "unlock" ),
740                                        {
741                                                get_monitor_unlock
742                                        }
743                                )
744                        )
745                );
746                unlock_decl->set_statements( unlock_statement );
747               
748                // pushes routines to declsToAddAfter to add at a later time
749                declsToAddAfter.push_back( lock_decl );
750                declsToAddAfter.push_back( unlock_decl );
751        }
752
[427854b]753        //=============================================================================================
754        // Suspend keyword implementation
755        //=============================================================================================
756        bool SuspendKeyword::is_real_suspend( FunctionDecl * func ) {
757                if(isMangled(func->linkage)) return false; // the real suspend isn't mangled
758                if(func->name != "__cfactx_suspend") return false; // the real suspend has a specific name
759                if(func->type->parameters.size() != 0) return false; // Too many parameters
760                if(func->type->returnVals.size() != 0) return false; // Too many return values
761
762                return true;
[b32ada31]763        }
764
[427854b]765        void SuspendKeyword::premutate( FunctionDecl * func ) {
766                GuardValue(in_generator);
767                in_generator = nullptr;
768
769                // Is this the real suspend?
770                if(is_real_suspend(func)) {
771                        decl_suspend = decl_suspend ? decl_suspend : func;
772                        return;
773                }
774
775                // Is this the main of a generator?
[1c01c58]776                auto param = isMainFor( func, AggregateDecl::Aggregate::Generator );
[427854b]777                if(!param) return;
778
779                if(func->type->returnVals.size() != 0) SemanticError(func->location, "Generator main must return void");
780
781                in_generator = param;
782                GuardValue(labels);
783                labels.clear();
784        }
785
786        DeclarationWithType * SuspendKeyword::postmutate( FunctionDecl * func ) {
787                if( !func->statements ) return func; // Not the actual definition, don't do anything
788                if( !in_generator     ) return func; // Not in a generator, don't do anything
789                if( labels.empty()    ) return func; // Generator has no states, nothing to do, could throw a warning
790
791                // This is a generator main, we need to add the following code to the top
792                // static void * __generator_labels[] = {&&s0, &&s1, ...};
793                // goto * __generator_labels[gen.__generator_state];
794                const auto & loc = func->location;
795
796                const auto first_label = gen.newLabel("generator");
797
798                // for each label add to declaration
799                std::list<Initializer*> inits = { new SingleInit( new LabelAddressExpr( first_label ) ) };
800                for(const auto & label : labels) {
801                        inits.push_back(
802                                new SingleInit(
803                                        new LabelAddressExpr( label )
804                                )
805                        );
806                }
807                auto init = new ListInit(std::move(inits), noDesignators, true);
808                labels.clear();
809
810                // create decl
811                auto decl = new ObjectDecl(
812                        "__generator_labels",
813                        Type::StorageClasses( Type::Static ),
814                        LinkageSpec::AutoGen,
815                        nullptr,
816                        new ArrayType(
817                                Type::Qualifiers(),
818                                new PointerType(
819                                        Type::Qualifiers(),
820                                        new VoidType( Type::Qualifiers() )
821                                ),
822                                nullptr,
823                                false, false
824                        ),
825                        init
826                );
827
828                // create the goto
829                assert(in_generator);
830
831                auto go_decl = new ObjectDecl(
832                        "__generator_label",
833                        noStorageClasses,
834                        LinkageSpec::AutoGen,
835                        nullptr,
836                        new PointerType(
837                                Type::Qualifiers(),
838                                new VoidType( Type::Qualifiers() )
839                        ),
840                        new SingleInit(
841                                new UntypedExpr(
842                                        new NameExpr("?[?]"),
843                                        {
844                                                new NameExpr("__generator_labels"),
845                                                new UntypedMemberExpr(
846                                                        new NameExpr("__generator_state"),
847                                                        new VariableExpr( in_generator )
848                                                )
849                                        }
850                                )
851                        )
852                );
853                go_decl->location = loc;
854
855                auto go = new BranchStmt(
856                        new VariableExpr( go_decl ),
857                        BranchStmt::Goto
858                );
859                go->location = loc;
860                go->computedTarget->location = loc;
861
862                auto noop = new NullStmt({ first_label });
863                noop->location = loc;
864
865                // wrap everything in a nice compound
866                auto body = new CompoundStmt({
867                        new DeclStmt( decl ),
868                        new DeclStmt( go_decl ),
869                        go,
870                        noop,
871                        func->statements
872                });
873                body->location   = loc;
874                func->statements = body;
875
876                return func;
877        }
878
879        Statement * SuspendKeyword::postmutate( SuspendStmt * stmt ) {
880                SuspendStmt::Type type = stmt->type;
881                if(type == SuspendStmt::None) {
882                        // This suspend has a implicit target, find it
883                        type = in_generator ? SuspendStmt::Generator : SuspendStmt::Coroutine;
884                }
885
886                // Check that the target makes sense
887                if(!in_generator && type == SuspendStmt::Generator) SemanticError( stmt->location, "'suspend generator' must be used inside main of generator type.");
888
889                // Act appropriately
890                switch(type) {
891                        case SuspendStmt::Generator: return make_generator_suspend(stmt);
892                        case SuspendStmt::Coroutine: return make_coroutine_suspend(stmt);
893                        default: abort();
894                }
895        }
896
897        Statement * SuspendKeyword::make_generator_suspend( SuspendStmt * stmt ) {
898                assert(in_generator);
899                // Target code is :
900                //   gen.__generator_state = X;
901                //   { THEN }
902                //   return;
903                //   __gen_X:;
904
905                // Save the location and delete the old statement, we only need the location from this point on
906                auto loc = stmt->location;
907
908                // Build the label and get its index
909                auto label = make_label();
910
911                // Create the context saving statement
912                auto save = new ExprStmt( new UntypedExpr(
913                        new NameExpr( "?=?" ),
914                        {
915                                new UntypedMemberExpr(
916                                        new NameExpr("__generator_state"),
917                                        new VariableExpr( in_generator )
918                                ),
919                                new ConstantExpr(
920                                        Constant::from_int( label.idx )
921                                )
922                        }
923                ));
924                assert(save->expr);
925                save->location = loc;
926                stmtsToAddBefore.push_back( save );
927
928                // if we have a then add it here
929                auto then = stmt->then;
930                stmt->then = nullptr;
931                delete stmt;
932                if(then) stmtsToAddBefore.push_back( then );
933
934                // Create the return statement
935                auto ret = new ReturnStmt( nullptr );
936                ret->location = loc;
937                stmtsToAddBefore.push_back( ret );
938
939                // Create the null statement with the created label
940                auto noop = new NullStmt({ label.obj });
941                noop->location = loc;
942
943                // Return the null statement to take the place of the previous statement
944                return noop;
945        }
946
947        Statement * SuspendKeyword::make_coroutine_suspend( SuspendStmt * stmt ) {
948                if(stmt->then) SemanticError( stmt->location, "Compound statement following coroutines is not implemented.");
949
950                // Save the location and delete the old statement, we only need the location from this point on
951                auto loc = stmt->location;
952                delete stmt;
953
954                // Create the call expression
955                if(!decl_suspend) SemanticError( loc, "suspend keyword applied to coroutines requires coroutines to be in scope, add #include <coroutine.hfa>\n");
956                auto expr = new UntypedExpr( VariableExpr::functionPointer( decl_suspend ) );
[e6cfa8ff]957                expr->location = loc;
[427854b]958
959                // Change this statement into a regular expr
960                assert(expr);
961                auto nstmt = new ExprStmt( expr );
[e6cfa8ff]962                nstmt->location = loc;
[427854b]963                return nstmt;
964        }
965
966
[64adb03]967        //=============================================================================================
968        // Mutex keyword implementation
969        //=============================================================================================
[97e3296]970
[2065609]971        void MutexKeyword::postvisit(FunctionDecl* decl) {
[102a58b]972
[db4d8e3]973                bool first = false;
974                std::list<DeclarationWithType*> mutexArgs = findMutexArgs( decl, first );
[ab8c6a6]975                bool const isDtor = CodeGen::isDestructor( decl->name );
[64adb03]976
[ceedde6]977                // Is this function relevant to monitors
978                if( mutexArgs.empty() ) {
979                        // If this is the destructor for a monitor it must be mutex
980                        if(isDtor) {
[3cc1111]981                                // This reflects MutexKeyword::validate, except does not produce an error.
[ceedde6]982                                Type* ty = decl->get_functionType()->get_parameters().front()->get_type();
983
984                                // If it's a copy, it's not a mutex
985                                ReferenceType* rty = dynamic_cast< ReferenceType * >( ty );
986                                if( ! rty ) return;
987
988                                // If we are not pointing directly to a type, it's not a mutex
989                                Type* base = rty->get_base();
990                                if( dynamic_cast< ReferenceType * >( base ) ) return;
991                                if( dynamic_cast< PointerType * >( base ) ) return;
992
993                                // Check if its a struct
994                                StructInstType * baseStruct = dynamic_cast< StructInstType * >( base );
995                                if( !baseStruct ) return;
996
997                                // Check if its a monitor
998                                if(baseStruct->baseStruct->is_monitor() || baseStruct->baseStruct->is_thread())
999                                        SemanticError( decl, "destructors for structures declared as \"monitor\" must use mutex parameters\n" );
1000                        }
1001                        return;
1002                }
[549c006]1003
[ceedde6]1004                // Monitors can't be constructed with mutual exclusion
1005                if( CodeGen::isConstructor(decl->name) && !first ) SemanticError( decl, "constructors cannot have mutex parameters" );
[549c006]1006
[ceedde6]1007                // It makes no sense to have multiple mutex parameters for the destructor
[a16764a6]1008                if( isDtor && mutexArgs.size() != 1 ) SemanticError( decl, "destructors can only have 1 mutex argument" );
[549c006]1009
[ceedde6]1010                // Make sure all the mutex arguments are monitors
[64adb03]1011                for(auto arg : mutexArgs) {
1012                        validate( arg );
1013                }
1014
[ceedde6]1015                // Check if we need to instrument the body
[64adb03]1016                CompoundStmt* body = decl->get_statements();
1017                if( ! body ) return;
1018
[ceedde6]1019                // Do we have the required headers
[a16764a6]1020                if( !monitor_decl || !guard_decl || !dtor_guard_decl )
[73abe95]1021                        SemanticError( decl, "mutex keyword requires monitors to be in scope, add #include <monitor.hfa>\n" );
[b32ada31]1022
[ceedde6]1023                // Instrument the body
[ab8c6a6]1024                if ( isDtor && isThread( mutexArgs.front() ) ) {
1025                        if( !thread_guard_decl ) {
1026                                SemanticError( decl, "thread destructor requires threads to be in scope, add #include <thread.hfa>\n" );
1027                        }
1028                        addThreadDtorStatements( decl, body, mutexArgs );
1029                }
1030                else if ( isDtor ) {
1031                        addDtorStatements( decl, body, mutexArgs );
[549c006]1032                }
1033                else {
[ab8c6a6]1034                        addStatements( decl, body, mutexArgs );
[549c006]1035                }
[64adb03]1036        }
1037
[2065609]1038        void MutexKeyword::postvisit(StructDecl* decl) {
[102a58b]1039
[e84ab3d]1040                if( decl->name == "monitor$" && decl->body ) {
[9243cc91]1041                        assert( !monitor_decl );
1042                        monitor_decl = decl;
1043                }
[88d955f]1044                else if( decl->name == "monitor_guard_t" && decl->body ) {
[ef42b143]1045                        assert( !guard_decl );
1046                        guard_decl = decl;
1047                }
[88d955f]1048                else if( decl->name == "monitor_dtor_guard_t" && decl->body ) {
[549c006]1049                        assert( !dtor_guard_decl );
1050                        dtor_guard_decl = decl;
1051                }
[ab8c6a6]1052                else if( decl->name == "thread_dtor_guard_t" && decl->body ) {
1053                        assert( !thread_guard_decl );
1054                        thread_guard_decl = decl;
[af67ee1]1055                } 
1056                else if ( decl->name == "__mutex_stmt_lock_guard" && decl->body ) {
1057                        assert( !lock_guard_decl );
1058                        lock_guard_decl = decl;
[ab8c6a6]1059                }
[9243cc91]1060        }
1061
[6cebfef]1062        Statement * MutexKeyword::postmutate( MutexStmt * stmt ) {
1063                std::list<Statement *> stmtsForCtor;
1064                stmtsForCtor.push_back(stmt->stmt);
1065                CompoundStmt * body = new CompoundStmt( stmtsForCtor );
1066                addStatements( body, stmt->mutexObjs);
1067                return body;
1068        }
1069
[db4d8e3]1070        std::list<DeclarationWithType*> MutexKeyword::findMutexArgs( FunctionDecl* decl, bool & first ) {
[64adb03]1071                std::list<DeclarationWithType*> mutexArgs;
1072
[db4d8e3]1073                bool once = true;
[64adb03]1074                for( auto arg : decl->get_functionType()->get_parameters()) {
1075                        //Find mutex arguments
1076                        Type* ty = arg->get_type();
[615a096]1077                        if( ! ty->get_mutex() ) continue;
[64adb03]1078
[db4d8e3]1079                        if(once) {first = true;}
1080                        once = false;
1081
[64adb03]1082                        //Append it to the list
1083                        mutexArgs.push_back( arg );
1084                }
1085
1086                return mutexArgs;
1087        }
1088
1089        void MutexKeyword::validate( DeclarationWithType * arg ) {
1090                Type* ty = arg->get_type();
1091
1092                //Makes sure it's not a copy
[870d1f0]1093                ReferenceType* rty = dynamic_cast< ReferenceType * >( ty );
[a16764a6]1094                if( ! rty ) SemanticError( arg, "Mutex argument must be of reference type " );
[64adb03]1095
1096                //Make sure the we are pointing directly to a type
[83a071f9]1097                Type* base = rty->get_base();
[a16764a6]1098                if( dynamic_cast< ReferenceType * >( base ) ) SemanticError( arg, "Mutex argument have exactly one level of indirection " );
1099                if( dynamic_cast< PointerType * >( base ) ) SemanticError( arg, "Mutex argument have exactly one level of indirection " );
[64adb03]1100
1101                //Make sure that typed isn't mutex
[a16764a6]1102                if( base->get_mutex() ) SemanticError( arg, "mutex keyword may only appear once per argument " );
[64adb03]1103        }
1104
[ab8c6a6]1105        void MutexKeyword::addDtorStatements( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args ) {
[549c006]1106                Type * arg_type = args.front()->get_type()->clone();
1107                arg_type->set_mutex( false );
1108
1109                ObjectDecl * monitors = new ObjectDecl(
1110                        "__monitor",
[ba3706f]1111                        noStorageClasses,
[549c006]1112                        LinkageSpec::Cforall,
1113                        nullptr,
1114                        new PointerType(
1115                                noQualifiers,
1116                                new StructInstType(
1117                                        noQualifiers,
1118                                        monitor_decl
1119                                )
1120                        ),
1121                        new SingleInit( new UntypedExpr(
1122                                new NameExpr( "get_monitor" ),
[b81fd95]1123                                {  new CastExpr( new VariableExpr( args.front() ), arg_type, false ) }
[549c006]1124                        ))
1125                );
1126
1127                assert(generic_func);
1128
1129                //in reverse order :
[2bf7ef6]1130                // monitor_dtor_guard_t __guard = { __monitors, func };
[549c006]1131                body->push_front(
[ba3706f]1132                        new DeclStmt( new ObjectDecl(
[549c006]1133                                "__guard",
[ba3706f]1134                                noStorageClasses,
[549c006]1135                                LinkageSpec::Cforall,
1136                                nullptr,
1137                                new StructInstType(
1138                                        noQualifiers,
1139                                        dtor_guard_decl
1140                                ),
1141                                new ListInit(
1142                                        {
1143                                                new SingleInit( new AddressExpr( new VariableExpr( monitors ) ) ),
[77a2994]1144                                                new SingleInit( new CastExpr( new VariableExpr( func ), generic_func->clone(), false ) ),
1145                                                new SingleInit( new ConstantExpr( Constant::from_bool( false ) ) )
[549c006]1146                                        },
1147                                        noDesignators,
1148                                        true
1149                                )
1150                        ))
1151                );
1152
[e84ab3d]1153                //monitor$ * __monitors[] = { get_monitor(a), get_monitor(b) };
[ab8c6a6]1154                body->push_front( new DeclStmt( monitors ) );
1155        }
1156
1157        void MutexKeyword::addThreadDtorStatements(
1158                        FunctionDecl*, CompoundStmt * body,
1159                        const std::list<DeclarationWithType * > & args ) {
1160                assert( args.size() == 1 );
1161                DeclarationWithType * arg = args.front();
1162                Type * arg_type = arg->get_type()->clone();
1163                assert( arg_type->get_mutex() );
1164                arg_type->set_mutex( false );
1165
1166                // thread_dtor_guard_t __guard = { this, intptr( 0 ) };
1167                body->push_front(
1168                        new DeclStmt( new ObjectDecl(
1169                                "__guard",
1170                                noStorageClasses,
1171                                LinkageSpec::Cforall,
1172                                nullptr,
1173                                new StructInstType(
1174                                        noQualifiers,
1175                                        thread_guard_decl
1176                                ),
1177                                new ListInit(
1178                                        {
1179                                                new SingleInit( new CastExpr( new VariableExpr( arg ), arg_type ) ),
1180                                                new SingleInit( new UntypedExpr(
1181                                                        new NameExpr( "intptr" ), {
1182                                                                new ConstantExpr( Constant::from_int( 0 ) ),
1183                                                        }
1184                                                ) ),
1185                                        },
1186                                        noDesignators,
1187                                        true
1188                                )
1189                        ))
1190                );
[549c006]1191        }
1192
[6cebfef]1193        void MutexKeyword::addStatements( CompoundStmt * body, const std::list<Expression * > & args ) {
1194                ObjectDecl * monitors = new ObjectDecl(
1195                        "__monitors",
1196                        noStorageClasses,
1197                        LinkageSpec::Cforall,
1198                        nullptr,
1199                        new ArrayType(
1200                                noQualifiers,
1201                                new PointerType(
1202                                        noQualifiers,
[a8367eb]1203                                        //new TypeofType( noQualifiers, args.front()->clone() )
1204                                        new TypeofType( noQualifiers, new UntypedExpr(
1205                                                        new NameExpr( "__get_type" ),
1206                                                        { args.front()->clone() }
1207                                                ) 
1208                                        )
[6cebfef]1209                                ),
1210                                new ConstantExpr( Constant::from_ulong( args.size() ) ),
1211                                false,
1212                                false
1213                        ),
1214                        new ListInit(
1215                                map_range < std::list<Initializer*> > ( args, [](Expression * var ){
[a8367eb]1216                                        return new SingleInit( new UntypedExpr(
1217                                                        new NameExpr( "__get_ptr" ),
1218                                                        { var }
1219                                        ) );
1220                                        //return new SingleInit( new AddressExpr( var ) );
[6cebfef]1221                                })
1222                        )
1223                );
1224
[af67ee1]1225                StructInstType * lock_guard_struct = new StructInstType( noQualifiers, lock_guard_decl );
[a8367eb]1226                TypeExpr * lock_type_expr = new TypeExpr( 
1227                        new TypeofType( noQualifiers, new UntypedExpr(
1228                                new NameExpr( "__get_type" ),
1229                                { args.front()->clone() }
1230                                ) 
1231                        ) 
1232                );
[af67ee1]1233
1234                lock_guard_struct->parameters.push_back( lock_type_expr ) ;
1235
[6cebfef]1236                // in reverse order :
1237                // monitor_guard_t __guard = { __monitors, # };
1238                body->push_front(
1239                        new DeclStmt( new ObjectDecl(
1240                                "__guard",
1241                                noStorageClasses,
1242                                LinkageSpec::Cforall,
1243                                nullptr,
[af67ee1]1244                                lock_guard_struct,
[6cebfef]1245                                new ListInit(
1246                                        {
1247                                                new SingleInit( new VariableExpr( monitors ) ),
1248                                                new SingleInit( new ConstantExpr( Constant::from_ulong( args.size() ) ) )
1249                                        },
1250                                        noDesignators,
1251                                        true
1252                                )
1253                        ))
1254                );
1255
1256                //monitor$ * __monitors[] = { get_monitor(a), get_monitor(b) };
1257                body->push_front( new DeclStmt( monitors) );
1258        }
1259
[ab8c6a6]1260        void MutexKeyword::addStatements( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args ) {
[9243cc91]1261                ObjectDecl * monitors = new ObjectDecl(
1262                        "__monitors",
[ba3706f]1263                        noStorageClasses,
[9243cc91]1264                        LinkageSpec::Cforall,
1265                        nullptr,
1266                        new ArrayType(
1267                                noQualifiers,
1268                                new PointerType(
1269                                        noQualifiers,
1270                                        new StructInstType(
1271                                                noQualifiers,
1272                                                monitor_decl
1273                                        )
1274                                ),
1275                                new ConstantExpr( Constant::from_ulong( args.size() ) ),
1276                                false,
1277                                false
1278                        ),
1279                        new ListInit(
[bd41764]1280                                map_range < std::list<Initializer*> > ( args, [](DeclarationWithType * var ){
[cb0e6de]1281                                        Type * type = var->get_type()->clone();
1282                                        type->set_mutex( false );
[9243cc91]1283                                        return new SingleInit( new UntypedExpr(
1284                                                new NameExpr( "get_monitor" ),
[b81fd95]1285                                                {  new CastExpr( new VariableExpr( var ), type, false ) }
[9243cc91]1286                                        ) );
1287                                })
1288                        )
1289                );
1290
[97e3296]1291                assert(generic_func);
1292
[2bf7ef6]1293                // in reverse order :
[97e3296]1294                // monitor_guard_t __guard = { __monitors, #, func };
[64adb03]1295                body->push_front(
[ba3706f]1296                        new DeclStmt( new ObjectDecl(
[64adb03]1297                                "__guard",
[ba3706f]1298                                noStorageClasses,
[64adb03]1299                                LinkageSpec::Cforall,
1300                                nullptr,
1301                                new StructInstType(
1302                                        noQualifiers,
[ef42b143]1303                                        guard_decl
[64adb03]1304                                ),
1305                                new ListInit(
1306                                        {
[9243cc91]1307                                                new SingleInit( new VariableExpr( monitors ) ),
[97e3296]1308                                                new SingleInit( new ConstantExpr( Constant::from_ulong( args.size() ) ) ),
[b81fd95]1309                                                new SingleInit( new CastExpr( new VariableExpr( func ), generic_func->clone(), false ) )
[ef42b143]1310                                        },
1311                                        noDesignators,
1312                                        true
[64adb03]1313                                )
1314                        ))
1315                );
1316
[e84ab3d]1317                //monitor$ * __monitors[] = { get_monitor(a), get_monitor(b) };
[ba3706f]1318                body->push_front( new DeclStmt( monitors) );
[64adb03]1319        }
[bd4d011]1320
1321        //=============================================================================================
1322        // General entry routine
1323        //=============================================================================================
[549c006]1324        void ThreadStarter::previsit( StructDecl * decl ) {
[e84ab3d]1325                if( decl->name == "thread$" && decl->body ) {
[549c006]1326                        assert( !thread_decl );
1327                        thread_decl = decl;
1328                }
1329        }
1330
[2065609]1331        void ThreadStarter::postvisit(FunctionDecl * decl) {
[9f5ecf5]1332                if( ! CodeGen::isConstructor(decl->name) ) return;
[bd4d011]1333
[549c006]1334                Type * typeof_this = InitTweak::getTypeofThis(decl->type);
1335                StructInstType * ctored_type = dynamic_cast< StructInstType * >( typeof_this );
1336                if( ctored_type && ctored_type->baseStruct == thread_decl ) {
1337                        thread_ctor_seen = true;
1338                }
1339
[bd4d011]1340                DeclarationWithType * param = decl->get_functionType()->get_parameters().front();
[ce8c12f]1341                auto type  = dynamic_cast< StructInstType * >( InitTweak::getPointerBase( param->get_type() ) );
[bd4d011]1342                if( type && type->get_baseStruct()->is_thread() ) {
[549c006]1343                        if( !thread_decl || !thread_ctor_seen ) {
[73abe95]1344                                SemanticError( type->get_baseStruct()->location, "thread keyword requires threads to be in scope, add #include <thread.hfa>");
[549c006]1345                        }
1346
[bd4d011]1347                        addStartStatement( decl, param );
1348                }
1349        }
1350
1351        void ThreadStarter::addStartStatement( FunctionDecl * decl, DeclarationWithType * param ) {
1352                CompoundStmt * stmt = decl->get_statements();
1353
1354                if( ! stmt ) return;
1355
[bf2438c]1356                stmt->push_back(
[bd4d011]1357                        new ExprStmt(
1358                                new UntypedExpr(
1359                                        new NameExpr( "__thrd_start" ),
[09f357ec]1360                                        { new VariableExpr( param ), new NameExpr("main") }
[bd4d011]1361                                )
1362                        )
1363                );
1364        }
[68fe077a]1365};
[6b0b624]1366
1367// Local Variables: //
1368// mode: c //
1369// tab-width: 4 //
1370// End: //
[1c01c58]1371
Note: See TracBrowser for help on using the repository browser.