source: src/GenPoly/BoxNew.cpp @ 4604bf5

Last change on this file since 4604bf5 was 4604bf5, checked in by Andrew Beach <ajbeach@…>, 9 months ago

Clean-up of some names and comments. Removed some TODO comments which are too old to do anything with.

  • Property mode set to 100644
File size: 89.7 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// BoxNew.cpp -- Implement polymorphic function calls and types.
8//
9// Author           : Andrew Beach
10// Created On       : Thr Oct  6 13:39:00 2022
11// Last Modified By : Andrew Beach
12// Last Modified On : Mon Oct  2 17:00:00 2023
13// Update Count     : 0
14//
15
16#include "Box.h"
17
18#include "AST/Decl.hpp"                // for Decl, FunctionDecl, ...
19#include "AST/Expr.hpp"                // for AlignofExpr, ConstantExpr, ...
20#include "AST/Init.hpp"                // for Init, SingleInit
21#include "AST/Inspect.hpp"             // for getFunctionName
22#include "AST/Pass.hpp"                // for Pass, WithDeclsToAdd, ...
23#include "AST/Stmt.hpp"                // for CompoundStmt, ExprStmt, ...
24#include "AST/Vector.hpp"              // for vector
25#include "AST/GenericSubstitution.hpp" // for genericSubstitution
26#include "CodeGen/OperatorTable.h"     // for isAssignment
27#include "Common/ScopedMap.h"          // for ScopedMap
28#include "Common/UniqueName.h"         // for UniqueName
29#include "Common/utility.h"            // for toCString, group_iterate
30#include "GenPoly/FindFunction.h"      // for findFunction
31#include "GenPoly/GenPoly.h"           // for getFunctionType, ...
32#include "GenPoly/Lvalue.h"            // for generalizedLvalue
33#include "GenPoly/ScopedSet.h"         // for ScopedSet
34#include "GenPoly/ScrubTyVars.h"       // for scrubTypeVars, scrubAllTypeVars
35#include "ResolvExpr/Unify.h"          // for typesCompatible
36#include "SymTab/Mangler.h"            // for mangle, mangleType
37
38namespace GenPoly {
39
40namespace {
41
42/// Common field of several sub-passes of box.
43struct BoxPass {
44        TypeVarMap scopeTypeVars;
45        BoxPass() : scopeTypeVars( ast::TypeData() ) {}
46};
47
48// TODO: Could this be a common helper somewhere?
49ast::FunctionType * makeFunctionType( ast::FunctionDecl const * decl ) {
50        ast::FunctionType * type = new ast::FunctionType(
51                decl->type->isVarArgs, decl->type->qualifiers
52        );
53        for ( auto type_param : decl->type_params ) {
54                type->forall.emplace_back( new ast::TypeInstType( type_param ) );
55        }
56        for ( auto assertion : decl->assertions ) {
57                type->assertions.emplace_back( new ast::VariableExpr(
58                        assertion->location, assertion ) );
59        }
60        for ( auto param : decl->params ) {
61                type->params.emplace_back( param->get_type() );
62        }
63        for ( auto retval : decl->returns ) {
64                type->returns.emplace_back( retval->get_type() );
65        }
66        return type;
67}
68
69// --------------------------------------------------------------------------
70/// Adds layout-generation functions to polymorphic types.
71struct LayoutFunctionBuilder final :
72                public ast::WithDeclsToAdd<>,
73                public ast::WithShortCircuiting,
74                public ast::WithVisitorRef<LayoutFunctionBuilder> {
75        void previsit( ast::StructDecl const * decl );
76        void previsit( ast::UnionDecl const * decl );
77};
78
79/// Get all sized type declarations; those that affect a layout function.
80ast::vector<ast::TypeDecl> takeSizedParams(
81                ast::vector<ast::TypeDecl> const & decls ) {
82        ast::vector<ast::TypeDecl> sizedParams;
83        for ( ast::ptr<ast::TypeDecl> const & decl : decls ) {
84                if ( decl->isComplete() ) {
85                        sizedParams.emplace_back( decl );
86                }
87        }
88        return sizedParams;
89}
90
91ast::BasicType * makeSizeAlignType() {
92        return new ast::BasicType( ast::BasicType::LongUnsignedInt );
93}
94
95/// Adds parameters for otype size and alignment to a function type.
96void addSTypeParams(
97                ast::FunctionDecl * decl,
98                ast::vector<ast::TypeDecl> const & sizedParams ) {
99        // TODO: Can we fold this into buildLayoutFunction to avoid rebuilding?
100        ast::FunctionType * type = ast::mutate( decl->type.get() );
101        for ( ast::ptr<ast::TypeDecl> const & sizedParam : sizedParams ) {
102                ast::TypeInstType inst( sizedParam );
103                std::string paramName = Mangle::mangleType( &inst );
104                decl->params.emplace_back( new ast::ObjectDecl(
105                        sizedParam->location,
106                        sizeofName( paramName ),
107                        makeSizeAlignType()
108                ) );
109                type->params.emplace_back( makeSizeAlignType() );
110                decl->params.emplace_back( new ast::ObjectDecl(
111                        sizedParam->location,
112                        alignofName( paramName ),
113                        makeSizeAlignType()
114                ) );
115                type->params.emplace_back( makeSizeAlignType() );
116        }
117        decl->type = type;
118}
119
120ast::Type * makeSizeAlignOutType() {
121        return new ast::PointerType( makeSizeAlignType() );
122}
123
124struct LayoutData {
125        ast::FunctionDecl * function;
126        ast::ObjectDecl * sizeofParam;
127        ast::ObjectDecl * alignofParam;
128        ast::ObjectDecl * offsetofParam;
129};
130
131// TODO: Is there a better way to handle the different besides a flag?
132LayoutData buildLayoutFunction(
133                CodeLocation const & location, ast::AggregateDecl const * aggr,
134                bool isInFunction, bool isStruct ) {
135        ast::ObjectDecl * sizeParam = new ast::ObjectDecl(
136                location,
137                sizeofName( aggr->name ),
138                makeSizeAlignOutType()
139        );
140        ast::ObjectDecl * alignParam = new ast::ObjectDecl(
141                location,
142                alignofName( aggr->name ),
143                makeSizeAlignOutType()
144        );
145        ast::ObjectDecl * offsetParam = nullptr;
146        ast::vector<ast::DeclWithType> params = { sizeParam, alignParam };
147        if ( isStruct ) {
148                offsetParam = new ast::ObjectDecl(
149                        location,
150                        offsetofName( aggr->name ),
151                        makeSizeAlignOutType()
152                );
153                params.push_back( offsetParam );
154        }
155
156        // Routines at global scope marked "static" to prevent multiple
157        // definitions is separate translation units because each unit generates
158        // copies of the default routines for each aggregate.
159        ast::FunctionDecl * layoutDecl = new ast::FunctionDecl(
160                location,
161                layoutofName( aggr ),
162                {}, // forall
163                {}, // assertions
164                std::move( params ),
165                {}, // returns
166                new ast::CompoundStmt( location ),
167                isInFunction ? ast::Storage::Classes() : ast::Storage::Static,
168                ast::Linkage::AutoGen,
169                {}, // attrs
170                ast::Function::Inline,
171                ast::FixedArgs
172        );
173        layoutDecl->fixUniqueId();
174        return LayoutData{ layoutDecl, sizeParam, alignParam, offsetParam };
175}
176
177/// Makes a binary operation.
178ast::Expr * makeOp( CodeLocation const & location, std::string const & name,
179                ast::Expr const * lhs, ast::Expr const * rhs ) {
180        return new ast::UntypedExpr( location,
181                new ast::NameExpr( location, name ), { lhs, rhs } );
182}
183
184/// Make a binary operation and wrap it in a statement.
185ast::Stmt * makeOpStmt( CodeLocation const & location, std::string const & name,
186                ast::Expr const * lhs, ast::Expr const * rhs ) {
187        return new ast::ExprStmt( location, makeOp( location, name, lhs, rhs ) );
188}
189
190/// Returns the dereference of a local pointer variable.
191ast::Expr * derefVar(
192                CodeLocation const & location, ast::ObjectDecl const * var ) {
193        return ast::UntypedExpr::createDeref( location,
194                new ast::VariableExpr( location, var ) );
195}
196
197/// Makes an if-statement with a single-expression then and no else.
198ast::Stmt * makeCond( CodeLocation const & location,
199                ast::Expr const * cond, ast::Expr const * thenPart ) {
200        return new ast::IfStmt( location,
201                cond, new ast::ExprStmt( location, thenPart ), nullptr );
202}
203
204/// Makes a statement that aligns lhs to rhs (rhs should be an integer
205/// power of two).
206ast::Stmt * makeAlignTo( CodeLocation const & location,
207                ast::Expr const * lhs, ast::Expr const * rhs ) {
208        // Check that the lhs is zeroed out to the level of rhs.
209        ast::Expr * ifCond = makeOp( location, "?&?", lhs,
210                makeOp( location, "?-?", rhs,
211                                ast::ConstantExpr::from_ulong( location, 1 ) ) );
212        // If not aligned, increment to alignment.
213        ast::Expr * ifExpr = makeOp( location, "?+=?", ast::deepCopy( lhs ),
214                makeOp( location, "?-?", ast::deepCopy( rhs ),
215                                ast::deepCopy( ifCond ) ) );
216        return makeCond( location, ifCond, ifExpr );
217}
218
219/// Makes a statement that assigns rhs to lhs if lhs < rhs.
220ast::Stmt * makeAssignMax( CodeLocation const & location,
221                ast::Expr const * lhs, ast::Expr const * rhs ) {
222        return makeCond( location,
223                makeOp( location, "?<?", ast::deepCopy( lhs ), ast::deepCopy( rhs ) ),
224                makeOp( location, "?=?", lhs, rhs ) );
225}
226
227void LayoutFunctionBuilder::previsit( ast::StructDecl const * decl ) {
228        // Do not generate layout function for empty tag structures.
229        visit_children = false;
230        if ( decl->members.empty() ) return;
231
232        // Get parameters that can change layout, exiting early if none.
233        ast::vector<ast::TypeDecl> sizedParams =
234                takeSizedParams( decl->params );
235        if ( sizedParams.empty() ) return;
236
237        CodeLocation const & location = decl->location;
238
239        // Build layout function signature.
240        LayoutData layout =
241                buildLayoutFunction( location, decl, isInFunction(), true );
242        ast::FunctionDecl * layoutDecl = layout.function;
243        // Also return these or extract them from the parameter list?
244        ast::ObjectDecl const * sizeofParam = layout.sizeofParam;
245        ast::ObjectDecl const * alignofParam = layout.alignofParam;
246        ast::ObjectDecl const * offsetofParam = layout.offsetofParam;
247        assert( nullptr != layout.offsetofParam );
248        addSTypeParams( layoutDecl, sizedParams );
249
250        // Calculate structure layout in function body.
251        // Initialize size and alignment to 0 and 1
252        // (Will have at least one member to update size).
253        auto & kids = layoutDecl->stmts.get_and_mutate()->kids;
254        kids.emplace_back( makeOpStmt( location, "?=?",
255                derefVar( location, sizeofParam ),
256                ast::ConstantExpr::from_ulong( location, 0 )
257        ) );
258        kids.emplace_back( makeOpStmt( location, "?=?",
259                derefVar( location, alignofParam ),
260                ast::ConstantExpr::from_ulong( location, 1 )
261        ) );
262        // TODO: Polymorphic types will be out of the struct declaration scope.
263        // Should be removed by PolyGenericCalculator.
264        for ( auto const & member : enumerate( decl->members ) ) {
265                auto dwt = member.val.strict_as<ast::DeclWithType>();
266                ast::Type const * memberType = dwt->get_type();
267
268                if ( 0 < member.idx ) {
269                        // Make sure all later members have padding to align them.
270                        kids.emplace_back( makeAlignTo( location,
271                                derefVar( location, sizeofParam ),
272                                new ast::AlignofExpr( location, ast::deepCopy( memberType ) )
273                        ) );
274                }
275
276                // Place current size in the current offset index.
277                kids.emplace_back( makeOpStmt( location, "?=?",
278                        makeOp( location, "?[?]",
279                                new ast::VariableExpr( location, offsetofParam ),
280                                ast::ConstantExpr::from_ulong( location, member.idx ) ),
281                        derefVar( location, sizeofParam ) ) );
282
283                // Add member size to current size.
284                kids.emplace_back( makeOpStmt( location, "?+=?",
285                        derefVar( location, sizeofParam ),
286                        new ast::SizeofExpr( location, ast::deepCopy( memberType ) ) ) );
287
288                // Take max of member alignment and global alignment.
289                // (As align is always 2^n, this will always be a multiple of both.)
290                kids.emplace_back( makeAssignMax( location,
291                        derefVar( location, alignofParam ),
292                        new ast::AlignofExpr( location, ast::deepCopy( memberType ) ) ) );
293        }
294        // Make sure the type is end-padded to a multiple of its alignment.
295        kids.emplace_back( makeAlignTo( location,
296                derefVar( location, sizeofParam ),
297                derefVar( location, alignofParam ) ) );
298
299        declsToAddAfter.emplace_back( layoutDecl );
300}
301
302void LayoutFunctionBuilder::previsit( ast::UnionDecl const * decl ) {
303        visit_children = false;
304        // Do not generate layout function for empty tag unions.
305        if ( decl->members.empty() ) return;
306
307        // Get parameters that can change layout, exiting early if none.
308        ast::vector<ast::TypeDecl> sizedParams =
309                takeSizedParams( decl->params );
310        if ( sizedParams.empty() ) return;
311
312        CodeLocation const & location = decl->location;
313
314        // Build layout function signature.
315        LayoutData layout =
316                buildLayoutFunction( location, decl, isInFunction(), false );
317        ast::FunctionDecl * layoutDecl = layout.function;
318        // Also return these or extract them from the parameter list?
319        ast::ObjectDecl const * sizeofParam = layout.sizeofParam;
320        ast::ObjectDecl const * alignofParam = layout.alignofParam;
321        assert( nullptr == layout.offsetofParam );
322        addSTypeParams( layoutDecl, sizedParams );
323
324        // Calculate union layout in function body.
325        // Both are simply the maximum for union (actually align is always the
326        // LCM, but with powers of two that is also the maximum).
327        auto & kids = layoutDecl->stmts.get_and_mutate()->kids;
328        kids.emplace_back( makeOpStmt( location,
329                "?=?", derefVar( location, sizeofParam ),
330                ast::ConstantExpr::from_ulong( location, 1 )
331        ) );
332        kids.emplace_back( makeOpStmt( location,
333                "?=?", derefVar( location, alignofParam ),
334                ast::ConstantExpr::from_ulong( location, 1 )
335        ) );
336        // TODO: Polymorphic types will be out of the union declaration scope.
337        for ( auto const & member : decl->members ) {
338                auto dwt = member.strict_as<ast::DeclWithType>();
339                ast::Type const * memberType = dwt->get_type();
340
341                // Take max member size and global size.
342                kids.emplace_back( makeAssignMax( location,
343                        derefVar( location, sizeofParam ),
344                        new ast::SizeofExpr( location, ast::deepCopy( memberType ) )
345                ) );
346
347                // Take max of member alignment and global alignment.
348                kids.emplace_back( makeAssignMax( location,
349                        derefVar( location, alignofParam ),
350                        new ast::AlignofExpr( location, ast::deepCopy( memberType ) )
351                ) );
352        }
353        kids.emplace_back( makeAlignTo( location,
354                derefVar( location, sizeofParam ),
355                derefVar( location, alignofParam ) ) );
356
357        declsToAddAfter.emplace_back( layoutDecl );
358}
359
360// --------------------------------------------------------------------------
361/// Application expression transformer.
362/// * Replaces polymorphic return types with out-parameters.
363/// * Replaces call to polymorphic functions with adapter calls which handles
364///   dynamic arguments and return values.
365/// * Adds appropriate type variables to the function calls.
366struct CallAdapter final :
367                public BoxPass,
368                public ast::WithConstTypeSubstitution,
369                public ast::WithGuards,
370                public ast::WithShortCircuiting,
371                public ast::WithStmtsToAdd<>,
372                public ast::WithVisitorRef<CallAdapter> {
373        CallAdapter();
374
375        void previsit( ast::Decl const * decl );
376        ast::FunctionDecl const * previsit( ast::FunctionDecl const * decl );
377        void previsit( ast::TypeDecl const * decl );
378        void previsit( ast::CommaExpr const * expr );
379        ast::Expr const * postvisit( ast::ApplicationExpr const * expr );
380        ast::Expr const * postvisit( ast::UntypedExpr const * expr );
381        void previsit( ast::AddressExpr const * expr );
382        ast::Expr const * postvisit( ast::AddressExpr const * expr );
383        ast::ReturnStmt const * previsit( ast::ReturnStmt const * stmt );
384        void previsit( ast::PointerType const * type );
385        void previsit( ast::FunctionType const * type );
386
387        void beginScope();
388        void endScope();
389private:
390        // Many helpers here use a mutable ApplicationExpr as an in/out parameter
391        // instead of using the return value, to save on mutates and free up the
392        // return value.
393
394        /// Pass the extra type parameters from polymorphic generic arguments or
395        /// return types into a function application.
396        ast::vector<ast::Expr>::iterator passArgTypeVars(
397                ast::ApplicationExpr * expr, ast::Type const * parmType,
398                ast::Type const * argBaseType, ast::vector<ast::Expr>::iterator arg,
399                const TypeVarMap & exprTyVars, std::set<std::string> & seenTypes );
400        /// Passes extra type parameters into a polymorphic function application.
401        ast::vector<ast::Expr>::iterator passTypeVars(
402                ast::ApplicationExpr * expr,
403                ast::Type const * polyRetType,
404                ast::FunctionType const * funcType,
405                const TypeVarMap & exprTyVars );
406        /// Wraps a function application with a new temporary for the
407        /// out-parameter return value.
408        ast::Expr const * addRetParam(
409                ast::ApplicationExpr * expr, ast::Type const * retType );
410        /// Wraps a function application returning a polymorphic type with a new
411        /// temporary for the out-parameter return value.
412        ast::Expr const * addDynRetParam(
413                ast::ApplicationExpr * expr, ast::Type const * polyType );
414        /// Modify a call so it passes the function through the correct adapter.
415        ast::Expr const * applyAdapter(
416                ast::ApplicationExpr * expr,
417                ast::FunctionType const * function );
418        /// Convert a single argument into its boxed form to pass the parameter.
419        void boxParam( ast::ptr<ast::Expr> & arg,
420                ast::Type const * formal, TypeVarMap const & exprTyVars );
421        /// Box every argument from arg forward, matching the functionType
422        /// parameter list. arg should point into expr's argument list.
423        void boxParams(
424                ast::ApplicationExpr const * expr,
425                ast::vector<ast::Expr>::iterator arg,
426                ast::FunctionType const * function,
427                const TypeVarMap & typeVars );
428        /// Adds the inferred parameters derived from the assertions of the
429        /// expression to the call.
430        void addInferredParams(
431                ast::ApplicationExpr * expr,
432                ast::vector<ast::Expr>::iterator arg,
433                ast::FunctionType const * functionType,
434                const TypeVarMap & typeVars );
435        /// Stores assignment operators from assertion list in
436        /// local map of assignment operations.
437        void passAdapters(
438                ast::ApplicationExpr * expr,
439                ast::FunctionType const * type,
440                const TypeVarMap & typeVars );
441        /// Create an adapter function based on the type of the adaptee and the
442        /// real type with the type substitutions applied.
443        ast::FunctionDecl * makeAdapter(
444                ast::FunctionType const * adaptee,
445                ast::FunctionType const * realType,
446                std::string const & mangleName,
447                TypeVarMap const & typeVars,
448                CodeLocation const & location ) const;
449        /// Replaces intrinsic operator functions with their arithmetic desugaring.
450        ast::Expr const * handleIntrinsics( ast::ApplicationExpr const * );
451        /// Inserts a new temporary variable into the current scope with an
452        /// auto-generated name.
453        ast::ObjectDecl * makeTemporary(
454                CodeLocation const & location, ast::Type const * type );
455
456        /// Set of adapter functions in the current scope.
457        ScopedMap< std::string, ast::DeclWithType const * > adapters;
458        std::map< ast::ApplicationExpr const *, ast::Expr const * > retVals;
459        ast::DeclWithType const * retval;
460        UniqueName tmpNamer;
461};
462
463/// Replaces a polymorphic type with its concrete equivalant under the
464/// current environment (returns itself if concrete).
465/// If `doClone` is set to false, will not clone interior types
466ast::Type const * replaceWithConcrete(
467                ast::Type const * type,
468                ast::TypeSubstitution const & typeSubs,
469                bool doCopy = true );
470
471/// Replaces all the type parameters of a generic type with their
472/// concrete equivalents under the current environment.
473void replaceParametersWithConcrete(
474                ast::vector<ast::Expr> & params,
475                ast::TypeSubstitution const & typeSubs ) {
476        for ( ast::ptr<ast::Expr> & paramExpr : params ) {
477                ast::TypeExpr const * param = paramExpr.as<ast::TypeExpr>();
478                assertf( param, "Aggregate parameters should be type expressions." );
479                paramExpr = ast::mutate_field( param, &ast::TypeExpr::type,
480                        replaceWithConcrete( param->type.get(), typeSubs, false ) );
481        }
482}
483
484ast::Type const * replaceWithConcrete(
485                ast::Type const * type,
486                ast::TypeSubstitution const & typeSubs,
487                bool doCopy ) {
488        if ( auto instType = dynamic_cast<ast::TypeInstType const *>( type ) ) {
489                ast::Type const * concrete = typeSubs.lookup( instType );
490                return ( nullptr != concrete ) ? concrete : instType;
491        } else if ( auto structType =
492                        dynamic_cast<ast::StructInstType const *>( type ) ) {
493                ast::StructInstType * newType =
494                        doCopy ? ast::deepCopy( structType ) : ast::mutate( structType );
495                replaceParametersWithConcrete( newType->params, typeSubs );
496                return newType;
497        } else if ( auto unionType =
498                        dynamic_cast<ast::UnionInstType const *>( type ) ) {
499                ast::UnionInstType * newType =
500                        doCopy ? ast::deepCopy( unionType ) : ast::mutate( unionType );
501                replaceParametersWithConcrete( newType->params, typeSubs );
502                return newType;
503        } else {
504                return type;
505        }
506}
507
508std::string makePolyMonoSuffix(
509                ast::FunctionType const * function,
510                TypeVarMap const & typeVars ) {
511        // If the return type or a parameter type involved polymorphic types,
512        // then the adapter will need to take those polymorphic types as pointers.
513        // Therefore, there can be two different functions with the same mangled
514        // name, so we need to further mangle the names.
515        std::stringstream name;
516        for ( auto ret : function->returns ) {
517                name << ( isPolyType( ret, typeVars ) ? 'P' : 'M' );
518        }
519        name << '_';
520        for ( auto arg : function->params ) {
521                name << ( isPolyType( arg, typeVars ) ? 'P' : 'M' );
522        }
523        return name.str();
524}
525
526std::string mangleAdapterName(
527                ast::FunctionType const * function,
528                TypeVarMap const & typeVars ) {
529        return Mangle::mangle( function, {} )
530                + makePolyMonoSuffix( function, typeVars );
531}
532
533std::string makeAdapterName( std::string const & mangleName ) {
534        return "_adapter" + mangleName;
535}
536
537void makeRetParam( ast::FunctionType * type ) {
538        ast::ptr<ast::Type> & retParam = type->returns.front();
539
540        // Make a new parameter that is a pointer to the type of the old return value.
541        retParam = new ast::PointerType( retParam.get() );
542        type->params.emplace( type->params.begin(), retParam );
543
544        // We don't need the return value any more.
545        type->returns.clear();
546}
547
548ast::FunctionType * makeAdapterType(
549                ast::FunctionType const * adaptee,
550                TypeVarMap const & typeVars ) {
551        ast::FunctionType * adapter = ast::deepCopy( adaptee );
552        if ( isDynRet( adapter, typeVars ) ) {
553                makeRetParam( adapter );
554        }
555        adapter->params.emplace( adapter->params.begin(),
556                new ast::PointerType( new ast::FunctionType( ast::VariableArgs ) )
557        );
558        return adapter;
559}
560
561CallAdapter::CallAdapter() : tmpNamer( "_temp" ) {}
562
563void CallAdapter::previsit( ast::Decl const * ) {
564        // Prevent type declaration information from leaking out.
565        GuardScope( scopeTypeVars );
566}
567
568ast::FunctionDecl const * CallAdapter::previsit( ast::FunctionDecl const * decl ) {
569        if ( nullptr == decl->stmts ) {
570                // This may keep TypeDecls we don't ever want from sneaking in.
571                // Not visiting child nodes might just be faster.
572                GuardScope( scopeTypeVars );
573                return decl;
574        }
575
576        GuardScope( scopeTypeVars );
577        GuardValue( retval );
578
579        // Process polymorphic return value.
580        retval = nullptr;
581        ast::FunctionType const * type = decl->type;
582        if ( isDynRet( type ) && decl->linkage != ast::Linkage::C ) {
583                retval = decl->returns.front();
584
585                // Give names to unnamed return values.
586                if ( "" == retval->name ) {
587                        auto mutRet = ast::mutate( retval );
588                        mutRet->name = "_retparam";
589                        mutRet->linkage = ast::Linkage::C;
590                        retval = mutRet;
591                        decl = ast::mutate_field_index( decl,
592                                &ast::FunctionDecl::returns, 0, mutRet );
593                }
594        }
595
596        // The formal_usage/expr_id values may be off if we get them from the
597        // type, trying the declaration instead.
598        makeTypeVarMap( type, scopeTypeVars );
599
600        // Get all needed adapters from the call. We will forward them.
601        ast::vector<ast::FunctionType> functions;
602        for ( ast::ptr<ast::VariableExpr> const & assertion : type->assertions ) {
603                auto atype = assertion->result.get();
604                findFunction( atype, functions, scopeTypeVars, needsAdapter );
605        }
606
607        for ( ast::ptr<ast::Type> const & arg : type->params ) {
608                findFunction( arg, functions, scopeTypeVars, needsAdapter );
609        }
610
611        for ( auto funcType : functions ) {
612                std::string mangleName = mangleAdapterName( funcType, scopeTypeVars );
613                if ( adapters.contains( mangleName ) ) continue;
614                std::string adapterName = makeAdapterName( mangleName );
615                // TODO: The forwarding here is problematic because these
616                // declarations are not rooted anywhere in the translation unit.
617                adapters.insert(
618                        mangleName,
619                        new ast::ObjectDecl(
620                                decl->location,
621                                adapterName,
622                                new ast::PointerType(
623                                        makeAdapterType( funcType, scopeTypeVars ) ),
624                                nullptr, // init
625                                ast::Storage::Classes(),
626                                ast::Linkage::C
627                        )
628                );
629        }
630
631        return decl;
632}
633
634void CallAdapter::previsit( ast::TypeDecl const * decl ) {
635        addToTypeVarMap( decl, scopeTypeVars );
636}
637
638void CallAdapter::previsit( ast::CommaExpr const * expr ) {
639        // Attempting to find application expressions that were mutated by the
640        // copy constructor passes to use an explicit return variable, so that
641        // the variable can be reused as a parameter to the call rather than
642        // creating a new temporary variable. Previously this step was an
643        // optimization, but with the introduction of tuples and UniqueExprs,
644        // it is necessary to ensure that they use the same variable.
645        // Essentially, looking for pattern:
646        // (x=f(...), x)
647        // To compound the issue, the right side can be *x, etc.
648        // because of lvalue-returning functions
649        if ( auto assign = expr->arg1.as<ast::UntypedExpr>() ) {
650                if ( CodeGen::isAssignment( ast::getFunctionName( assign ) ) ) {
651                        assert( 2 == assign->args.size() );
652                        if ( auto app = assign->args.back().as<ast::ApplicationExpr>() ) {
653                                // First argument is assignable, so it must be an lvalue,
654                                // so it should be legal to takes its address.
655                                retVals.insert_or_assign( app, assign->args.front() );
656                        }
657                }
658        }
659}
660
661ast::Expr const * CallAdapter::postvisit( ast::ApplicationExpr const * expr ) {
662        assert( expr->func->result );
663        ast::FunctionType const * function = getFunctionType( expr->func->result );
664        assertf( function, "ApplicationExpr has non-function type %s",
665                        toCString( expr->func->result ) );
666
667        if ( auto newExpr = handleIntrinsics( expr ) ) {
668                return newExpr;
669        }
670
671        ast::ApplicationExpr * mutExpr = ast::mutate( expr );
672        ast::Expr const * ret = expr;
673
674        // TODO: This entire section should probably be refactored to do less
675        // pushing to the front/middle of a vector.
676        ptrdiff_t initArgCount = mutExpr->args.size();
677
678        TypeVarMap exprTypeVars = { ast::TypeData() };
679        // TODO: Should this take into account the variables already bound in
680        // scopeTypeVars ([ex] remove them from exprTypeVars)?
681        makeTypeVarMap( function, exprTypeVars );
682        auto dynRetType = isDynRet( function, exprTypeVars );
683
684        // NOTE: addDynRetParam needs to know the actual (generated) return type
685        // so it can make a temporary variable, so pass the result type form the
686        // `expr` `passTypeVars` needs to know the program-text return type ([ex]
687        // the distinction between _conc_T30 and T3(int)) concRetType may not be
688        // a good name in one or both of these places.
689        if ( dynRetType ) {
690                ast::Type const * result = mutExpr->result;
691                ast::Type const * concRetType = result->isVoid() ? nullptr : result;
692                // [Comment from before translation.]
693                // Used to use dynRetType instead of concRetType.
694                ret = addDynRetParam( mutExpr, concRetType );
695        } else if ( needsAdapter( function, scopeTypeVars )
696                        && !needsAdapter( function, exprTypeVars ) ) {
697                // Change the application so it calls the adapter rather than the
698                // passed function.
699                ret = applyAdapter( mutExpr, function );
700        }
701
702        assert( typeSubs );
703        ast::Type const * concRetType = replaceWithConcrete( dynRetType, *typeSubs );
704        // Used to use dynRetType instead of concRetType; this changed so that
705        // the correct type parameters are passed for return types (it should be
706        // the concrete type's parameters, not the formal type's).
707        ast::vector<ast::Expr>::iterator argIt =
708                passTypeVars( mutExpr, concRetType, function, exprTypeVars );
709        addInferredParams( mutExpr, argIt, function, exprTypeVars );
710
711        argIt = mutExpr->args.begin();
712        std::advance( argIt, ( mutExpr->args.size() - initArgCount ) );
713
714        boxParams( mutExpr, argIt, function, exprTypeVars );
715        passAdapters( mutExpr, function, exprTypeVars );
716
717        return ret;
718}
719
720bool isPolyDeref( ast::UntypedExpr const * expr,
721                TypeVarMap const & typeVars,
722                ast::TypeSubstitution const * typeSubs ) {
723        if ( expr->result && isPolyType( expr->result, typeVars, typeSubs ) ) {
724                if ( auto name = expr->func.as<ast::NameExpr>() ) {
725                        if ( "*?" == name->name ) {
726                                return true;
727                        }
728                }
729        }
730        return false;
731}
732
733ast::Expr const * CallAdapter::postvisit( ast::UntypedExpr const * expr ) {
734        if ( isPolyDeref( expr, scopeTypeVars, typeSubs ) ) {
735                return expr->args.front();
736        }
737        return expr;
738}
739
740void CallAdapter::previsit( ast::AddressExpr const * ) {
741        visit_children = false;
742}
743
744ast::Expr const * CallAdapter::postvisit( ast::AddressExpr const * expr ) {
745        assert( expr->arg->result );
746        assert( !expr->arg->result->isVoid() );
747
748        bool doesNeedAdapter = false;
749        if ( auto un = expr->arg.as<ast::UntypedExpr>() ) {
750                if ( isPolyDeref( un, scopeTypeVars, typeSubs ) ) {
751                        if ( auto app = un->args.front().as<ast::ApplicationExpr>() ) {
752                                assert( app->func->result );
753                                auto function = getFunctionType( app->func->result );
754                                assert( function );
755                                doesNeedAdapter = needsAdapter( function, scopeTypeVars );
756                        }
757                }
758        }
759        // isPolyType check needs to happen before mutating expr arg,
760        // so pull it forward out of the if condition.
761        expr = ast::mutate_field( expr, &ast::AddressExpr::arg,
762                        expr->arg->accept( *visitor ) );
763        // But must happen after mutate, since argument might change
764        // (ex. intrinsic *?, ?[?]) re-evaluate above comment.
765        bool polyType = isPolyType( expr->arg->result, scopeTypeVars, typeSubs );
766        if ( polyType || doesNeedAdapter ) {
767                ast::Expr * ret = ast::mutate( expr->arg.get() );
768                ret->result = ast::deepCopy( expr->result );
769                return ret;
770        } else {
771                return expr;
772        }
773}
774
775ast::ReturnStmt const * CallAdapter::previsit( ast::ReturnStmt const * stmt ) {
776        // Since retval is set when the return type is dynamic, this function
777        // should have been converted to void return & out parameter.
778        if ( retval && stmt->expr ) {
779                assert( stmt->expr->result );
780                assert( !stmt->expr->result->isVoid() );
781                return ast::mutate_field( stmt, &ast::ReturnStmt::expr, nullptr );
782        }
783        return stmt;
784}
785
786void CallAdapter::previsit( ast::PointerType const * type ) {
787        GuardScope( scopeTypeVars );
788        makeTypeVarMap( type, scopeTypeVars );
789}
790
791void CallAdapter::previsit( ast::FunctionType const * type ) {
792        GuardScope( scopeTypeVars );
793        makeTypeVarMap( type, scopeTypeVars );
794}
795
796void CallAdapter::beginScope() {
797        adapters.beginScope();
798}
799
800void CallAdapter::endScope() {
801        adapters.endScope();
802}
803
804/// Find instances of polymorphic type parameters.
805struct PolyFinder {
806        TypeVarMap const & typeVars;
807        bool result = false;
808        PolyFinder( TypeVarMap const & tvs ) : typeVars( tvs ) {}
809
810        void previsit( ast::TypeInstType const * type ) {
811                if ( isPolyType( type, typeVars ) ) result = true;
812        }
813};
814
815/// True if these is an instance of a polymorphic type parameter in the type.
816bool hasPolymorphism( ast::Type const * type, TypeVarMap const & typeVars ) {
817        return ast::Pass<PolyFinder>::read( type, typeVars );
818}
819
820// arg is an in/out parameter that matches the return value.
821ast::vector<ast::Expr>::iterator CallAdapter::passArgTypeVars(
822                ast::ApplicationExpr * expr, ast::Type const * paramType,
823                ast::Type const * argBaseType, ast::vector<ast::Expr>::iterator arg,
824                const TypeVarMap & exprTypeVars, std::set<std::string> & seenTypes ) {
825        ast::Type const * polyType = isPolyType( paramType, exprTypeVars );
826        if ( !polyType || dynamic_cast<ast::TypeInstType const *>( polyType ) ) {
827                return arg;
828        }
829
830        std::string typeName = Mangle::mangleType( polyType );
831        if ( seenTypes.count( typeName ) ) return arg;
832
833        arg = expr->args.insert( arg,
834                new ast::SizeofExpr( expr->location, ast::deepCopy( argBaseType ) )
835        );
836        arg++;
837        arg = expr->args.insert( arg,
838                new ast::AlignofExpr( expr->location, ast::deepCopy( argBaseType ) )
839        );
840        arg++;
841        if ( dynamic_cast<ast::StructInstType const *>( polyType ) ) {
842                auto argBaseStructType =
843                                dynamic_cast<ast::StructInstType const *>( argBaseType );
844                if ( nullptr == argBaseStructType ) {
845                        SemanticError( expr,
846                                "Cannot pass non-structure type for generic struct: " );
847                }
848
849                // Zero-length arrays are forbidden by C, so don't pass
850                // offset for empty structure.
851                if ( !argBaseStructType->base->members.empty() ) {
852                        arg = expr->args.insert( arg,
853                                new ast::OffsetPackExpr(
854                                        expr->location,
855                                        ast::deepCopy( argBaseStructType ) )
856                        );
857                        arg++;
858                }
859        }
860
861        seenTypes.insert( typeName );
862        return arg;
863}
864
865ast::vector<ast::Expr>::iterator CallAdapter::passTypeVars(
866                ast::ApplicationExpr * expr,
867                ast::Type const * polyRetType,
868                ast::FunctionType const * function,
869                const TypeVarMap & exprTypeVars ) {
870        assert( typeSubs );
871        ast::vector<ast::Expr>::iterator arg = expr->args.begin();
872        // Pass size/align for type variables.
873        for ( ast::ptr<ast::TypeInstType> const & typeVar : function->forall ) {
874                if ( !typeVar->base->isComplete() ) continue;
875                ast::Type const * concrete = typeSubs->lookup( typeVar );
876                if ( !concrete ) {
877                        // Should this be an assertion?
878                        SemanticError( expr, toString( typeSubs,
879                                "\nunbound type variable: ", typeVar->typeString(),
880                                " in application " ) );
881                }
882                arg = expr->args.insert( arg,
883                        new ast::SizeofExpr( expr->location, ast::deepCopy( concrete ) ) );
884                arg++;
885                arg = expr->args.insert( arg,
886                        new ast::AlignofExpr( expr->location, ast::deepCopy( concrete ) ) );
887                arg++;
888        }
889
890        // Add size/align for generic types to parameter list.
891        if ( !expr->func->result ) return arg;
892        ast::FunctionType const * funcType = getFunctionType( expr->func->result );
893        assert( funcType );
894
895        // This iterator points at first original argument.
896        ast::vector<ast::Expr>::const_iterator funcArg;
897        // Names for generic types we've seen.
898        std::set<std::string> seenTypes;
899
900        // A polymorphic return type may need to be added to the argument list.
901        if ( polyRetType ) {
902                assert( typeSubs );
903                auto concRetType = replaceWithConcrete( polyRetType, *typeSubs );
904                // TODO: This write-back may not be correct.
905                arg = passArgTypeVars( expr, polyRetType, concRetType,
906                                arg, exprTypeVars, seenTypes );
907                // Skip the return parameter in the argument list.
908                funcArg = arg + 1;
909        } else {
910                funcArg = arg;
911        }
912
913        // TODO:
914        // I believe this is (starts as) the number of original arguments to the
915        // function with the args before funcArg all being inserted.
916        ptrdiff_t argsToPass = std::distance( funcArg, expr->args.cend() );
917
918        // Add type information args for presently unseen types in parameter list.
919        ast::vector<ast::Type>::const_iterator funcParam = funcType->params.begin();
920        // assert( funcType->params.size() == argsToPass );
921        for ( ; funcParam != funcType->params.end() && 0 < argsToPass
922                        ; ++funcParam, --argsToPass ) {
923                assert( 0 < argsToPass );
924                assert( argsToPass <= (ptrdiff_t)expr->args.size() );
925                ptrdiff_t index = expr->args.size() - argsToPass;
926                ast::Type const * argType = expr->args[index]->result;
927                if ( nullptr == argType ) continue;
928                arg = passArgTypeVars( expr, *funcParam, argType,
929                                arg, exprTypeVars, seenTypes );
930        }
931        return arg;
932}
933
934ast::Expr const * CallAdapter::addRetParam(
935                ast::ApplicationExpr * expr, ast::Type const * retType ) {
936        // Create temporary to hold return value of polymorphic function and
937        // produce that temporary as a result using a comma expression.
938        assert( retType );
939
940        ast::Expr * paramExpr = nullptr;
941        // Try to use existing return value parameter if it exists,
942        // otherwise create a new temporary.
943        if ( retVals.count( expr ) ) {
944                paramExpr = ast::deepCopy( retVals[ expr ] );
945        } else {
946                auto newObj = makeTemporary( expr->location, ast::deepCopy( retType ) );
947                paramExpr = new ast::VariableExpr( expr->location, newObj );
948        }
949        ast::Expr * retExpr = ast::deepCopy( paramExpr );
950
951        // If the type of the temporary is not polpmorphic, box temporary by
952        // taking its address; otherwise the temporary is already boxed and can
953        // be used directly.
954        if ( !isPolyType( paramExpr->result, scopeTypeVars, typeSubs ) ) {
955                paramExpr = new ast::AddressExpr( paramExpr->location, paramExpr );
956        }
957        // Add argument to function call.
958        expr->args.insert( expr->args.begin(), paramExpr );
959        // Build a comma expression to call the function and return a value.
960        ast::CommaExpr * comma = new ast::CommaExpr(
961                expr->location, expr, retExpr );
962        comma->env = expr->env;
963        expr->env = nullptr;
964        return comma;
965}
966
967ast::Expr const * CallAdapter::addDynRetParam(
968                ast::ApplicationExpr * expr, ast::Type const * polyType ) {
969        assert( typeSubs );
970        ast::Type const * concrete = replaceWithConcrete( polyType, *typeSubs );
971        // Add out-parameter for return value.
972        return addRetParam( expr, concrete );
973}
974
975ast::Expr const * CallAdapter::applyAdapter(
976                ast::ApplicationExpr * expr,
977                ast::FunctionType const * function ) {
978        ast::Expr const * ret = expr;
979        if ( isDynRet( function, scopeTypeVars ) ) {
980                ret = addRetParam( expr, function->returns.front() );
981        }
982        std::string mangleName = mangleAdapterName( function, scopeTypeVars );
983        std::string adapterName = makeAdapterName( mangleName );
984
985        // Cast adaptee to `void (*)()`, since it may have any type inside a
986        // polymorphic function.
987        ast::Type const * adapteeType = new ast::PointerType(
988                new ast::FunctionType( ast::VariableArgs ) );
989        expr->args.insert( expr->args.begin(),
990                new ast::CastExpr( expr->location, expr->func, adapteeType ) );
991        // The result field is never set on NameExpr. / Now it is.
992        auto head = new ast::NameExpr( expr->location, adapterName );
993        head->result = ast::deepCopy( adapteeType );
994        expr->func = head;
995
996        return ret;
997}
998
999/// Cast parameters to polymorphic functions so that types are replaced with
1000/// `void *` if they are type parameters in the formal type.
1001/// This gets rid of warnings from gcc.
1002void addCast(
1003                ast::ptr<ast::Expr> & actual,
1004                ast::Type const * formal,
1005                TypeVarMap const & typeVars ) {
1006        // Type contains polymorphism, but isn't exactly a polytype, in which
1007        // case it has some real actual type (ex. unsigned int) and casting to
1008        // `void *` is wrong.
1009        if ( hasPolymorphism( formal, typeVars )
1010                        && !isPolyType( formal, typeVars ) ) {
1011                ast::Type const * newType = ast::deepCopy( formal );
1012                newType = scrubTypeVars( newType, typeVars );
1013                actual = new ast::CastExpr( actual->location, actual, newType );
1014        }
1015}
1016
1017void CallAdapter::boxParam( ast::ptr<ast::Expr> & arg,
1018                ast::Type const * param, TypeVarMap const & exprTypeVars ) {
1019        assertf( arg->result, "arg does not have result: %s", toCString( arg ) );
1020        addCast( arg, param, exprTypeVars );
1021        if ( !needsBoxing( param, arg->result, exprTypeVars, typeSubs ) ) {
1022                return;
1023        }
1024        CodeLocation const & location = arg->location;
1025
1026        if ( arg->get_lvalue() ) {
1027                // The argument expression may be CFA lvalue, but not C lvalue,
1028                // so apply generalizedLvalue transformations.
1029                // if ( auto var = dynamic_cast<ast::VariableExpr const *>( arg ) ) {
1030                //  if ( dynamic_cast<ast::ArrayType const *>( varExpr->var->get_type() ) ){
1031                //      // temporary hack - don't box arrays, because &arr is not the same as &arr[0]
1032                //      return;
1033                //  }
1034                // }
1035                arg = generalizedLvalue( new ast::AddressExpr( arg->location, arg ) );
1036                if ( !ResolvExpr::typesCompatible( param, arg->result ) ) {
1037                        // Silence warnings by casting boxed parameters when the actually
1038                        // type does not match up with the formal type.
1039                        arg = new ast::CastExpr( location, arg, ast::deepCopy( param ) );
1040                }
1041        } else {
1042                // Use type computed in unification to declare boxed variables.
1043                ast::ptr<ast::Type> newType = ast::deepCopy( param );
1044                if ( typeSubs ) typeSubs->apply( newType );
1045                ast::ObjectDecl * newObj = makeTemporary( location, newType );
1046                auto assign = ast::UntypedExpr::createCall( location, "?=?", {
1047                        new ast::VariableExpr( location, newObj ),
1048                        arg,
1049                } );
1050                stmtsToAddBefore.push_back( new ast::ExprStmt( location, assign ) );
1051                arg = new ast::AddressExpr(
1052                        new ast::VariableExpr( location, newObj ) );
1053        }
1054}
1055
1056void CallAdapter::boxParams(
1057                ast::ApplicationExpr const * expr,
1058                ast::vector<ast::Expr>::iterator arg,
1059                ast::FunctionType const * function,
1060                const TypeVarMap & typeVars ) {
1061        for ( auto param : function->params ) {
1062                assertf( arg != expr->args.end(),
1063                        "boxParams: missing argument for param %s to %s in %s",
1064                        toCString( param ), toCString( function ), toCString( expr ) );
1065                boxParam( *arg, param, typeVars );
1066                ++arg;
1067        }
1068}
1069
1070void CallAdapter::addInferredParams(
1071                ast::ApplicationExpr * expr,
1072                ast::vector<ast::Expr>::iterator arg,
1073                ast::FunctionType const * functionType,
1074                TypeVarMap const & typeVars ) {
1075        ast::vector<ast::Expr>::iterator cur = arg;
1076        for ( auto assertion : functionType->assertions ) {
1077                auto inferParam = expr->inferred.inferParams().find(
1078                        assertion->var->uniqueId );
1079                assertf( inferParam != expr->inferred.inferParams().end(),
1080                        "addInferredParams missing inferred parameter: %s in: %s",
1081                        toCString( assertion ), toCString( expr ) );
1082                ast::ptr<ast::Expr> newExpr = ast::deepCopy( inferParam->second.expr );
1083                boxParam( newExpr, assertion->result, typeVars );
1084                cur = expr->args.insert( cur, newExpr.release() );
1085                ++cur;
1086        }
1087}
1088
1089/// Modifies the ApplicationExpr to accept adapter functions for its
1090/// assertion and parameters, declares the required adapters.
1091void CallAdapter::passAdapters(
1092                ast::ApplicationExpr * expr,
1093                ast::FunctionType const * type,
1094                const TypeVarMap & exprTypeVars ) {
1095        // Collect a list of function types passed as parameters or implicit
1096        // parameters (assertions).
1097        ast::vector<ast::Type> const & paramList = type->params;
1098        ast::vector<ast::FunctionType> functions;
1099
1100        for ( ast::ptr<ast::VariableExpr> const & assertion : type->assertions ) {
1101                findFunction( assertion->result, functions, exprTypeVars, needsAdapter );
1102        }
1103        for ( ast::ptr<ast::Type> const & arg : paramList ) {
1104                findFunction( arg, functions, exprTypeVars, needsAdapter );
1105        }
1106
1107        // Parameter function types for which an appropriate adapter has been
1108        // generated. We cannot use the types after applying substitutions,
1109        // since two different parameter types may be unified to the same type.
1110        std::set<std::string> adaptersDone;
1111
1112        CodeLocation const & location = expr->location;
1113
1114        for ( ast::ptr<ast::FunctionType> const & funcType : functions ) {
1115                std::string mangleName = Mangle::mangle( funcType );
1116
1117                // Only attempt to create an adapter or pass one as a parameter if we
1118                // haven't already done so for this pre-substitution parameter
1119                // function type.
1120                // The second part of the result if is if the element was inserted.
1121                if ( !adaptersDone.insert( mangleName ).second ) continue;
1122
1123                // Apply substitution to type variables to figure out what the
1124                // adapter's type should look like. (Copy to make the release safe.)
1125                assert( typeSubs );
1126                auto result = typeSubs->apply( ast::deepCopy( funcType ) );
1127                ast::FunctionType * realType = ast::mutate( result.node.release() );
1128                mangleName = Mangle::mangle( realType );
1129                mangleName += makePolyMonoSuffix( funcType, exprTypeVars );
1130
1131                // Check if the adapter has already been created, or has to be.
1132                using AdapterIter = decltype(adapters)::iterator;
1133                AdapterIter adapter = adapters.find( mangleName );
1134                if ( adapter == adapters.end() ) {
1135                        ast::FunctionDecl * newAdapter = makeAdapter(
1136                                funcType, realType, mangleName, exprTypeVars, location );
1137                        std::pair<AdapterIter, bool> answer =
1138                                adapters.insert( mangleName, newAdapter );
1139                        adapter = answer.first;
1140                        stmtsToAddBefore.push_back(
1141                                new ast::DeclStmt( location, newAdapter ) );
1142                }
1143                assert( adapter != adapters.end() );
1144
1145                // Add the approprate adapter as a parameter.
1146                expr->args.insert( expr->args.begin(),
1147                        new ast::VariableExpr( location, adapter->second ) );
1148        }
1149}
1150
1151// Parameter and argument may be used wrong around here.
1152ast::Expr * makeAdapterArg(
1153                ast::DeclWithType const * param,
1154                ast::Type const * arg,
1155                ast::Type const * realParam,
1156                TypeVarMap const & typeVars,
1157                CodeLocation const & location ) {
1158        assert( param );
1159        assert( arg );
1160        assert( realParam );
1161        if ( isPolyType( realParam, typeVars ) && !isPolyType( arg ) ) {
1162                ast::UntypedExpr * deref = ast::UntypedExpr::createDeref(
1163                        location,
1164                        new ast::CastExpr( location,
1165                                new ast::VariableExpr( location, param ),
1166                                new ast::PointerType( ast::deepCopy( arg ) )
1167                        )
1168                );
1169                deref->result = ast::deepCopy( arg );
1170                return deref;
1171        }
1172        return new ast::VariableExpr( location, param );
1173}
1174
1175// This seems to be one of the problematic functions.
1176void addAdapterParams(
1177                ast::ApplicationExpr * adaptee,
1178                ast::vector<ast::Type>::const_iterator arg,
1179                ast::vector<ast::DeclWithType>::iterator param,
1180                ast::vector<ast::DeclWithType>::iterator paramEnd,
1181                ast::vector<ast::Type>::const_iterator realParam,
1182                TypeVarMap const & typeVars,
1183                CodeLocation const & location ) {
1184        UniqueName paramNamer( "_p" );
1185        for ( ; param != paramEnd ; ++param, ++arg, ++realParam ) {
1186                if ( "" == (*param)->name ) {
1187                        auto mutParam = (*param).get_and_mutate();
1188                        mutParam->name = paramNamer.newName();
1189                        mutParam->linkage = ast::Linkage::C;
1190                }
1191                adaptee->args.push_back(
1192                        makeAdapterArg( *param, *arg, *realParam, typeVars, location ) );
1193        }
1194}
1195
1196ast::FunctionDecl * CallAdapter::makeAdapter(
1197                ast::FunctionType const * adaptee,
1198                ast::FunctionType const * realType,
1199                std::string const & mangleName,
1200                TypeVarMap const & typeVars,
1201                CodeLocation const & location ) const {
1202        ast::FunctionType * adapterType = makeAdapterType( adaptee, typeVars );
1203        adapterType = ast::mutate( scrubTypeVars( adapterType, typeVars ) );
1204
1205        // Some of these names will be overwritten, but it gives a default.
1206        UniqueName pNamer( "_param" );
1207        UniqueName rNamer( "_ret" );
1208
1209        bool first = true;
1210
1211        ast::FunctionDecl * adapterDecl = new ast::FunctionDecl( location,
1212                makeAdapterName( mangleName ),
1213                {}, // forall
1214                {}, // assertions
1215                map_range<ast::vector<ast::DeclWithType>>( adapterType->params,
1216                                [&pNamer, &location, &first]( ast::ptr<ast::Type> const & param ) {
1217                        // [Trying to make the generated code match exactly more often.]
1218                        if ( first ) {
1219                                first = false;
1220                                return new ast::ObjectDecl( location, "_adaptee", param );
1221                        }
1222                        return new ast::ObjectDecl( location, pNamer.newName(), param );
1223                } ),
1224                map_range<ast::vector<ast::DeclWithType>>( adapterType->returns,
1225                                [&rNamer, &location]( ast::ptr<ast::Type> const & retval ) {
1226                        return new ast::ObjectDecl( location, rNamer.newName(), retval );
1227                } ),
1228                nullptr, // stmts
1229                {}, // storage
1230                ast::Linkage::C
1231        );
1232
1233        ast::DeclWithType * adapteeDecl =
1234                adapterDecl->params.front().get_and_mutate();
1235        adapteeDecl->name = "_adaptee";
1236
1237        // Do not carry over attributes to real type parameters/return values.
1238        auto mutRealType = ast::mutate( realType );
1239        for ( ast::ptr<ast::Type> & decl : mutRealType->params ) {
1240                if ( decl->attributes.empty() ) continue;
1241                auto mut = ast::mutate( decl.get() );
1242                mut->attributes.clear();
1243                decl = mut;
1244        }
1245        for ( ast::ptr<ast::Type> & decl : mutRealType->returns ) {
1246                if ( decl->attributes.empty() ) continue;
1247                auto mut = ast::mutate( decl.get() );
1248                mut->attributes.clear();
1249                decl = mut;
1250        }
1251        realType = mutRealType;
1252
1253        ast::ApplicationExpr * adapteeApp = new ast::ApplicationExpr( location,
1254                new ast::CastExpr( location,
1255                        new ast::VariableExpr( location, adapteeDecl ),
1256                        new ast::PointerType( realType )
1257                )
1258        );
1259
1260        for ( auto group : group_iterate( realType->assertions,
1261                        adapterType->assertions, adaptee->assertions ) ) {
1262                auto assertArg = std::get<0>( group );
1263                auto assertParam = std::get<1>( group );
1264                auto assertReal = std::get<2>( group );
1265                adapteeApp->args.push_back( makeAdapterArg(
1266                        assertParam->var, assertArg->var->get_type(),
1267                        assertReal->var->get_type(), typeVars, location
1268                ) );
1269        }
1270
1271        ast::vector<ast::Type>::const_iterator
1272                arg = realType->params.begin(),
1273                param = adapterType->params.begin(),
1274                realParam = adaptee->params.begin();
1275        ast::vector<ast::DeclWithType>::iterator
1276                paramDecl = adapterDecl->params.begin();
1277        // Skip adaptee parameter in the adapter type.
1278        ++param;
1279        ++paramDecl;
1280
1281        ast::Stmt * bodyStmt;
1282        // Returns void/nothing.
1283        if ( realType->returns.empty() ) {
1284                addAdapterParams( adapteeApp, arg, paramDecl, adapterDecl->params.end(),
1285                        realParam, typeVars, location );
1286                bodyStmt = new ast::ExprStmt( location, adapteeApp );
1287        // Returns a polymorphic type.
1288        } else if ( isDynType( adaptee->returns.front(), typeVars ) ) {
1289                ast::UntypedExpr * assign = new ast::UntypedExpr( location,
1290                        new ast::NameExpr( location, "?=?" ) );
1291                ast::UntypedExpr * deref = ast::UntypedExpr::createDeref( location,
1292                        new ast::CastExpr( location,
1293                                new ast::VariableExpr( location, *paramDecl++ ),
1294                                new ast::PointerType(
1295                                        ast::deepCopy( realType->returns.front() ) ) ) );
1296                assign->args.push_back( deref );
1297                addAdapterParams( adapteeApp, arg, paramDecl, adapterDecl->params.end(),
1298                        realParam, typeVars, location );
1299                assign->args.push_back( adapteeApp );
1300                bodyStmt = new ast::ExprStmt( location, assign );
1301        // Adapter for a function that returns a monomorphic value.
1302        } else {
1303                addAdapterParams( adapteeApp, arg, paramDecl, adapterDecl->params.end(),
1304                                realParam, typeVars, location );
1305                bodyStmt = new ast::ReturnStmt( location, adapteeApp );
1306        }
1307
1308        adapterDecl->stmts = new ast::CompoundStmt( location, { bodyStmt } );
1309        return adapterDecl;
1310}
1311
1312ast::Expr const * makeIncrDecrExpr(
1313                CodeLocation const & location,
1314                ast::ApplicationExpr const * expr,
1315                ast::Type const * polyType,
1316                bool isIncr ) {
1317        ast::NameExpr * opExpr =
1318                        new ast::NameExpr( location, isIncr ? "?+=?" : "?-=?" );
1319        ast::UntypedExpr * addAssign = new ast::UntypedExpr( location, opExpr );
1320        if ( auto address = expr->args.front().as<ast::AddressExpr>() ) {
1321                addAssign->args.push_back( address->arg );
1322        } else {
1323                addAssign->args.push_back( expr->args.front() );
1324        }
1325        addAssign->args.push_back( new ast::NameExpr( location,
1326                sizeofName( Mangle::mangleType( polyType ) ) ) );
1327        addAssign->result = ast::deepCopy( expr->result );
1328        addAssign->env = expr->env ? expr->env : addAssign->env;
1329        return addAssign;
1330}
1331
1332/// Handles intrinsic functions for postvisit ApplicationExpr.
1333ast::Expr const * CallAdapter::handleIntrinsics(
1334                ast::ApplicationExpr const * expr ) {
1335        auto varExpr = expr->func.as<ast::VariableExpr>();
1336        if ( !varExpr || varExpr->var->linkage != ast::Linkage::Intrinsic ) {
1337                return nullptr;
1338        }
1339        std::string const & varName = varExpr->var->name;
1340
1341        // Index Intrinsic:
1342        if ( "?[?]" == varName ) {
1343                assert( expr->result );
1344                assert( 2 == expr->args.size() );
1345
1346                ast::Type const * baseType1 =
1347                        isPolyPtr( expr->args.front()->result, scopeTypeVars, typeSubs );
1348                ast::Type const * baseType2 =
1349                        isPolyPtr( expr->args.back()->result, scopeTypeVars, typeSubs );
1350                // If neither argument is a polymorphic pointer, do nothing.
1351                if ( !baseType1 && !baseType2 ) {
1352                        return expr;
1353                }
1354                // The arguments cannot both be polymorphic pointers.
1355                assert( !baseType1 || !baseType2 );
1356                // (So exactly one of the arguments is a polymorphic pointer.)
1357
1358                CodeLocation const & location = expr->location;
1359                CodeLocation const & location1 = expr->args.front()->location;
1360                CodeLocation const & location2 = expr->args.back()->location;
1361
1362                ast::UntypedExpr * ret = new ast::UntypedExpr( location,
1363                                new ast::NameExpr( location, "?+?" ) );
1364                if ( baseType1 ) {
1365                        auto multiply = ast::UntypedExpr::createCall( location2, "?*?", {
1366                                expr->args.back(),
1367                                new ast::SizeofExpr( location1, deepCopy( baseType1 ) ),
1368                        } );
1369                        ret->args.push_back( expr->args.front() );
1370                        ret->args.push_back( multiply );
1371                } else {
1372                        assert( baseType2 );
1373                        auto multiply = ast::UntypedExpr::createCall( location1, "?*?", {
1374                                expr->args.front(),
1375                                new ast::SizeofExpr( location2, deepCopy( baseType2 ) ),
1376                        } );
1377                        ret->args.push_back( multiply );
1378                        ret->args.push_back( expr->args.back() );
1379                }
1380                ret->result = ast::deepCopy( expr->result );
1381                ret->env = expr->env ? expr->env : ret->env;
1382                return ret;
1383        // Dereference Intrinsic:
1384        } else if ( "*?" == varName ) {
1385                assert( expr->result );
1386                assert( 1 == expr->args.size() );
1387
1388                // If this isn't for a poly type, then do nothing.
1389                if ( !isPolyType( expr->result, scopeTypeVars, typeSubs ) ) {
1390                        return expr;
1391                }
1392
1393                // Remove dereference from polymorphic types since they are boxed.
1394                ast::Expr * ret = ast::deepCopy( expr->args.front() );
1395                // Fix expression type to remove pointer.
1396                ret->result = expr->result;
1397                ret->env = expr->env ? expr->env : ret->env;
1398                return ret;
1399        // Post-Increment/Decrement Intrinsics:
1400        } else if ( "?++" == varName || "?--" == varName ) {
1401                assert( expr->result );
1402                assert( 1 == expr->args.size() );
1403
1404                ast::Type const * baseType =
1405                        isPolyType( expr->result, scopeTypeVars, typeSubs );
1406                if ( nullptr == baseType ) {
1407                        return expr;
1408                }
1409                ast::Type * tempType = ast::deepCopy( expr->result );
1410                if ( typeSubs ) {
1411                        auto result = typeSubs->apply( tempType );
1412                        tempType = ast::mutate( result.node.release() );
1413                }
1414                CodeLocation const & location = expr->location;
1415                ast::ObjectDecl * newObj = makeTemporary( location, tempType );
1416                ast::VariableExpr * tempExpr =
1417                        new ast::VariableExpr( location, newObj );
1418                ast::UntypedExpr * assignExpr = new ast::UntypedExpr( location,
1419                        new ast::NameExpr( location, "?=?" ) );
1420                assignExpr->args.push_back( ast::deepCopy( tempExpr ) );
1421                if ( auto address = expr->args.front().as<ast::AddressExpr>() ) {
1422                        assignExpr->args.push_back( ast::deepCopy( address->arg ) );
1423                } else {
1424                        assignExpr->args.push_back( ast::deepCopy( expr->args.front() ) );
1425                }
1426                return new ast::CommaExpr( location,
1427                        new ast::CommaExpr( location,
1428                                assignExpr,
1429                                makeIncrDecrExpr( location, expr, baseType, "?++" == varName )
1430                        ),
1431                        tempExpr
1432                );
1433        // Pre-Increment/Decrement Intrinsics:
1434        } else if ( "++?" == varName || "--?" == varName ) {
1435                assert( expr->result );
1436                assert( 1 == expr->args.size() );
1437
1438                ast::Type const * baseType =
1439                        isPolyType( expr->result, scopeTypeVars, typeSubs );
1440                if ( nullptr == baseType ) {
1441                        return expr;
1442                }
1443                return makeIncrDecrExpr(
1444                        expr->location, expr, baseType, "++?" == varName );
1445        // Addition and Subtration Intrinsics:
1446        } else if ( "?+?" == varName || "?-?" == varName ) {
1447                assert( expr->result );
1448                assert( 2 == expr->args.size() );
1449
1450                auto baseType1 =
1451                        isPolyPtr( expr->args.front()->result, scopeTypeVars, typeSubs );
1452                auto baseType2 =
1453                        isPolyPtr( expr->args.back()->result, scopeTypeVars, typeSubs );
1454
1455                CodeLocation const & location = expr->location;
1456                CodeLocation const & location1 = expr->args.front()->location;
1457                CodeLocation const & location2 = expr->args.back()->location;
1458                // LHS op RHS -> (LHS op RHS) / sizeof(LHS)
1459                if ( baseType1 && baseType2 ) {
1460                        auto divide = ast::UntypedExpr::createCall( location, "?/?", {
1461                                expr,
1462                                new ast::SizeofExpr( location, deepCopy( baseType1 ) ),
1463                        } );
1464                        if ( expr->env ) divide->env = expr->env;
1465                        return divide;
1466                // LHS op RHS -> LHS op (RHS * sizeof(LHS))
1467                } else if ( baseType1 ) {
1468                        auto multiply = ast::UntypedExpr::createCall( location2, "?*?", {
1469                                expr->args.back(),
1470                                new ast::SizeofExpr( location1, deepCopy( baseType1 ) ),
1471                        } );
1472                        return ast::mutate_field_index(
1473                                expr, &ast::ApplicationExpr::args, 1, multiply );
1474                // LHS op RHS -> (LHS * sizeof(RHS)) op RHS
1475                } else if ( baseType2 ) {
1476                        auto multiply = ast::UntypedExpr::createCall( location1, "?*?", {
1477                                expr->args.front(),
1478                                new ast::SizeofExpr( location2, deepCopy( baseType2 ) ),
1479                        } );
1480                        return ast::mutate_field_index(
1481                                expr, &ast::ApplicationExpr::args, 0, multiply );
1482                }
1483        // Addition and Subtration Relative Assignment Intrinsics:
1484        } else if ( "?+=?" == varName || "?-=?" == varName ) {
1485                assert( expr->result );
1486                assert( 2 == expr->args.size() );
1487
1488                CodeLocation const & location1 = expr->args.front()->location;
1489                CodeLocation const & location2 = expr->args.back()->location;
1490                auto baseType = isPolyPtr( expr->result, scopeTypeVars, typeSubs );
1491                // LHS op RHS -> LHS op (RHS * sizeof(LHS))
1492                if ( baseType ) {
1493                        auto multiply = ast::UntypedExpr::createCall( location2, "?*?", {
1494                                expr->args.back(),
1495                                new ast::SizeofExpr( location1, deepCopy( baseType ) ),
1496                        } );
1497                        return ast::mutate_field_index(
1498                                expr, &ast::ApplicationExpr::args, 1, multiply );
1499                }
1500        }
1501        return expr;
1502}
1503
1504ast::ObjectDecl * CallAdapter::makeTemporary(
1505                CodeLocation const & location, ast::Type const * type ) {
1506        auto newObj = new ast::ObjectDecl( location, tmpNamer.newName(), type );
1507        stmtsToAddBefore.push_back( new ast::DeclStmt( location, newObj ) );
1508        return newObj;
1509}
1510
1511// --------------------------------------------------------------------------
1512/// Modifies declarations to accept implicit parameters.
1513/// * Move polymorphic returns in function types to pointer-type parameters.
1514/// * Adds type size and assertion parameters to parameter lists.
1515struct DeclAdapter final {
1516        ast::FunctionDecl const * previsit( ast::FunctionDecl const * decl );
1517        ast::FunctionDecl const * postvisit( ast::FunctionDecl const * decl );
1518private:
1519        void addAdapters( ast::FunctionDecl * decl, TypeVarMap & localTypeVars );
1520};
1521
1522// size/align/offset parameters may not be used, so add the unused attribute.
1523ast::ObjectDecl * makeObj(
1524                CodeLocation const & location, std::string const & name ) {
1525        return new ast::ObjectDecl( location, name,
1526                makeSizeAlignType(),
1527                nullptr, ast::Storage::Classes(), ast::Linkage::C, nullptr,
1528                { new ast::Attribute( "unused" ) } );
1529}
1530
1531ast::ObjectDecl * makePtr(
1532                CodeLocation const & location, std::string const & name ) {
1533        return new ast::ObjectDecl( location, name,
1534                new ast::PointerType( makeSizeAlignType() ),
1535                nullptr, ast::Storage::Classes(), ast::Linkage::C, nullptr );
1536}
1537
1538ast::FunctionDecl const * DeclAdapter::previsit( ast::FunctionDecl const * decl ) {
1539        TypeVarMap localTypeVars = { ast::TypeData() };
1540        makeTypeVarMap( decl, localTypeVars );
1541
1542        auto mutDecl = mutate( decl );
1543
1544        // Move polymorphic return type to parameter list.
1545        if ( isDynRet( mutDecl->type ) ) {
1546                auto ret = strict_dynamic_cast<ast::ObjectDecl *>(
1547                        mutDecl->returns.front().get_and_mutate() );
1548                ret->set_type( new ast::PointerType( ret->type ) );
1549                mutDecl->params.insert( mutDecl->params.begin(), ret );
1550                mutDecl->returns.erase( mutDecl->returns.begin() );
1551                ret->init = nullptr;
1552        }
1553
1554        // Add size/align and assertions for type parameters to parameter list.
1555        ast::vector<ast::DeclWithType> inferredParams;
1556        ast::vector<ast::DeclWithType> layoutParams;
1557        for ( ast::ptr<ast::TypeDecl> & typeParam : mutDecl->type_params ) {
1558                auto mutParam = mutate( typeParam.get() );
1559                // Add all size and alignment parameters to parameter list.
1560                if ( mutParam->isComplete() ) {
1561                        ast::TypeInstType paramType( mutParam );
1562                        std::string paramName = Mangle::mangleType( &paramType );
1563
1564                        auto sizeParam = makeObj( typeParam->location, sizeofName( paramName ) );
1565                        layoutParams.emplace_back( sizeParam );
1566
1567                        auto alignParam = makeObj( typeParam->location, alignofName( paramName ) );
1568                        layoutParams.emplace_back( alignParam );
1569                }
1570                // TODO: These should possibly all be gone.
1571                // More all assertions into parameter list.
1572                for ( ast::ptr<ast::DeclWithType> & assert : mutParam->assertions ) {
1573                        // Assertion parameters may not be used in body,
1574                        // pass along with unused attribute.
1575                        assert.get_and_mutate()->attributes.push_back(
1576                                new ast::Attribute( "unused" ) );
1577                        inferredParams.push_back( assert );
1578                }
1579                mutParam->assertions.clear();
1580                typeParam = mutParam;
1581        }
1582        // TODO: New version of inner loop.
1583        for ( ast::ptr<ast::DeclWithType> & assert : mutDecl->assertions ) {
1584                // Assertion parameters may not be used in body,
1585                // pass along with unused attribute.
1586                assert.get_and_mutate()->attributes.push_back(
1587                        new ast::Attribute( "unused" ) );
1588                inferredParams.push_back( assert );
1589        }
1590        mutDecl->assertions.clear();
1591
1592        // Add size/align for generic parameter types to parameter list.
1593        std::set<std::string> seenTypes;
1594        ast::vector<ast::DeclWithType> otypeParams;
1595        for ( ast::ptr<ast::DeclWithType> & funcParam : mutDecl->params ) {
1596                ast::Type const * polyType = isPolyType( funcParam->get_type(), localTypeVars );
1597                if ( !polyType || dynamic_cast<ast::TypeInstType const *>( polyType ) ) {
1598                        continue;
1599                }
1600                std::string typeName = Mangle::mangleType( polyType );
1601                if ( seenTypes.count( typeName ) ) continue;
1602                seenTypes.insert( typeName );
1603
1604                auto sizeParam = makeObj( funcParam->location, sizeofName( typeName ) );
1605                otypeParams.emplace_back( sizeParam );
1606
1607                auto alignParam = makeObj( funcParam->location, alignofName( typeName ) );
1608                otypeParams.emplace_back( alignParam );
1609
1610                // Zero-length arrays are illegal in C, so empty structs have no
1611                // offset array.
1612                if ( auto * polyStruct =
1613                                dynamic_cast<ast::StructInstType const *>( polyType ) ;
1614                                polyStruct && !polyStruct->base->members.empty() ) {
1615                        auto offsetParam = makePtr( funcParam->location, offsetofName( typeName ) );
1616                        otypeParams.emplace_back( offsetParam );
1617                }
1618        }
1619
1620        // Prepend each argument group. From last group to first. addAdapters
1621        // does do the same, it just does it itself and see all other parameters.
1622        spliceBegin( mutDecl->params, inferredParams );
1623        spliceBegin( mutDecl->params, otypeParams );
1624        spliceBegin( mutDecl->params, layoutParams );
1625        addAdapters( mutDecl, localTypeVars );
1626
1627        return mutDecl;
1628}
1629
1630ast::FunctionDecl const * DeclAdapter::postvisit(
1631                ast::FunctionDecl const * decl ) {
1632        ast::FunctionDecl * mutDecl = mutate( decl );
1633        if ( !mutDecl->returns.empty() && mutDecl->stmts
1634                        // Intrinsic functions won't be using the _retval so no need to
1635                        // generate it.
1636                        && mutDecl->linkage != ast::Linkage::Intrinsic
1637                        // Remove check for prefix once thunks properly use ctor/dtors.
1638                        && !isPrefix( mutDecl->name, "_thunk" )
1639                        && !isPrefix( mutDecl->name, "_adapter" ) ) {
1640                assert( 1 == mutDecl->returns.size() );
1641                ast::DeclWithType const * retval = mutDecl->returns.front();
1642                if ( "" == retval->name ) {
1643                        retval = ast::mutate_field(
1644                                retval, &ast::DeclWithType::name, "_retval" );
1645                        mutDecl->returns.front() = retval;
1646                }
1647                auto stmts = mutDecl->stmts.get_and_mutate();
1648                stmts->kids.push_front( new ast::DeclStmt( retval->location, retval ) );
1649                ast::DeclWithType * newRet = ast::deepCopy( retval );
1650                mutDecl->returns.front() = newRet;
1651        }
1652        // Errors should have been caught by this point, remove initializers from
1653        // parameters to allow correct codegen of default arguments.
1654        for ( ast::ptr<ast::DeclWithType> & param : mutDecl->params ) {
1655                if ( auto obj = param.as<ast::ObjectDecl>() ) {
1656                        param = ast::mutate_field( obj, &ast::ObjectDecl::init, nullptr );
1657                }
1658        }
1659        // TODO: Can this be updated as we go along?
1660        mutDecl->type = makeFunctionType( mutDecl );
1661        return mutDecl;
1662}
1663
1664void DeclAdapter::addAdapters(
1665                ast::FunctionDecl * mutDecl, TypeVarMap & localTypeVars ) {
1666        ast::vector<ast::FunctionType> functions;
1667        for ( ast::ptr<ast::DeclWithType> & arg : mutDecl->params ) {
1668                ast::Type const * type = arg->get_type();
1669                type = findAndReplaceFunction( type, functions, localTypeVars, needsAdapter );
1670                arg.get_and_mutate()->set_type( type );
1671        }
1672        std::set<std::string> adaptersDone;
1673        for ( ast::ptr<ast::FunctionType> const & func : functions ) {
1674                std::string mangleName = mangleAdapterName( func, localTypeVars );
1675                if ( adaptersDone.find( mangleName ) != adaptersDone.end() ) {
1676                        continue;
1677                }
1678                std::string adapterName = makeAdapterName( mangleName );
1679                // The adapter may not actually be used, so make sure it has unused.
1680                mutDecl->params.insert( mutDecl->params.begin(), new ast::ObjectDecl(
1681                        mutDecl->location, adapterName,
1682                        new ast::PointerType( makeAdapterType( func, localTypeVars ) ),
1683                        nullptr, {}, {}, nullptr,
1684                        { new ast::Attribute( "unused" ) } ) );
1685                adaptersDone.insert( adaptersDone.begin(), mangleName );
1686        }
1687}
1688
1689// --------------------------------------------------------------------------
1690// TODO: Ideally, there would be no floating nodes at all.
1691/// Corrects the floating nodes created in CallAdapter.
1692struct RewireAdapters final : public ast::WithGuards {
1693        ScopedMap<std::string, ast::ObjectDecl const *> adapters;
1694        void beginScope() { adapters.beginScope(); }
1695        void endScope() { adapters.endScope(); }
1696        void previsit( ast::FunctionDecl const * decl );
1697        ast::VariableExpr const * previsit( ast::VariableExpr const * expr );
1698};
1699
1700void RewireAdapters::previsit( ast::FunctionDecl const * decl ) {
1701        GuardScope( adapters );
1702        for ( ast::ptr<ast::DeclWithType> const & param : decl->params ) {
1703                if ( auto objectParam = param.as<ast::ObjectDecl>() ) {
1704                        adapters.insert( objectParam->name, objectParam );
1705                }
1706        }
1707}
1708
1709ast::VariableExpr const * RewireAdapters::previsit(
1710                ast::VariableExpr const * expr ) {
1711        // If the node is not floating, we can skip.
1712        if ( expr->var->isManaged() ) return expr;
1713        auto it = adapters.find( expr->var->name );
1714        assertf( it != adapters.end(), "Could not correct floating node." );
1715        return ast::mutate_field( expr, &ast::VariableExpr::var, it->second );
1716
1717}
1718
1719// --------------------------------------------------------------------------
1720/// Inserts code to access polymorphic layout inforation.
1721/// * Replaces member and size/alignment/offsetof expressions on polymorphic
1722///   generic types with calculated expressions.
1723/// * Replaces member expressions for polymorphic types with calculated
1724///   add-field-offset-and-dereference.
1725/// * Calculates polymorphic offsetof expressions from offset array.
1726/// * Inserts dynamic calculation of polymorphic type layouts where needed.
1727struct PolyGenericCalculator final :
1728                public BoxPass,
1729                public ast::WithConstTypeSubstitution,
1730                public ast::WithDeclsToAdd<>,
1731                public ast::WithGuards,
1732                public ast::WithStmtsToAdd<>,
1733                public ast::WithVisitorRef<PolyGenericCalculator> {
1734        PolyGenericCalculator();
1735
1736        void previsit( ast::ObjectDecl const * decl );
1737        void previsit( ast::FunctionDecl const * decl );
1738        void previsit( ast::TypedefDecl const * decl );
1739        void previsit( ast::TypeDecl const * decl );
1740        ast::Decl const * postvisit( ast::TypeDecl const * decl );
1741        ast::StructDecl const * previsit( ast::StructDecl const * decl );
1742        ast::UnionDecl const * previsit( ast::UnionDecl const * decl );
1743        void previsit( ast::PointerType const * type );
1744        void previsit( ast::FunctionType const * type );
1745        ast::DeclStmt const * previsit( ast::DeclStmt const * stmt );
1746        ast::Expr const * postvisit( ast::MemberExpr const * expr );
1747        void previsit( ast::AddressExpr const * expr );
1748        ast::Expr const * postvisit( ast::AddressExpr const * expr );
1749        ast::Expr const * postvisit( ast::SizeofExpr const * expr );
1750        ast::Expr const * postvisit( ast::AlignofExpr const * expr );
1751        ast::Expr const * postvisit( ast::OffsetofExpr const * expr );
1752        ast::Expr const * postvisit( ast::OffsetPackExpr const * expr );
1753
1754        void beginScope();
1755        void endScope();
1756private:
1757        /// Makes a new variable in the current scope with the given name,
1758        /// type and optional initializer.
1759        ast::ObjectDecl * makeVar(
1760                        CodeLocation const & location, std::string const & name,
1761                        ast::Type const * type, ast::Init const * init = nullptr );
1762        /// Returns true if the type has a dynamic layout;
1763        /// such a layout will be stored in appropriately-named local variables
1764        /// when the function returns.
1765        bool findGeneric( CodeLocation const & location, ast::Type const * );
1766        /// Adds type parameters to the layout call; will generate the
1767        /// appropriate parameters if needed.
1768        void addSTypeParamsToLayoutCall(
1769                ast::UntypedExpr * layoutCall,
1770                const ast::vector<ast::Type> & otypeParams );
1771        /// Change the type of generic aggregate members to char[].
1772        void mutateMembers( ast::AggregateDecl * aggr );
1773        /// Returns the calculated sizeof expression for type, or nullptr for use
1774        /// C sizeof().
1775        ast::Expr const * genSizeof( CodeLocation const &, ast::Type const * );
1776
1777        /// Enters a new scope for type-variables,
1778        /// adding the type variables from the provided type.
1779        void beginTypeScope( ast::Type const * );
1780        /// Enters a new scope for known layouts and offsets, and queues exit calls.
1781        void beginGenericScope();
1782
1783        /// Set of generic type layouts known in the current scope,
1784        /// indexed by sizeofName.
1785        ScopedSet<std::string> knownLayouts;
1786        /// Set of non-generic types for which the offset array exists in the
1787        /// current scope, indexed by offsetofName.
1788        ScopedSet<std::string> knownOffsets;
1789        /// Namer for VLA (variable length array) buffers.
1790        UniqueName bufNamer;
1791        /// If the argument of an AddressExpr is MemberExpr, it is stored here.
1792        ast::MemberExpr const * addrMember = nullptr;
1793        /// Used to avoid recursing too deep in type declarations.
1794        bool expect_func_type = false;
1795};
1796
1797PolyGenericCalculator::PolyGenericCalculator() :
1798        knownLayouts(), knownOffsets(), bufNamer( "_buf" )
1799{}
1800
1801/// Converts polymorphic type into a suitable monomorphic representation.
1802/// Currently: __attribute__((aligned(8) )) char[size_T];
1803ast::Type * polyToMonoType( CodeLocation const & location,
1804                ast::Type const * declType ) {
1805        auto charType = new ast::BasicType( ast::BasicType::Char );
1806        auto size = new ast::NameExpr( location,
1807                sizeofName( Mangle::mangleType( declType ) ) );
1808        auto aligned = new ast::Attribute( "aligned",
1809                { ast::ConstantExpr::from_int( location, 8 ) } );
1810        auto ret = new ast::ArrayType( charType, size,
1811                ast::VariableLen, ast::DynamicDim, ast::CV::Qualifiers() );
1812        ret->attributes.push_back( aligned );
1813        return ret;
1814}
1815
1816void PolyGenericCalculator::previsit( ast::ObjectDecl const * decl ) {
1817        beginTypeScope( decl->type );
1818}
1819
1820void PolyGenericCalculator::previsit( ast::FunctionDecl const * decl ) {
1821        beginGenericScope();
1822        beginTypeScope( decl->type );
1823
1824        // TODO: Going though dec->params does not work for some reason.
1825        for ( ast::ptr<ast::Type> const & funcParam : decl->type->params ) {
1826                // Condition here duplicates that in `DeclAdapter::previsit( FunctionDecl const * )`
1827                ast::Type const * polyType = isPolyType( funcParam, scopeTypeVars );
1828                if ( polyType && !dynamic_cast<ast::TypeInstType const *>( polyType ) ) {
1829                        knownLayouts.insert( Mangle::mangleType( polyType ) );
1830                }
1831        }
1832}
1833
1834void PolyGenericCalculator::previsit( ast::TypedefDecl const * decl ) {
1835        assertf( false, "All typedef declarations should be removed." );
1836        beginTypeScope( decl->base );
1837}
1838
1839void PolyGenericCalculator::previsit( ast::TypeDecl const * decl ) {
1840        addToTypeVarMap( decl, scopeTypeVars );
1841}
1842
1843ast::Decl const * PolyGenericCalculator::postvisit(
1844                ast::TypeDecl const * decl ) {
1845        ast::Type const * base = decl->base;
1846        if ( nullptr == base) return decl;
1847
1848        // Add size/align variables for opaque type declarations.
1849        ast::TypeInstType inst( decl->name, decl );
1850        std::string typeName = Mangle::mangleType( &inst );
1851        ast::Type * layoutType = new ast::BasicType(
1852                ast::BasicType::LongUnsignedInt );
1853
1854        ast::ObjectDecl * sizeDecl = new ast::ObjectDecl( decl->location,
1855                sizeofName( typeName ), layoutType,
1856                new ast::SingleInit( decl->location,
1857                        new ast::SizeofExpr( decl->location, deepCopy( base ) )
1858                )
1859        );
1860        ast::ObjectDecl * alignDecl = new ast::ObjectDecl( decl->location,
1861                alignofName( typeName ), layoutType,
1862                new ast::SingleInit( decl->location,
1863                        new ast::AlignofExpr( decl->location, deepCopy( base ) )
1864                )
1865        );
1866
1867        // Ensure that the initializing sizeof/alignof exprs are properly mutated.
1868        sizeDecl->accept( *visitor );
1869        alignDecl->accept( *visitor );
1870
1871        // Can't use [makeVar], because it inserts into stmtsToAdd and TypeDecls
1872        // can occur at global scope.
1873        declsToAddAfter.push_back( alignDecl );
1874        // replace with sizeDecl.
1875        return sizeDecl;
1876}
1877
1878ast::StructDecl const * PolyGenericCalculator::previsit(
1879                ast::StructDecl const * decl ) {
1880        auto mutDecl = mutate( decl );
1881        mutateMembers( mutDecl );
1882        return mutDecl;
1883}
1884
1885ast::UnionDecl const * PolyGenericCalculator::previsit(
1886                ast::UnionDecl const * decl ) {
1887        auto mutDecl = mutate( decl );
1888        mutateMembers( mutDecl );
1889        return mutDecl;
1890}
1891
1892void PolyGenericCalculator::previsit( ast::PointerType const * type ) {
1893        beginTypeScope( type );
1894}
1895
1896void PolyGenericCalculator::previsit( ast::FunctionType const * type ) {
1897        beginTypeScope( type );
1898
1899        GuardValue( expect_func_type );
1900        GuardScope( *this );
1901
1902        // The other functions type we will see in this scope are probably
1903        // function parameters they don't help us with the layout and offsets so
1904        // don't mark them as known in this scope.
1905        expect_func_type = false;
1906
1907        // Make sure that any type information passed into the function is
1908        // accounted for.
1909        for ( ast::ptr<ast::Type> const & funcParam : type->params ) {
1910                // Condition here duplicates that in `DeclAdapter::previsit( FunctionDecl const * )`
1911                ast::Type const * polyType = isPolyType( funcParam, scopeTypeVars );
1912                if ( polyType && !dynamic_cast<ast::TypeInstType const *>( polyType ) ) {
1913                        knownLayouts.insert( Mangle::mangleType( polyType ) );
1914                }
1915        }
1916}
1917
1918//void PolyGenericCalculator::previsit( ast::DeclStmt const * stmt ) {
1919ast::DeclStmt const * PolyGenericCalculator::previsit( ast::DeclStmt const * stmt ) {
1920        ast::ObjectDecl const * decl = stmt->decl.as<ast::ObjectDecl>();
1921        if ( !decl || !findGeneric( decl->location, decl->type ) ) {
1922                return stmt;
1923        }
1924
1925        // Change initialization of a polymorphic value object to allocate via a
1926        // variable-length-array (alloca was previouly used, but it cannot be
1927        // safely used in loops).
1928        ast::ObjectDecl * newBuf = new ast::ObjectDecl( decl->location,
1929                bufNamer.newName(),
1930                polyToMonoType( decl->location, decl->type ),
1931                nullptr, {}, ast::Linkage::C
1932        );
1933        stmtsToAddBefore.push_back( new ast::DeclStmt( stmt->location, newBuf ) );
1934
1935        // If the object has a cleanup attribute, the clean-up should be on the
1936        // buffer, not the pointer. [Perhaps this should be lifted?]
1937        auto matchAndMove = [newBuf]( ast::ptr<ast::Attribute> & attr ) {
1938                if ( "cleanup" == attr->name ) {
1939                        newBuf->attributes.push_back( attr );
1940                        return true;
1941                }
1942                return false;
1943        };
1944
1945        auto mutDecl = mutate( decl );
1946
1947        // Forally, side effects are not safe in this function. But it works.
1948        erase_if( mutDecl->attributes, matchAndMove );
1949
1950        mutDecl->init = new ast::SingleInit( decl->location,
1951                new ast::VariableExpr( decl->location, newBuf ) );
1952
1953        return ast::mutate_field( stmt, &ast::DeclStmt::decl, mutDecl );
1954}
1955
1956/// Checks if memberDecl matches the decl from an aggregate.
1957bool isMember( ast::DeclWithType const * memberDecl, ast::Decl const * decl ) {
1958        // No matter the field, if the name is different it is not the same.
1959        if ( memberDecl->name != decl->name ) {
1960                return false;
1961        }
1962
1963        if ( memberDecl->name.empty() ) {
1964                // Plan-9 Field: Match on unique_id.
1965                return ( memberDecl->uniqueId == decl->uniqueId );
1966        }
1967
1968        ast::DeclWithType const * declWithType =
1969                strict_dynamic_cast<ast::DeclWithType const *>( decl );
1970
1971        if ( memberDecl->mangleName.empty() || declWithType->mangleName.empty() ) {
1972                // Tuple-Element Field: Expect neither had mangled name;
1973                // accept match on simple name (like field_2) only.
1974                assert( memberDecl->mangleName.empty() );
1975                assert( declWithType->mangleName.empty() );
1976                return true;
1977        }
1978
1979        // Ordinary Field: Use full name to accommodate overloading.
1980        return ( memberDecl->mangleName == declWithType->mangleName );
1981}
1982
1983/// Finds the member in the base list that matches the given declaration;
1984/// returns its index, or -1 if not present.
1985long findMember( ast::DeclWithType const * memberDecl,
1986                const ast::vector<ast::Decl> & baseDecls ) {
1987        for ( auto pair : enumerate( baseDecls ) ) {
1988                if ( isMember( memberDecl, pair.val.get() ) ) {
1989                        return pair.idx;
1990                }
1991        }
1992        return -1;
1993}
1994
1995/// Returns an index expression into the offset array for a type.
1996ast::Expr * makeOffsetIndex( CodeLocation const & location,
1997                ast::Type const * objectType, long i ) {
1998        std::string name = offsetofName( Mangle::mangleType( objectType ) );
1999        return ast::UntypedExpr::createCall( location, "?[?]", {
2000                new ast::NameExpr( location, name ),
2001                ast::ConstantExpr::from_ulong( location, i ),
2002        } );
2003}
2004
2005ast::Expr const * PolyGenericCalculator::postvisit(
2006                ast::MemberExpr const * expr ) {
2007        // Only mutate member expressions for polymorphic types.
2008        ast::Type const * objectType = hasPolyBase(
2009                expr->aggregate->result, scopeTypeVars
2010        );
2011        if ( !objectType ) return expr;
2012        // Ensure layout for this type is available.
2013        // The boolean result is ignored.
2014        findGeneric( expr->location, objectType );
2015
2016        // Replace member expression with dynamically-computed layout expression.
2017        ast::Expr * newMemberExpr = nullptr;
2018        if ( auto structType = dynamic_cast<ast::StructInstType const *>( objectType ) ) {
2019                long offsetIndex = findMember( expr->member, structType->base->members );
2020                if ( -1 == offsetIndex ) return expr;
2021
2022                // Replace member expression with pointer to struct plus offset.
2023                ast::UntypedExpr * fieldLoc = new ast::UntypedExpr( expr->location,
2024                                new ast::NameExpr( expr->location, "?+?" ) );
2025                ast::Expr * aggr = deepCopy( expr->aggregate );
2026                aggr->env = nullptr;
2027                fieldLoc->args.push_back( aggr );
2028                fieldLoc->args.push_back(
2029                        makeOffsetIndex( expr->location, objectType, offsetIndex ) );
2030                fieldLoc->result = deepCopy( expr->result );
2031                newMemberExpr = fieldLoc;
2032        // Union members are all at offset zero, so just use the aggregate expr.
2033        } else if ( dynamic_cast<ast::UnionInstType const *>( objectType ) ) {
2034                ast::Expr * aggr = deepCopy( expr->aggregate );
2035                aggr->env = nullptr;
2036                aggr->result = deepCopy( expr->result );
2037                newMemberExpr = aggr;
2038        } else {
2039                return expr;
2040        }
2041        assert( newMemberExpr );
2042
2043        // Must apply the generic substitution to the member type to handle cases
2044        // where the member is a generic parameter subsituted by a known concrete
2045        // type. [ex]
2046        //      forall( T ) struct Box { T x; }
2047        //      forall( T ) void f() {
2048        //              Box( T * ) b; b.x;
2049        //      }
2050        // TODO: expr->result should be exactly expr->member->get_type() after
2051        // substitution, so it doesn't seem like it should be necessary to apply
2052        // the substitution manually. For some reason this is not currently the
2053        // case. This requires more investigation.
2054        ast::ptr<ast::Type> memberType = deepCopy( expr->member->get_type() );
2055        ast::TypeSubstitution sub = genericSubstitution( objectType );
2056        sub.apply( memberType );
2057
2058        // Not all members of a polymorphic type are themselves of a polymorphic
2059        // type; in this cas the member expression should be wrapped and
2060        // dereferenced to form an lvalue.
2061        if ( !isPolyType( memberType, scopeTypeVars ) ) {
2062                auto ptrCastExpr = new ast::CastExpr( expr->location, newMemberExpr,
2063                        new ast::PointerType( memberType ) );
2064                auto derefExpr = ast::UntypedExpr::createDeref( expr->location,
2065                        ptrCastExpr );
2066                newMemberExpr = derefExpr;
2067        }
2068
2069        return newMemberExpr;
2070}
2071
2072void PolyGenericCalculator::previsit( ast::AddressExpr const * expr ) {
2073        GuardValue( addrMember ) = expr->arg.as<ast::MemberExpr>();
2074}
2075
2076ast::Expr const * PolyGenericCalculator::postvisit(
2077                ast::AddressExpr const * expr ) {
2078        // arg has to have been a MemberExpr and has been mutated.
2079        if ( nullptr == addrMember || expr->arg == addrMember ) {
2080                return expr;
2081        }
2082        ast::UntypedExpr const * untyped = expr->arg.as<ast::UntypedExpr>();
2083        if ( !untyped || getFunctionName( untyped ) != "?+?" ) {
2084                return expr;
2085        }
2086        // MemberExpr was converted to pointer + offset; and it is not valid C to
2087        // take the address of an addition, so strip away the address-of.
2088        // It also preserves the env value.
2089        return ast::mutate_field( expr->arg.get(), &ast::Expr::env, expr->env );
2090}
2091
2092ast::Expr const * PolyGenericCalculator::postvisit(
2093                ast::SizeofExpr const * expr ) {
2094        ast::Type const * type = expr->type ? expr->type : expr->expr->result;
2095        ast::Expr const * gen = genSizeof( expr->location, type );
2096        return ( gen ) ? gen : expr;
2097}
2098
2099ast::Expr const * PolyGenericCalculator::postvisit(
2100                ast::AlignofExpr const * expr ) {
2101        ast::Type const * type = expr->type ? expr->type : expr->expr->result;
2102        if ( findGeneric( expr->location, type ) ) {
2103                return new ast::NameExpr( expr->location,
2104                        alignofName( Mangle::mangleType( type ) ) );
2105        } else {
2106                return expr;
2107        }
2108}
2109
2110ast::Expr const * PolyGenericCalculator::postvisit(
2111                ast::OffsetofExpr const * expr ) {
2112        ast::Type const * type = expr->type;
2113        if ( !findGeneric( expr->location, type ) ) return expr;
2114
2115        // Structures replace offsetof expression with an index into offset array.
2116        if ( auto structType = dynamic_cast<ast::StructInstType const *>( type ) ) {
2117                long offsetIndex = findMember( expr->member, structType->base->members );
2118                if ( -1 == offsetIndex ) return expr;
2119
2120                return makeOffsetIndex( expr->location, type, offsetIndex );
2121        // All union members are at offset zero.
2122        } else if ( dynamic_cast<ast::UnionInstType const *>( type ) ) {
2123                return ast::ConstantExpr::from_ulong( expr->location, 0 );
2124        } else {
2125                return expr;
2126        }
2127}
2128
2129ast::Expr const * PolyGenericCalculator::postvisit(
2130                ast::OffsetPackExpr const * expr ) {
2131        ast::StructInstType const * type = expr->type;
2132
2133        // Pull offset back from generated type information.
2134        if ( findGeneric( expr->location, type ) ) {
2135                return new ast::NameExpr( expr->location,
2136                        offsetofName( Mangle::mangleType( type ) ) );
2137        }
2138
2139        std::string offsetName = offsetofName( Mangle::mangleType( type ) );
2140        // Use the already generated offsets for this type.
2141        if ( knownOffsets.contains( offsetName ) ) {
2142                return new ast::NameExpr( expr->location, offsetName );
2143        }
2144
2145        knownOffsets.insert( offsetName );
2146
2147        auto baseMembers = type->base->members;
2148        ast::Type const * offsetType = new ast::BasicType(
2149                ast::BasicType::LongUnsignedInt );
2150
2151        // Build initializer list for offset array.
2152        ast::vector<ast::Init> inits;
2153        for ( ast::ptr<ast::Decl> & member : baseMembers ) {
2154                auto memberDecl = member.as<ast::DeclWithType>();
2155                assertf( memberDecl, "Requesting offset of non-DWT member: %s",
2156                        toCString( member ) );
2157                inits.push_back( new ast::SingleInit( expr->location,
2158                        new ast::OffsetofExpr( expr->location,
2159                                deepCopy( type ),
2160                                memberDecl
2161                        )
2162                ) );
2163        }
2164
2165        auto offsetArray = makeVar( expr->location, offsetName,
2166                new ast::ArrayType(
2167                        offsetType,
2168                        ast::ConstantExpr::from_ulong( expr->location, baseMembers.size() ),
2169                        ast::FixedLen,
2170                        ast::DynamicDim
2171                ),
2172                new ast::ListInit( expr->location, std::move( inits ) )
2173        );
2174
2175        return new ast::VariableExpr( expr->location, offsetArray );
2176}
2177
2178void PolyGenericCalculator::beginScope() {
2179        knownLayouts.beginScope();
2180        knownOffsets.beginScope();
2181}
2182
2183void PolyGenericCalculator::endScope() {
2184        knownOffsets.endScope();
2185        knownLayouts.endScope();
2186}
2187
2188ast::ObjectDecl * PolyGenericCalculator::makeVar(
2189                CodeLocation const & location, std::string const & name,
2190                ast::Type const * type, ast::Init const * init ) {
2191        ast::ObjectDecl * ret = new ast::ObjectDecl( location, name, type, init );
2192        stmtsToAddBefore.push_back( new ast::DeclStmt( location, ret ) );
2193        return ret;
2194}
2195
2196/// Returns true if any of the otype parameters have a dynamic layout; and
2197/// puts all otype parameters in the output list.
2198bool findGenericParams(
2199                ast::vector<ast::Type> & out,
2200                ast::vector<ast::TypeDecl> const & baseParams,
2201                ast::vector<ast::Expr> const & typeParams ) {
2202        bool hasDynamicLayout = false;
2203
2204        for ( auto pair : group_iterate( baseParams, typeParams ) ) {
2205                auto baseParam = std::get<0>( pair );
2206                auto typeParam = std::get<1>( pair );
2207                if ( !baseParam->isComplete() ) continue;
2208                ast::TypeExpr const * typeExpr = typeParam.as<ast::TypeExpr>();
2209                assertf( typeExpr, "All type parameters should be type expressions." );
2210
2211                ast::Type const * type = typeExpr->type.get();
2212                out.push_back( type );
2213                if ( isPolyType( type ) ) hasDynamicLayout = true;
2214        }
2215
2216        return hasDynamicLayout;
2217}
2218
2219bool PolyGenericCalculator::findGeneric(
2220                CodeLocation const & location, ast::Type const * type ) {
2221        type = replaceTypeInst( type, typeSubs );
2222
2223        if ( auto inst = dynamic_cast<ast::TypeInstType const *>( type ) ) {
2224                // Assumes that getting put in the scopeTypeVars includes having the
2225                // layout variables set.
2226                if ( scopeTypeVars.contains( *inst ) ) {
2227                        return true;
2228                }
2229        } else if ( auto inst = dynamic_cast<ast::StructInstType const *>( type ) ) {
2230                // Check if this type already has a layout generated for it.
2231                std::string typeName = Mangle::mangleType( type );
2232                if ( knownLayouts.contains( typeName ) ) return true;
2233
2234                // Check if any type parameters have dynamic layout;
2235                // If none do, this type is (or will be) monomorphized.
2236                ast::vector<ast::Type> sizedParams;
2237                if ( !findGenericParams( sizedParams,
2238                                inst->base->params, inst->params ) ) {
2239                        return false;
2240                }
2241
2242                // Insert local variables for layout and generate call to layout
2243                // function.
2244                // Done early so as not to interfere with the later addition of
2245                // parameters to the layout call.
2246                knownLayouts.insert( typeName );
2247                ast::Type const * layoutType = makeSizeAlignType();
2248
2249                int memberCount = inst->base->members.size();
2250                if ( 0 == memberCount ) {
2251                        // All empty structures have the same layout (size 1, align 1).
2252                        makeVar( location,
2253                                sizeofName( typeName ), layoutType,
2254                                new ast::SingleInit( location,
2255                                                ast::ConstantExpr::from_ulong( location, 1 ) ) );
2256                        makeVar( location,
2257                                alignofName( typeName ), ast::deepCopy( layoutType ),
2258                                new ast::SingleInit( location,
2259                                                ast::ConstantExpr::from_ulong( location, 1 ) ) );
2260                        // Since 0-length arrays are forbidden in C, skip the offset array.
2261                } else {
2262                        ast::ObjectDecl const * sizeofVar = makeVar( location,
2263                                sizeofName( typeName ), deepCopy( layoutType ), nullptr );
2264                        ast::ObjectDecl const * alignofVar = makeVar( location,
2265                                alignofName( typeName ), deepCopy( layoutType ), nullptr );
2266                        ast::ObjectDecl const * offsetofVar = makeVar( location,
2267                                offsetofName( typeName ),
2268                                new ast::ArrayType(
2269                                        layoutType,
2270                                        ast::ConstantExpr::from_int( location, memberCount ),
2271                                        ast::FixedLen,
2272                                        ast::DynamicDim
2273                                ),
2274                                nullptr
2275                        );
2276
2277                        // Generate call to layout function.
2278                        ast::UntypedExpr * layoutCall = new ast::UntypedExpr( location,
2279                                new ast::NameExpr( location, layoutofName( inst->base ) ),
2280                                {
2281                                        new ast::AddressExpr(
2282                                                new ast::VariableExpr( location, sizeofVar ) ),
2283                                        new ast::AddressExpr(
2284                                                new ast::VariableExpr( location, alignofVar ) ),
2285                                        new ast::VariableExpr( location, offsetofVar ),
2286                                } );
2287
2288                        addSTypeParamsToLayoutCall( layoutCall, sizedParams );
2289
2290                        stmtsToAddBefore.emplace_back(
2291                                new ast::ExprStmt( location, layoutCall ) );
2292                }
2293
2294                return true;
2295        } else if ( auto inst = dynamic_cast<ast::UnionInstType const *>( type ) ) {
2296                // Check if this type already has a layout generated for it.
2297                std::string typeName = Mangle::mangleType( type );
2298                if ( knownLayouts.contains( typeName ) ) return true;
2299
2300                // Check if any type parameters have dynamic layout;
2301                // If none do, this type is (or will be) monomorphized.
2302                ast::vector<ast::Type> sizedParams;
2303                if ( !findGenericParams( sizedParams,
2304                                inst->base->params, inst->params ) ) {
2305                        return false;
2306                }
2307
2308                // Insert local variables for layout and generate call to layout
2309                // function.
2310                // Done early so as not to interfere with the later addition of
2311                // parameters to the layout call.
2312                knownLayouts.insert( typeName );
2313                ast::Type const * layoutType = makeSizeAlignType();
2314
2315                ast::ObjectDecl * sizeofVar = makeVar( location,
2316                        sizeofName( typeName ), layoutType );
2317                ast::ObjectDecl * alignofVar = makeVar( location,
2318                        alignofName( typeName ), ast::deepCopy( layoutType ) );
2319
2320                ast::UntypedExpr * layoutCall = new ast::UntypedExpr( location,
2321                        new ast::NameExpr( location, layoutofName( inst->base ) ),
2322                        {
2323                                new ast::AddressExpr(
2324                                        new ast::VariableExpr( location, sizeofVar ) ),
2325                                new ast::AddressExpr(
2326                                        new ast::VariableExpr( location, alignofVar ) ),
2327                        } );
2328
2329                addSTypeParamsToLayoutCall( layoutCall, sizedParams );
2330
2331                stmtsToAddBefore.emplace_back(
2332                        new ast::ExprStmt( location, layoutCall ) );
2333
2334                return true;
2335        }
2336        return false;
2337}
2338
2339void PolyGenericCalculator::addSTypeParamsToLayoutCall(
2340                ast::UntypedExpr * layoutCall,
2341                const ast::vector<ast::Type> & otypeParams ) {
2342        CodeLocation const & location = layoutCall->location;
2343        ast::vector<ast::Expr> & args = layoutCall->args;
2344        for ( ast::ptr<ast::Type> const & param : otypeParams ) {
2345                if ( findGeneric( location, param ) ) {
2346                        // Push size/align vars for a generic parameter back.
2347                        std::string paramName = Mangle::mangleType( param );
2348                        args.emplace_back(
2349                                new ast::NameExpr( location, sizeofName( paramName ) ) );
2350                        args.emplace_back(
2351                                new ast::NameExpr( location, alignofName( paramName ) ) );
2352                } else {
2353                        args.emplace_back(
2354                                new ast::SizeofExpr( location, ast::deepCopy( param ) ) );
2355                        args.emplace_back(
2356                                new ast::AlignofExpr( location, ast::deepCopy( param ) ) );
2357                }
2358        }
2359}
2360
2361void PolyGenericCalculator::mutateMembers( ast::AggregateDecl * aggr ) {
2362        std::set<std::string> genericParams;
2363        for ( ast::ptr<ast::TypeDecl> const & decl : aggr->params ) {
2364                genericParams.insert( decl->name );
2365        }
2366        for ( ast::ptr<ast::Decl> & decl : aggr->members ) {
2367                auto field = decl.as<ast::ObjectDecl>();
2368                if ( nullptr == field ) continue;
2369
2370                ast::Type const * type = replaceTypeInst( field->type, typeSubs );
2371                auto typeInst = dynamic_cast<ast::TypeInstType const *>( type );
2372                if ( nullptr == typeInst ) continue;
2373
2374                // Do not try to monoporphize generic parameters.
2375                if ( scopeTypeVars.contains( ast::TypeEnvKey( *typeInst ) ) &&
2376                                !genericParams.count( typeInst->name ) ) {
2377                        // Polymorphic aggregate members should be converted into
2378                        // monomorphic members. Using char[size_T] here respects
2379                        // the expected sizing rules of an aggregate type.
2380                        decl = ast::mutate_field( field, &ast::ObjectDecl::type,
2381                                polyToMonoType( field->location, field->type ) );
2382                }
2383        }
2384}
2385
2386ast::Expr const * PolyGenericCalculator::genSizeof(
2387                CodeLocation const & location, ast::Type const * type ) {
2388        if ( auto * array = dynamic_cast<ast::ArrayType const *>( type ) ) {
2389                // Generate calculated size for possibly generic array.
2390                ast::Expr const * sizeofBase = genSizeof( location, array->base );
2391                if ( nullptr == sizeofBase ) return nullptr;
2392                ast::Expr const * dim = array->dimension;
2393                return makeOp( location, "?*?", sizeofBase, dim );
2394        } else if ( findGeneric( location, type ) ) {
2395                // Generate calculated size for generic type.
2396                return new ast::NameExpr( location, sizeofName(
2397                                Mangle::mangleType( type ) ) );
2398        } else {
2399                return nullptr;
2400        }
2401}
2402
2403void PolyGenericCalculator::beginTypeScope( ast::Type const * type ) {
2404        GuardScope( scopeTypeVars );
2405        makeTypeVarMap( type, scopeTypeVars );
2406}
2407
2408void PolyGenericCalculator::beginGenericScope() {
2409        GuardScope( *this );
2410        // We expect the first function type see to be the type relating to this
2411        // scope but any further type is probably some unrelated function pointer
2412        // keep track of whrich is the first.
2413        GuardValue( expect_func_type ) = true;
2414}
2415
2416// --------------------------------------------------------------------------
2417/// No common theme found.
2418/// * Replaces initialization of polymorphic values with alloca.
2419/// * Replaces declaration of dtype/ftype with appropriate void expression.
2420/// * Replaces sizeof expressions of polymorphic types with a variable.
2421/// * Strips fields from generic structure declarations.
2422struct Eraser final :
2423                public BoxPass,
2424                public ast::WithGuards {
2425        void guardTypeVarMap( ast::Type const * type ) {
2426                GuardScope( scopeTypeVars );
2427                makeTypeVarMap( type, scopeTypeVars );
2428        }
2429
2430        ast::ObjectDecl const * previsit( ast::ObjectDecl const * decl );
2431        ast::FunctionDecl const * previsit( ast::FunctionDecl const * decl );
2432        ast::TypedefDecl const * previsit( ast::TypedefDecl const * decl );
2433        ast::StructDecl const * previsit( ast::StructDecl const * decl );
2434        ast::UnionDecl const * previsit( ast::UnionDecl const * decl );
2435        void previsit( ast::TypeDecl const * decl );
2436        void previsit( ast::PointerType const * type );
2437        void previsit( ast::FunctionType const * type );
2438};
2439
2440ast::ObjectDecl const * Eraser::previsit( ast::ObjectDecl const * decl ) {
2441        guardTypeVarMap( decl->type );
2442        return scrubAllTypeVars( decl );
2443}
2444
2445ast::FunctionDecl const * Eraser::previsit( ast::FunctionDecl const * decl ) {
2446        guardTypeVarMap( decl->type );
2447        return scrubAllTypeVars( decl );
2448}
2449
2450ast::TypedefDecl const * Eraser::previsit( ast::TypedefDecl const * decl ) {
2451        guardTypeVarMap( decl->base );
2452        return scrubAllTypeVars( decl );
2453}
2454
2455/// Strips the members from a generic aggregate.
2456template<typename node_t>
2457node_t const * stripGenericMembers( node_t const * decl ) {
2458        if ( decl->params.empty() ) return decl;
2459        auto mutDecl = ast::mutate( decl );
2460        mutDecl->members.clear();
2461        return mutDecl;
2462}
2463
2464ast::StructDecl const * Eraser::previsit( ast::StructDecl const * decl ) {
2465        return stripGenericMembers( decl );
2466}
2467
2468ast::UnionDecl const * Eraser::previsit( ast::UnionDecl const * decl ) {
2469        return stripGenericMembers( decl );
2470}
2471
2472void Eraser::previsit( ast::TypeDecl const * decl ) {
2473        addToTypeVarMap( decl, scopeTypeVars );
2474}
2475
2476void Eraser::previsit( ast::PointerType const * type ) {
2477        guardTypeVarMap( type );
2478}
2479
2480void Eraser::previsit( ast::FunctionType const * type ) {
2481        guardTypeVarMap( type );
2482}
2483
2484} // namespace
2485
2486// --------------------------------------------------------------------------
2487void box( ast::TranslationUnit & translationUnit ) {
2488        ast::Pass<LayoutFunctionBuilder>::run( translationUnit );
2489        ast::Pass<CallAdapter>::run( translationUnit );
2490        ast::Pass<DeclAdapter>::run( translationUnit );
2491        ast::Pass<RewireAdapters>::run( translationUnit );
2492        ast::Pass<PolyGenericCalculator>::run( translationUnit );
2493        ast::Pass<Eraser>::run( translationUnit );
2494}
2495
2496} // namespace GenPoly
2497
2498// Local Variables: //
2499// tab-width: 4 //
2500// mode: c++ //
2501// compile-command: "make install" //
2502// End: //
Note: See TracBrowser for help on using the repository browser.