source: src/SymTab/Autogen.cc@ ca278c1

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 ca278c1 was 8404321, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Add genCopyType and genDefaultType to Autogen.h

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