source: src/SymTab/Autogen.cc@ 1a5ad8c

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new stuck-waitfor-destruct with_gc
Last change on this file since 1a5ad8c was 1a5ad8c, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

Update autogen to generate reference rebind for reference member copy constructors

  • Property mode set to 100644
File size: 34.0 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// Autogen.cc --
8//
9// Author : Rob Schluntz
10// Created On : Thu Mar 03 15:45:56 2016
11// Last Modified By : Andrew Beach
12// Last Modified On : Fri Jul 14 16:41:00 2017
13// Update Count : 62
14//
15
16#include "Autogen.h"
17
18#include <algorithm> // for count_if
19#include <cassert> // for strict_dynamic_cast, assert, assertf
20#include <iterator> // for back_insert_iterator, back_inserter
21#include <list> // for list, _List_iterator, list<>::iter...
22#include <set> // for set, _Rb_tree_const_iterator
23#include <utility> // for pair
24#include <vector> // for vector
25
26#include "AddVisit.h" // for addVisit
27#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
28#include "Common/PassVisitor.h" // for PassVisitor
29#include "Common/ScopedMap.h" // for ScopedMap<>::const_iterator, Scope...
30#include "Common/utility.h" // for cloneAll, operator+
31#include "GenPoly/ScopedSet.h" // for ScopedSet, ScopedSet<>::iterator
32#include "InitTweak/GenInit.h" // for fixReturnStatements
33#include "ResolvExpr/Resolver.h" // for resolveDecl
34#include "SymTab/Mangler.h" // for Mangler
35#include "SynTree/Attribute.h" // For Attribute
36#include "SynTree/Mutator.h" // for maybeMutate
37#include "SynTree/Statement.h" // for CompoundStmt, ReturnStmt, ExprStmt
38#include "SynTree/Type.h" // for FunctionType, Type, TypeInstType
39#include "SynTree/Visitor.h" // for maybeAccept, Visitor, acceptAll
40
41class Attribute;
42
43namespace SymTab {
44 Type * SizeType = 0;
45
46 /// Data used to generate functions generically. Specifically, the name of the generated function and a function which generates the routine protoype
47 struct FuncData {
48 typedef FunctionType * (*TypeGen)( Type * );
49 FuncData( const std::string & fname, const TypeGen & genType ) : fname( fname ), genType( genType ) {}
50 std::string fname;
51 TypeGen genType;
52 };
53
54 struct AutogenerateRoutines final : public WithDeclsToAdd, public WithVisitorRef<AutogenerateRoutines>, public WithGuards, public WithShortCircuiting, public WithIndexer {
55 AutogenerateRoutines();
56
57 void previsit( EnumDecl * enumDecl );
58 void previsit( StructDecl * structDecl );
59 void previsit( UnionDecl * structDecl );
60 void previsit( TypeDecl * typeDecl );
61 void previsit( TraitDecl * traitDecl );
62 void previsit( FunctionDecl * functionDecl );
63
64 void previsit( FunctionType * ftype );
65 void previsit( PointerType * ptype );
66
67 void previsit( CompoundStmt * compoundStmt );
68
69 private:
70
71 GenPoly::ScopedSet< std::string > structsDone;
72 unsigned int functionNesting = 0; // current level of nested functions
73
74 InitTweak::ManagedTypes managedTypes;
75 std::vector< FuncData > data;
76 };
77
78 /// generates routines for tuple types.
79 struct AutogenTupleRoutines : public WithDeclsToAdd, public WithVisitorRef<AutogenTupleRoutines>, public WithGuards, public WithShortCircuiting {
80 void previsit( FunctionDecl * functionDecl );
81
82 void postvisit( TupleType * tupleType );
83
84 void previsit( CompoundStmt * compoundStmt );
85
86 private:
87 unsigned int functionNesting = 0; // current level of nested functions
88 GenPoly::ScopedSet< std::string > seenTuples;
89 };
90
91 void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
92 PassVisitor<AutogenerateRoutines> generator;
93 acceptAll( translationUnit, generator );
94
95 // needs to be done separately because AutogenerateRoutines skips types that appear as function arguments, etc.
96 // AutogenTupleRoutines tupleGenerator;
97 // acceptAll( translationUnit, tupleGenerator );
98 }
99
100 //=============================================================================================
101 // FuncGenerator definitions
102 //=============================================================================================
103 class FuncGenerator {
104 public:
105 std::list< Declaration * > definitions, forwards;
106
107 FuncGenerator( Type * type, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : type( type ), data( data ), functionNesting( functionNesting ), indexer( indexer ) {}
108
109 virtual bool shouldAutogen() const = 0;
110 void genStandardFuncs();
111 virtual void genFieldCtors() = 0;
112 protected:
113 Type * type;
114 const std::vector< FuncData > & data;
115 unsigned int functionNesting;
116 SymTab::Indexer & indexer;
117
118 virtual void genFuncBody( FunctionDecl * dcl ) = 0;
119 virtual bool isConcurrentType() const = 0;
120
121 void resolve( FunctionDecl * dcl );
122 void generatePrototypes( std::list< FunctionDecl * > & newFuncs );
123 };
124
125 class StructFuncGenerator : public FuncGenerator {
126 StructDecl * aggregateDecl;
127 public:
128 StructFuncGenerator( StructDecl * aggregateDecl, StructInstType * refType, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), aggregateDecl( aggregateDecl) {}
129
130 virtual bool shouldAutogen() const override;
131 virtual bool isConcurrentType() const override;
132
133 virtual void genFuncBody( FunctionDecl * dcl ) override;
134 virtual void genFieldCtors() override;
135
136 private:
137 /// generates a single struct member operation (constructor call, destructor call, assignment call)
138 void makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward = true );
139
140 /// generates the body of a struct function by iterating the struct members (via parameters) - generates default ctor, copy ctor, assignment, and dtor bodies, but NOT field ctor bodies
141 template<typename Iterator>
142 void makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true );
143
144 /// generate the body of a constructor which takes parameters that match fields, e.g.
145 /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
146 template<typename Iterator>
147 void makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func );
148 };
149
150 class UnionFuncGenerator : public FuncGenerator {
151 UnionDecl * aggregateDecl;
152 public:
153 UnionFuncGenerator( UnionDecl * aggregateDecl, UnionInstType * refType, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), aggregateDecl( aggregateDecl) {}
154
155 virtual bool shouldAutogen() const override;
156 virtual bool isConcurrentType() const override;
157
158 virtual void genFuncBody( FunctionDecl * dcl ) override;
159 virtual void genFieldCtors() override;
160
161 private:
162 /// generates a single struct member operation (constructor call, destructor call, assignment call)
163 template<typename OutputIterator>
164 void makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out );
165
166 /// generates the body of a struct function by iterating the struct members (via parameters) - generates default ctor, copy ctor, assignment, and dtor bodies, but NOT field ctor bodies
167 template<typename Iterator>
168 void makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true );
169
170 /// generate the body of a constructor which takes parameters that match fields, e.g.
171 /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
172 template<typename Iterator>
173 void makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func );
174 };
175
176 class EnumFuncGenerator : public FuncGenerator {
177 public:
178 EnumFuncGenerator( EnumInstType * refType, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ) {}
179
180 virtual bool shouldAutogen() const override;
181 virtual bool isConcurrentType() const override;
182
183 virtual void genFuncBody( FunctionDecl * dcl ) override;
184 virtual void genFieldCtors() override;
185
186 private:
187 };
188
189 class TypeFuncGenerator : public FuncGenerator {
190 TypeDecl * typeDecl;
191 public:
192 TypeFuncGenerator( TypeDecl * typeDecl, TypeInstType * refType, const std::vector<FuncData> & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), typeDecl( typeDecl ) {}
193
194 virtual bool shouldAutogen() const override;
195 virtual void genFuncBody( FunctionDecl * dcl ) override;
196 virtual bool isConcurrentType() const override;
197 virtual void genFieldCtors() override;
198 };
199
200 //=============================================================================================
201 // helper functions
202 //=============================================================================================
203 void generateFunctions( FuncGenerator & gen, std::list< Declaration * > & declsToAdd ) {
204 if ( ! gen.shouldAutogen() ) return;
205
206 // generate each of the functions based on the supplied FuncData objects
207 gen.genStandardFuncs();
208 gen.genFieldCtors();
209
210 declsToAdd.splice( declsToAdd.end(), gen.forwards );
211 declsToAdd.splice( declsToAdd.end(), gen.definitions );
212 }
213
214 bool isUnnamedBitfield( ObjectDecl * obj ) {
215 return obj != nullptr && obj->get_name() == "" && obj->get_bitfieldWidth() != nullptr;
216 }
217
218 /// inserts a forward declaration for functionDecl into declsToAdd
219 void addForwardDecl( FunctionDecl * functionDecl, std::list< Declaration * > & declsToAdd ) {
220 FunctionDecl * decl = functionDecl->clone();
221 delete decl->get_statements();
222 decl->set_statements( nullptr );
223 declsToAdd.push_back( decl );
224 decl->fixUniqueId();
225 }
226
227 /// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
228 FunctionType * genDefaultType( Type * paramType ) {
229 FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
230 ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new ReferenceType( Type::Qualifiers(), paramType->clone() ), nullptr );
231 ftype->get_parameters().push_back( dstParam );
232 return ftype;
233 }
234
235 /// given type T, generate type of copy ctor, i.e. function type void (*) (T *, T)
236 FunctionType * genCopyType( Type * paramType ) {
237 FunctionType *ftype = genDefaultType( paramType );
238 ObjectDecl *srcParam = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
239 ftype->get_parameters().push_back( srcParam );
240 return ftype;
241 }
242
243 /// given type T, generate type of assignment, i.e. function type T (*) (T *, T)
244 FunctionType * genAssignType( Type * paramType ) {
245 FunctionType *ftype = genCopyType( paramType );
246 ObjectDecl *returnVal = new ObjectDecl( "_ret", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
247 ftype->get_returnVals().push_back( returnVal );
248 return ftype;
249 }
250
251 /// generate a function decl from a name and type. Nesting depth determines whether
252 /// the declaration is static or not; optional paramter determines if declaration is intrinsic
253 FunctionDecl * genFunc( const std::string & fname, FunctionType * ftype, unsigned int functionNesting, bool isIntrinsic = false ) {
254 // Routines at global scope marked "static" to prevent multiple definitions in separate translation units
255 // because each unit generates copies of the default routines for each aggregate.
256 Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
257 LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
258 FunctionDecl * decl = new FunctionDecl( fname, scs, spec, ftype, new CompoundStmt( noLabels ),
259 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
260 decl->fixUniqueId();
261 return decl;
262 }
263
264 Type * declToType( Declaration * decl ) {
265 if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
266 return dwt->get_type();
267 }
268 return nullptr;
269 }
270
271 Type * declToTypeDeclBase( Declaration * decl ) {
272 if ( TypeDecl * td = dynamic_cast< TypeDecl * >( decl ) ) {
273 return td->base;
274 }
275 return nullptr;
276 }
277
278 const std::list< TypeDecl * > getGenericParams( Type * t ) {
279 std::list< TypeDecl * > * ret = nullptr;
280 if ( StructInstType * inst = dynamic_cast< StructInstType * > ( t ) ) {
281 ret = inst->get_baseParameters();
282 } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( t ) ) {
283 ret = inst->get_baseParameters();
284 }
285 return ret ? *ret : std::list< TypeDecl * >();
286 }
287
288 //=============================================================================================
289 // FuncGenerator member definitions
290 //=============================================================================================
291 void FuncGenerator::genStandardFuncs() {
292 std::list< FunctionDecl * > newFuncs;
293 generatePrototypes( newFuncs );
294
295 for ( FunctionDecl * dcl : newFuncs ) {
296 genFuncBody( dcl );
297 if ( CodeGen::isAssignment( dcl->name ) ) {
298 // assignment needs to return a value
299 FunctionType * assignType = dcl->type;
300 assert( assignType->parameters.size() == 2 );
301 assert( assignType->returnVals.size() == 1 );
302 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( assignType->parameters.front() );
303 dcl->statements->push_back( new ReturnStmt( noLabels, new VariableExpr( dstParam ) ) );
304 }
305 resolve( dcl );
306 }
307 }
308
309 void FuncGenerator::generatePrototypes( std::list< FunctionDecl * > & newFuncs ) {
310 bool concurrent_type = isConcurrentType();
311 for ( const FuncData & data : data ) {
312 // generate a function (?{}, ?=?, ^?{}) based on the current FuncData.
313 FunctionType * ftype = data.genType( type );
314
315 // destructor for concurrent type must be mutex
316 if ( concurrent_type && CodeGen::isDestructor( data.fname ) ) {
317 ftype->parameters.front()->get_type()->set_mutex( true );
318 }
319
320 // Make function polymorphic in same parameters as generic struct, if applicable
321 std::list< TypeDecl * > typeParams = getGenericParams( type ); // List of type variables to be placed on the generated functions
322 cloneAll( typeParams, ftype->forall );
323
324 newFuncs.push_back( genFunc( data.fname, ftype, functionNesting ) );
325 }
326 }
327
328 void FuncGenerator::resolve( FunctionDecl * dcl ) {
329 try {
330 ResolvExpr::resolveDecl( dcl, indexer );
331 if ( functionNesting == 0 ) {
332 // forward declare if top-level struct, so that
333 // type is complete as soon as its body ends
334 // Note: this is necessary if we want structs which contain
335 // generic (otype) structs as members.
336 addForwardDecl( dcl, forwards );
337 }
338 definitions.push_back( dcl );
339 indexer.addId( dcl );
340 } catch ( SemanticError err ) {
341 // okay if decl does not resolve - that means the function should not be generated
342 delete dcl;
343 }
344 }
345
346 bool StructFuncGenerator::shouldAutogen() const {
347 // Builtins do not use autogeneration.
348 return ! aggregateDecl->linkage.is_builtin;
349 }
350 bool StructFuncGenerator::isConcurrentType() const { return aggregateDecl->is_thread() || aggregateDecl->is_monitor(); }
351
352 void StructFuncGenerator::genFuncBody( FunctionDecl * dcl ) {
353 // generate appropriate calls to member ctor, assignment
354 // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
355 if ( ! CodeGen::isDestructor( dcl->get_name() ) ) {
356 makeFunctionBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), dcl );
357 } else {
358 makeFunctionBody( aggregateDecl->members.rbegin(), aggregateDecl->members.rend(), dcl, false );
359 }
360 }
361
362 void StructFuncGenerator::genFieldCtors() {
363 // field ctors are only generated if default constructor and copy constructor are both generated
364 unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->get_name() ); } );
365
366 // Field constructors are only generated if default and copy constructor
367 // are generated, since they need access to both
368 if ( numCtors != 2 ) return;
369
370 // create constructors which take each member type as a parameter.
371 // for example, for struct A { int x, y; }; generate
372 // void ?{}(A *, int) and void ?{}(A *, int, int)
373 const auto & typeParams = aggregateDecl->parameters;
374 FunctionType * memCtorType = genDefaultType( type );
375 cloneAll( typeParams, memCtorType->forall );
376 for ( Declaration * member : aggregateDecl->members ) {
377 DeclarationWithType * field = strict_dynamic_cast<DeclarationWithType *>( member );
378 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
379 // don't make a function whose parameter is an unnamed bitfield
380 continue;
381 }
382 memCtorType->parameters.push_back( new ObjectDecl( field->name, Type::StorageClasses(), LinkageSpec::Cforall, 0, field->get_type()->clone(), 0 ) );
383 FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
384 makeFieldCtorBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), ctor );
385 resolve( ctor );
386 }
387 delete memCtorType;
388 }
389
390 void StructFuncGenerator::makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward ) {
391 InitTweak::InitExpander srcParam( src );
392
393 // assign to destination
394 Expression *dstselect = new MemberExpr( field, new CastExpr( new VariableExpr( dstParam ), strict_dynamic_cast< ReferenceType* >( dstParam->get_type() )->get_base()->clone() ) );
395 genImplicitCall( srcParam, dstselect, func->get_name(), back_inserter( func->get_statements()->get_kids() ), field, forward );
396 }
397
398 template<typename Iterator>
399 void StructFuncGenerator::makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward ) {
400 for ( ; member != end; ++member ) {
401 if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
402 // query the type qualifiers of this field and skip assigning it if it is marked const.
403 // If it is an array type, we need to strip off the array layers to find its qualifiers.
404 Type * type = field->get_type();
405 while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
406 type = at->get_base();
407 }
408
409 if ( type->get_const() && CodeGen::isAssignment( func->name ) ) {
410 // don't assign const members, but do construct/destruct
411 continue;
412 }
413
414 assert( ! func->get_functionType()->get_parameters().empty() );
415 ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
416 ObjectDecl * srcParam = nullptr;
417 if ( func->get_functionType()->get_parameters().size() == 2 ) {
418 srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
419 }
420
421 // srcParam may be NULL, in which case we have default ctor/dtor
422 assert( dstParam );
423
424 Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : nullptr;
425 makeMemberOp( dstParam, srcselect, field, func, forward );
426 } // if
427 } // for
428 } // makeFunctionBody
429
430 template<typename Iterator>
431 void StructFuncGenerator::makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
432 FunctionType * ftype = func->type;
433 std::list<DeclarationWithType*> & params = ftype->parameters;
434 assert( params.size() >= 2 ); // should not call this function for default ctor, etc.
435
436 // skip 'this' parameter
437 ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
438 assert( dstParam );
439 std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
440 for ( ; member != end; ++member ) {
441 if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
442 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
443 // don't make a function whose parameter is an unnamed bitfield
444 continue;
445 } else if ( parameter != params.end() ) {
446 // matching parameter, initialize field with copy ctor
447 Expression *srcselect = new VariableExpr(*parameter);
448 makeMemberOp( dstParam, srcselect, field, func );
449 ++parameter;
450 } else {
451 // no matching parameter, initialize field with default ctor
452 makeMemberOp( dstParam, nullptr, field, func );
453 }
454 }
455 }
456 }
457
458 bool UnionFuncGenerator::shouldAutogen() const {
459 // Builtins do not use autogeneration.
460 return ! aggregateDecl->linkage.is_builtin;
461 }
462
463 // xxx - is this right?
464 bool UnionFuncGenerator::isConcurrentType() const { return false; };
465
466 /// generate a single union assignment expression (using memcpy)
467 template< typename OutputIterator >
468 void UnionFuncGenerator::makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
469 UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
470 copy->args.push_back( new AddressExpr( new VariableExpr( dstParam ) ) );
471 copy->args.push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
472 copy->args.push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
473 *out++ = new ExprStmt( noLabels, copy );
474 }
475
476 /// generates the body of a union assignment/copy constructor/field constructor
477 void UnionFuncGenerator::genFuncBody( FunctionDecl * funcDecl ) {
478 FunctionType * ftype = funcDecl->type;
479 if ( InitTweak::isCopyConstructor( funcDecl ) || InitTweak::isAssignment( funcDecl ) ) {
480 assert( ftype->parameters.size() == 2 );
481 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
482 ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.back() );
483 makeMemberOp( srcParam, dstParam, back_inserter( funcDecl->statements->kids ) );
484 } else {
485 // default ctor/dtor body is empty - add unused attribute to parameter to silence warnings
486 assert( ftype->parameters.size() == 1 );
487 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
488 dstParam->attributes.push_back( new Attribute( "unused" ) );
489 }
490 }
491
492 /// generate the body of a constructor which takes parameters that match fields, e.g.
493 /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
494 void UnionFuncGenerator::genFieldCtors() {
495 // field ctors are only generated if default constructor and copy constructor are both generated
496 unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->get_name() ); } );
497
498 // Field constructors are only generated if default and copy constructor
499 // are generated, since they need access to both
500 if ( numCtors != 2 ) return;
501
502 // create a constructor which takes the first member type as a parameter.
503 // for example, for Union A { int x; double y; }; generate
504 // void ?{}(A *, int)
505 // This is to mimic C's behaviour which initializes the first member of the union.
506 const auto & typeParams = aggregateDecl->parameters;
507 FunctionType * memCtorType = genDefaultType( type );
508 cloneAll( typeParams, memCtorType->forall );
509 for ( Declaration * member : aggregateDecl->members ) {
510 DeclarationWithType * field = strict_dynamic_cast<DeclarationWithType *>( member );
511 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
512 // don't make a function whose parameter is an unnamed bitfield
513 break;
514 }
515 memCtorType->parameters.push_back( new ObjectDecl( field->name, Type::StorageClasses(), LinkageSpec::Cforall, nullptr, field->get_type()->clone(), nullptr ) );
516 FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
517 ObjectDecl * srcParam = strict_dynamic_cast<ObjectDecl *>( ctor->type->parameters.back() );
518 srcParam->fixUniqueId();
519 ObjectDecl * dstParam = InitTweak::getParamThis( ctor->type );
520 makeMemberOp( srcParam, dstParam, back_inserter( ctor->statements->kids ) );
521 resolve( ctor );
522 // only generate one field ctor for unions
523 break;
524 }
525 delete memCtorType;
526 }
527
528 void EnumFuncGenerator::genFuncBody( FunctionDecl * funcDecl ) {
529 // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
530 // Really they're something of a cross between instrinsic and autogen, so should
531 // probably make a new linkage type
532 funcDecl->linkage = LinkageSpec::Intrinsic;
533 FunctionType * ftype = funcDecl->type;
534 if ( InitTweak::isCopyConstructor( funcDecl ) || InitTweak::isAssignment( funcDecl ) ) {
535 assert( ftype->parameters.size() == 2 );
536 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
537 ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.back() );
538
539 // enum copy construct and assignment is just C-style assignment.
540 // this looks like a bad recursive call, but code gen will turn it into
541 // a C-style assignment.
542 // This happens before function pointer type conversion, so need to do it manually here
543 ApplicationExpr * callExpr = new ApplicationExpr( VariableExpr::functionPointer( funcDecl ) );
544 callExpr->get_args().push_back( new VariableExpr( dstParam ) );
545 callExpr->get_args().push_back( new VariableExpr( srcParam ) );
546 funcDecl->statements->push_back( new ExprStmt( noLabels, callExpr ) );
547 } else {
548 // default ctor/dtor body is empty - add unused attribute to parameter to silence warnings
549 assert( ftype->parameters.size() == 1 );
550 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
551 dstParam->attributes.push_back( new Attribute( "unused" ) );
552 }
553 }
554
555 bool EnumFuncGenerator::shouldAutogen() const { return true; }
556 bool EnumFuncGenerator::isConcurrentType() const { return false; }
557 // enums do not have field constructors
558 void EnumFuncGenerator::genFieldCtors() {}
559
560 bool TypeFuncGenerator::shouldAutogen() const { return true; };
561
562 void TypeFuncGenerator::genFuncBody( FunctionDecl * dcl ) {
563 FunctionType * ftype = dcl->type;
564 assertf( ftype->parameters.size() == 1 || ftype->parameters.size() == 2, "Incorrect number of parameters in autogenerated typedecl function: %zd", ftype->parameters.size() );
565 DeclarationWithType * dst = ftype->parameters.front();
566 DeclarationWithType * src = ftype->parameters.size() == 2 ? ftype->parameters.back() : nullptr;
567 // generate appropriate calls to member ctor, assignment
568 UntypedExpr * expr = new UntypedExpr( new NameExpr( dcl->name ) );
569 expr->args.push_back( new CastExpr( new VariableExpr( dst ), new ReferenceType( Type::Qualifiers(), typeDecl->base->clone() ) ) );
570 if ( src ) expr->args.push_back( new CastExpr( new VariableExpr( src ), typeDecl->base->clone() ) );
571 dcl->statements->kids.push_back( new ExprStmt( noLabels, expr ) );
572 };
573
574 // xxx - should reach in and determine if base type is concurrent?
575 bool TypeFuncGenerator::isConcurrentType() const { return false; };
576
577 // opaque types do not have field constructors
578 void TypeFuncGenerator::genFieldCtors() {};
579
580 //=============================================================================================
581 // Visitor definitions
582 //=============================================================================================
583 AutogenerateRoutines::AutogenerateRoutines() {
584 // the order here determines the order that these functions are generated.
585 // assignment should come last since it uses copy constructor in return.
586 data.emplace_back( "?{}", genDefaultType );
587 data.emplace_back( "?{}", genCopyType );
588 data.emplace_back( "^?{}", genDefaultType );
589 data.emplace_back( "?=?", genAssignType );
590 }
591
592 void AutogenerateRoutines::previsit( EnumDecl * enumDecl ) {
593 // must visit children (enum constants) to add them to the indexer
594 if ( enumDecl->has_body() ) {
595 EnumInstType enumInst( Type::Qualifiers(), enumDecl->get_name() );
596 enumInst.set_baseEnum( enumDecl );
597 EnumFuncGenerator gen( &enumInst, data, functionNesting, indexer );
598 generateFunctions( gen, declsToAddAfter );
599 }
600 }
601
602 void AutogenerateRoutines::previsit( StructDecl * structDecl ) {
603 visit_children = false;
604 if ( structDecl->has_body() ) {
605 StructInstType structInst( Type::Qualifiers(), structDecl->name );
606 structInst.set_baseStruct( structDecl );
607 for ( TypeDecl * typeDecl : structDecl->parameters ) {
608 structInst.parameters.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->name, typeDecl ) ) );
609 }
610 StructFuncGenerator gen( structDecl, &structInst, data, functionNesting, indexer );
611 generateFunctions( gen, declsToAddAfter );
612 } // if
613 }
614
615 void AutogenerateRoutines::previsit( UnionDecl * unionDecl ) {
616 visit_children = false;
617 if ( unionDecl->has_body() ) {
618 UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
619 unionInst.set_baseUnion( unionDecl );
620 for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
621 unionInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
622 }
623 UnionFuncGenerator gen( unionDecl, &unionInst, data, functionNesting, indexer );
624 generateFunctions( gen, declsToAddAfter );
625 } // if
626 }
627
628 // generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
629 void AutogenerateRoutines::previsit( TypeDecl * typeDecl ) {
630 visit_children = false;
631 if ( ! typeDecl->base ) return;
632
633 TypeInstType refType( Type::Qualifiers(), typeDecl->name, typeDecl );
634 TypeFuncGenerator gen( typeDecl, &refType, data, functionNesting, indexer );
635 generateFunctions( gen, declsToAddAfter );
636 }
637
638 void AutogenerateRoutines::previsit( FunctionType *) {
639 // ensure that we don't add assignment ops for types defined as part of the function
640 visit_children = false;
641 }
642
643 void AutogenerateRoutines::previsit( PointerType *) {
644 // ensure that we don't add assignment ops for types defined as part of the pointer
645 visit_children = false;
646 }
647
648 void AutogenerateRoutines::previsit( TraitDecl * ) {
649 // ensure that we don't add assignment ops for types defined as part of the trait
650 visit_children = false;
651 }
652
653 void AutogenerateRoutines::previsit( FunctionDecl * functionDecl ) {
654 visit_children = false;
655 // record the existence of this function as appropriate
656 managedTypes.handleDWT( functionDecl );
657
658 maybeAccept( functionDecl->type, *visitor );
659 functionNesting += 1;
660 maybeAccept( functionDecl->statements, *visitor );
661 functionNesting -= 1;
662 }
663
664 void AutogenerateRoutines::previsit( CompoundStmt * ) {
665 GuardScope( managedTypes );
666 GuardScope( structsDone );
667 }
668
669 void makeTupleFunctionBody( FunctionDecl * function ) {
670 FunctionType * ftype = function->get_functionType();
671 assertf( ftype->get_parameters().size() == 1 || ftype->get_parameters().size() == 2, "too many parameters in generated tuple function" );
672
673 UntypedExpr * untyped = new UntypedExpr( new NameExpr( function->get_name() ) );
674
675 /// xxx - &* is used to make this easier for later passes to handle
676 untyped->get_args().push_back( new AddressExpr( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
677 if ( ftype->get_parameters().size() == 2 ) {
678 untyped->get_args().push_back( new VariableExpr( ftype->get_parameters().back() ) );
679 }
680 function->get_statements()->get_kids().push_back( new ExprStmt( noLabels, untyped ) );
681 function->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
682 }
683
684 void AutogenTupleRoutines::postvisit( TupleType * tupleType ) {
685 std::string mangleName = SymTab::Mangler::mangleType( tupleType );
686 if ( seenTuples.find( mangleName ) != seenTuples.end() ) return;
687 seenTuples.insert( mangleName );
688
689 // T ?=?(T *, T);
690 FunctionType *assignType = genAssignType( tupleType );
691
692 // void ?{}(T *); void ^?{}(T *);
693 FunctionType *ctorType = genDefaultType( tupleType );
694 FunctionType *dtorType = genDefaultType( tupleType );
695
696 // void ?{}(T *, T);
697 FunctionType *copyCtorType = genCopyType( tupleType );
698
699 std::set< TypeDecl* > done;
700 std::list< TypeDecl * > typeParams;
701 for ( Type * t : *tupleType ) {
702 if ( TypeInstType * ty = dynamic_cast< TypeInstType * >( t ) ) {
703 if ( ! done.count( ty->get_baseType() ) ) {
704 TypeDecl * newDecl = new TypeDecl( ty->get_baseType()->get_name(), Type::StorageClasses(), nullptr, TypeDecl::Any );
705 TypeInstType * inst = new TypeInstType( Type::Qualifiers(), newDecl->get_name(), newDecl );
706 newDecl->get_assertions().push_back( new FunctionDecl( "?=?", Type::StorageClasses(), LinkageSpec::Cforall, genAssignType( inst ), nullptr,
707 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
708 newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
709 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
710 newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genCopyType( inst ), nullptr,
711 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
712 newDecl->get_assertions().push_back( new FunctionDecl( "^?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
713 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
714 typeParams.push_back( newDecl );
715 done.insert( ty->get_baseType() );
716 }
717 }
718 }
719 cloneAll( typeParams, ctorType->get_forall() );
720 cloneAll( typeParams, dtorType->get_forall() );
721 cloneAll( typeParams, copyCtorType->get_forall() );
722 cloneAll( typeParams, assignType->get_forall() );
723
724 FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
725 FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting );
726 FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
727 FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
728
729 makeTupleFunctionBody( assignDecl );
730 makeTupleFunctionBody( ctorDecl );
731 makeTupleFunctionBody( copyCtorDecl );
732 makeTupleFunctionBody( dtorDecl );
733
734 declsToAddBefore.push_back( ctorDecl );
735 declsToAddBefore.push_back( copyCtorDecl );
736 declsToAddBefore.push_back( dtorDecl );
737 declsToAddBefore.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
738 }
739
740 void AutogenTupleRoutines::previsit( FunctionDecl *functionDecl ) {
741 visit_children = false;
742 maybeAccept( functionDecl->type, *visitor );
743 functionNesting += 1;
744 maybeAccept( functionDecl->statements, *visitor );
745 functionNesting -= 1;
746 }
747
748 void AutogenTupleRoutines::previsit( CompoundStmt * ) {
749 GuardScope( seenTuples );
750 }
751} // SymTab
752
753// Local Variables: //
754// tab-width: 4 //
755// mode: c++ //
756// compile-command: "make install" //
757// End: //
Note: See TracBrowser for help on using the repository browser.