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