source: src/Concurrency/Actors.cpp @ a6bb5fc

ADTast-experimental
Last change on this file since a6bb5fc was 3830c84, checked in by caparsons <caparson@…>, 20 months ago

cleaned up actor pass and added virtual destructor pass

  • Property mode set to 100644
File size: 20.2 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 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// Actors.cpp -- generate code needed by the actor system
8//
9// Author           : Colby Parsons
10// Created On       : Thurs Jan  19 15:34:00 2023
11// Last Modified By : Colby Parsons
12// Last Modified On : Thurs Jan  19 15:34:00 2023
13// Update Count     : 0
14//
15
16#include "AST/Print.hpp"
17#include "AST/Decl.hpp"
18#include "AST/Pass.hpp"
19#include "AST/Type.hpp"
20#include "AST/Stmt.hpp"
21#include "AST/TranslationUnit.hpp"
22#include "AST/Expr.hpp"
23#include <algorithm>
24using namespace ast;
25using namespace std;
26
27namespace Concurrency {
28
29struct CollectactorStructDecls : public ast::WithGuards {
30    unordered_set<const StructDecl *> & actorStructDecls;
31    unordered_set<const StructDecl *>  & messageStructDecls;
32    const StructDecl ** requestDecl;
33    const EnumDecl ** allocationDecl;
34    const StructDecl ** actorDecl;
35    const StructDecl ** msgDecl;
36    StructDecl * parentDecl;
37    bool insideStruct = false;
38    bool namedDecl = false;
39
40    // finds and sets a ptr to the Allocation enum, which is needed in the next pass
41    void previsit( const EnumDecl * decl ) {
42        if( decl->name == "Allocation" ) *allocationDecl = decl;
43    }
44
45    // finds and sets a ptr to the actor, message, and request structs, which are needed in the next pass
46    void previsit( const StructDecl * decl ) {
47        if ( !decl->body ) return;
48        if ( decl->name == "actor" ) {
49            actorStructDecls.insert( decl ); // skip inserting fwd decl
50            *actorDecl = decl;
51        } else if( decl->name == "message" ) {
52            messageStructDecls.insert( decl ); // skip inserting fwd decl
53            *msgDecl = decl;
54        } else if( decl->name == "request" ) *requestDecl = decl;
55        else {
56            GuardValue(insideStruct);
57            insideStruct = true;
58            parentDecl = mutate( decl );
59        }
60        }
61
62    // this catches structs of the form:
63    //     struct dummy_actor { actor a; };
64    // since they should be:
65    //     struct dummy_actor { inline actor; };
66    void previsit ( const ObjectDecl * decl ) {
67        if ( insideStruct && ! decl->name.empty() ) {
68            GuardValue(namedDecl);
69            namedDecl = true;
70        }
71    }
72
73    // this collects the derived actor and message struct decl ptrs
74    void postvisit( const StructInstType * node ) {
75        if ( ! *actorDecl || ! *msgDecl ) return;
76        if ( insideStruct && !namedDecl ) {
77            auto actorIter = actorStructDecls.find( node->aggr() );   
78            if ( actorIter != actorStructDecls.end() ) {
79                actorStructDecls.insert( parentDecl );
80                return;
81            }
82            auto messageIter = messageStructDecls.find( node->aggr() );
83            if ( messageIter != messageStructDecls.end() ) {
84                messageStructDecls.insert( parentDecl );
85            }
86        }
87        }
88
89  public:
90    CollectactorStructDecls( unordered_set<const StructDecl *> & actorStructDecls, unordered_set<const StructDecl *> & messageStructDecls,
91        const StructDecl ** requestDecl, const EnumDecl ** allocationDecl, const StructDecl ** actorDecl, const StructDecl ** msgDecl ) 
92        : actorStructDecls( actorStructDecls ), messageStructDecls( messageStructDecls ), requestDecl( requestDecl ), 
93        allocationDecl( allocationDecl ), actorDecl(actorDecl), msgDecl(msgDecl) {}
94};
95
96// keeps track of all fwdDecls of message routines so that we can hoist them to right after the appropriate decls
97class FwdDeclTable {
98
99    // tracks which decls we have seen so that we can hoist the FunctionDecl to the highest point possible
100    struct FwdDeclData { 
101        const StructDecl * actorDecl;
102        const StructDecl * msgDecl;
103        FunctionDecl * fwdDecl;
104        bool actorFound;
105        bool msgFound;
106
107        bool readyToInsert() { return actorFound && msgFound; }
108        bool foundActor() { actorFound = true; return readyToInsert(); }
109        bool foundMsg() { msgFound = true; return readyToInsert(); }
110
111        FwdDeclData( const StructDecl * actorDecl, const StructDecl * msgDecl, FunctionDecl * fwdDecl ) :
112            actorDecl(actorDecl), msgDecl(msgDecl), fwdDecl(fwdDecl), actorFound(false), msgFound(false) {}
113    };
114
115    // map indexed by actor struct ptr
116    // value is map of all FwdDeclData that contains said actor struct ptr
117    // inner map is indexed by the message struct ptr of FwdDeclData
118    unordered_map<const StructDecl *, unordered_map<const StructDecl *, FwdDeclData *>> actorMap;
119
120    // this map is the same except the outer map is indexed by message ptr and the inner is indexed by actor ptr
121    unordered_map<const StructDecl *, unordered_map<const StructDecl *, FwdDeclData *>> msgMap;
122
123    void insert( const StructDecl * decl, const StructDecl * otherDecl, unordered_map<const StructDecl *, unordered_map<const StructDecl *, FwdDeclData *>> & map, FwdDeclData * data ) {
124        auto iter = map.find( decl );
125        if ( iter != map.end() ) { // if decl exists in map append data to existing inner map
126            iter->second.emplace( make_pair( otherDecl, data ) );
127        } else { // else create inner map for key
128            map.emplace( make_pair( decl, unordered_map<const StructDecl *, FwdDeclData *>( { make_pair( otherDecl, data ) } ) ) );
129        }
130    }
131
132  public:
133    // insert decl into table so that we can fwd declare it later (average cost: O(1))
134    void insertDecl( const StructDecl * actorDecl, const StructDecl * msgDecl, FunctionDecl * fwdDecl ) {
135        FwdDeclData * declToInsert = new FwdDeclData( actorDecl, msgDecl, fwdDecl );
136        insert( actorDecl, msgDecl, actorMap, declToInsert );
137        insert( msgDecl, actorDecl, msgMap, declToInsert );
138    }
139
140    // returns list of decls to insert after current struct decl
141    // Over the entire pass the runtime of this routine is O(r) where r is the # of receive routines
142    list<FunctionDecl *> updateDecl( const StructDecl * decl, bool isMsg ) {
143        unordered_map<const StructDecl *, unordered_map<const StructDecl *, FwdDeclData *>> & map = isMsg ? msgMap : actorMap;
144        unordered_map<const StructDecl *, unordered_map<const StructDecl *, FwdDeclData *>> & otherMap =  isMsg ? actorMap : msgMap;
145        auto iter = map.find( decl );
146        list<FunctionDecl *> toInsertAfter; // this is populated with decls that are ready to insert
147        if ( iter == map.end() ) return toInsertAfter;
148       
149        // iterate over inner map
150        unordered_map<const StructDecl *, FwdDeclData *> & currInnerMap = iter->second;
151        for ( auto innerIter = currInnerMap.begin(); innerIter != currInnerMap.end(); ) {
152            FwdDeclData * currentDatum = innerIter->second;
153            bool readyToInsert = isMsg ? currentDatum->foundMsg() : currentDatum->foundActor();
154            if ( ! readyToInsert ) { ++innerIter; continue; }
155           
156            // readyToInsert is true so we are good to insert the forward decl of the message fn
157            toInsertAfter.push_back( currentDatum->fwdDecl );
158
159            // need to remove from other map before deleting
160            // find inner map in other map ( other map is actor map if original is msg map and vice versa )
161            const StructDecl * otherDecl = isMsg ? currentDatum->actorDecl : currentDatum->msgDecl;
162            auto otherMapIter = otherMap.find( otherDecl );
163
164            unordered_map<const StructDecl *, FwdDeclData *> & otherInnerMap = otherMapIter->second;
165
166            // find the FwdDeclData we need to remove in the other inner map
167            auto otherInnerIter = otherInnerMap.find( decl );
168
169            // remove references to deleted FwdDeclData from current inner map
170            innerIter = currInnerMap.erase( innerIter ); // this does the increment so no explicit inc needed
171
172            // remove references to deleted FwdDeclData from other inner map
173            otherInnerMap.erase( otherInnerIter );
174           
175            // if other inner map is now empty, remove key from other outer map
176            if ( otherInnerMap.empty() )
177                otherMap.erase( otherDecl );
178
179            // now we are safe to delete the FwdDeclData since we are done with it
180            // and we have removed all references to it from our data structures
181            delete currentDatum;
182        }
183
184        // if current inner map is now empty, remove key from outer map.
185        // Have to do this after iterating for safety
186        if ( currInnerMap.empty() )
187            map.erase( decl );
188
189        return toInsertAfter;
190    }
191};
192
193// generates the definitions of send operators for actors
194// collects data needed for next pass that does the circular defn resolution
195//     for message send operators (via table above)
196struct GenFuncsCreateTables : public ast::WithDeclsToAdd<> {
197    unordered_set<const StructDecl *> & actorStructDecls;
198    unordered_set<const StructDecl *>  & messageStructDecls;
199    const StructDecl ** requestDecl;
200    const EnumDecl ** allocationDecl;
201    const StructDecl ** actorDecl;
202    const StructDecl ** msgDecl;
203    FwdDeclTable & forwardDecls;
204
205    // generates the operator for actor message sends
206        void postvisit( const FunctionDecl * decl ) {
207        // return if not of the form receive( param1, param2 ) or if it is a forward decl
208        if ( decl->name != "receive" || decl->params.size() != 2 || !decl->stmts ) return;
209
210        // the params should be references
211        const ReferenceType * derivedActorRef = dynamic_cast<const ReferenceType *>(decl->params.at(0)->get_type());
212        const ReferenceType * derivedMsgRef = dynamic_cast<const ReferenceType *>(decl->params.at(1)->get_type());
213        if ( !derivedActorRef || !derivedMsgRef ) return;
214
215        // the references should be to struct instances
216        const StructInstType * arg1InstType = dynamic_cast<const StructInstType *>(derivedActorRef->base.get());
217        const StructInstType * arg2InstType = dynamic_cast<const StructInstType *>(derivedMsgRef->base.get());
218        if ( !arg1InstType || !arg2InstType ) return;
219
220        // If the struct instances are derived actor and message types then generate the message send routine
221        auto actorIter = actorStructDecls.find( arg1InstType->aggr() );
222        auto messageIter = messageStructDecls.find( arg2InstType->aggr() );
223        if ( actorIter != actorStructDecls.end() && messageIter != messageStructDecls.end() ) {
224            //////////////////////////////////////////////////////////////////////
225            // The following generates this send message operator routine for all receive(derived_actor &, derived_msg &) functions
226            /*
227                static inline derived_actor & ?|?( derived_actor & receiver, derived_msg & msg ) {
228                    request new_req;
229                    Allocation (*my_work_fn)( derived_actor &, derived_msg & ) = receive;
230                    __receive_fn fn = (__receive_fn)my_work_fn;
231                    new_req{ &receiver, &msg, fn };
232                    send( receiver, new_req );
233                    return receiver;
234                }
235            */ 
236            CompoundStmt * sendBody = new CompoundStmt( decl->location );
237
238            // Generates: request new_req;
239            sendBody->push_back( new DeclStmt(
240                decl->location,
241                new ObjectDecl(
242                    decl->location,
243                    "new_req",
244                    new StructInstType( *requestDecl )
245                )
246            ));
247           
248            // Function type is: Allocation (*)( derived_actor &, derived_msg & )
249            FunctionType * derivedReceive = new FunctionType();
250            derivedReceive->params.push_back( ast::deepCopy( derivedActorRef ) );
251            derivedReceive->params.push_back( ast::deepCopy( derivedMsgRef ) );
252            derivedReceive->returns.push_back( new EnumInstType( *allocationDecl ) );
253
254            // Generates: Allocation (*my_work_fn)( derived_actor &, derived_msg & ) = receive;
255            sendBody->push_back( new DeclStmt(
256                decl->location,
257                new ObjectDecl(
258                    decl->location,
259                    "my_work_fn",
260                    new PointerType( derivedReceive ),
261                    new SingleInit( decl->location, new NameExpr( decl->location, "receive" ) )
262                )
263            ));
264
265            // Function type is: Allocation (*)( actor &, message & )
266            FunctionType * genericReceive = new FunctionType();
267            genericReceive->params.push_back( new ReferenceType( new StructInstType( *actorDecl ) ) );
268            genericReceive->params.push_back( new ReferenceType( new StructInstType( *msgDecl ) ) );
269            genericReceive->returns.push_back( new EnumInstType( *allocationDecl ) );
270
271            // Generates: Allocation (*fn)( actor &, message & ) = (Allocation (*)( actor &, message & ))my_work_fn;
272            // More readable synonymous code:
273            //     typedef Allocation (*__receive_fn)(actor &, message &);
274            //     __receive_fn fn = (__receive_fn)my_work_fn;
275            sendBody->push_back( new DeclStmt(
276                decl->location,
277                new ObjectDecl(
278                    decl->location,
279                    "fn",
280                    new PointerType( genericReceive ),
281                    new SingleInit( decl->location, 
282                        new CastExpr( decl->location, new NameExpr( decl->location, "my_work_fn" ), new PointerType( genericReceive ), ExplicitCast )
283                    )
284                )
285            ));
286
287            // Generates: new_req{ &receiver, &msg, fn };
288            sendBody->push_back( new ExprStmt(
289                decl->location,
290                                new UntypedExpr (
291                    decl->location, 
292                                        new NameExpr( decl->location, "?{}" ),
293                                        {
294                                                new NameExpr( decl->location, "new_req" ),
295                        new AddressExpr( new NameExpr( decl->location, "receiver" ) ),
296                        new AddressExpr( new NameExpr( decl->location, "msg" ) ),
297                        new NameExpr( decl->location, "fn" )
298                                        }
299                                )
300                        ));
301
302            // Generates: send( receiver, new_req );
303            sendBody->push_back( new ExprStmt(
304                decl->location,
305                                new UntypedExpr (
306                    decl->location,
307                                        new NameExpr( decl->location, "send" ),
308                                        {
309                                                {
310                            new NameExpr( decl->location, "receiver" ),
311                            new NameExpr( decl->location, "new_req" )
312                        }
313                                        }
314                                )
315                        ));
316           
317            // Generates: return receiver;
318            sendBody->push_back( new ReturnStmt( decl->location, new NameExpr( decl->location, "receiver" ) ) );
319
320            // put it all together into the complete function decl from above
321            FunctionDecl * sendOperatorFunction = new FunctionDecl(
322                decl->location,
323                "?<<?",
324                {},                     // forall
325                {
326                    new ObjectDecl(
327                        decl->location,
328                        "receiver",
329                        ast::deepCopy( derivedActorRef )
330                    ),
331                    new ObjectDecl(
332                        decl->location,
333                        "msg",
334                        ast::deepCopy( derivedMsgRef )
335                    )
336                },                      // params
337                { 
338                    new ObjectDecl(
339                        decl->location,
340                        "receiver_ret",
341                        ast::deepCopy( derivedActorRef )
342                    )
343                },
344                nullptr,               // body
345                { Storage::Static },    // storage
346                Linkage::Cforall,       // linkage
347                {},                     // attributes
348                { Function::Inline }
349            );
350           
351            // forward decls to resolve use before decl problem for '|' routines
352            forwardDecls.insertDecl( *actorIter, *messageIter , ast::deepCopy( sendOperatorFunction ) );
353
354            sendOperatorFunction->stmts = sendBody;
355            declsToAddAfter.push_back( sendOperatorFunction );
356        }
357        }
358
359  public:
360    GenFuncsCreateTables( unordered_set<const StructDecl *> & actorStructDecls, unordered_set<const StructDecl *> & messageStructDecls,
361        const StructDecl ** requestDecl, const EnumDecl ** allocationDecl, const StructDecl ** actorDecl, const StructDecl ** msgDecl, 
362        FwdDeclTable & forwardDecls ) : actorStructDecls(actorStructDecls), messageStructDecls(messageStructDecls), 
363        requestDecl(requestDecl), allocationDecl(allocationDecl), actorDecl(actorDecl), msgDecl(msgDecl), forwardDecls(forwardDecls) {}
364};
365
366
367// separate pass is needed since this pass resolves circular defn issues
368// generates the forward declarations of the send operator for actor routines
369struct FwdDeclOperator : public ast::WithDeclsToAdd<> {
370    unordered_set<const StructDecl *> & actorStructDecls;
371    unordered_set<const StructDecl *>  & messageStructDecls;
372    FwdDeclTable & forwardDecls;
373
374    // handles forward declaring the message operator
375    void postvisit( const StructDecl * decl ) {
376        list<FunctionDecl *> toAddAfter;
377        auto actorIter = actorStructDecls.find( decl );
378        if ( actorIter != actorStructDecls.end() ) { // this is a derived actor decl
379            // get list of fwd decls that we can now insert
380            toAddAfter = forwardDecls.updateDecl( decl, false );
381
382            // get rid of decl from actorStructDecls since we no longer need it
383            actorStructDecls.erase( actorIter );
384        } else {
385            auto messageIter = messageStructDecls.find( decl );
386            if ( messageIter == messageStructDecls.end() ) return;
387
388            toAddAfter = forwardDecls.updateDecl( decl, true );
389
390            // get rid of decl from messageStructDecls since we no longer need it
391            messageStructDecls.erase( messageIter );
392        }
393
394        // add the fwd decls to declsToAddAfter
395        for ( FunctionDecl * func : toAddAfter ) {
396            declsToAddAfter.push_back( func );
397        }
398    }
399
400  public:
401    FwdDeclOperator( unordered_set<const StructDecl *> & actorStructDecls, unordered_set<const StructDecl *> & messageStructDecls, 
402        FwdDeclTable & forwardDecls ) : actorStructDecls(actorStructDecls), messageStructDecls(messageStructDecls), forwardDecls(forwardDecls) {}
403};
404
405void implementActors( TranslationUnit & translationUnit ) {
406    // unordered_maps to collect all derived actor and message types
407    unordered_set<const StructDecl *> actorStructDecls;
408    unordered_set<const StructDecl *> messageStructDecls;
409    FwdDeclTable forwardDecls;
410
411    // for storing through the passes
412    // these are populated with various important struct decls
413    const StructDecl * requestDeclPtr = nullptr;
414    const EnumDecl * allocationDeclPtr = nullptr;
415    const StructDecl * actorDeclPtr = nullptr;
416    const StructDecl * msgDeclPtr = nullptr;
417
418    // double pointer to modify local ptrs above
419    const StructDecl ** requestDecl = &requestDeclPtr;
420    const EnumDecl ** allocationDecl = &allocationDeclPtr;
421    const StructDecl ** actorDecl = &actorDeclPtr;
422    const StructDecl ** msgDecl = &msgDeclPtr;
423
424    // first pass collects ptrs to Allocation enum, request type, and generic receive fn typedef
425    // also populates maps of all derived actors and messages
426    Pass<CollectactorStructDecls>::run( translationUnit, actorStructDecls, messageStructDecls, requestDecl, 
427        allocationDecl, actorDecl, msgDecl );
428
429    // check that we have found all the decls we need from <actor.hfa>, if not no need to run the rest of this pass
430    if ( !allocationDeclPtr || !requestDeclPtr || !actorDeclPtr || !msgDeclPtr ) 
431        return;
432
433    // second pass locates all receive() routines that overload the generic receive fn
434    // it then generates the appropriate operator '|' send routines for the receive routines
435    Pass<GenFuncsCreateTables>::run( translationUnit, actorStructDecls, messageStructDecls, requestDecl, 
436        allocationDecl, actorDecl, msgDecl, forwardDecls );
437
438    // The third pass forward declares operator '|' send routines
439    Pass<FwdDeclOperator>::run( translationUnit, actorStructDecls, messageStructDecls, forwardDecls );
440}
441
442
443} // namespace Concurrency
444
445// Local Variables: //
446// tab-width: 4 //
447// mode: c++ //
448// compile-command: "make install" //
449// End: //
450
Note: See TracBrowser for help on using the repository browser.