source: src/SymTab/Autogen.cc@ 4b1c8da

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 4b1c8da was 0dd9a5e, checked in by Fangren Yu <f37yu@…>, 5 years ago

delay autogen resolve

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