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