source: src/Concurrency/Keywords.cc@ eba74ba

new-env with_gc
Last change on this file since eba74ba was 42107b4, checked in by Aaron Moss <a3moss@…>, 8 years ago

Leftover cleanup from merge

  • Property mode set to 100644
File size: 20.6 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Keywords.cc --
8//
9// Author : Thierry Delisle
10// Created On : Mon Mar 13 12:41:22 2017
11// Last Modified By :
12// Last Modified On :
13// Update Count : 5
14//
15
16#include "Concurrency/Keywords.h"
17
18#include <cassert> // for assert
19#include <string> // for string, operator==
20
21#include "Common/GC.h" // for new_static_root
22#include "Common/PassVisitor.h" // for PassVisitor
23#include "Common/SemanticError.h" // for SemanticError
24#include "Common/utility.h" // for deleteAll, map_range
25#include "CodeGen/OperatorTable.h" // for isConstructor
26#include "InitTweak/InitTweak.h" // for getPointerBase
27#include "Parser/LinkageSpec.h" // for Cforall
28#include "SynTree/Constant.h" // for Constant
29#include "SynTree/Declaration.h" // for StructDecl, FunctionDecl, ObjectDecl
30#include "SynTree/Expression.h" // for VariableExpr, ConstantExpr, Untype...
31#include "SynTree/Initializer.h" // for SingleInit, ListInit, Initializer ...
32#include "SynTree/Label.h" // for Label
33#include "SynTree/Statement.h" // for CompoundStmt, DeclStmt, ExprStmt
34#include "SynTree/Type.h" // for StructInstType, Type, PointerType
35#include "SynTree/Visitor.h" // for Visitor, acceptAll
36
37class Attribute;
38
39namespace Concurrency {
40 //=============================================================================================
41 // Pass declarations
42 //=============================================================================================
43
44 //-----------------------------------------------------------------------------
45 //Handles sue type declarations :
46 // sue MyType { struct MyType {
47 // int data; int data;
48 // a_struct_t more_data; a_struct_t more_data;
49 // => NewField_t newField;
50 // }; };
51 // static inline NewField_t * getter_name( MyType * this ) { return &this->newField; }
52 //
53 class ConcurrentSueKeyword : public WithDeclsToAdd {
54 public:
55
56 ConcurrentSueKeyword( std::string&& type_name, std::string&& field_name, std::string&& getter_name, std::string&& context_error, bool needs_main, KeywordCastExpr::Target cast_target ) :
57 type_name( type_name ), field_name( field_name ), getter_name( getter_name ), context_error( context_error ), needs_main( needs_main ), cast_target( cast_target ) {}
58
59 virtual ~ConcurrentSueKeyword() {}
60
61 Declaration * postmutate( StructDecl * decl );
62
63 void handle( StructDecl * );
64 FunctionDecl * forwardDeclare( StructDecl * );
65 ObjectDecl * addField( StructDecl * );
66 void addRoutines( ObjectDecl *, FunctionDecl * );
67
68 virtual bool is_target( StructDecl * decl ) = 0;
69
70 Expression * postmutate( KeywordCastExpr * cast );
71
72 private:
73 const std::string type_name;
74 const std::string field_name;
75 const std::string getter_name;
76 const std::string context_error;
77 bool needs_main;
78 KeywordCastExpr::Target cast_target;
79
80 StructDecl* type_decl = nullptr;
81 };
82
83
84 //-----------------------------------------------------------------------------
85 //Handles thread type declarations :
86 // thread Mythread { struct MyThread {
87 // int data; int data;
88 // a_struct_t more_data; a_struct_t more_data;
89 // => thread_desc __thrd_d;
90 // }; };
91 // static inline thread_desc * get_thread( MyThread * this ) { return &this->__thrd_d; }
92 //
93 class ThreadKeyword final : public ConcurrentSueKeyword {
94 public:
95
96 ThreadKeyword() : ConcurrentSueKeyword(
97 "thread_desc",
98 "__thrd",
99 "get_thread",
100 "thread keyword requires threads to be in scope, add #include <thread>",
101 true,
102 KeywordCastExpr::Thread
103 )
104 {}
105
106 virtual ~ThreadKeyword() {}
107
108 virtual bool is_target( StructDecl * decl ) override final { return decl->is_thread(); }
109
110 static void implement( std::list< Declaration * > & translationUnit ) {
111 PassVisitor< ThreadKeyword > impl;
112 mutateAll( translationUnit, impl );
113 }
114 };
115
116 //-----------------------------------------------------------------------------
117 //Handles coroutine type declarations :
118 // coroutine MyCoroutine { struct MyCoroutine {
119 // int data; int data;
120 // a_struct_t more_data; a_struct_t more_data;
121 // => coroutine_desc __cor_d;
122 // }; };
123 // static inline coroutine_desc * get_coroutine( MyCoroutine * this ) { return &this->__cor_d; }
124 //
125 class CoroutineKeyword final : public ConcurrentSueKeyword {
126 public:
127
128 CoroutineKeyword() : ConcurrentSueKeyword(
129 "coroutine_desc",
130 "__cor",
131 "get_coroutine",
132 "coroutine keyword requires coroutines to be in scope, add #include <coroutine>",
133 true,
134 KeywordCastExpr::Coroutine
135 )
136 {}
137
138 virtual ~CoroutineKeyword() {}
139
140 virtual bool is_target( StructDecl * decl ) override final { return decl->is_coroutine(); }
141
142 static void implement( std::list< Declaration * > & translationUnit ) {
143 PassVisitor< CoroutineKeyword > impl;
144 mutateAll( translationUnit, impl );
145 }
146 };
147
148 //-----------------------------------------------------------------------------
149 //Handles monitor type declarations :
150 // monitor MyMonitor { struct MyMonitor {
151 // int data; int data;
152 // a_struct_t more_data; a_struct_t more_data;
153 // => monitor_desc __mon_d;
154 // }; };
155 // static inline monitor_desc * get_coroutine( MyMonitor * this ) { return &this->__cor_d; }
156 //
157 class MonitorKeyword final : public ConcurrentSueKeyword {
158 public:
159
160 MonitorKeyword() : ConcurrentSueKeyword(
161 "monitor_desc",
162 "__mon",
163 "get_monitor",
164 "monitor keyword requires monitors to be in scope, add #include <monitor>",
165 false,
166 KeywordCastExpr::Monitor
167 )
168 {}
169
170 virtual ~MonitorKeyword() {}
171
172 virtual bool is_target( StructDecl * decl ) override final { return decl->is_monitor(); }
173
174 static void implement( std::list< Declaration * > & translationUnit ) {
175 PassVisitor< MonitorKeyword > impl;
176 mutateAll( translationUnit, impl );
177 }
178 };
179
180 //-----------------------------------------------------------------------------
181 //Handles mutex routines definitions :
182 // void foo( A * mutex a, B * mutex b, int i ) { void foo( A * a, B * b, int i ) {
183 // monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
184 // monitor_guard_t __guard = { __monitors, 2 };
185 // /*Some code*/ => /*Some code*/
186 // } }
187 //
188 class MutexKeyword final {
189 public:
190
191 void postvisit( FunctionDecl * decl );
192 void postvisit( StructDecl * decl );
193
194 std::list<DeclarationWithType*> findMutexArgs( FunctionDecl* );
195 void validate( DeclarationWithType * );
196 void addDtorStatments( FunctionDecl* func, CompoundStmt *, const std::list<DeclarationWithType * > &);
197 void addStatments( FunctionDecl* func, CompoundStmt *, const std::list<DeclarationWithType * > &);
198
199 static void implement( std::list< Declaration * > & translationUnit ) {
200 PassVisitor< MutexKeyword > impl;
201 acceptAll( translationUnit, impl );
202 }
203
204 private:
205 StructDecl* monitor_decl = nullptr;
206 StructDecl* guard_decl = nullptr;
207 StructDecl* dtor_guard_decl = nullptr;
208
209 static Type* generic_func;
210 };
211
212 Type* MutexKeyword::generic_func = new_static_root<FunctionType>( noQualifiers, true );
213
214 //-----------------------------------------------------------------------------
215 //Handles mutex routines definitions :
216 // void foo( A * mutex a, B * mutex b, int i ) { void foo( A * a, B * b, int i ) {
217 // monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
218 // monitor_guard_t __guard = { __monitors, 2 };
219 // /*Some code*/ => /*Some code*/
220 // } }
221 //
222 class ThreadStarter final {
223 public:
224
225 void postvisit( FunctionDecl * decl );
226 void previsit ( StructDecl * decl );
227
228 void addStartStatement( FunctionDecl * decl, DeclarationWithType * param );
229
230 static void implement( std::list< Declaration * > & translationUnit ) {
231 PassVisitor< ThreadStarter > impl;
232 acceptAll( translationUnit, impl );
233 }
234
235 private :
236 bool thread_ctor_seen = false;
237 StructDecl * thread_decl = nullptr;
238 };
239
240 //=============================================================================================
241 // General entry routine
242 //=============================================================================================
243 void applyKeywords( std::list< Declaration * > & translationUnit ) {
244 ThreadKeyword ::implement( translationUnit );
245 CoroutineKeyword ::implement( translationUnit );
246 MonitorKeyword ::implement( translationUnit );
247 }
248
249 void implementMutexFuncs( std::list< Declaration * > & translationUnit ) {
250 MutexKeyword ::implement( translationUnit );
251 }
252
253 void implementThreadStarter( std::list< Declaration * > & translationUnit ) {
254 ThreadStarter ::implement( translationUnit );
255 }
256
257 //=============================================================================================
258 // Generic keyword implementation
259 //=============================================================================================
260 void fixupGenerics(FunctionType * func, StructDecl * decl) {
261 cloneAll(decl->parameters, func->forall);
262 for ( TypeDecl * td : func->forall ) {
263 strict_dynamic_cast<StructInstType*>(
264 func->parameters.front()->get_type()->stripReferences()
265 )->parameters.push_back(
266 new TypeExpr( new TypeInstType( noQualifiers, td->name, td ) )
267 );
268 }
269 }
270
271 Declaration * ConcurrentSueKeyword::postmutate(StructDecl * decl) {
272 if( decl->name == type_name && decl->body ) {
273 assert( !type_decl );
274 type_decl = decl;
275 }
276 else if ( is_target(decl) ) {
277 handle( decl );
278 }
279 return decl;
280 }
281
282 Expression * ConcurrentSueKeyword::postmutate( KeywordCastExpr * cast ) {
283 if ( cast_target == cast->target ) {
284 // convert (thread &)t to (thread_desc &)*get_thread(t), etc.
285 if( !type_decl ) SemanticError( cast, context_error );
286 return new CastExpr(
287 UntypedExpr::createDeref(
288 new UntypedExpr( new NameExpr( getter_name ), { cast->arg } )
289 ),
290 new ReferenceType(
291 noQualifiers,
292 new StructInstType( noQualifiers, type_decl ) )
293 );
294 }
295 return cast;
296 }
297
298
299 void ConcurrentSueKeyword::handle( StructDecl * decl ) {
300 if( ! decl->body ) return;
301
302 if( !type_decl ) SemanticError( decl, context_error );
303
304 FunctionDecl * func = forwardDeclare( decl );
305 ObjectDecl * field = addField( decl );
306 addRoutines( field, func );
307 }
308
309 FunctionDecl * ConcurrentSueKeyword::forwardDeclare( StructDecl * decl ) {
310
311 StructDecl * forward = decl->clone();
312 forward->set_body( false );
313 forward->get_members().clear();
314
315 FunctionType * get_type = new FunctionType( noQualifiers, false );
316 ObjectDecl * this_decl = new ObjectDecl(
317 "this",
318 noStorageClasses,
319 LinkageSpec::Cforall,
320 nullptr,
321 new ReferenceType(
322 noQualifiers,
323 new StructInstType(
324 noQualifiers,
325 decl
326 )
327 ),
328 nullptr
329 );
330
331 get_type->get_parameters().push_back( this_decl->clone() );
332 get_type->get_returnVals().push_back(
333 new ObjectDecl(
334 "ret",
335 noStorageClasses,
336 LinkageSpec::Cforall,
337 nullptr,
338 new PointerType(
339 noQualifiers,
340 new StructInstType(
341 noQualifiers,
342 type_decl
343 )
344 ),
345 nullptr
346 )
347 );
348 fixupGenerics(get_type, decl);
349
350 FunctionDecl * get_decl = new FunctionDecl(
351 getter_name,
352 Type::Static,
353 LinkageSpec::Cforall,
354 get_type,
355 nullptr,
356 noAttributes,
357 Type::Inline
358 );
359
360 FunctionDecl * main_decl = nullptr;
361
362 if( needs_main ) {
363 FunctionType * main_type = new FunctionType( noQualifiers, false );
364
365 main_type->get_parameters().push_back( this_decl->clone() );
366
367 main_decl = new FunctionDecl(
368 "main",
369 noStorageClasses,
370 LinkageSpec::Cforall,
371 main_type,
372 nullptr
373 );
374 fixupGenerics(main_type, decl);
375 }
376
377 declsToAddBefore.push_back( forward );
378 if( needs_main ) declsToAddBefore.push_back( main_decl );
379 declsToAddBefore.push_back( get_decl );
380
381 return get_decl;
382 }
383
384 ObjectDecl * ConcurrentSueKeyword::addField( StructDecl * decl ) {
385 ObjectDecl * field = new ObjectDecl(
386 field_name,
387 noStorageClasses,
388 LinkageSpec::Cforall,
389 nullptr,
390 new StructInstType(
391 noQualifiers,
392 type_decl
393 ),
394 nullptr
395 );
396
397 decl->get_members().push_back( field );
398
399 return field;
400 }
401
402 void ConcurrentSueKeyword::addRoutines( ObjectDecl * field, FunctionDecl * func ) {
403 CompoundStmt * statement = new CompoundStmt();
404 statement->push_back(
405 new ReturnStmt(
406 new AddressExpr(
407 new MemberExpr(
408 field,
409 new CastExpr(
410 new VariableExpr( func->get_functionType()->get_parameters().front() ),
411 func->get_functionType()->get_parameters().front()->get_type()->stripReferences()->clone()
412 )
413 )
414 )
415 )
416 );
417
418 FunctionDecl * get_decl = func->clone();
419
420 get_decl->set_statements( statement );
421
422 declsToAddAfter.push_back( get_decl );
423
424 // get_decl->fixUniqueId();
425 }
426
427 //=============================================================================================
428 // Mutex keyword implementation
429 //=============================================================================================
430
431 void MutexKeyword::postvisit(FunctionDecl* decl) {
432
433 std::list<DeclarationWithType*> mutexArgs = findMutexArgs( decl );
434 if( mutexArgs.empty() ) return;
435
436 if( CodeGen::isConstructor(decl->name) ) SemanticError( decl, "constructors cannot have mutex parameters" );
437
438 bool isDtor = CodeGen::isDestructor( decl->name );
439
440 if( isDtor && mutexArgs.size() != 1 ) SemanticError( decl, "destructors can only have 1 mutex argument" );
441
442 for(auto arg : mutexArgs) {
443 validate( arg );
444 }
445
446 CompoundStmt* body = decl->get_statements();
447 if( ! body ) return;
448
449 if( !monitor_decl || !guard_decl || !dtor_guard_decl )
450 SemanticError( decl, "mutex keyword requires monitors to be in scope, add #include <monitor>" );
451
452 if( isDtor ) {
453 addDtorStatments( decl, body, mutexArgs );
454 }
455 else {
456 addStatments( decl, body, mutexArgs );
457 }
458 }
459
460 void MutexKeyword::postvisit(StructDecl* decl) {
461
462 if( decl->name == "monitor_desc" ) {
463 assert( !monitor_decl );
464 monitor_decl = decl;
465 }
466 else if( decl->name == "monitor_guard_t" ) {
467 assert( !guard_decl );
468 guard_decl = decl;
469 }
470 else if( decl->name == "monitor_dtor_guard_t" ) {
471 assert( !dtor_guard_decl );
472 dtor_guard_decl = decl;
473 }
474 }
475
476 std::list<DeclarationWithType*> MutexKeyword::findMutexArgs( FunctionDecl* decl ) {
477 std::list<DeclarationWithType*> mutexArgs;
478
479 for( auto arg : decl->get_functionType()->get_parameters()) {
480 //Find mutex arguments
481 Type* ty = arg->get_type();
482 if( ! ty->get_mutex() ) continue;
483
484 //Append it to the list
485 mutexArgs.push_back( arg );
486 }
487
488 return mutexArgs;
489 }
490
491 void MutexKeyword::validate( DeclarationWithType * arg ) {
492 Type* ty = arg->get_type();
493
494 //Makes sure it's not a copy
495 ReferenceType* rty = dynamic_cast< ReferenceType * >( ty );
496 if( ! rty ) SemanticError( arg, "Mutex argument must be of reference type " );
497
498 //Make sure the we are pointing directly to a type
499 Type* base = rty->get_base();
500 if( dynamic_cast< ReferenceType * >( base ) ) SemanticError( arg, "Mutex argument have exactly one level of indirection " );
501 if( dynamic_cast< PointerType * >( base ) ) SemanticError( arg, "Mutex argument have exactly one level of indirection " );
502
503 //Make sure that typed isn't mutex
504 if( base->get_mutex() ) SemanticError( arg, "mutex keyword may only appear once per argument " );
505 }
506
507 void MutexKeyword::addDtorStatments( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args ) {
508 Type * arg_type = args.front()->get_type()->clone();
509 arg_type->set_mutex( false );
510
511 ObjectDecl * monitors = new ObjectDecl(
512 "__monitor",
513 noStorageClasses,
514 LinkageSpec::Cforall,
515 nullptr,
516 new PointerType(
517 noQualifiers,
518 new StructInstType(
519 noQualifiers,
520 monitor_decl
521 )
522 ),
523 new SingleInit( new UntypedExpr(
524 new NameExpr( "get_monitor" ),
525 { new CastExpr( new VariableExpr( args.front() ), arg_type ) }
526 ))
527 );
528
529 assert(generic_func);
530
531 //in reverse order :
532 // monitor_guard_t __guard = { __monitors, #, func };
533 body->push_front(
534 new DeclStmt( new ObjectDecl(
535 "__guard",
536 noStorageClasses,
537 LinkageSpec::Cforall,
538 nullptr,
539 new StructInstType(
540 noQualifiers,
541 dtor_guard_decl
542 ),
543 new ListInit(
544 {
545 new SingleInit( new AddressExpr( new VariableExpr( monitors ) ) ),
546 new SingleInit( new CastExpr( new VariableExpr( func ), generic_func->clone() ) )
547 },
548 noDesignators,
549 true
550 )
551 ))
552 );
553
554 //monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
555 body->push_front( new DeclStmt( monitors) );
556 }
557
558 void MutexKeyword::addStatments( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args ) {
559 ObjectDecl * monitors = new ObjectDecl(
560 "__monitors",
561 noStorageClasses,
562 LinkageSpec::Cforall,
563 nullptr,
564 new ArrayType(
565 noQualifiers,
566 new PointerType(
567 noQualifiers,
568 new StructInstType(
569 noQualifiers,
570 monitor_decl
571 )
572 ),
573 new ConstantExpr( Constant::from_ulong( args.size() ) ),
574 false,
575 false
576 ),
577 new ListInit(
578 map_range < std::list<Initializer*> > ( args, [](DeclarationWithType * var ){
579 Type * type = var->get_type()->clone();
580 type->set_mutex( false );
581 return new SingleInit( new UntypedExpr(
582 new NameExpr( "get_monitor" ),
583 { new CastExpr( new VariableExpr( var ), type ) }
584 ) );
585 })
586 )
587 );
588
589 assert(generic_func);
590
591 //in reverse order :
592 // monitor_guard_t __guard = { __monitors, #, func };
593 body->push_front(
594 new DeclStmt( new ObjectDecl(
595 "__guard",
596 noStorageClasses,
597 LinkageSpec::Cforall,
598 nullptr,
599 new StructInstType(
600 noQualifiers,
601 guard_decl
602 ),
603 new ListInit(
604 {
605 new SingleInit( new VariableExpr( monitors ) ),
606 new SingleInit( new ConstantExpr( Constant::from_ulong( args.size() ) ) ),
607 new SingleInit( new CastExpr( new VariableExpr( func ), generic_func->clone() ) )
608 },
609 noDesignators,
610 true
611 )
612 ))
613 );
614
615 //monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
616 body->push_front( new DeclStmt( monitors) );
617 }
618
619 //=============================================================================================
620 // General entry routine
621 //=============================================================================================
622 void ThreadStarter::previsit( StructDecl * decl ) {
623 if( decl->name == "thread_desc" && decl->body ) {
624 assert( !thread_decl );
625 thread_decl = decl;
626 }
627 }
628
629 void ThreadStarter::postvisit(FunctionDecl * decl) {
630 if( ! CodeGen::isConstructor(decl->name) ) return;
631
632 Type * typeof_this = InitTweak::getTypeofThis(decl->type);
633 StructInstType * ctored_type = dynamic_cast< StructInstType * >( typeof_this );
634 if( ctored_type && ctored_type->baseStruct == thread_decl ) {
635 thread_ctor_seen = true;
636 }
637
638 DeclarationWithType * param = decl->get_functionType()->get_parameters().front();
639 auto type = dynamic_cast< StructInstType * >( InitTweak::getPointerBase( param->get_type() ) );
640 if( type && type->get_baseStruct()->is_thread() ) {
641 if( !thread_decl || !thread_ctor_seen ) {
642 SemanticError( type->get_baseStruct()->location, "thread keyword requires threads to be in scope, add #include <thread>");
643 }
644
645 addStartStatement( decl, param );
646 }
647 }
648
649 void ThreadStarter::addStartStatement( FunctionDecl * decl, DeclarationWithType * param ) {
650 CompoundStmt * stmt = decl->get_statements();
651
652 if( ! stmt ) return;
653
654 stmt->push_back(
655 new ExprStmt(
656 new UntypedExpr(
657 new NameExpr( "__thrd_start" ),
658 { new VariableExpr( param ) }
659 )
660 )
661 );
662 }
663};
664
665// Local Variables: //
666// mode: c //
667// tab-width: 4 //
668// End: //
Note: See TracBrowser for help on using the repository browser.