source: src/SymTab/Autogen.cc@ 21ea170

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 21ea170 was 189d800, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Rework autogen to resolve struct functions as they are generated [fixes #43]

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