source: src/Concurrency/Keywords.cc @ aaf92de

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since aaf92de was b583113, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Recovered the polymorphic CoroutineCancelled? exception. The interface might need a bit of polish.

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