source: src/SymTab/Autogen.cc@ c443d1d

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 c443d1d was dd020c0, checked in by Peter A. Buhr <pabuhr@…>, 9 years ago

first attempt to create function specifiers

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