source: src/Validate/Autogen.cpp @ 59c8dff

Last change on this file since 59c8dff was 59c8dff, checked in by JiadaL <j82liang@…>, 7 months ago

Draft Implementation for enum position pesudo function (posE). EnumPosExpr? is mostly irrelevant for now. It is used in development/code probing and will be removed later

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