source: src/Validate/Autogen.cpp@ d66a43b

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