source: src/SymTab/Autogen.cc@ fc72845d

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 with_gc
Last change on this file since fc72845d was ac74057, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Convert AutogenTupleRoutines to PassVisitor

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