source: src/GenPoly/Box.cpp @ 2ff76d25

Last change on this file since 2ff76d25 was 82d5816, checked in by Andrew Beach <ajbeach@…>, 7 hours ago

Bit of clean-up to the box pass. Mostly just wrapping a new common set of operations and checks into a helpper function.

  • Property mode set to 100644
File size: 84.3 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.hpp"
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.hpp"   // for isAssignment
27#include "Common/Iterate.hpp"          // for group_iterate
28#include "Common/ScopedMap.hpp"        // for ScopedMap
29#include "Common/ToString.hpp"         // for toCString
30#include "Common/UniqueName.hpp"       // for UniqueName
31#include "GenPoly/FindFunction.hpp"    // for findFunction
32#include "GenPoly/GenPoly.hpp"         // for getFunctionType, isPolyType, ...
33#include "GenPoly/Lvalue.hpp"          // for generalizedLvalue
34#include "GenPoly/ScopedSet.hpp"       // for ScopedSet
35#include "GenPoly/ScrubTypeVars.hpp"   // for scrubTypeVars, scrubAllTypeVars
36#include "ResolvExpr/Unify.hpp"        // for typesCompatible
37#include "SymTab/Mangler.hpp"          // 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::BasicKind::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::BasicKind::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
672// Get the referent (base type of pointer). Must succeed.
673ast::Type const * getReferentType( ast::ptr<ast::Type> const & type ) {
674        auto pointerType = type.strict_as<ast::PointerType>();
675        assertf( pointerType->base, "getReferentType: pointer base is nullptr." );
676        return pointerType->base.get();
677}
678
679bool isPolyDeref( ast::UntypedExpr const * expr,
680                TypeVarMap const & typeVars,
681                ast::TypeSubstitution const * typeSubs ) {
682        auto name = expr->func.as<ast::NameExpr>();
683        if ( name && "*?" == name->name ) {
684                // It's a deref.
685                // Must look under the * (and strip its ptr-ty) because expr's
686                // result could be ar/ptr-decayed.  If expr.inner:T(*)[n], then
687                // expr is a poly deref, even though expr:T*, which is not poly.
688                auto referentType = getReferentType( expr->args.front()->result );
689                return isPolyType( referentType, typeVars, typeSubs );
690        }
691        return false;
692}
693
694ast::Expr const * CallAdapter::postvisit( ast::UntypedExpr const * expr ) {
695        if ( isPolyDeref( expr, scopeTypeVars, typeSubs ) ) {
696                return expr->args.front();
697        }
698        return expr;
699}
700
701void CallAdapter::previsit( ast::AddressExpr const * ) {
702        visit_children = false;
703}
704
705ast::Expr const * CallAdapter::postvisit( ast::AddressExpr const * expr ) {
706        assert( expr->arg->result );
707        assert( !expr->arg->result->isVoid() );
708
709        bool doesNeedAdapter = false;
710        if ( auto un = expr->arg.as<ast::UntypedExpr>() ) {
711                if ( isPolyDeref( un, scopeTypeVars, typeSubs ) ) {
712                        if ( auto app = un->args.front().as<ast::ApplicationExpr>() ) {
713                                assert( app->func->result );
714                                auto function = getFunctionType( app->func->result );
715                                assert( function );
716                                doesNeedAdapter = needsAdapter( function, scopeTypeVars );
717                        }
718                }
719        }
720        // isPolyType check needs to happen before mutating expr arg,
721        // so pull it forward out of the if condition.
722        expr = ast::mutate_field( expr, &ast::AddressExpr::arg,
723                        expr->arg->accept( *visitor ) );
724        // But must happen after mutate, since argument might change
725        // (ex. intrinsic *?, ?[?]) re-evaluate above comment.
726        bool polyType = isPolyType( expr->arg->result, scopeTypeVars, typeSubs );
727        if ( polyType || doesNeedAdapter ) {
728                ast::Expr * ret = ast::mutate( expr->arg.get() );
729                ret->result = ast::deepCopy( expr->result );
730                return ret;
731        } else {
732                return expr;
733        }
734}
735
736ast::ReturnStmt const * CallAdapter::previsit( ast::ReturnStmt const * stmt ) {
737        // Since retval is set when the return type is dynamic, this function
738        // should have been converted to void return & out parameter.
739        if ( retval && stmt->expr ) {
740                assert( stmt->expr->result );
741                assert( !stmt->expr->result->isVoid() );
742                return ast::mutate_field( stmt, &ast::ReturnStmt::expr, nullptr );
743        }
744        return stmt;
745}
746
747void CallAdapter::beginScope() {
748        adapters.beginScope();
749}
750
751void CallAdapter::endScope() {
752        adapters.endScope();
753}
754
755/// Find instances of polymorphic type parameters.
756struct PolyFinder {
757        TypeVarMap const & typeVars;
758        bool result = false;
759        PolyFinder( TypeVarMap const & tvs ) : typeVars( tvs ) {}
760
761        void previsit( ast::TypeInstType const * type ) {
762                if ( isPolyType( type, typeVars ) ) result = true;
763        }
764};
765
766/// True if these is an instance of a polymorphic type parameter in the type.
767bool hasPolymorphism( ast::Type const * type, TypeVarMap const & typeVars ) {
768        return ast::Pass<PolyFinder>::read( type, typeVars );
769}
770
771void CallAdapter::passTypeVars(
772                ast::ApplicationExpr * expr,
773                ast::vector<ast::Expr> & extraArgs,
774                ast::FunctionType const * function ) {
775        assert( typeSubs );
776        // Pass size/align for type variables.
777        for ( ast::ptr<ast::TypeInstType> const & typeVar : function->forall ) {
778                if ( !typeVar->base->isComplete() ) continue;
779                ast::Type const * concrete = typeSubs->lookup( typeVar );
780                if ( !concrete ) {
781                        // Should this be an assertion?
782                        SemanticError( expr->location, "\nunbound type variable %s in application %s",
783                                                   toString( typeSubs ).c_str(), typeVar->typeString().c_str() );
784                }
785                extraArgs.emplace_back(
786                        new ast::SizeofExpr( expr->location, ast::deepCopy( concrete ) ) );
787                extraArgs.emplace_back(
788                        new ast::AlignofExpr( expr->location, ast::deepCopy( concrete ) ) );
789        }
790}
791
792ast::Expr const * CallAdapter::addRetParam(
793                ast::ApplicationExpr * expr, ast::Type const * retType ) {
794        // Create temporary to hold return value of polymorphic function and
795        // produce that temporary as a result using a comma expression.
796        assert( retType );
797
798        ast::Expr * paramExpr = nullptr;
799        // Try to use existing return value parameter if it exists,
800        // otherwise create a new temporary.
801        if ( retVals.count( expr ) ) {
802                paramExpr = ast::deepCopy( retVals[ expr ] );
803        } else {
804                auto newObj = makeTemporary( expr->location, ast::deepCopy( retType ) );
805                paramExpr = new ast::VariableExpr( expr->location, newObj );
806        }
807        ast::Expr * retExpr = ast::deepCopy( paramExpr );
808
809        // If the type of the temporary is not polpmorphic, box temporary by
810        // taking its address; otherwise the temporary is already boxed and can
811        // be used directly.
812        if ( !isPolyType( paramExpr->result, scopeTypeVars, typeSubs ) ) {
813                paramExpr = new ast::AddressExpr( paramExpr->location, paramExpr );
814        }
815        // Add argument to function call.
816        expr->args.insert( expr->args.begin(), paramExpr );
817        // Build a comma expression to call the function and return a value.
818        ast::CommaExpr * comma = new ast::CommaExpr(
819                expr->location, expr, retExpr );
820        comma->env = expr->env;
821        expr->env = nullptr;
822        return comma;
823}
824
825ast::Expr const * CallAdapter::addDynRetParam(
826                ast::ApplicationExpr * expr, ast::Type const * polyType ) {
827        assert( typeSubs );
828        ast::Type const * concrete = replaceWithConcrete( polyType, *typeSubs );
829        // Add out-parameter for return value.
830        return addRetParam( expr, concrete );
831}
832
833ast::Expr const * CallAdapter::applyAdapter(
834                ast::ApplicationExpr * expr,
835                ast::FunctionType const * function ) {
836        ast::Expr const * ret = expr;
837        if ( isDynRet( function, scopeTypeVars ) ) {
838                ret = addRetParam( expr, function->returns.front() );
839        }
840        std::string mangleName = mangleAdapterName( function, scopeTypeVars );
841        std::string adapterName = makeAdapterName( mangleName );
842
843        // Cast adaptee to `void (*)()`, since it may have any type inside a
844        // polymorphic function.
845        ast::Type const * adapteeType = new ast::PointerType(
846                new ast::FunctionType( ast::VariableArgs ) );
847        expr->args.insert( expr->args.begin(),
848                new ast::CastExpr( expr->location, expr->func, adapteeType ) );
849        // The result field is never set on NameExpr. / Now it is.
850        auto head = new ast::NameExpr( expr->location, adapterName );
851        head->result = ast::deepCopy( adapteeType );
852        expr->func = head;
853
854        return ret;
855}
856
857/// Cast parameters to polymorphic functions so that types are replaced with
858/// `void *` if they are type parameters in the formal type.
859/// This gets rid of warnings from gcc.
860void addCast(
861                ast::ptr<ast::Expr> & actual,
862                ast::Type const * formal,
863                TypeVarMap const & typeVars ) {
864        // Type contains polymorphism, but isn't exactly a polytype, in which
865        // case it has some real actual type (ex. unsigned int) and casting to
866        // `void *` is wrong.
867        if ( hasPolymorphism( formal, typeVars )
868                        && !isPolyType( formal, typeVars ) ) {
869                ast::Type const * newType = ast::deepCopy( formal );
870                newType = scrubTypeVars( newType, typeVars );
871                actual = new ast::CastExpr( actual->location, actual, newType );
872        }
873}
874
875void CallAdapter::boxParam( ast::ptr<ast::Expr> & arg,
876                ast::Type const * param, TypeVarMap const & exprTypeVars ) {
877        assertf( arg->result, "arg does not have result: %s", toCString( arg ) );
878        addCast( arg, param, exprTypeVars );
879        if ( !needsBoxing( param, arg->result, exprTypeVars, typeSubs ) ) {
880                return;
881        }
882        CodeLocation const & location = arg->location;
883
884        if ( arg->get_lvalue() ) {
885                // The argument expression may be CFA lvalue, but not C lvalue,
886                // so apply generalizedLvalue transformations.
887                // if ( auto var = dynamic_cast<ast::VariableExpr const *>( arg ) ) {
888                //  if ( dynamic_cast<ast::ArrayType const *>( varExpr->var->get_type() ) ){
889                //      // temporary hack - don't box arrays, because &arr is not the same as &arr[0]
890                //      return;
891                //  }
892                // }
893                arg = generalizedLvalue( new ast::AddressExpr( arg->location, arg ) );
894                if ( !ResolvExpr::typesCompatible( param, arg->result ) ) {
895                        // Silence warnings by casting boxed parameters when the actually
896                        // type does not match up with the formal type.
897                        arg = new ast::CastExpr( location, arg, ast::deepCopy( param ) );
898                }
899        } else {
900                // Use type computed in unification to declare boxed variables.
901                ast::ptr<ast::Type> newType = ast::deepCopy( param );
902                if ( typeSubs ) typeSubs->apply( newType );
903                ast::ObjectDecl * newObj = makeTemporary( location, newType );
904                auto assign = ast::UntypedExpr::createCall( location, "?=?", {
905                        new ast::VariableExpr( location, newObj ),
906                        arg,
907                } );
908                stmtsToAddBefore.push_back( new ast::ExprStmt( location, assign ) );
909                arg = new ast::AddressExpr(
910                        new ast::VariableExpr( location, newObj ) );
911        }
912}
913
914void CallAdapter::boxParams(
915                ast::ApplicationExpr * expr,
916                ast::Type const * polyRetType,
917                ast::FunctionType const * function,
918                const TypeVarMap & typeVars ) {
919        // Start at the beginning, but the return argument may have been added.
920        auto arg = expr->args.begin();
921        if ( polyRetType ) ++arg;
922
923        for ( auto param : function->params ) {
924                assertf( arg != expr->args.end(),
925                        "boxParams: missing argument for param %s to %s in %s",
926                        toCString( param ), toCString( function ), toCString( expr ) );
927                boxParam( *arg, param, typeVars );
928                ++arg;
929        }
930}
931
932void CallAdapter::addInferredParams(
933                ast::ApplicationExpr * expr,
934                ast::vector<ast::Expr> & extraArgs,
935                ast::FunctionType const * functionType,
936                TypeVarMap const & typeVars ) {
937        for ( auto assertion : functionType->assertions ) {
938                auto inferParam = expr->inferred.inferParams().find(
939                        assertion->var->uniqueId );
940                assertf( inferParam != expr->inferred.inferParams().end(),
941                        "addInferredParams missing inferred parameter: %s in: %s",
942                        toCString( assertion ), toCString( expr ) );
943                ast::ptr<ast::Expr> newExpr = ast::deepCopy( inferParam->second.expr );
944                boxParam( newExpr, assertion->result, typeVars );
945                extraArgs.emplace_back( newExpr.release() );
946        }
947}
948
949/// Modifies the ApplicationExpr to accept adapter functions for its
950/// assertion and parameters, declares the required adapters.
951void CallAdapter::passAdapters(
952                ast::ApplicationExpr * expr,
953                ast::FunctionType const * type,
954                const TypeVarMap & exprTypeVars ) {
955        // Collect a list of function types passed as parameters or implicit
956        // parameters (assertions).
957        ast::vector<ast::Type> const & paramList = type->params;
958        ast::vector<ast::FunctionType> functions;
959
960        for ( ast::ptr<ast::VariableExpr> const & assertion : type->assertions ) {
961                findFunction( assertion->result, functions, exprTypeVars, needsAdapter );
962        }
963        for ( ast::ptr<ast::Type> const & arg : paramList ) {
964                findFunction( arg, functions, exprTypeVars, needsAdapter );
965        }
966
967        // Parameter function types for which an appropriate adapter has been
968        // generated. We cannot use the types after applying substitutions,
969        // since two different parameter types may be unified to the same type.
970        std::set<std::string> adaptersDone;
971
972        CodeLocation const & location = expr->location;
973
974        for ( ast::ptr<ast::FunctionType> const & funcType : functions ) {
975                std::string mangleName = Mangle::mangle( funcType );
976
977                // Only attempt to create an adapter or pass one as a parameter if we
978                // haven't already done so for this pre-substitution parameter
979                // function type.
980                // The second part of the result if is if the element was inserted.
981                if ( !adaptersDone.insert( mangleName ).second ) continue;
982
983                // Apply substitution to type variables to figure out what the
984                // adapter's type should look like. (Copy to make the release safe.)
985                assert( typeSubs );
986                auto result = typeSubs->apply( ast::deepCopy( funcType ) );
987                ast::FunctionType * realType = ast::mutate( result.node.release() );
988                mangleName = Mangle::mangle( realType );
989                mangleName += makePolyMonoSuffix( funcType, exprTypeVars );
990
991                // Check if the adapter has already been created, or has to be.
992                using AdapterIter = decltype(adapters)::iterator;
993                AdapterIter adapter = adapters.find( mangleName );
994                if ( adapter == adapters.end() ) {
995                        ast::FunctionDecl * newAdapter = makeAdapter(
996                                funcType, realType, mangleName, exprTypeVars, location );
997                        std::pair<AdapterIter, bool> answer =
998                                adapters.insert( mangleName, newAdapter );
999                        adapter = answer.first;
1000                        stmtsToAddBefore.push_back(
1001                                new ast::DeclStmt( location, newAdapter ) );
1002                }
1003                assert( adapter != adapters.end() );
1004
1005                // Add the approprate adapter as a parameter.
1006                expr->args.insert( expr->args.begin(),
1007                        new ast::VariableExpr( location, adapter->second ) );
1008        }
1009}
1010
1011// Parameter and argument may be used wrong around here.
1012ast::Expr * makeAdapterArg(
1013                ast::DeclWithType const * param,
1014                ast::Type const * arg,
1015                ast::Type const * realParam,
1016                TypeVarMap const & typeVars,
1017                CodeLocation const & location ) {
1018        assert( param );
1019        assert( arg );
1020        assert( realParam );
1021        if ( isPolyType( realParam, typeVars ) && !isPolyType( arg ) ) {
1022                ast::UntypedExpr * deref = ast::UntypedExpr::createDeref(
1023                        location,
1024                        new ast::CastExpr( location,
1025                                new ast::VariableExpr( location, param ),
1026                                new ast::PointerType( ast::deepCopy( arg ) )
1027                        )
1028                );
1029                deref->result = ast::deepCopy( arg );
1030                return deref;
1031        }
1032        return new ast::VariableExpr( location, param );
1033}
1034
1035// This seems to be one of the problematic functions.
1036void addAdapterParams(
1037                ast::ApplicationExpr * adaptee,
1038                ast::vector<ast::Type>::const_iterator arg,
1039                ast::vector<ast::DeclWithType>::iterator param,
1040                ast::vector<ast::DeclWithType>::iterator paramEnd,
1041                ast::vector<ast::Type>::const_iterator realParam,
1042                TypeVarMap const & typeVars,
1043                CodeLocation const & location ) {
1044        UniqueName paramNamer( "_p" );
1045        for ( ; param != paramEnd ; ++param, ++arg, ++realParam ) {
1046                if ( "" == (*param)->name ) {
1047                        auto mutParam = (*param).get_and_mutate();
1048                        mutParam->name = paramNamer.newName();
1049                        mutParam->linkage = ast::Linkage::C;
1050                }
1051                adaptee->args.push_back(
1052                        makeAdapterArg( *param, *arg, *realParam, typeVars, location ) );
1053        }
1054}
1055
1056ast::FunctionDecl * CallAdapter::makeAdapter(
1057                ast::FunctionType const * adaptee,
1058                ast::FunctionType const * realType,
1059                std::string const & mangleName,
1060                TypeVarMap const & typeVars,
1061                CodeLocation const & location ) const {
1062        ast::FunctionType * adapterType = makeAdapterType( adaptee, typeVars );
1063        adapterType = ast::mutate( scrubTypeVars( adapterType, typeVars ) );
1064
1065        // Some of these names will be overwritten, but it gives a default.
1066        UniqueName pNamer( "_param" );
1067        UniqueName rNamer( "_ret" );
1068
1069        bool first = true;
1070
1071        ast::FunctionDecl * adapterDecl = new ast::FunctionDecl( location,
1072                makeAdapterName( mangleName ),
1073                {}, // forall
1074                {}, // assertions
1075                map_range<ast::vector<ast::DeclWithType>>( adapterType->params,
1076                                [&pNamer, &location, &first]( ast::ptr<ast::Type> const & param ) {
1077                        // [Trying to make the generated code match exactly more often.]
1078                        if ( first ) {
1079                                first = false;
1080                                return new ast::ObjectDecl( location, "_adaptee", param );
1081                        }
1082                        return new ast::ObjectDecl( location, pNamer.newName(), param );
1083                } ),
1084                map_range<ast::vector<ast::DeclWithType>>( adapterType->returns,
1085                                [&rNamer, &location]( ast::ptr<ast::Type> const & retval ) {
1086                        return new ast::ObjectDecl( location, rNamer.newName(), retval );
1087                } ),
1088                nullptr, // stmts
1089                {}, // storage
1090                ast::Linkage::C
1091        );
1092
1093        ast::DeclWithType * adapteeDecl =
1094                adapterDecl->params.front().get_and_mutate();
1095        adapteeDecl->name = "_adaptee";
1096
1097        // Do not carry over attributes to real type parameters/return values.
1098        auto mutRealType = ast::mutate( realType );
1099        for ( ast::ptr<ast::Type> & decl : mutRealType->params ) {
1100                if ( decl->attributes.empty() ) continue;
1101                auto mut = ast::mutate( decl.get() );
1102                mut->attributes.clear();
1103                decl = mut;
1104        }
1105        for ( ast::ptr<ast::Type> & decl : mutRealType->returns ) {
1106                if ( decl->attributes.empty() ) continue;
1107                auto mut = ast::mutate( decl.get() );
1108                mut->attributes.clear();
1109                decl = mut;
1110        }
1111        realType = mutRealType;
1112
1113        ast::ApplicationExpr * adapteeApp = new ast::ApplicationExpr( location,
1114                new ast::CastExpr( location,
1115                        new ast::VariableExpr( location, adapteeDecl ),
1116                        new ast::PointerType( realType )
1117                )
1118        );
1119
1120        for ( auto const & [assertArg, assertParam, assertReal] : group_iterate(
1121                        realType->assertions, adapterType->assertions, adaptee->assertions ) ) {
1122                adapteeApp->args.push_back( makeAdapterArg(
1123                        assertParam->var, assertArg->var->get_type(),
1124                        assertReal->var->get_type(), typeVars, location
1125                ) );
1126        }
1127
1128        ast::vector<ast::Type>::const_iterator
1129                arg = realType->params.begin(),
1130                param = adapterType->params.begin(),
1131                realParam = adaptee->params.begin();
1132        ast::vector<ast::DeclWithType>::iterator
1133                paramDecl = adapterDecl->params.begin();
1134        // Skip adaptee parameter in the adapter type.
1135        ++param;
1136        ++paramDecl;
1137
1138        ast::Stmt * bodyStmt;
1139        // Returns void/nothing.
1140        if ( realType->returns.empty() ) {
1141                addAdapterParams( adapteeApp, arg, paramDecl, adapterDecl->params.end(),
1142                        realParam, typeVars, location );
1143                bodyStmt = new ast::ExprStmt( location, adapteeApp );
1144        // Returns a polymorphic type.
1145        } else if ( isDynType( adaptee->returns.front(), typeVars ) ) {
1146                ast::UntypedExpr * assign = new ast::UntypedExpr( location,
1147                        new ast::NameExpr( location, "?=?" ) );
1148                ast::UntypedExpr * deref = ast::UntypedExpr::createDeref( location,
1149                        new ast::CastExpr( location,
1150                                new ast::VariableExpr( location, *paramDecl++ ),
1151                                new ast::PointerType(
1152                                        ast::deepCopy( realType->returns.front() ) ) ) );
1153                assign->args.push_back( deref );
1154                addAdapterParams( adapteeApp, arg, paramDecl, adapterDecl->params.end(),
1155                        realParam, typeVars, location );
1156                assign->args.push_back( adapteeApp );
1157                bodyStmt = new ast::ExprStmt( location, assign );
1158        // Adapter for a function that returns a monomorphic value.
1159        } else {
1160                addAdapterParams( adapteeApp, arg, paramDecl, adapterDecl->params.end(),
1161                                realParam, typeVars, location );
1162                bodyStmt = new ast::ReturnStmt( location, adapteeApp );
1163        }
1164
1165        adapterDecl->stmts = new ast::CompoundStmt( location, { bodyStmt } );
1166        return adapterDecl;
1167}
1168
1169ast::Expr const * makeIncrDecrExpr(
1170                CodeLocation const & location,
1171                ast::ApplicationExpr const * expr,
1172                ast::Type const * polyType,
1173                bool isIncr ) {
1174        ast::NameExpr * opExpr =
1175                        new ast::NameExpr( location, isIncr ? "?+=?" : "?-=?" );
1176        ast::UntypedExpr * addAssign = new ast::UntypedExpr( location, opExpr );
1177        if ( auto address = expr->args.front().as<ast::AddressExpr>() ) {
1178                addAssign->args.push_back( address->arg );
1179        } else {
1180                addAssign->args.push_back( expr->args.front() );
1181        }
1182        addAssign->args.push_back( new ast::NameExpr( location,
1183                sizeofName( Mangle::mangleType( polyType ) ) ) );
1184        addAssign->result = ast::deepCopy( expr->result );
1185        addAssign->env = expr->env ? expr->env : addAssign->env;
1186        return addAssign;
1187}
1188
1189/// Handles intrinsic functions for postvisit ApplicationExpr.
1190ast::Expr const * CallAdapter::handleIntrinsics(
1191                ast::ApplicationExpr const * expr ) {
1192        auto varExpr = expr->func.as<ast::VariableExpr>();
1193        if ( !varExpr || varExpr->var->linkage != ast::Linkage::Intrinsic ) {
1194                return nullptr;
1195        }
1196        std::string const & varName = varExpr->var->name;
1197
1198        // Index Intrinsic:
1199        if ( "?[?]" == varName ) {
1200                assert( expr->result );
1201                assert( 2 == expr->args.size() );
1202
1203                ast::ptr<ast::Type> const & argType1 = expr->args.front()->result;
1204                ast::ptr<ast::Type> const & argType2 = expr->args.back()->result;
1205
1206                // Two Cases: a[i] with first arg poly ptr, i[a] with second arg poly ptr
1207                bool isPoly1 = isPolyPtr( argType1, scopeTypeVars, typeSubs ) != nullptr;
1208                bool isPoly2 = isPolyPtr( argType2, scopeTypeVars, typeSubs ) != nullptr;
1209
1210                // If neither argument is a polymorphic pointer, do nothing.
1211                if ( !isPoly1 && !isPoly2 ) {
1212                        return expr;
1213                }
1214                // The arguments cannot both be polymorphic pointers.
1215                assert( !isPoly1 || !isPoly2 );
1216                // (So exactly one of the arguments is a polymorphic pointer.)
1217
1218                CodeLocation const & location = expr->location;
1219                CodeLocation const & location1 = expr->args.front()->location;
1220                CodeLocation const & location2 = expr->args.back()->location;
1221
1222                ast::UntypedExpr * ret = new ast::UntypedExpr( location,
1223                                new ast::NameExpr( location, "?+?" ) );
1224                if ( isPoly1 ) {
1225                        auto referentType = getReferentType( argType1 );
1226                        auto multiply = ast::UntypedExpr::createCall( location2, "?*?", {
1227                                expr->args.back(),
1228                                new ast::SizeofExpr( location1, deepCopy( referentType ) ),
1229                        } );
1230                        ret->args.push_back( expr->args.front() );
1231                        ret->args.push_back( multiply );
1232                } else {
1233                        assert( isPoly2 );
1234                        auto referentType = getReferentType( argType2 );
1235                        auto multiply = ast::UntypedExpr::createCall( location1, "?*?", {
1236                                expr->args.front(),
1237                                new ast::SizeofExpr( location2, deepCopy( referentType ) ),
1238                        } );
1239                        ret->args.push_back( multiply );
1240                        ret->args.push_back( expr->args.back() );
1241                }
1242                ret->result = ast::deepCopy( expr->result );
1243                ret->env = expr->env ? expr->env : ret->env;
1244                return ret;
1245        // Dereference Intrinsic:
1246        } else if ( "*?" == varName ) {
1247                assert( expr->result );
1248                assert( 1 == expr->args.size() );
1249
1250                // If this isn't for a poly type, then do nothing.
1251                auto referentType = getReferentType( expr->args.front()->result );
1252                if ( !isPolyType( referentType, scopeTypeVars, typeSubs ) ) {
1253                        return expr;
1254                }
1255
1256                // Remove dereference from polymorphic types since they are boxed.
1257                ast::Expr * ret = ast::deepCopy( expr->args.front() );
1258                // Fix expression type to remove pointer.
1259                ret->result = expr->result;
1260                // apply pointer decay
1261                if (auto retArTy = ret->result.as<ast::ArrayType>()) {
1262                        ret->result = new ast::PointerType( retArTy->base );
1263                }
1264                ret->env = expr->env ? expr->env : ret->env;
1265                return ret;
1266        // Post-Increment/Decrement Intrinsics:
1267        } else if ( "?++" == varName || "?--" == varName ) {
1268                assert( expr->result );
1269                assert( 1 == expr->args.size() );
1270
1271                ast::Type const * baseType =
1272                        isPolyType( expr->result, scopeTypeVars, typeSubs );
1273                if ( nullptr == baseType ) {
1274                        return expr;
1275                }
1276                ast::Type * tempType = ast::deepCopy( expr->result );
1277                if ( typeSubs ) {
1278                        auto result = typeSubs->apply( tempType );
1279                        tempType = ast::mutate( result.node.release() );
1280                }
1281                CodeLocation const & location = expr->location;
1282                ast::ObjectDecl * newObj = makeTemporary( location, tempType );
1283                ast::VariableExpr * tempExpr =
1284                        new ast::VariableExpr( location, newObj );
1285                ast::UntypedExpr * assignExpr = new ast::UntypedExpr( location,
1286                        new ast::NameExpr( location, "?=?" ) );
1287                assignExpr->args.push_back( ast::deepCopy( tempExpr ) );
1288                if ( auto address = expr->args.front().as<ast::AddressExpr>() ) {
1289                        assignExpr->args.push_back( ast::deepCopy( address->arg ) );
1290                } else {
1291                        assignExpr->args.push_back( ast::deepCopy( expr->args.front() ) );
1292                }
1293                return new ast::CommaExpr( location,
1294                        new ast::CommaExpr( location,
1295                                assignExpr,
1296                                makeIncrDecrExpr( location, expr, baseType, "?++" == varName )
1297                        ),
1298                        tempExpr
1299                );
1300        // Pre-Increment/Decrement Intrinsics:
1301        } else if ( "++?" == varName || "--?" == varName ) {
1302                assert( expr->result );
1303                assert( 1 == expr->args.size() );
1304
1305                ast::Type const * baseType =
1306                        isPolyType( expr->result, scopeTypeVars, typeSubs );
1307                if ( nullptr == baseType ) {
1308                        return expr;
1309                }
1310                return makeIncrDecrExpr(
1311                        expr->location, expr, baseType, "++?" == varName );
1312        // Addition and Subtraction Intrinsics:
1313        } else if ( "?+?" == varName || "?-?" == varName ) {
1314                assert( expr->result );
1315                assert( 2 == expr->args.size() );
1316
1317                ast::ptr<ast::Type> const & argType1 = expr->args.front()->result;
1318                ast::ptr<ast::Type> const & argType2 = expr->args.back()->result;
1319
1320                bool isPoly1 = isPolyPtr( argType1, scopeTypeVars, typeSubs ) != nullptr;
1321                bool isPoly2 = isPolyPtr( argType2, scopeTypeVars, typeSubs ) != nullptr;
1322
1323                CodeLocation const & location = expr->location;
1324                CodeLocation const & location1 = expr->args.front()->location;
1325                CodeLocation const & location2 = expr->args.back()->location;
1326                // LHS - RHS -> (LHS - RHS) / sizeof(LHS)
1327                if ( isPoly1 && isPoly2 ) {
1328                        // There are only subtraction intrinsics for this pattern.
1329                        assert( "?-?" == varName );
1330                        auto referentType = getReferentType( argType1 );
1331                        auto divide = ast::UntypedExpr::createCall( location, "?/?", {
1332                                expr,
1333                                new ast::SizeofExpr( location, deepCopy( referentType ) ),
1334                        } );
1335                        if ( expr->env ) divide->env = expr->env;
1336                        return divide;
1337                // LHS op RHS -> LHS op (RHS * sizeof(LHS))
1338                } else if ( isPoly1 ) {
1339                        auto referentType = getReferentType( argType1 );
1340                        auto multiply = ast::UntypedExpr::createCall( location2, "?*?", {
1341                                expr->args.back(),
1342                                new ast::SizeofExpr( location1, deepCopy( referentType ) ),
1343                        } );
1344                        return ast::mutate_field_index(
1345                                expr, &ast::ApplicationExpr::args, 1, multiply );
1346                // LHS op RHS -> (LHS * sizeof(RHS)) op RHS
1347                } else if ( isPoly2 ) {
1348                        auto referentType = getReferentType( argType2 );
1349                        auto multiply = ast::UntypedExpr::createCall( location1, "?*?", {
1350                                expr->args.front(),
1351                                new ast::SizeofExpr( location2, deepCopy( referentType ) ),
1352                        } );
1353                        return ast::mutate_field_index(
1354                                expr, &ast::ApplicationExpr::args, 0, multiply );
1355                }
1356        // Addition and Subtraction Relative Assignment Intrinsics:
1357        } else if ( "?+=?" == varName || "?-=?" == varName ) {
1358                assert( expr->result );
1359                assert( 2 == expr->args.size() );
1360
1361                CodeLocation const & location1 = expr->args.front()->location;
1362                CodeLocation const & location2 = expr->args.back()->location;
1363                auto baseType = isPolyPtr( expr->result, scopeTypeVars, typeSubs );
1364                // LHS op RHS -> LHS op (RHS * sizeof(LHS))
1365                if ( baseType ) {
1366                        auto multiply = ast::UntypedExpr::createCall( location2, "?*?", {
1367                                expr->args.back(),
1368                                new ast::SizeofExpr( location1, deepCopy( baseType ) ),
1369                        } );
1370                        return ast::mutate_field_index(
1371                                expr, &ast::ApplicationExpr::args, 1, multiply );
1372                }
1373        }
1374        return expr;
1375}
1376
1377ast::ObjectDecl * CallAdapter::makeTemporary(
1378                CodeLocation const & location, ast::Type const * type ) {
1379        auto newObj = new ast::ObjectDecl( location, tmpNamer.newName(), type );
1380        stmtsToAddBefore.push_back( new ast::DeclStmt( location, newObj ) );
1381        return newObj;
1382}
1383
1384// --------------------------------------------------------------------------
1385/// Modifies declarations to accept implicit parameters.
1386/// * Move polymorphic returns in function types to pointer-type parameters.
1387/// * Adds type size and assertion parameters to parameter lists.
1388struct DeclAdapter final {
1389        ast::FunctionDecl const * previsit( ast::FunctionDecl const * decl );
1390        ast::FunctionDecl const * postvisit( ast::FunctionDecl const * decl );
1391private:
1392        void addAdapters( ast::FunctionDecl * decl, TypeVarMap & localTypeVars );
1393};
1394
1395ast::ObjectDecl * makeObj(
1396                CodeLocation const & location, std::string const & name ) {
1397        // The size/align parameters may be unused, so add the unused attribute.
1398        return new ast::ObjectDecl( location, name,
1399                makeLayoutCType(),
1400                nullptr, ast::Storage::Classes(), ast::Linkage::C, nullptr,
1401                { new ast::Attribute( "unused" ) } );
1402}
1403
1404/// A modified and specialized version of ast::add_qualifiers.
1405ast::Type const * addConst( ast::Type const * type ) {
1406        ast::CV::Qualifiers cvq = { ast::CV::Const };
1407        if ( ( type->qualifiers & cvq ) != 0 ) return type;
1408        auto mutType = ast::mutate( type );
1409        mutType->qualifiers |= cvq;
1410        return mutType;
1411}
1412
1413ast::FunctionDecl const * DeclAdapter::previsit( ast::FunctionDecl const * decl ) {
1414        TypeVarMap localTypeVars;
1415        makeTypeVarMap( decl, localTypeVars );
1416
1417        auto mutDecl = mutate( decl );
1418
1419        // Move polymorphic return type to parameter list.
1420        if ( isDynRet( mutDecl->type ) ) {
1421                auto ret = strict_dynamic_cast<ast::ObjectDecl *>(
1422                        mutDecl->returns.front().get_and_mutate() );
1423                ret->set_type( new ast::PointerType( ret->type ) );
1424                mutDecl->params.insert( mutDecl->params.begin(), ret );
1425                mutDecl->returns.erase( mutDecl->returns.begin() );
1426                ret->init = nullptr;
1427        }
1428
1429        // Add size/align and assertions for type parameters to parameter list.
1430        ast::vector<ast::DeclWithType> inferredParams;
1431        ast::vector<ast::DeclWithType> layoutParams;
1432        for ( ast::ptr<ast::TypeDecl> & typeParam : mutDecl->type_params ) {
1433                auto mutParam = mutate( typeParam.get() );
1434                // Add all size and alignment parameters to parameter list.
1435                if ( mutParam->isComplete() ) {
1436                        ast::TypeInstType paramType( mutParam );
1437                        std::string paramName = Mangle::mangleType( &paramType );
1438
1439                        auto sizeParam = makeObj( typeParam->location, sizeofName( paramName ) );
1440                        layoutParams.emplace_back( sizeParam );
1441
1442                        auto alignParam = makeObj( typeParam->location, alignofName( paramName ) );
1443                        layoutParams.emplace_back( alignParam );
1444                }
1445                // Assertions should be stored in the main list.
1446                assert( mutParam->assertions.empty() );
1447                typeParam = mutParam;
1448        }
1449        for ( ast::ptr<ast::DeclWithType> & assert : mutDecl->assertions ) {
1450                ast::DeclWithType * mutAssert = ast::mutate( assert.get() );
1451                // Assertion parameters may not be used in body,
1452                // pass along with unused attribute.
1453                mutAssert->attributes.push_back( new ast::Attribute( "unused" ) );
1454                mutAssert->set_type( addConst( mutAssert->get_type() ) );
1455                inferredParams.emplace_back( mutAssert );
1456        }
1457        mutDecl->assertions.clear();
1458
1459        // Prepend each argument group. From last group to first. addAdapters
1460        // does do the same, it just does it itself and see all other parameters.
1461        spliceBegin( mutDecl->params, inferredParams );
1462        spliceBegin( mutDecl->params, layoutParams );
1463        addAdapters( mutDecl, localTypeVars );
1464
1465        // Now have to update the type to match the declaration.
1466        ast::FunctionType * type = new ast::FunctionType(
1467                mutDecl->type->isVarArgs, mutDecl->type->qualifiers );
1468        // The forall clauses don't match until Eraser. The assertions are empty.
1469        for ( auto param : mutDecl->params ) {
1470                type->params.emplace_back( param->get_type() );
1471        }
1472        for ( auto retval : mutDecl->returns ) {
1473                type->returns.emplace_back( retval->get_type() );
1474        }
1475        mutDecl->type = type;
1476
1477        return mutDecl;
1478}
1479
1480ast::FunctionDecl const * DeclAdapter::postvisit(
1481                ast::FunctionDecl const * decl ) {
1482        ast::FunctionDecl * mutDecl = mutate( decl );
1483        if ( !mutDecl->returns.empty() && mutDecl->stmts
1484                        // Intrinsic functions won't be using the _retval so no need to
1485                        // generate it.
1486                        && mutDecl->linkage != ast::Linkage::Intrinsic
1487                        // Remove check for prefix once thunks properly use ctor/dtors.
1488                        && !isPrefix( mutDecl->name, "_thunk" )
1489                        && !isPrefix( mutDecl->name, "_adapter" ) ) {
1490                assert( 1 == mutDecl->returns.size() );
1491                ast::DeclWithType const * retval = mutDecl->returns.front();
1492                if ( "" == retval->name ) {
1493                        retval = ast::mutate_field(
1494                                retval, &ast::DeclWithType::name, "_retval" );
1495                        mutDecl->returns.front() = retval;
1496                }
1497                auto stmts = mutDecl->stmts.get_and_mutate();
1498                stmts->kids.push_front( new ast::DeclStmt( retval->location, retval ) );
1499                ast::DeclWithType * newRet = ast::deepCopy( retval );
1500                mutDecl->returns.front() = newRet;
1501        }
1502        // Errors should have been caught by this point, remove initializers from
1503        // parameters to allow correct codegen of default arguments.
1504        for ( ast::ptr<ast::DeclWithType> & param : mutDecl->params ) {
1505                if ( auto obj = param.as<ast::ObjectDecl>() ) {
1506                        param = ast::mutate_field( obj, &ast::ObjectDecl::init, nullptr );
1507                }
1508        }
1509        return mutDecl;
1510}
1511
1512void DeclAdapter::addAdapters(
1513                ast::FunctionDecl * mutDecl, TypeVarMap & localTypeVars ) {
1514        ast::vector<ast::FunctionType> functions;
1515        for ( ast::ptr<ast::DeclWithType> & arg : mutDecl->params ) {
1516                ast::Type const * type = arg->get_type();
1517                type = findAndReplaceFunction( type, functions, localTypeVars, needsAdapter );
1518                arg.get_and_mutate()->set_type( type );
1519        }
1520        std::set<std::string> adaptersDone;
1521        for ( ast::ptr<ast::FunctionType> const & func : functions ) {
1522                std::string mangleName = mangleAdapterName( func, localTypeVars );
1523                if ( adaptersDone.find( mangleName ) != adaptersDone.end() ) {
1524                        continue;
1525                }
1526                std::string adapterName = makeAdapterName( mangleName );
1527                // The adapter may not actually be used, so make sure it has unused.
1528                mutDecl->params.insert( mutDecl->params.begin(), new ast::ObjectDecl(
1529                        mutDecl->location, adapterName,
1530                        new ast::PointerType( makeAdapterType( func, localTypeVars ) ),
1531                        nullptr, {}, {}, nullptr,
1532                        { new ast::Attribute( "unused" ) } ) );
1533                adaptersDone.insert( adaptersDone.begin(), mangleName );
1534        }
1535}
1536
1537// --------------------------------------------------------------------------
1538/// Corrects the floating nodes created in CallAdapter.
1539struct RewireAdapters final : public ast::WithGuards {
1540        ScopedMap<std::string, ast::ObjectDecl const *> adapters;
1541        void beginScope() { adapters.beginScope(); }
1542        void endScope() { adapters.endScope(); }
1543        void previsit( ast::FunctionDecl const * decl );
1544        ast::VariableExpr const * previsit( ast::VariableExpr const * expr );
1545};
1546
1547void RewireAdapters::previsit( ast::FunctionDecl const * decl ) {
1548        GuardScope( adapters );
1549        for ( ast::ptr<ast::DeclWithType> const & param : decl->params ) {
1550                if ( auto objectParam = param.as<ast::ObjectDecl>() ) {
1551                        adapters.insert( objectParam->name, objectParam );
1552                }
1553        }
1554}
1555
1556ast::VariableExpr const * RewireAdapters::previsit(
1557                ast::VariableExpr const * expr ) {
1558        // If the node is not floating, we can skip.
1559        if ( expr->var->isManaged() ) return expr;
1560        auto it = adapters.find( expr->var->name );
1561        assertf( it != adapters.end(), "Could not correct floating node." );
1562        return ast::mutate_field( expr, &ast::VariableExpr::var, it->second );
1563}
1564
1565// --------------------------------------------------------------------------
1566/// Inserts code to access polymorphic layout inforation.
1567/// * Replaces member and size/alignment/offsetof expressions on polymorphic
1568///   generic types with calculated expressions.
1569/// * Replaces member expressions for polymorphic types with calculated
1570///   add-field-offset-and-dereference.
1571/// * Calculates polymorphic offsetof expressions from offset array.
1572/// * Inserts dynamic calculation of polymorphic type layouts where needed.
1573struct PolyGenericCalculator final :
1574                public ast::WithConstTypeSubstitution,
1575                public ast::WithDeclsToAdd<>,
1576                public ast::WithGuards,
1577                public ast::WithStmtsToAdd<>,
1578                public ast::WithVisitorRef<PolyGenericCalculator> {
1579        PolyGenericCalculator();
1580
1581        void previsit( ast::FunctionDecl const * decl );
1582        void previsit( ast::TypedefDecl const * decl );
1583        void previsit( ast::TypeDecl const * decl );
1584        ast::Decl const * postvisit( ast::TypeDecl const * decl );
1585        ast::StructDecl const * previsit( ast::StructDecl const * decl );
1586        ast::UnionDecl const * previsit( ast::UnionDecl const * decl );
1587        ast::DeclStmt const * previsit( ast::DeclStmt const * stmt );
1588        ast::Expr const * postvisit( ast::MemberExpr const * expr );
1589        void previsit( ast::AddressExpr const * expr );
1590        ast::Expr const * postvisit( ast::AddressExpr const * expr );
1591        ast::Expr const * postvisit( ast::SizeofExpr const * expr );
1592        ast::Expr const * postvisit( ast::AlignofExpr const * expr );
1593        ast::Expr const * postvisit( ast::OffsetofExpr const * expr );
1594        ast::Expr const * postvisit( ast::OffsetPackExpr const * expr );
1595
1596        void beginScope();
1597        void endScope();
1598private:
1599        /// Makes a new variable in the current scope with the given name,
1600        /// type and optional initializer.
1601        ast::ObjectDecl * makeVar(
1602                        CodeLocation const & location, std::string const & name,
1603                        ast::Type const * type, ast::Init const * init = nullptr );
1604        /// Returns true if the type has a dynamic layout;
1605        /// such a layout will be stored in appropriately-named local variables
1606        /// when the function returns.
1607        bool findGeneric( CodeLocation const & location, ast::Type const * );
1608        /// Adds type parameters to the layout call; will generate the
1609        /// appropriate parameters if needed.
1610        void addSTypeParamsToLayoutCall(
1611                ast::UntypedExpr * layoutCall,
1612                const ast::vector<ast::Type> & otypeParams );
1613        /// Change the type of generic aggregate members to char[].
1614        void mutateMembers( ast::AggregateDecl * aggr );
1615        /// Returns the calculated sizeof/alignof expressions for type, or
1616        /// nullptr for use C size/alignof().
1617        ast::Expr const * genSizeof( CodeLocation const &, ast::Type const * );
1618        ast::Expr const * genAlignof( CodeLocation const &, ast::Type const * );
1619        /// Enters a new scope for type-variables,
1620        /// adding the type variables from the provided type.
1621        void beginTypeScope( ast::Type const * );
1622
1623        /// The type variables and polymorphic parameters currently in scope.
1624        TypeVarMap scopeTypeVars;
1625        /// Set of generic type layouts known in the current scope,
1626        /// indexed by sizeofName.
1627        ScopedSet<std::string> knownLayouts;
1628        /// Set of non-generic types for which the offset array exists in the
1629        /// current scope, indexed by offsetofName.
1630        ScopedSet<std::string> knownOffsets;
1631        /// Namer for VLA (variable length array) buffers.
1632        UniqueName bufNamer;
1633        /// If the argument of an AddressExpr is MemberExpr, it is stored here.
1634        ast::MemberExpr const * addrMember = nullptr;
1635};
1636
1637PolyGenericCalculator::PolyGenericCalculator() :
1638        knownLayouts(), knownOffsets(), bufNamer( "_buf" )
1639{}
1640
1641static ast::Type * polyToMonoTypeRec( CodeLocation const & loc,
1642                ast::Type const * ty ) {
1643        ast::Type * ret;
1644        if ( auto aTy = dynamic_cast<ast::ArrayType const *>( ty ) ) {
1645                // recursive case
1646                auto monoBase = polyToMonoTypeRec( loc, aTy->base );
1647                ret = new ast::ArrayType( monoBase, aTy->dimension,
1648                        aTy->isVarLen, aTy->isStatic, aTy->qualifiers );
1649        } else {
1650                // base case
1651                auto charType = new ast::BasicType( ast::BasicKind::Char );
1652                auto size = new ast::NameExpr( loc,
1653                        sizeofName( Mangle::mangleType( ty ) ) );
1654                ret = new ast::ArrayType( charType, size,
1655                        ast::VariableLen, ast::DynamicDim, ast::CV::Qualifiers() );
1656        }
1657        return ret;
1658}
1659
1660/// Converts polymorphic type into a suitable monomorphic representation.
1661/// Simple cases: T -> __attribute__(( aligned(8) )) char[sizeof_T];
1662/// Array cases: T[eOut][eIn] ->  __attribute__(( aligned(8) )) char[eOut][eIn][sizeof_T];
1663ast::Type * polyToMonoType( CodeLocation const & loc, ast::Type const * ty ) {
1664        auto ret = polyToMonoTypeRec( loc, ty );
1665        ret->attributes.emplace_back( new ast::Attribute( "aligned",
1666                { ast::ConstantExpr::from_int( loc, 8 ) } ) );
1667        return ret;
1668}
1669
1670void PolyGenericCalculator::previsit( ast::FunctionDecl const * decl ) {
1671        GuardScope( *this );
1672        beginTypeScope( decl->type );
1673}
1674
1675void PolyGenericCalculator::previsit( ast::TypedefDecl const * decl ) {
1676        assertf( false, "All typedef declarations should be removed." );
1677        beginTypeScope( decl->base );
1678}
1679
1680void PolyGenericCalculator::previsit( ast::TypeDecl const * decl ) {
1681        addToTypeVarMap( decl, scopeTypeVars );
1682}
1683
1684ast::Decl const * PolyGenericCalculator::postvisit(
1685                ast::TypeDecl const * decl ) {
1686        ast::Type const * base = decl->base;
1687        if ( nullptr == base ) return decl;
1688
1689        // Add size/align variables for opaque type declarations.
1690        ast::TypeInstType inst( decl->name, decl );
1691        std::string typeName = Mangle::mangleType( &inst );
1692
1693        ast::ObjectDecl * sizeDecl = new ast::ObjectDecl( decl->location,
1694                sizeofName( typeName ), makeLayoutCType(),
1695                new ast::SingleInit( decl->location,
1696                        new ast::SizeofExpr( decl->location, deepCopy( base ) )
1697                )
1698        );
1699        ast::ObjectDecl * alignDecl = new ast::ObjectDecl( decl->location,
1700                alignofName( typeName ), makeLayoutCType(),
1701                new ast::SingleInit( decl->location,
1702                        new ast::AlignofExpr( decl->location, deepCopy( base ) )
1703                )
1704        );
1705
1706        // Ensure that the initializing sizeof/alignof exprs are properly mutated.
1707        sizeDecl->accept( *visitor );
1708        alignDecl->accept( *visitor );
1709
1710        // A little trick to replace this with two declarations.
1711        // Adding after makes sure that there is no conflict with adding stmts.
1712        declsToAddAfter.push_back( alignDecl );
1713        return sizeDecl;
1714}
1715
1716ast::StructDecl const * PolyGenericCalculator::previsit(
1717                ast::StructDecl const * decl ) {
1718        auto mutDecl = mutate( decl );
1719        mutateMembers( mutDecl );
1720        return mutDecl;
1721}
1722
1723ast::UnionDecl const * PolyGenericCalculator::previsit(
1724                ast::UnionDecl const * decl ) {
1725        auto mutDecl = mutate( decl );
1726        mutateMembers( mutDecl );
1727        return mutDecl;
1728}
1729
1730ast::DeclStmt const * PolyGenericCalculator::previsit( ast::DeclStmt const * stmt ) {
1731        ast::ObjectDecl const * decl = stmt->decl.as<ast::ObjectDecl>();
1732        if ( !decl || !findGeneric( decl->location, decl->type ) ) {
1733                return stmt;
1734        }
1735
1736        // Change initialization of a polymorphic value object to allocate via a
1737        // variable-length-array (alloca cannot be safely used in loops).
1738        ast::ObjectDecl * newBuf = new ast::ObjectDecl( decl->location,
1739                bufNamer.newName(),
1740                polyToMonoType( decl->location, decl->type ),
1741                nullptr, {}, ast::Linkage::C
1742        );
1743        stmtsToAddBefore.push_back( new ast::DeclStmt( stmt->location, newBuf ) );
1744
1745        // If the object has a cleanup attribute, the clean-up should be on the
1746        // buffer, not the pointer. [Perhaps this should be lifted?]
1747        auto matchAndMove = [newBuf]( ast::ptr<ast::Attribute> & attr ) {
1748                if ( "cleanup" == attr->name ) {
1749                        newBuf->attributes.push_back( attr );
1750                        return true;
1751                }
1752                return false;
1753        };
1754
1755        auto mutDecl = mutate( decl );
1756
1757        // Forally, side effects are not safe in this function. But it works.
1758        erase_if( mutDecl->attributes, matchAndMove );
1759
1760        // Change the decl's type.
1761        // Upon finishing the box pass, it shall be void*.
1762        // At this middle-of-box-pass point, that type is T.
1763
1764        // example 1
1765        // before box:                                  T     t ;
1766        // before here:  char _bufxx    [_sizeof_Y1T];  T     t = _bufxx;
1767        // after here:   char _bufxx    [_sizeof_Y1T];  T     t = _bufxx;  (no change here - non array case)
1768        // after box:    char _bufxx    [_sizeof_Y1T];  void *t = _bufxx;
1769
1770        // example 2
1771        // before box:                                  T     t[42] ;
1772        // before here:  char _bufxx[42][_sizeof_Y1T];  T     t[42] = _bufxx;
1773        // after here:   char _bufxx[42][_sizeof_Y1T];  T     t     = _bufxx;
1774        // after box:    char _bufxx[42][_sizeof_Y1T];  void *t     = _bufxx;
1775
1776        // Strip all "array of" wrappers
1777        while ( auto arrayType = dynamic_cast<ast::ArrayType const *>( mutDecl->type.get() ) ) {
1778                mutDecl->type = arrayType->base;
1779        }
1780
1781        mutDecl->init = new ast::SingleInit( decl->location,
1782                new ast::VariableExpr( decl->location, newBuf ) );
1783
1784        return ast::mutate_field( stmt, &ast::DeclStmt::decl, mutDecl );
1785}
1786
1787/// Checks if memberDecl matches the decl from an aggregate.
1788bool isMember( ast::DeclWithType const * memberDecl, ast::Decl const * decl ) {
1789        // No matter the field, if the name is different it is not the same.
1790        if ( memberDecl->name != decl->name ) {
1791                return false;
1792        }
1793
1794        if ( memberDecl->name.empty() ) {
1795                // Plan-9 Field: Match on unique_id.
1796                return ( memberDecl->uniqueId == decl->uniqueId );
1797        }
1798
1799        ast::DeclWithType const * declWithType =
1800                strict_dynamic_cast<ast::DeclWithType const *>( decl );
1801
1802        if ( memberDecl->mangleName.empty() || declWithType->mangleName.empty() ) {
1803                // Tuple-Element Field: Expect neither had mangled name;
1804                // accept match on simple name (like field_2) only.
1805                assert( memberDecl->mangleName.empty() );
1806                assert( declWithType->mangleName.empty() );
1807                return true;
1808        }
1809
1810        // Ordinary Field: Use full name to accommodate overloading.
1811        return ( memberDecl->mangleName == declWithType->mangleName );
1812}
1813
1814/// Finds the member in the base list that matches the given declaration;
1815/// returns its index, or -1 if not present.
1816long findMember( ast::DeclWithType const * memberDecl,
1817                const ast::vector<ast::Decl> & baseDecls ) {
1818        for ( auto const & [index, value] : enumerate( baseDecls ) ) {
1819                if ( isMember( memberDecl, value.get() ) ) {
1820                        return index;
1821                }
1822        }
1823        return -1;
1824}
1825
1826/// Returns an index expression into the offset array for a type.
1827ast::Expr * makeOffsetIndex( CodeLocation const & location,
1828                ast::Type const * objectType, long i ) {
1829        std::string name = offsetofName( Mangle::mangleType( objectType ) );
1830        return ast::UntypedExpr::createCall( location, "?[?]", {
1831                new ast::NameExpr( location, name ),
1832                ast::ConstantExpr::from_ulong( location, i ),
1833        } );
1834}
1835
1836ast::Expr const * PolyGenericCalculator::postvisit(
1837                ast::MemberExpr const * expr ) {
1838        // Only mutate member expressions for polymorphic types.
1839        ast::Type const * objectType = hasPolyBase(
1840                expr->aggregate->result, scopeTypeVars
1841        );
1842        if ( !objectType ) return expr;
1843        // Ensure layout for this type is available.
1844        // The boolean result is ignored.
1845        findGeneric( expr->location, objectType );
1846
1847        // Replace member expression with dynamically-computed layout expression.
1848        ast::Expr * newMemberExpr = nullptr;
1849        if ( auto structType = dynamic_cast<ast::StructInstType const *>( objectType ) ) {
1850                long offsetIndex = findMember( expr->member, structType->base->members );
1851                if ( -1 == offsetIndex ) return expr;
1852
1853                // Replace member expression with pointer to struct plus offset.
1854                ast::UntypedExpr * fieldLoc = new ast::UntypedExpr( expr->location,
1855                                new ast::NameExpr( expr->location, "?+?" ) );
1856                ast::Expr * aggr = deepCopy( expr->aggregate );
1857                aggr->env = nullptr;
1858                fieldLoc->args.push_back( aggr );
1859                fieldLoc->args.push_back(
1860                        makeOffsetIndex( expr->location, objectType, offsetIndex ) );
1861                fieldLoc->result = deepCopy( expr->result );
1862                newMemberExpr = fieldLoc;
1863        // Union members are all at offset zero, so just use the aggregate expr.
1864        } else if ( dynamic_cast<ast::UnionInstType const *>( objectType ) ) {
1865                ast::Expr * aggr = deepCopy( expr->aggregate );
1866                aggr->env = nullptr;
1867                aggr->result = deepCopy( expr->result );
1868                newMemberExpr = aggr;
1869        } else {
1870                return expr;
1871        }
1872        assert( newMemberExpr );
1873
1874        // Must apply the generic substitution to the member type to handle cases
1875        // where the member is a generic parameter subsituted by a known concrete
1876        // type. [ex]
1877        //      forall( T ) struct Box { T x; }
1878        //      forall( T ) void f() {
1879        //              Box( T * ) b; b.x;
1880        //      }
1881        // TODO: expr->result should be exactly expr->member->get_type() after
1882        // substitution, so it doesn't seem like it should be necessary to apply
1883        // the substitution manually. For some reason this is not currently the
1884        // case. This requires more investigation.
1885        ast::ptr<ast::Type> memberType = deepCopy( expr->member->get_type() );
1886        ast::TypeSubstitution sub = genericSubstitution( objectType );
1887        sub.apply( memberType );
1888
1889        // Not all members of a polymorphic type are themselves of a polymorphic
1890        // type; in this case the member expression should be wrapped and
1891        // dereferenced to form an lvalue.
1892        if ( !isPolyType( memberType, scopeTypeVars ) ) {
1893                auto ptrCastExpr = new ast::CastExpr( expr->location, newMemberExpr,
1894                        new ast::PointerType( memberType ) );
1895                auto derefExpr = ast::UntypedExpr::createDeref( expr->location,
1896                        ptrCastExpr );
1897                newMemberExpr = derefExpr;
1898        }
1899
1900        return newMemberExpr;
1901}
1902
1903void PolyGenericCalculator::previsit( ast::AddressExpr const * expr ) {
1904        GuardValue( addrMember ) = expr->arg.as<ast::MemberExpr>();
1905}
1906
1907ast::Expr const * PolyGenericCalculator::postvisit(
1908                ast::AddressExpr const * expr ) {
1909        // arg has to have been a MemberExpr and has been mutated.
1910        if ( nullptr == addrMember || expr->arg == addrMember ) {
1911                return expr;
1912        }
1913        ast::UntypedExpr const * untyped = expr->arg.as<ast::UntypedExpr>();
1914        if ( !untyped || getFunctionName( untyped ) != "?+?" ) {
1915                return expr;
1916        }
1917        // MemberExpr was converted to pointer + offset; and it is not valid C to
1918        // take the address of an addition, so strip away the address-of.
1919        // It also preserves the env value.
1920        return ast::mutate_field( expr->arg.get(), &ast::Expr::env, expr->env );
1921}
1922
1923ast::Expr const * PolyGenericCalculator::postvisit(
1924                ast::SizeofExpr const * expr ) {
1925        ast::Type const * type = expr->type ? expr->type : expr->expr->result;
1926        ast::Expr const * gen = genSizeof( expr->location, type );
1927        return ( gen ) ? gen : expr;
1928}
1929
1930ast::Expr const * PolyGenericCalculator::postvisit(
1931                ast::AlignofExpr const * expr ) {
1932        ast::Type const * type = expr->type ? expr->type : expr->expr->result;
1933        ast::Expr const * gen = genAlignof( expr->location, type );
1934        return ( gen ) ? gen : expr;
1935}
1936
1937ast::Expr const * PolyGenericCalculator::postvisit(
1938                ast::OffsetofExpr const * expr ) {
1939        ast::Type const * type = expr->type;
1940        if ( !findGeneric( expr->location, type ) ) return expr;
1941
1942        // Structures replace offsetof expression with an index into offset array.
1943        if ( auto structType = dynamic_cast<ast::StructInstType const *>( type ) ) {
1944                long offsetIndex = findMember( expr->member, structType->base->members );
1945                if ( -1 == offsetIndex ) return expr;
1946
1947                return makeOffsetIndex( expr->location, type, offsetIndex );
1948        // All union members are at offset zero.
1949        } else if ( dynamic_cast<ast::UnionInstType const *>( type ) ) {
1950                return ast::ConstantExpr::from_ulong( expr->location, 0 );
1951        } else {
1952                return expr;
1953        }
1954}
1955
1956ast::Expr const * PolyGenericCalculator::postvisit(
1957                ast::OffsetPackExpr const * expr ) {
1958        ast::StructInstType const * type = expr->type;
1959
1960        // Pull offset back from generated type information.
1961        if ( findGeneric( expr->location, type ) ) {
1962                return new ast::NameExpr( expr->location,
1963                        offsetofName( Mangle::mangleType( type ) ) );
1964        }
1965
1966        std::string offsetName = offsetofName( Mangle::mangleType( type ) );
1967        // Use the already generated offsets for this type.
1968        if ( knownOffsets.contains( offsetName ) ) {
1969                return new ast::NameExpr( expr->location, offsetName );
1970        }
1971
1972        knownOffsets.insert( offsetName );
1973
1974        // Build initializer list for offset array.
1975        ast::vector<ast::Init> inits;
1976        for ( ast::ptr<ast::Decl> const & member : type->base->members ) {
1977                auto memberDecl = member.as<ast::DeclWithType>();
1978                assertf( memberDecl, "Requesting offset of non-DWT member: %s",
1979                        toCString( member ) );
1980                inits.push_back( new ast::SingleInit( expr->location,
1981                        new ast::OffsetofExpr( expr->location,
1982                                deepCopy( type ),
1983                                memberDecl
1984                        )
1985                ) );
1986        }
1987
1988        auto offsetArray = makeVar( expr->location, offsetName,
1989                new ast::ArrayType(
1990                        makeLayoutType(),
1991                        ast::ConstantExpr::from_ulong( expr->location, inits.size() ),
1992                        ast::FixedLen,
1993                        ast::DynamicDim
1994                ),
1995                new ast::ListInit( expr->location, std::move( inits ) )
1996        );
1997
1998        return new ast::VariableExpr( expr->location, offsetArray );
1999}
2000
2001void PolyGenericCalculator::beginScope() {
2002        knownLayouts.beginScope();
2003        knownOffsets.beginScope();
2004}
2005
2006void PolyGenericCalculator::endScope() {
2007        knownOffsets.endScope();
2008        knownLayouts.endScope();
2009}
2010
2011ast::ObjectDecl * PolyGenericCalculator::makeVar(
2012                CodeLocation const & location, std::string const & name,
2013                ast::Type const * type, ast::Init const * init ) {
2014        ast::ObjectDecl * ret = new ast::ObjectDecl( location, name, type, init );
2015        stmtsToAddBefore.push_back( new ast::DeclStmt( location, ret ) );
2016        return ret;
2017}
2018
2019/// Returns true if any of the otype parameters have a dynamic layout; and
2020/// puts all otype parameters in the output list.
2021bool findGenericParams(
2022                ast::vector<ast::Type> & out,
2023                ast::vector<ast::TypeDecl> const & baseParams,
2024                ast::vector<ast::Expr> const & typeParams ) {
2025        bool hasDynamicLayout = false;
2026
2027        for ( auto const & [baseParam, typeParam] : group_iterate(
2028                        baseParams, typeParams ) ) {
2029                if ( !baseParam->isComplete() ) continue;
2030                ast::TypeExpr const * typeExpr = typeParam.as<ast::TypeExpr>();
2031                assertf( typeExpr, "All type parameters should be type expressions." );
2032
2033                ast::Type const * type = typeExpr->type.get();
2034                out.push_back( type );
2035                if ( isPolyType( type ) ) hasDynamicLayout = true;
2036        }
2037
2038        return hasDynamicLayout;
2039}
2040
2041bool PolyGenericCalculator::findGeneric(
2042                CodeLocation const & location, ast::Type const * type ) {
2043        type = replaceTypeInst( type, typeSubs );
2044
2045        if ( auto inst = dynamic_cast<ast::TypeInstType const *>( type ) ) {
2046                // Assumes that getting put in the scopeTypeVars includes having the
2047                // layout variables set.
2048                if ( scopeTypeVars.contains( *inst ) ) {
2049                        return true;
2050                }
2051        } else if ( auto inst = dynamic_cast<ast::StructInstType const *>( type ) ) {
2052                // Check if this type already has a layout generated for it.
2053                std::string typeName = Mangle::mangleType( type );
2054                if ( knownLayouts.contains( typeName ) ) return true;
2055
2056                // Check if any type parameters have dynamic layout;
2057                // If none do, this type is (or will be) monomorphized.
2058                ast::vector<ast::Type> sizedParams;
2059                if ( !findGenericParams( sizedParams,
2060                                inst->base->params, inst->params ) ) {
2061                        return false;
2062                }
2063
2064                // Insert local variables for layout and generate call to layout
2065                // function.
2066                // Done early so as not to interfere with the later addition of
2067                // parameters to the layout call.
2068                knownLayouts.insert( typeName );
2069
2070                int memberCount = inst->base->members.size();
2071                if ( 0 == memberCount ) {
2072                        // All empty structures have the same layout (size 1, align 1).
2073                        makeVar( location,
2074                                sizeofName( typeName ), makeLayoutType(),
2075                                new ast::SingleInit( location,
2076                                                ast::ConstantExpr::from_ulong( location, 1 ) ) );
2077                        makeVar( location,
2078                                alignofName( typeName ), makeLayoutType(),
2079                                new ast::SingleInit( location,
2080                                                ast::ConstantExpr::from_ulong( location, 1 ) ) );
2081                        // Since 0-length arrays are forbidden in C, skip the offset array.
2082                } else {
2083                        ast::ObjectDecl const * sizeofVar = makeVar( location,
2084                                sizeofName( typeName ), makeLayoutType(), nullptr );
2085                        ast::ObjectDecl const * alignofVar = makeVar( location,
2086                                alignofName( typeName ), makeLayoutType(), nullptr );
2087                        ast::ObjectDecl const * offsetofVar = makeVar( location,
2088                                offsetofName( typeName ),
2089                                new ast::ArrayType(
2090                                        makeLayoutType(),
2091                                        ast::ConstantExpr::from_int( location, memberCount ),
2092                                        ast::FixedLen,
2093                                        ast::DynamicDim
2094                                ),
2095                                nullptr
2096                        );
2097
2098                        // Generate call to layout function.
2099                        ast::UntypedExpr * layoutCall = new ast::UntypedExpr( location,
2100                                new ast::NameExpr( location, layoutofName( inst->base ) ),
2101                                {
2102                                        new ast::AddressExpr(
2103                                                new ast::VariableExpr( location, sizeofVar ) ),
2104                                        new ast::AddressExpr(
2105                                                new ast::VariableExpr( location, alignofVar ) ),
2106                                        new ast::VariableExpr( location, offsetofVar ),
2107                                } );
2108
2109                        addSTypeParamsToLayoutCall( layoutCall, sizedParams );
2110
2111                        stmtsToAddBefore.emplace_back(
2112                                new ast::ExprStmt( location, layoutCall ) );
2113                }
2114
2115                return true;
2116        } else if ( auto inst = dynamic_cast<ast::UnionInstType const *>( type ) ) {
2117                // Check if this type already has a layout generated for it.
2118                std::string typeName = Mangle::mangleType( type );
2119                if ( knownLayouts.contains( typeName ) ) return true;
2120
2121                // Check if any type parameters have dynamic layout;
2122                // If none do, this type is (or will be) monomorphized.
2123                ast::vector<ast::Type> sizedParams;
2124                if ( !findGenericParams( sizedParams,
2125                                inst->base->params, inst->params ) ) {
2126                        return false;
2127                }
2128
2129                // Insert local variables for layout and generate call to layout
2130                // function.
2131                // Done early so as not to interfere with the later addition of
2132                // parameters to the layout call.
2133                knownLayouts.insert( typeName );
2134
2135                ast::ObjectDecl * sizeofVar = makeVar( location,
2136                        sizeofName( typeName ), makeLayoutType() );
2137                ast::ObjectDecl * alignofVar = makeVar( location,
2138                        alignofName( typeName ), makeLayoutType() );
2139
2140                ast::UntypedExpr * layoutCall = new ast::UntypedExpr( location,
2141                        new ast::NameExpr( location, layoutofName( inst->base ) ),
2142                        {
2143                                new ast::AddressExpr(
2144                                        new ast::VariableExpr( location, sizeofVar ) ),
2145                                new ast::AddressExpr(
2146                                        new ast::VariableExpr( location, alignofVar ) ),
2147                        } );
2148
2149                addSTypeParamsToLayoutCall( layoutCall, sizedParams );
2150
2151                stmtsToAddBefore.emplace_back(
2152                        new ast::ExprStmt( location, layoutCall ) );
2153
2154                return true;
2155
2156        } else if ( auto inst = dynamic_cast<ast::ArrayType const *>( type ) ) {
2157                return findGeneric( location, inst->base );
2158        }
2159        return false;
2160}
2161
2162void PolyGenericCalculator::addSTypeParamsToLayoutCall(
2163                ast::UntypedExpr * layoutCall,
2164                const ast::vector<ast::Type> & otypeParams ) {
2165        CodeLocation const & location = layoutCall->location;
2166        ast::vector<ast::Expr> & args = layoutCall->args;
2167        for ( ast::ptr<ast::Type> const & param : otypeParams ) {
2168                if ( findGeneric( location, param ) ) {
2169                        // Push size/align vars for a generic parameter back.
2170                        std::string paramName = Mangle::mangleType( param );
2171                        args.emplace_back(
2172                                new ast::NameExpr( location, sizeofName( paramName ) ) );
2173                        args.emplace_back(
2174                                new ast::NameExpr( location, alignofName( paramName ) ) );
2175                } else {
2176                        args.emplace_back(
2177                                new ast::SizeofExpr( location, ast::deepCopy( param ) ) );
2178                        args.emplace_back(
2179                                new ast::AlignofExpr( location, ast::deepCopy( param ) ) );
2180                }
2181        }
2182}
2183
2184void PolyGenericCalculator::mutateMembers( ast::AggregateDecl * aggr ) {
2185        std::set<std::string> genericParams;
2186        for ( ast::ptr<ast::TypeDecl> const & decl : aggr->params ) {
2187                genericParams.insert( decl->name );
2188        }
2189        for ( ast::ptr<ast::Decl> & decl : aggr->members ) {
2190                auto field = decl.as<ast::ObjectDecl>();
2191                if ( nullptr == field ) continue;
2192
2193                ast::Type const * type = replaceTypeInst( field->type, typeSubs );
2194                auto typeInst = dynamic_cast<ast::TypeInstType const *>( type );
2195                if ( nullptr == typeInst ) continue;
2196
2197                // Do not try to monoporphize generic parameters.
2198                if ( scopeTypeVars.contains( ast::TypeEnvKey( *typeInst ) ) &&
2199                                !genericParams.count( typeInst->name ) ) {
2200                        // Polymorphic aggregate members should be converted into
2201                        // monomorphic members. Using char[size_T] here respects
2202                        // the expected sizing rules of an aggregate type.
2203                        decl = ast::mutate_field( field, &ast::ObjectDecl::type,
2204                                polyToMonoType( field->location, field->type ) );
2205                }
2206        }
2207}
2208
2209ast::Expr const * PolyGenericCalculator::genSizeof(
2210                CodeLocation const & location, ast::Type const * type ) {
2211        if ( auto * array = dynamic_cast<ast::ArrayType const *>( type ) ) {
2212                // Generate calculated size for possibly generic array.
2213                ast::Expr const * sizeofBase = genSizeof( location, array->base );
2214                if ( nullptr == sizeofBase ) return nullptr;
2215                ast::Expr const * dim = array->dimension;
2216                return makeOp( location, "?*?", sizeofBase, dim );
2217        } else if ( findGeneric( location, type ) ) {
2218                // Generate reference to _sizeof parameter
2219                return new ast::NameExpr( location, sizeofName(
2220                                Mangle::mangleType( type ) ) );
2221        } else {
2222                return nullptr;
2223        }
2224}
2225
2226ast::Expr const * PolyGenericCalculator::genAlignof(
2227                CodeLocation const & location, ast::Type const * type ) {
2228        if ( auto * array = dynamic_cast<ast::ArrayType const *>( type ) ) {
2229                // alignof array is alignof element
2230                return genAlignof( location, array->base );
2231        } else if ( findGeneric( location, type ) ) {
2232                // Generate reference to _alignof parameter
2233                return new ast::NameExpr( location, alignofName(
2234                                Mangle::mangleType( type ) ) );
2235        } else {
2236                return nullptr;
2237        }
2238}
2239
2240void PolyGenericCalculator::beginTypeScope( ast::Type const * type ) {
2241        GuardScope( scopeTypeVars );
2242        makeTypeVarMap( type, scopeTypeVars );
2243}
2244
2245// --------------------------------------------------------------------------
2246/// Removes unneeded or incorrect type information.
2247/// * Replaces initialization of polymorphic values with alloca.
2248/// * Replaces declaration of dtype/ftype with appropriate void expression.
2249/// * Replaces sizeof expressions of polymorphic types with a variable.
2250/// * Strips fields from generic structure declarations.
2251struct Eraser final :
2252                public ast::WithGuards {
2253        void guardTypeVarMap( ast::Type const * type ) {
2254                GuardScope( scopeTypeVars );
2255                makeTypeVarMap( type, scopeTypeVars );
2256        }
2257
2258        ast::ObjectDecl const * previsit( ast::ObjectDecl const * decl );
2259        ast::FunctionDecl const * previsit( ast::FunctionDecl const * decl );
2260        ast::FunctionDecl const * postvisit( ast::FunctionDecl const * decl );
2261        ast::TypedefDecl const * previsit( ast::TypedefDecl const * decl );
2262        ast::StructDecl const * previsit( ast::StructDecl const * decl );
2263        ast::UnionDecl const * previsit( ast::UnionDecl const * decl );
2264        void previsit( ast::TypeDecl const * decl );
2265        void previsit( ast::PointerType const * type );
2266        void previsit( ast::FunctionType const * type );
2267public:
2268        TypeVarMap scopeTypeVars;
2269};
2270
2271ast::ObjectDecl const * Eraser::previsit( ast::ObjectDecl const * decl ) {
2272        guardTypeVarMap( decl->type );
2273        return scrubAllTypeVars( decl );
2274}
2275
2276ast::FunctionDecl const * Eraser::previsit( ast::FunctionDecl const * decl ) {
2277        guardTypeVarMap( decl->type );
2278        return scrubAllTypeVars( decl );
2279}
2280
2281ast::FunctionDecl const * Eraser::postvisit( ast::FunctionDecl const * decl ) {
2282        if ( decl->type_params.empty() ) return decl;
2283        auto mutDecl = mutate( decl );
2284        mutDecl->type_params.clear();
2285        return mutDecl;
2286}
2287
2288ast::TypedefDecl const * Eraser::previsit( ast::TypedefDecl const * decl ) {
2289        guardTypeVarMap( decl->base );
2290        return scrubAllTypeVars( decl );
2291}
2292
2293/// Strips the members from a generic aggregate.
2294template<typename node_t>
2295node_t const * stripGenericMembers( node_t const * decl ) {
2296        if ( decl->params.empty() ) return decl;
2297        auto mutDecl = ast::mutate( decl );
2298        mutDecl->members.clear();
2299        return mutDecl;
2300}
2301
2302ast::StructDecl const * Eraser::previsit( ast::StructDecl const * decl ) {
2303        return stripGenericMembers( decl );
2304}
2305
2306ast::UnionDecl const * Eraser::previsit( ast::UnionDecl const * decl ) {
2307        return stripGenericMembers( decl );
2308}
2309
2310void Eraser::previsit( ast::TypeDecl const * decl ) {
2311        addToTypeVarMap( decl, scopeTypeVars );
2312}
2313
2314void Eraser::previsit( ast::PointerType const * type ) {
2315        guardTypeVarMap( type );
2316}
2317
2318void Eraser::previsit( ast::FunctionType const * type ) {
2319        guardTypeVarMap( type );
2320}
2321
2322} // namespace
2323
2324// --------------------------------------------------------------------------
2325void box( ast::TranslationUnit & translationUnit ) {
2326        ast::Pass<LayoutFunctionBuilder>::run( translationUnit );
2327        ast::Pass<CallAdapter>::run( translationUnit );
2328        ast::Pass<DeclAdapter>::run( translationUnit );
2329        ast::Pass<RewireAdapters>::run( translationUnit );
2330        ast::Pass<PolyGenericCalculator>::run( translationUnit );
2331        ast::Pass<Eraser>::run( translationUnit );
2332}
2333
2334} // namespace GenPoly
2335
2336// Local Variables: //
2337// tab-width: 4 //
2338// mode: c++ //
2339// compile-command: "make install" //
2340// End: //
Note: See TracBrowser for help on using the repository browser.