source: src/Validate/Autogen.cpp@ 994030ce

Last change on this file since 994030ce was 8913de4, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Update in autogen that should help with some resolver issues and invariant checks. Some related headers were cleaned up to reduce new code files including old ones.

  • Property mode set to 100644
File size: 27.6 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Autogen.cpp -- Generate automatic routines for data types.
8//
9// Author : Andrew Beach
10// Created On : Thu Dec 2 13:44:00 2021
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Sep 20 16:00:00 2022
13// Update Count : 2
14//
15
16#include "Autogen.hpp"
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/Attribute.hpp"
27#include "AST/Copy.hpp"
28#include "AST/Create.hpp"
29#include "AST/Decl.hpp"
30#include "AST/DeclReplacer.hpp"
31#include "AST/Expr.hpp"
32#include "AST/Inspect.hpp"
33#include "AST/Pass.hpp"
34#include "AST/Stmt.hpp"
35#include "AST/SymbolTable.hpp"
36#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
37#include "Common/ScopedMap.h" // for ScopedMap<>::const_iterator, Scope...
38#include "Common/utility.h" // for cloneAll, operator+
39#include "GenPoly/ScopedSet.h" // for ScopedSet, ScopedSet<>::iterator
40#include "InitTweak/GenInit.h" // for fixReturnStatements
41#include "InitTweak/InitTweak.h" // for isAssignment, isCopyConstructor
42#include "SymTab/GenImplicitCall.hpp" // for genImplicitCall
43#include "SymTab/Mangler.h" // for Mangler
44#include "CompilationState.h"
45
46namespace Validate {
47
48namespace {
49
50// --------------------------------------------------------------------------
51struct AutogenerateRoutines_new final :
52 public ast::WithDeclsToAdd<>,
53 public ast::WithShortCircuiting {
54 void previsit( const ast::EnumDecl * enumDecl );
55 void previsit( const ast::StructDecl * structDecl );
56 void previsit( const ast::UnionDecl * structDecl );
57 void previsit( const ast::TypeDecl * typeDecl );
58 void previsit( const ast::TraitDecl * traitDecl );
59 void previsit( const ast::FunctionDecl * functionDecl );
60 void postvisit( const ast::FunctionDecl * functionDecl );
61
62private:
63 // Current level of nested functions.
64 unsigned int functionNesting = 0;
65};
66
67// --------------------------------------------------------------------------
68/// Class used to generate functions for a particular declaration.
69/// Note it isn't really stored, it is just a class for organization and to
70/// help pass around some of the common arguments.
71class FuncGenerator {
72public:
73 std::list<ast::ptr<ast::Decl>> forwards;
74 std::list<ast::ptr<ast::Decl>> definitions;
75
76 FuncGenerator( const ast::Type * type, unsigned int functionNesting ) :
77 type( type ), functionNesting( functionNesting )
78 {}
79
80 /// Generate functions (and forward decls.) and append them to the list.
81 void generateAndAppendFunctions( std::list<ast::ptr<ast::Decl>> & );
82
83 virtual bool shouldAutogen() const = 0;
84protected:
85 const ast::Type * type;
86 unsigned int functionNesting;
87 ast::Linkage::Spec proto_linkage = ast::Linkage::AutoGen;
88
89 // Internal helpers:
90 void genStandardFuncs();
91 void produceDecl( const ast::FunctionDecl * decl );
92 void produceForwardDecl( const ast::FunctionDecl * decl );
93
94 const CodeLocation& getLocation() const { return getDecl()->location; }
95 ast::FunctionDecl * genProto( std::string&& name,
96 std::vector<ast::ptr<ast::DeclWithType>>&& params,
97 std::vector<ast::ptr<ast::DeclWithType>>&& returns ) const;
98
99 ast::ObjectDecl * dstParam() const;
100 ast::ObjectDecl * srcParam() const;
101 ast::FunctionDecl * genCtorProto() const;
102 ast::FunctionDecl * genCopyProto() const;
103 ast::FunctionDecl * genDtorProto() const;
104 ast::FunctionDecl * genAssignProto() const;
105 ast::FunctionDecl * genFieldCtorProto( unsigned int fields ) const;
106
107 // Internal Hooks:
108 virtual void genFuncBody( ast::FunctionDecl * decl ) = 0;
109 virtual void genFieldCtors() = 0;
110 virtual bool isConcurrentType() const { return false; }
111 virtual const ast::Decl * getDecl() const = 0;
112};
113
114class StructFuncGenerator final : public FuncGenerator {
115 const ast::StructDecl * decl;
116public:
117 StructFuncGenerator( const ast::StructDecl * decl,
118 const ast::StructInstType * type,
119 unsigned int functionNesting ) :
120 FuncGenerator( type, functionNesting ), decl( decl )
121 {}
122
123 // Built-ins do not use autogeneration.
124 bool shouldAutogen() const final { return !decl->linkage.is_builtin && !structHasFlexibleArray(decl); }
125private:
126 void genFuncBody( ast::FunctionDecl * decl ) final;
127 void genFieldCtors() final;
128 bool isConcurrentType() const final {
129 return decl->is_thread() || decl->is_monitor();
130 }
131 virtual const ast::Decl * getDecl() const final { return decl; }
132
133 /// Generates a single struct member operation.
134 /// (constructor call, destructor call, assignment call)
135 // This is managed because it uses another helper that returns a ast::ptr.
136 ast::ptr<ast::Stmt> makeMemberOp(
137 const CodeLocation& location,
138 const ast::ObjectDecl * dstParam, const ast::Expr * src,
139 const ast::ObjectDecl * field, ast::FunctionDecl * func,
140 SymTab::LoopDirection direction );
141
142 /// Generates the body of a struct function by iterating the struct members
143 /// (via parameters). Generates default constructor, copy constructor,
144 /// copy assignment, and destructor bodies. No field constructor bodies.
145 template<typename Iterator>
146 void makeFunctionBody( Iterator member, Iterator end,
147 ast::FunctionDecl * func, SymTab::LoopDirection direction );
148
149 /// Generate the body of a constructor which takes parameters that match
150 /// fields. (With arguments for one to all of the fields.)
151 template<typename Iterator>
152 void makeFieldCtorBody( Iterator member, Iterator end,
153 ast::FunctionDecl * func );
154};
155
156class UnionFuncGenerator final : public FuncGenerator {
157 const ast::UnionDecl * decl;
158public:
159 UnionFuncGenerator( const ast::UnionDecl * decl,
160 const ast::UnionInstType * type,
161 unsigned int functionNesting ) :
162 FuncGenerator( type, functionNesting ), decl( decl )
163 {}
164
165 // Built-ins do not use autogeneration.
166 bool shouldAutogen() const final { return !decl->linkage.is_builtin; }
167private:
168 void genFuncBody( ast::FunctionDecl * decl ) final;
169 void genFieldCtors() final;
170 const ast::Decl * getDecl() const final { return decl; }
171
172 /// Generate a single union assignment expression (using memcpy).
173 ast::ExprStmt * makeAssignOp( const CodeLocation& location,
174 const ast::ObjectDecl * dstParam, const ast::ObjectDecl * srcParam );
175};
176
177class EnumFuncGenerator final : public FuncGenerator {
178 const ast::EnumDecl * decl;
179public:
180 EnumFuncGenerator( const ast::EnumDecl * decl,
181 const ast::EnumInstType * type,
182 unsigned int functionNesting ) :
183 FuncGenerator( type, functionNesting ), decl( decl )
184 {
185 // TODO: These functions are somewhere between instrinsic and autogen,
186 // could possibly use a new linkage type. For now we just make the
187 // basic ones intrinsic to code-gen them as C assignments.
188 const auto & real_type = decl->base;
189 const auto & basic = real_type.as<ast::BasicType>();
190 if(!real_type || (basic && basic->isInteger())) proto_linkage = ast::Linkage::Intrinsic;
191 }
192
193 bool shouldAutogen() const final { return true; }
194private:
195 void genFuncBody( ast::FunctionDecl * decl ) final;
196 void genFieldCtors() final;
197 const ast::Decl * getDecl() const final { return decl; }
198};
199
200class TypeFuncGenerator final : public FuncGenerator {
201 const ast::TypeDecl * decl;
202public:
203 TypeFuncGenerator( const ast::TypeDecl * decl,
204 ast::TypeInstType * type,
205 unsigned int functionNesting ) :
206 FuncGenerator( type, functionNesting ), decl( decl )
207 {}
208
209 bool shouldAutogen() const final { return true; }
210 void genFieldCtors() final;
211private:
212 void genFuncBody( ast::FunctionDecl * decl ) final;
213 const ast::Decl * getDecl() const final { return decl; }
214};
215
216// --------------------------------------------------------------------------
217const std::vector<ast::ptr<ast::TypeDecl>>& getGenericParams( const ast::Type * t ) {
218 if ( auto inst = dynamic_cast< const ast::StructInstType * >( t ) ) {
219 return inst->base->params;
220 } else if ( auto inst = dynamic_cast< const ast::UnionInstType * >( t ) ) {
221 return inst->base->params;
222 }
223 static std::vector<ast::ptr<ast::TypeDecl>> const empty;
224 return empty;
225}
226
227/// Changes the node inside a pointer so that it has the unused attribute.
228void addUnusedAttribute( ast::ptr<ast::DeclWithType> & declPtr ) {
229 ast::DeclWithType * decl = declPtr.get_and_mutate();
230 decl->attributes.push_back( new ast::Attribute( "unused" ) );
231}
232
233// --------------------------------------------------------------------------
234void AutogenerateRoutines_new::previsit( const ast::EnumDecl * enumDecl ) {
235 // Must visit children (enum constants) to add them to the symbol table.
236 if ( !enumDecl->body ) return;
237
238 // if ( auto enumBaseType = enumDecl->base ) {
239 // if ( auto enumBaseTypeAsStructInst = dynamic_cast<const ast::StructInstType *>(enumBaseType.get()) ) {
240 // const ast::StructDecl * structDecl = enumBaseTypeAsStructInst->base.get();
241 // this->previsit( structDecl );
242 // }
243 // }
244
245 ast::EnumInstType enumInst( enumDecl->name );
246 enumInst.base = enumDecl;
247 EnumFuncGenerator gen( enumDecl, &enumInst, functionNesting );
248 gen.generateAndAppendFunctions( declsToAddAfter );
249}
250
251void AutogenerateRoutines_new::previsit( const ast::StructDecl * structDecl ) {
252 visit_children = false;
253 if ( !structDecl->body ) return;
254
255 ast::StructInstType structInst( structDecl->name );
256 structInst.base = structDecl;
257 for ( const ast::TypeDecl * typeDecl : structDecl->params ) {
258 structInst.params.push_back( new ast::TypeExpr(
259 typeDecl->location,
260 new ast::TypeInstType( typeDecl )
261 ) );
262 }
263 StructFuncGenerator gen( structDecl, &structInst, functionNesting );
264 gen.generateAndAppendFunctions( declsToAddAfter );
265}
266
267void AutogenerateRoutines_new::previsit( const ast::UnionDecl * unionDecl ) {
268 visit_children = false;
269 if ( !unionDecl->body ) return;
270
271 ast::UnionInstType unionInst( unionDecl->name );
272 unionInst.base = unionDecl;
273 for ( const ast::TypeDecl * typeDecl : unionDecl->params ) {
274 unionInst.params.push_back( new ast::TypeExpr(
275 unionDecl->location,
276 new ast::TypeInstType( typeDecl )
277 ) );
278 }
279 UnionFuncGenerator gen( unionDecl, &unionInst, functionNesting );
280 gen.generateAndAppendFunctions( declsToAddAfter );
281}
282
283/// Generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
284void AutogenerateRoutines_new::previsit( const ast::TypeDecl * typeDecl ) {
285 if ( !typeDecl->base ) return;
286
287 ast::TypeInstType refType( typeDecl->name, typeDecl );
288 TypeFuncGenerator gen( typeDecl, &refType, functionNesting );
289 gen.generateAndAppendFunctions( declsToAddAfter );
290}
291
292void AutogenerateRoutines_new::previsit( const ast::TraitDecl * ) {
293 // Ensure that we don't add assignment ops for types defined as part of the trait
294 visit_children = false;
295}
296
297void AutogenerateRoutines_new::previsit( const ast::FunctionDecl * ) {
298 // Track whether we're currently in a function.
299 // Can ignore function type idiosyncrasies, because function type can never
300 // declare a new type.
301 functionNesting += 1;
302}
303
304void AutogenerateRoutines_new::postvisit( const ast::FunctionDecl * ) {
305 functionNesting -= 1;
306}
307
308void FuncGenerator::generateAndAppendFunctions(
309 std::list<ast::ptr<ast::Decl>> & decls ) {
310 if ( !shouldAutogen() ) return;
311
312 // Generate the functions (they go into forwards and definitions).
313 genStandardFuncs();
314 genFieldCtors();
315
316 // Now export the lists contents.
317 decls.splice( decls.end(), forwards );
318 decls.splice( decls.end(), definitions );
319}
320
321void FuncGenerator::produceDecl( const ast::FunctionDecl * decl ) {
322 assert( nullptr != decl->stmts );
323
324 definitions.push_back( decl );
325}
326
327/// Make a forward declaration of the decl and add it to forwards.
328void FuncGenerator::produceForwardDecl( const ast::FunctionDecl * decl ) {
329 if (0 != functionNesting) return;
330 ast::FunctionDecl * fwd =
331 ( decl->stmts ) ? ast::asForward( decl ) : ast::deepCopy( decl ) ;
332 fwd->fixUniqueId();
333 forwards.push_back( fwd );
334}
335
336void replaceAll( std::vector<ast::ptr<ast::DeclWithType>> & dwts,
337 const ast::DeclReplacer::TypeMap & map ) {
338 for ( auto & dwt : dwts ) {
339 dwt = strict_dynamic_cast<const ast::DeclWithType *>(
340 ast::DeclReplacer::replace( dwt, map ) );
341 }
342}
343
344/// Generates a basic prototype function declaration.
345ast::FunctionDecl * FuncGenerator::genProto( std::string&& name,
346 std::vector<ast::ptr<ast::DeclWithType>>&& params,
347 std::vector<ast::ptr<ast::DeclWithType>>&& returns ) const {
348
349 // Handle generic prameters and assertions, if any.
350 auto const & old_type_params = getGenericParams( type );
351 ast::DeclReplacer::TypeMap oldToNew;
352 std::vector<ast::ptr<ast::TypeDecl>> type_params;
353 std::vector<ast::ptr<ast::DeclWithType>> assertions;
354 for ( auto & old_param : old_type_params ) {
355 ast::TypeDecl * decl = ast::deepCopy( old_param );
356 decl->init = nullptr;
357 splice( assertions, decl->assertions );
358 oldToNew.emplace( std::make_pair( old_param, decl ) );
359 type_params.push_back( decl );
360 }
361 replaceAll( params, oldToNew );
362 replaceAll( returns, oldToNew );
363 replaceAll( assertions, oldToNew );
364
365 ast::FunctionDecl * decl = new ast::FunctionDecl(
366 // Auto-generated routines use the type declaration's location.
367 getLocation(),
368 std::move( name ),
369 std::move( type_params ),
370 std::move( assertions ),
371 std::move( params ),
372 std::move( returns ),
373 // Only a prototype, no body.
374 nullptr,
375 // Use static storage if we are at the top level.
376 (0 < functionNesting) ? ast::Storage::Classes() : ast::Storage::Static,
377 proto_linkage,
378 std::vector<ast::ptr<ast::Attribute>>(),
379 // Auto-generated routines are inline to avoid conflicts.
380 ast::Function::Specs( ast::Function::Inline ) );
381 decl->fixUniqueId();
382 return decl;
383}
384
385ast::ObjectDecl * FuncGenerator::dstParam() const {
386 return new ast::ObjectDecl( getLocation(), "_dst",
387 new ast::ReferenceType( ast::deepCopy( type ) ) );
388}
389
390ast::ObjectDecl * FuncGenerator::srcParam() const {
391 return new ast::ObjectDecl( getLocation(), "_src",
392 ast::deepCopy( type ) );
393}
394
395/// Use the current type T to create `void ?{}(T & _dst)`.
396ast::FunctionDecl * FuncGenerator::genCtorProto() const {
397 return genProto( "?{}", { dstParam() }, {} );
398}
399
400/// Use the current type T to create `void ?{}(T & _dst, T _src)`.
401ast::FunctionDecl * FuncGenerator::genCopyProto() const {
402 return genProto( "?{}", { dstParam(), srcParam() }, {} );
403}
404
405/// Use the current type T to create `void ?{}(T & _dst)`.
406ast::FunctionDecl * FuncGenerator::genDtorProto() const {
407 // The destructor must be mutex on a concurrent type.
408 auto dst = dstParam();
409 if ( isConcurrentType() ) {
410 add_qualifiers( dst->type, ast::CV::Qualifiers( ast::CV::Mutex ) );
411 }
412 return genProto( "^?{}", { dst }, {} );
413}
414
415/// Use the current type T to create `T ?{}(T & _dst, T _src)`.
416ast::FunctionDecl * FuncGenerator::genAssignProto() const {
417 // Only the name is different, so just reuse the generation function.
418 auto retval = srcParam();
419 retval->name = "_ret";
420 return genProto( "?=?", { dstParam(), srcParam() }, { retval } );
421}
422
423// This one can return null if the last field is an unnamed bitfield.
424ast::FunctionDecl * FuncGenerator::genFieldCtorProto(
425 unsigned int fields ) const {
426 assert( 0 < fields );
427 auto aggr = strict_dynamic_cast<const ast::AggregateDecl *>( getDecl() );
428
429 std::vector<ast::ptr<ast::DeclWithType>> params = { dstParam() };
430 for ( unsigned int index = 0 ; index < fields ; ++index ) {
431 auto member = aggr->members[index].strict_as<ast::DeclWithType>();
432 if ( ast::isUnnamedBitfield(
433 dynamic_cast<const ast::ObjectDecl *>( member ) ) ) {
434 if ( index == fields - 1 ) {
435 return nullptr;
436 }
437 continue;
438 }
439
440 auto * paramType = ast::deepCopy( member->get_type() );
441 paramType->attributes.clear();
442 ast::ObjectDecl * param = new ast::ObjectDecl(
443 getLocation(), member->name, paramType );
444 for ( auto & attr : member->attributes ) {
445 if ( attr->isValidOnFuncParam() ) {
446 param->attributes.push_back( attr );
447 }
448 }
449 params.emplace_back( param );
450 }
451 return genProto( "?{}", std::move( params ), {} );
452}
453
454void appendReturnThis( ast::FunctionDecl * decl ) {
455 assert( 1 <= decl->params.size() );
456 assert( 1 == decl->returns.size() );
457 assert( decl->stmts );
458
459 const CodeLocation& location = (decl->stmts->kids.empty())
460 ? decl->stmts->location : decl->stmts->kids.back()->location;
461 const ast::DeclWithType * thisParam = decl->params.front();
462 decl->stmts.get_and_mutate()->push_back(
463 new ast::ReturnStmt( location,
464 new ast::VariableExpr( location, thisParam )
465 )
466 );
467}
468
469void FuncGenerator::genStandardFuncs() {
470 // The order here determines the order that these functions are generated.
471 // Assignment should come last since it uses copy constructor in return.
472 ast::FunctionDecl *(FuncGenerator::*standardProtos[4])() const = {
473 &FuncGenerator::genCtorProto, &FuncGenerator::genCopyProto,
474 &FuncGenerator::genDtorProto, &FuncGenerator::genAssignProto };
475 for ( auto & generator : standardProtos ) {
476 ast::FunctionDecl * decl = (this->*generator)();
477 produceForwardDecl( decl );
478 genFuncBody( decl );
479 if ( CodeGen::isAssignment( decl->name ) ) {
480 appendReturnThis( decl );
481 }
482 produceDecl( decl );
483 }
484}
485
486void StructFuncGenerator::genFieldCtors() {
487 // The field constructors are only generated if the default constructor
488 // and copy constructor are both generated, since the need both.
489 unsigned numCtors = std::count_if( definitions.begin(), definitions.end(),
490 [](const ast::Decl * decl){ return CodeGen::isConstructor( decl->name ); }
491 );
492 if ( 2 != numCtors ) return;
493
494 for ( unsigned int num = 1 ; num <= decl->members.size() ; ++num ) {
495 ast::FunctionDecl * ctor = genFieldCtorProto( num );
496 if ( nullptr == ctor ) {
497 continue;
498 }
499 produceForwardDecl( ctor );
500 makeFieldCtorBody( decl->members.begin(), decl->members.end(), ctor );
501 produceDecl( ctor );
502 }
503}
504
505void StructFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
506 // Generate appropriate calls to member constructors and assignment.
507 // Destructor needs to do everything in reverse,
508 // so pass "forward" based on whether the function is a destructor
509 if ( CodeGen::isDestructor( functionDecl->name ) ) {
510 makeFunctionBody( decl->members.rbegin(), decl->members.rend(),
511 functionDecl, SymTab::LoopBackward );
512 } else {
513 makeFunctionBody( decl->members.begin(), decl->members.end(),
514 functionDecl, SymTab::LoopForward );
515 }
516}
517
518ast::ptr<ast::Stmt> StructFuncGenerator::makeMemberOp(
519 const CodeLocation& location, const ast::ObjectDecl * dstParam,
520 const ast::Expr * src, const ast::ObjectDecl * field,
521 ast::FunctionDecl * func, SymTab::LoopDirection direction ) {
522 InitTweak::InitExpander_new srcParam( src );
523 // Assign to destination.
524 ast::Expr * dstSelect = new ast::MemberExpr(
525 location,
526 field,
527 new ast::CastExpr(
528 location,
529 new ast::VariableExpr( location, dstParam ),
530 dstParam->type.strict_as<ast::ReferenceType>()->base
531 )
532 );
533 return genImplicitCall(
534 srcParam, dstSelect, location, func->name,
535 field, direction
536 );
537}
538
539template<typename Iterator>
540void StructFuncGenerator::makeFunctionBody( Iterator current, Iterator end,
541 ast::FunctionDecl * func, SymTab::LoopDirection direction ) {
542 // Trying to get the best code location. Should probably use a helper or
543 // just figure out what that would be given where this is called.
544 assert( nullptr == func->stmts );
545 const CodeLocation& location = func->location;
546
547 ast::CompoundStmt * stmts = new ast::CompoundStmt( location );
548
549 for ( ; current != end ; ++current ) {
550 const ast::ptr<ast::Decl> & member = *current;
551 auto field = member.as<ast::ObjectDecl>();
552 if ( nullptr == field ) {
553 continue;
554 }
555
556 // Don't assign to constant members (but do construct/destruct them).
557 if ( CodeGen::isAssignment( func->name ) ) {
558 // For array types we need to strip off the array layers.
559 const ast::Type * type = field->get_type();
560 while ( auto at = dynamic_cast<const ast::ArrayType *>( type ) ) {
561 type = at->base;
562 }
563 if ( type->is_const() ) {
564 continue;
565 }
566 }
567
568 assert( !func->params.empty() );
569 const ast::ObjectDecl * dstParam =
570 func->params.front().strict_as<ast::ObjectDecl>();
571 const ast::ObjectDecl * srcParam = nullptr;
572 if ( 2 == func->params.size() ) {
573 srcParam = func->params.back().strict_as<ast::ObjectDecl>();
574 }
575
576 ast::Expr * srcSelect = (srcParam) ? new ast::MemberExpr(
577 location, field, new ast::VariableExpr( location, srcParam )
578 ) : nullptr;
579 ast::ptr<ast::Stmt> stmt =
580 makeMemberOp( location, dstParam, srcSelect, field, func, direction );
581
582 if ( nullptr != stmt ) {
583 stmts->kids.push_back( stmt );
584 }
585 }
586
587 func->stmts = stmts;
588}
589
590template<typename Iterator>
591void StructFuncGenerator::makeFieldCtorBody( Iterator current, Iterator end,
592 ast::FunctionDecl * func ) {
593 const CodeLocation& location = func->location;
594 auto & params = func->params;
595 // Need at least the constructed parameter and one field parameter.
596 assert( 2 <= params.size() );
597
598 ast::CompoundStmt * stmts = new ast::CompoundStmt( location );
599
600 auto dstParam = params.front().strict_as<ast::ObjectDecl>();
601 // Skip over the 'this' parameter.
602 for ( auto param = params.begin() + 1 ; current != end ; ++current ) {
603 const ast::ptr<ast::Decl> & member = *current;
604 ast::ptr<ast::Stmt> stmt = nullptr;
605 auto field = member.as<ast::ObjectDecl>();
606 // Not sure why it could be null.
607 // Don't make a function for a parameter that is an unnamed bitfield.
608 if ( nullptr == field || ast::isUnnamedBitfield( field ) ) {
609 continue;
610 // Matching Parameter: Initialize the field by copy.
611 } else if ( params.end() != param ) {
612 const ast::Expr *srcSelect = new ast::VariableExpr(
613 func->location, param->get() );
614 stmt = makeMemberOp( location, dstParam, srcSelect, field, func, SymTab::LoopForward );
615 ++param;
616 // No Matching Parameter: Initialize the field by default constructor.
617 } else {
618 stmt = makeMemberOp( location, dstParam, nullptr, field, func, SymTab::LoopForward );
619 }
620
621 if ( nullptr != stmt ) {
622 stmts->kids.push_back( stmt );
623 }
624 }
625 func->stmts = stmts;
626}
627
628void UnionFuncGenerator::genFieldCtors() {
629 // Field constructors are only generated if default and copy constructor
630 // are generated, since they need access to both
631 unsigned numCtors = std::count_if( definitions.begin(), definitions.end(),
632 []( const ast::Decl * d ){ return CodeGen::isConstructor( d->name ); }
633 );
634 if ( 2 != numCtors ) {
635 return;
636 }
637
638 // Create a constructor which takes the first member type as a
639 // parameter. For example for `union A { int x; char y; };` generate
640 // a function with signature `void ?{}(A *, int)`. This mimics C's
641 // behaviour which initializes the first member of the union.
642
643 // Still, there must be some members.
644 if ( !decl->members.empty() ) {
645 ast::FunctionDecl * ctor = genFieldCtorProto( 1 );
646 if ( nullptr == ctor ) {
647 return;
648 }
649 produceForwardDecl( ctor );
650 auto params = ctor->params;
651 auto dstParam = params.front().strict_as<ast::ObjectDecl>();
652 auto srcParam = params.back().strict_as<ast::ObjectDecl>();
653 ctor->stmts = new ast::CompoundStmt( getLocation(),
654 { makeAssignOp( getLocation(), dstParam, srcParam ) }
655 );
656 produceDecl( ctor );
657 }
658}
659
660void UnionFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
661 const CodeLocation& location = functionDecl->location;
662 auto & params = functionDecl->params;
663 if ( InitTweak::isCopyConstructor( functionDecl )
664 || InitTweak::isAssignment( functionDecl ) ) {
665 assert( 2 == params.size() );
666 auto dstParam = params.front().strict_as<ast::ObjectDecl>();
667 auto srcParam = params.back().strict_as<ast::ObjectDecl>();
668 functionDecl->stmts = new ast::CompoundStmt( location,
669 { makeAssignOp( location, dstParam, srcParam ) }
670 );
671 } else {
672 assert( 1 == params.size() );
673 // Default constructor and destructor is empty.
674 functionDecl->stmts = new ast::CompoundStmt( location );
675 // Add unused attribute to parameter to silence warnings.
676 addUnusedAttribute( params.front() );
677
678 // Just an extra step to make the forward and declaration match.
679 if ( forwards.empty() ) return;
680 ast::FunctionDecl * fwd = strict_dynamic_cast<ast::FunctionDecl *>(
681 forwards.back().get_and_mutate() );
682 addUnusedAttribute( fwd->params.front() );
683 }
684}
685
686ast::ExprStmt * UnionFuncGenerator::makeAssignOp( const CodeLocation& location,
687 const ast::ObjectDecl * dstParam, const ast::ObjectDecl * srcParam ) {
688 return new ast::ExprStmt( location, new ast::UntypedExpr(
689 location,
690 new ast::NameExpr( location, "__builtin_memcpy" ),
691 {
692 new ast::AddressExpr( location,
693 new ast::VariableExpr( location, dstParam ) ),
694 new ast::AddressExpr( location,
695 new ast::VariableExpr( location, srcParam ) ),
696 new ast::SizeofExpr( location, srcParam->type ),
697 } ) );
698}
699
700void EnumFuncGenerator::genFieldCtors() {
701 // Enumerations to not have field constructors.
702}
703
704void EnumFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
705 const CodeLocation& location = functionDecl->location;
706 auto & params = functionDecl->params;
707 if ( InitTweak::isCopyConstructor( functionDecl )
708 || InitTweak::isAssignment( functionDecl ) ) {
709 assert( 2 == params.size() );
710 auto dstParam = params.front().strict_as<ast::ObjectDecl>();
711 auto srcParam = params.back().strict_as<ast::ObjectDecl>();
712
713 /* This looks like a recursive call, but code-gen will turn it into
714 * a C-style assignment.
715 *
716 * This is still before function pointer type conversion,
717 * so this will have to do it manually.
718 *
719 * It will also reference the parent function declaration, creating
720 * a cycle for references. This also means that the ref-counts are
721 * now non-zero and the declaration will be deleted if it ever
722 * returns to zero.
723 */
724 auto callExpr = new ast::ApplicationExpr( location,
725 ast::VariableExpr::functionPointer( location, functionDecl ),
726 {
727 new ast::VariableExpr( location, dstParam ),
728 new ast::VariableExpr( location, srcParam ),
729 }
730 );
731 functionDecl->stmts = new ast::CompoundStmt( location,
732 { new ast::ExprStmt( location, callExpr ) }
733 );
734 } else {
735 assert( 1 == params.size() );
736 // Default constructor and destructor is empty.
737 functionDecl->stmts = new ast::CompoundStmt( location );
738 // Just add unused attribute to parameter to silence warnings.
739 addUnusedAttribute( params.front() );
740
741 // Just an extra step to make the forward and declaration match.
742 if ( forwards.empty() ) return;
743 ast::FunctionDecl * fwd = strict_dynamic_cast<ast::FunctionDecl *>(
744 forwards.back().get_and_mutate() );
745 addUnusedAttribute( fwd->params.front() );
746 }
747}
748
749void TypeFuncGenerator::genFieldCtors() {
750 // Opaque types do not have field constructors.
751}
752
753void TypeFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
754 const CodeLocation& location = functionDecl->location;
755 auto & params = functionDecl->type->params;
756 assertf( 1 == params.size() || 2 == params.size(),
757 "Incorrect number of parameters in autogenerated typedecl function: %zd",
758 params.size() );
759 auto dstParam = params.front().strict_as<ast::ObjectDecl>();
760 auto srcParam = (2 == params.size())
761 ? params.back().strict_as<ast::ObjectDecl>() : nullptr;
762 // Generate appropriate calls to member constructor and assignment.
763 ast::UntypedExpr * expr = new ast::UntypedExpr( location,
764 new ast::NameExpr( location, functionDecl->name )
765 );
766 expr->args.push_back( new ast::CastExpr( location,
767 new ast::VariableExpr( location, dstParam ),
768 new ast::ReferenceType( decl->base )
769 ) );
770 if ( srcParam ) {
771 expr->args.push_back( new ast::CastExpr( location,
772 new ast::VariableExpr( location, srcParam ),
773 decl->base
774 ) );
775 }
776 functionDecl->stmts = new ast::CompoundStmt( location,
777 { new ast::ExprStmt( location, expr ) }
778 );
779}
780
781} // namespace
782
783void autogenerateRoutines( ast::TranslationUnit & translationUnit ) {
784 ast::Pass<AutogenerateRoutines_new>::run( translationUnit );
785}
786
787} // Validate
788
789// Local Variables: //
790// tab-width: 4 //
791// mode: c++ //
792// compile-command: "make install" //
793// End: //
Note: See TracBrowser for help on using the repository browser.