source: src/Concurrency/Waitfor.cc @ ba3706f

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since ba3706f was ba3706f, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Remove label lists from various Statement constructors

  • Property mode set to 100644
File size: 15.1 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Waitfor.cc --
8//
9// Author           : Thierry Delisle
10// Created On       : Mon Aug 28 11:06:52 2017
11// Last Modified By :
12// Last Modified On :
13// Update Count     : 5
14//
15
16#include "Concurrency/Keywords.h"
17
18#include <cassert>                 // for assert
19#include <string>                  // for string, operator==
20
21using namespace std::string_literals;
22
23#include "Common/PassVisitor.h"    // for PassVisitor
24#include "Common/SemanticError.h"  // for SemanticError
25#include "Common/utility.h"        // for deleteAll, map_range
26#include "CodeGen/OperatorTable.h" // for isConstructor
27#include "InitTweak/InitTweak.h"   // for getPointerBase
28#include "Parser/LinkageSpec.h"    // for Cforall
29#include "ResolvExpr/Resolver.h"   // for findVoidExpression
30#include "SynTree/Constant.h"      // for Constant
31#include "SynTree/Declaration.h"   // for StructDecl, FunctionDecl, ObjectDecl
32#include "SynTree/Expression.h"    // for VariableExpr, ConstantExpr, Untype...
33#include "SynTree/Initializer.h"   // for SingleInit, ListInit, Initializer ...
34#include "SynTree/Label.h"         // for Label
35#include "SynTree/Statement.h"     // for CompoundStmt, DeclStmt, ExprStmt
36#include "SynTree/Type.h"          // for StructInstType, Type, PointerType
37#include "SynTree/Visitor.h"       // for Visitor, acceptAll
38
39class Attribute;
40/*
41void foo() {
42        while( true ) {
43                when( a < 1 ) waitfor( f, a ) { bar(); }
44                or timeout( swagl() );
45                or waitfor( g, a ) { baz(); }
46                or waitfor( ^?{}, a ) { break; }
47                or waitfor( ^?{} ) { break; }
48        }
49}
50
51void f(int i, float f, A & mutex b, struct foo *  );
52void f(int );
53
54
55                      |  |
56                      |  |
57                            |  |
58                      |  |
59                      |  |
60                    \ |  | /
61                     \    /
62                      \  /
63                       \/
64
65
66void foo() {
67        while( true ) {
68
69                acceptable_t acceptables[3];
70                if( a < 1 ) {
71                        acceptables[0].func = f;
72                        acceptables[0].mon = a;
73                }
74                acceptables[1].func = g;
75                acceptables[1].mon = a;
76
77                acceptables[2].func = f;
78                acceptables[2].mon = a;
79                acceptables[2].is_dtor = true;
80
81                int ret = waitfor_internal( acceptables, swagl() );
82
83                switch( ret ) {
84                        case 0:
85                        {
86                                bar();
87                        }
88                        case 1:
89                        {
90                                baz();
91                        }
92                        case 2:
93                                signal(a);
94                                {
95                                        break;
96                                }
97                }
98        }
99}*/
100
101namespace Concurrency {
102        //=============================================================================================
103        // Pass declarations
104        //=============================================================================================
105
106        class GenerateWaitForPass final : public WithIndexer {
107          public:
108
109                void premutate( FunctionDecl * decl );
110                void premutate( StructDecl   * decl );
111
112                Statement * postmutate( WaitForStmt * stmt );
113
114                static void generate( std::list< Declaration * > & translationUnit ) {
115                        PassVisitor< GenerateWaitForPass > impl;
116                        acceptAll( translationUnit, impl );
117                }
118
119                ObjectDecl * declare( unsigned long count, CompoundStmt * stmt );
120                ObjectDecl * declareFlag( CompoundStmt * stmt );
121                Statement  * makeSetter( ObjectDecl * flag );
122                ObjectDecl * declMon( WaitForStmt::Clause & clause, CompoundStmt * stmt );
123                void         init( ObjectDecl * acceptables, int index, WaitForStmt::Clause & clause, Statement * settter, CompoundStmt * stmt );
124                Expression * init_timeout( Expression *& time, Expression *& time_cond, bool has_else, Expression *& else_cond, Statement * settter, CompoundStmt * stmt );
125                Expression * call(size_t count, ObjectDecl * acceptables, Expression * timeout, CompoundStmt * stmt);
126                void         choose( WaitForStmt * waitfor, Expression  * result, CompoundStmt * stmt );
127
128                static void implement( std::list< Declaration * > & translationUnit ) {
129                        PassVisitor< GenerateWaitForPass > impl;
130                        mutateAll( translationUnit, impl );
131                }
132
133
134          private:
135                FunctionDecl        * decl_waitfor    = nullptr;
136                StructDecl          * decl_mask       = nullptr;
137                StructDecl          * decl_acceptable = nullptr;
138                StructDecl          * decl_monitor    = nullptr;
139
140                static std::unique_ptr< Type > generic_func;
141
142                UniqueName namer_acc = "__acceptables_"s;
143                UniqueName namer_idx = "__index_"s;
144                UniqueName namer_flg = "__do_run_"s;
145                UniqueName namer_msk = "__mask_"s;
146                UniqueName namer_mon = "__monitors_"s;
147                UniqueName namer_tim = "__timeout_"s;
148        };
149
150        //=============================================================================================
151        // General entry routine
152        //=============================================================================================
153        void generateWaitFor( std::list< Declaration * > & translationUnit ) {
154                GenerateWaitForPass     ::implement( translationUnit );
155        }
156
157        //=============================================================================================
158        // Generic helper routine
159        //=============================================================================================
160
161        namespace {
162                Expression * makeOpIndex( DeclarationWithType * array, unsigned long index ) {
163                        return new UntypedExpr(
164                                new NameExpr( "?[?]" ),
165                                {
166                                        new VariableExpr( array ),
167                                        new ConstantExpr( Constant::from_ulong( index ) )
168                                }
169                        );
170                }
171
172                Expression * makeOpAssign( Expression * lhs, Expression * rhs ) {
173                        return new UntypedExpr(
174                                        new NameExpr( "?=?" ),
175                                        { lhs, rhs }
176                        );
177                }
178
179                Expression * makeOpMember( Expression * sue, const std::string & mem ) {
180                        return new UntypedMemberExpr( new NameExpr( mem ), sue );
181                }
182
183                Statement * makeAccStatement( DeclarationWithType * object, unsigned long index, const std::string & member, Expression * value, const SymTab::Indexer & indexer ) {
184                        Expression * expr = makeOpAssign(
185                                makeOpMember(
186                                        makeOpIndex(
187                                                object,
188                                                index
189                                        ),
190                                        member
191                                ),
192                                value
193                        );
194
195                        ResolvExpr::findVoidExpression( expr, indexer );
196
197                        return new ExprStmt( expr );
198                }
199
200                Expression * safeCond( Expression * expr, bool ifnull = true ) {
201                        if( expr ) return expr;
202
203                        return new ConstantExpr( Constant::from_bool( ifnull ) );
204                }
205
206                VariableExpr * extractVariable( Expression * func ) {
207                        if( VariableExpr * var = dynamic_cast< VariableExpr * >( func ) ) {
208                                return var;
209                        }
210
211                        CastExpr * cast = strict_dynamic_cast< CastExpr * >( func );
212                        return strict_dynamic_cast< VariableExpr * >( cast->arg );
213                }
214
215                Expression * detectIsDtor( Expression * func ) {
216                        VariableExpr * typed_func = extractVariable( func );
217                        bool is_dtor = InitTweak::isDestructor( typed_func->var );
218                        return new ConstantExpr( Constant::from_bool( is_dtor ) );
219                }
220        };
221
222
223        //=============================================================================================
224        // Generate waitfor implementation
225        //=============================================================================================
226
227        void GenerateWaitForPass::premutate( FunctionDecl * decl) {
228                if( decl->name != "__waitfor_internal" ) return;
229
230                decl_waitfor = decl;
231        }
232
233        void GenerateWaitForPass::premutate( StructDecl   * decl ) {
234                if( ! decl->body ) return;
235
236                if( decl->name == "__acceptable_t" ) {
237                        assert( !decl_acceptable );
238                        decl_acceptable = decl;
239                }
240                else if( decl->name == "__waitfor_mask_t" ) {
241                        assert( !decl_mask );
242                        decl_mask = decl;
243                }
244                else if( decl->name == "monitor_desc" ) {
245                        assert( !decl_monitor );
246                        decl_monitor = decl;
247                }
248        }
249
250        Statement * GenerateWaitForPass::postmutate( WaitForStmt * waitfor ) {
251                if( !decl_monitor || !decl_acceptable || !decl_mask ) throw SemanticError( "waitfor keyword requires monitors to be in scope, add #include <monitor>", waitfor );
252
253                CompoundStmt * stmt = new CompoundStmt();
254
255                ObjectDecl * acceptables = declare( waitfor->clauses.size(), stmt );
256                ObjectDecl * flag        = declareFlag( stmt );
257                Statement  * setter      = makeSetter( flag );
258
259                int index = 0;
260                for( auto & clause : waitfor->clauses ) {
261                        init( acceptables, index, clause, setter, stmt );
262
263                        index++;
264                }
265
266                Expression * timeout = init_timeout(
267                        waitfor->timeout.time,
268                        waitfor->timeout.condition,
269                        waitfor->orelse .statement,
270                        waitfor->orelse .condition,
271                        setter,
272                        stmt
273                );
274
275                CompoundStmt * compound = new CompoundStmt();
276                stmt->push_back( new IfStmt(
277                        safeCond( new VariableExpr( flag ) ),
278                        compound,
279                        nullptr
280                ));
281
282                Expression * result = call( waitfor->clauses.size(), acceptables, timeout, compound );
283
284                choose( waitfor, result, compound );
285
286                return stmt;
287        }
288
289        ObjectDecl * GenerateWaitForPass::declare( unsigned long count, CompoundStmt * stmt )
290        {
291                ObjectDecl * acceptables = ObjectDecl::newObject(
292                        namer_acc.newName(),
293                        new ArrayType(
294                                noQualifiers,
295                                new StructInstType(
296                                        noQualifiers,
297                                        decl_acceptable
298                                ),
299                                new ConstantExpr( Constant::from_ulong( count ) ),
300                                false,
301                                false
302                        ),
303                        nullptr
304                );
305
306                stmt->push_back( new DeclStmt( acceptables) );
307
308                Expression * set = new UntypedExpr(
309                        new NameExpr( "__builtin_memset" ),
310                        {
311                                new VariableExpr( acceptables ),
312                                new ConstantExpr( Constant::from_int( 0 ) ),
313                                new SizeofExpr( new VariableExpr( acceptables ) )
314                        }
315                );
316
317                ResolvExpr::findVoidExpression( set, indexer );
318
319                stmt->push_back( new ExprStmt( set ) );
320
321                return acceptables;
322        }
323
324        ObjectDecl * GenerateWaitForPass::declareFlag( CompoundStmt * stmt ) {
325                ObjectDecl * flag = ObjectDecl::newObject(
326                        namer_flg.newName(),
327                        new BasicType(
328                                noQualifiers,
329                                BasicType::Bool
330                        ),
331                        new SingleInit( new ConstantExpr( Constant::from_ulong( 0 ) ) )
332                );
333
334                stmt->push_back( new DeclStmt( flag) );
335
336                return flag;
337        }
338
339        Statement * GenerateWaitForPass::makeSetter( ObjectDecl * flag ) {
340                Expression * expr = new UntypedExpr(
341                        new NameExpr( "?=?" ),
342                        {
343                                new VariableExpr( flag ),
344                                new ConstantExpr( Constant::from_ulong( 1 ) )
345                        }
346                );
347
348                ResolvExpr::findVoidExpression( expr, indexer );
349
350                return new ExprStmt( expr );
351        }
352
353        ObjectDecl * GenerateWaitForPass::declMon( WaitForStmt::Clause & clause, CompoundStmt * stmt ) {
354
355                ObjectDecl * mon = ObjectDecl::newObject(
356                        namer_mon.newName(),
357                        new ArrayType(
358                                noQualifiers,
359                                new PointerType(
360                                        noQualifiers,
361                                        new StructInstType(
362                                                noQualifiers,
363                                                decl_monitor
364                                        )
365                                ),
366                                new ConstantExpr( Constant::from_ulong( clause.target.arguments.size() ) ),
367                                false,
368                                false
369                        ),
370                        new ListInit(
371                                map_range < std::list<Initializer*> > ( clause.target.arguments, [this](Expression * expr ){
372                                        Expression * init = new CastExpr(
373                                                new UntypedExpr(
374                                                        new NameExpr( "get_monitor" ),
375                                                        { expr }
376                                                ),
377                                                new PointerType(
378                                                        noQualifiers,
379                                                        new StructInstType(
380                                                                noQualifiers,
381                                                                decl_monitor
382                                                        )
383                                                )
384                                        );
385
386                                        ResolvExpr::findSingleExpression( init, indexer );
387                                        return new SingleInit( init );
388                                })
389                        )
390                );
391
392                stmt->push_back( new DeclStmt( mon) );
393
394                return mon;
395        }
396
397        void GenerateWaitForPass::init( ObjectDecl * acceptables, int index, WaitForStmt::Clause & clause, Statement * setter, CompoundStmt * stmt ) {
398
399                ObjectDecl * monitors = declMon( clause, stmt );
400
401                Type * fptr_t = new PointerType( noQualifiers, new FunctionType( noQualifiers, true ) );
402
403                stmt->push_back( new IfStmt(
404                        safeCond( clause.condition ),
405                        new CompoundStmt({
406                                makeAccStatement( acceptables, index, "is_dtor", detectIsDtor( clause.target.function )                                    , indexer ),
407                                makeAccStatement( acceptables, index, "func"   , new CastExpr( clause.target.function, fptr_t )                            , indexer ),
408                                makeAccStatement( acceptables, index, "data"   , new VariableExpr( monitors )                                              , indexer ),
409                                makeAccStatement( acceptables, index, "size"   , new ConstantExpr( Constant::from_ulong( clause.target.arguments.size() ) ), indexer ),
410                                setter->clone()
411                        }),
412                        nullptr
413                ));
414
415                clause.target.function = nullptr;
416                clause.target.arguments.empty();
417                clause.condition = nullptr;
418        }
419
420        Expression * GenerateWaitForPass::init_timeout(
421                Expression *& time,
422                Expression *& time_cond,
423                bool has_else,
424                Expression *& else_cond,
425                Statement * setter,
426                CompoundStmt * stmt
427        ) {
428                ObjectDecl * timeout = ObjectDecl::newObject(
429                        namer_tim.newName(),
430                        new BasicType(
431                                noQualifiers,
432                                BasicType::LongLongUnsignedInt
433                        ),
434                        new SingleInit(
435                                new ConstantExpr( Constant::from_int( -1 ) )
436                        )
437                );
438
439                stmt->push_back( new DeclStmt( timeout ) );
440
441                if( time ) {
442                        stmt->push_back( new IfStmt(
443                                safeCond( time_cond ),
444                                new CompoundStmt({
445                                        new ExprStmt(
446                                                makeOpAssign(
447                                                        new VariableExpr( timeout ),
448                                                        time
449                                                )
450                                        ),
451                                        setter->clone()
452                                }),
453                                nullptr
454                        ));
455
456                        time = time_cond = nullptr;
457                }
458
459                if( has_else ) {
460                        stmt->push_back( new IfStmt(
461                                safeCond( else_cond ),
462                                new CompoundStmt({
463                                        new ExprStmt(
464                                                makeOpAssign(
465                                                        new VariableExpr( timeout ),
466                                                        new ConstantExpr( Constant::from_ulong( 0 ) )
467                                                )
468                                        ),
469                                        setter->clone()
470                                }),
471                                nullptr
472                        ));
473
474                        else_cond = nullptr;
475                }
476
477                delete setter;
478
479                return new VariableExpr( timeout );
480        }
481
482        Expression * GenerateWaitForPass::call(
483                size_t count,
484                ObjectDecl * acceptables,
485                Expression * timeout,
486                CompoundStmt * stmt
487        ) {
488                ObjectDecl * index = ObjectDecl::newObject(
489                        namer_idx.newName(),
490                        new BasicType(
491                                noQualifiers,
492                                BasicType::ShortSignedInt
493                        ),
494                        new SingleInit(
495                                new ConstantExpr( Constant::from_int( -1 ) )
496                        )
497                );
498
499                stmt->push_back( new DeclStmt( index ) );
500
501                ObjectDecl * mask = ObjectDecl::newObject(
502                        namer_msk.newName(),
503                        new StructInstType(
504                                noQualifiers,
505                                decl_mask
506                        ),
507                        new ListInit({
508                                new SingleInit( new AddressExpr( new VariableExpr( index ) ) ),
509                                new SingleInit( new VariableExpr( acceptables ) ),
510                                new SingleInit( new ConstantExpr( Constant::from_ulong( count ) ) )
511                        })
512                );
513
514                stmt->push_back( new DeclStmt( mask ) );
515
516                stmt->push_back( new ExprStmt(
517                        new ApplicationExpr(
518                                VariableExpr::functionPointer( decl_waitfor ),
519                                {
520                                        new CastExpr(
521                                                new VariableExpr( mask ),
522                                                new ReferenceType(
523                                                        noQualifiers,
524                                                        new StructInstType(
525                                                                noQualifiers,
526                                                                decl_mask
527                                                        )
528                                                )
529                                        ),
530                                        timeout
531                                }
532                        )
533                ));
534
535                return new VariableExpr( index );
536        }
537
538        void GenerateWaitForPass::choose(
539                WaitForStmt * waitfor,
540                Expression  * result,
541                CompoundStmt * stmt
542        ) {
543                SwitchStmt * swtch = new SwitchStmt(
544                        result,
545                        std::list<Statement *>()
546                );
547
548                unsigned long i = 0;
549                for( auto & clause : waitfor->clauses ) {
550                        swtch->statements.push_back(
551                                new CaseStmt(
552                                        new ConstantExpr( Constant::from_ulong( i++ ) ),
553                                        {
554                                                clause.statement,
555                                                new BranchStmt(
556                                                        "",
557                                                        BranchStmt::Break
558                                                )
559                                        }
560                                )
561                        );
562                }
563
564                if(waitfor->timeout.statement) {
565                        swtch->statements.push_back(
566                                new CaseStmt(
567                                        new ConstantExpr( Constant::from_int( -2 ) ),
568                                        {
569                                                waitfor->timeout.statement,
570                                                new BranchStmt(
571                                                        "",
572                                                        BranchStmt::Break
573                                                )
574                                        }
575                                )
576                        );
577                }
578
579                if(waitfor->orelse.statement) {
580                        swtch->statements.push_back(
581                                new CaseStmt(
582                                        new ConstantExpr( Constant::from_int( -1 ) ),
583                                        {
584                                                waitfor->orelse.statement,
585                                                new BranchStmt(
586                                                        "",
587                                                        BranchStmt::Break
588                                                )
589                                        }
590                                )
591                        );
592                }
593
594                stmt->push_back( swtch );
595        }
596};
597
598// Local Variables: //
599// mode: c //
600// tab-width: 4 //
601// End: //
Note: See TracBrowser for help on using the repository browser.