source: src/GenPoly/Box.cpp @ f936e23

Last change on this file since f936e23 was 23a0e576, checked in by Andrew Beach <ajbeach@…>, 5 months ago

Remove mid-array assertion from the Box pass.

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