source: src/Validate/GenericParameter.cpp @ caf06aa

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

Added the check for bitfields in sized polymorphic types. It was folded into a logically related but implimentationally seprate pass.

  • Property mode set to 100644
File size: 10.3 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2018 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// GenericParameter.cpp -- Generic parameter related passes.
8//
9// Author           : Andrew Beach
10// Created On       : Fri Mar 21 10:02:00 2022
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Sep 20 16:28:00 2022
13// Update Count     : 2
14//
15
16#include "GenericParameter.hpp"
17
18#include "AST/Copy.hpp"
19#include "AST/Decl.hpp"
20#include "AST/Expr.hpp"
21#include "AST/ParseNode.hpp"
22#include "AST/Pass.hpp"
23#include "AST/TranslationUnit.hpp"
24#include "AST/Type.hpp"
25#include "Validate/NoIdSymbolTable.hpp"
26
27namespace Validate {
28
29namespace {
30
31// Test for special name on a generic parameter.  Special treatment for the
32// special name is a bootstrapping hack.  In most cases, the worlds of T's
33// and of N's don't overlap (normal treamtemt).  The foundations in
34// array.hfa use tagging for both types and dimensions.  Tagging treats
35// its subject parameter even more opaquely than T&, which assumes it is
36// possible to have a pointer/reference to such an object.  Tagging only
37// seeks to identify the type-system resident at compile time.  Both N's
38// and T's can make tags.  The tag definition uses the special name, which
39// is treated as "an N or a T."  This feature is not inteded to be used
40// outside of the definition and immediate uses of a tag.
41inline bool isReservedTysysIdOnlyName( const std::string & name ) {
42        // The name might be wrapped in __..._generic so check for that as well.
43        int foundAt = name.find("__CFA_tysys_id_only");
44        if (foundAt == 0) return true;
45        if (foundAt == 2 && name[0] == '_' && name[1] == '_') return true;
46        return false;
47}
48
49template< typename InstType >
50const InstType * validateGeneric(
51                const CodeLocation & location, const InstType * type ) {
52        const typename InstType::base_type * base = type->base.get();
53        if ( nullptr == base ) {
54                return type;
55        }
56
57        const std::vector<ast::ptr<ast::TypeDecl>> & params = base->params;
58        if ( params.empty() ) {
59                return type;
60        }
61
62        // I think I can move this check up, or it should check the result of
63        // the substuition.
64
65        auto mutType = ast::mutate( type );
66        std::vector<ast::ptr<ast::Expr>> & args = mutType->params;
67
68        // Quick check before we get into the real work.
69        if ( params.size() < args.size() ) {
70                SemanticError( location, type, "Too many type arguments in generic type " );
71        }
72
73        // Insert defaults arguments when a type argument is missing (currently
74        // only supports missing arguments at the end of the list).
75        // A substitution is used to ensure that defaults are replaced correctly:
76        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
77        //   vector(int) v;
78        // After insertion of default values becomes:
79        //   vector(int, heap_allocator(T))
80        // The substitution is built with T=int so the result is:
81        //   vector(int, heap_allocator(int))
82
83        ast::TypeSubstitution sub;
84        // Build the substution:
85        auto paramIter = params.begin();
86        auto argIter = args.begin();
87        for ( ; paramIter != params.end() ; ++paramIter, ++argIter ) {
88                if ( argIter != args.end() ) {
89                        if ( auto expr = argIter->as<ast::TypeExpr>() ) {
90                                sub.add( paramIter->get(), ast::deepCopy( expr->type ) );
91                        }
92                } else if ( const ast::Type * defaultType = (*paramIter)->init ) {
93                        args.push_back( new ast::TypeExpr(
94                                location, ast::deepCopy( defaultType ) ) );
95                        sub.add( paramIter->get(), ast::deepCopy( defaultType ) );
96                        argIter = std::prev( args.end() );
97                } else {
98                        SemanticError( location, type, "Too few type arguments in generic type " );
99                }
100                assert( argIter != args.end() );
101                bool typeParamDeclared = (*paramIter)->kind != ast::TypeDecl::Dimension;
102                bool typeArgGiven;
103                if ( isReservedTysysIdOnlyName( (*paramIter)->name ) ) {
104                        // Always match when declaration is reserved name, means "either".
105                        typeArgGiven = typeParamDeclared;
106                } else {
107                        typeArgGiven = argIter->as<ast::TypeExpr>();
108                }
109                if ( !typeParamDeclared && typeArgGiven ) {
110                        SemanticError( location, type, "Type argument given for value parameter: " );
111                }
112                if ( typeParamDeclared && !typeArgGiven ) {
113                        SemanticError( location, type, "Expression argument given for type parameter: " );
114                }
115        }
116
117        // Actually do the application:
118        auto result = sub.apply( mutType );
119        return result.node.release();
120}
121
122bool isSizedPolymorphic( const ast::AggregateDecl * decl ) {
123        for ( const auto & param : decl->params ) {
124                if ( param->sized ) return true;
125        }
126        return false;
127}
128
129struct ValidateGenericParamsCore :
130                public ast::WithCodeLocation, public ast::WithGuards {
131        // Generic parameter filling and checks:
132        const ast::StructInstType * previsit( const ast::StructInstType * type ) {
133                assert( location );
134                return validateGeneric( *location, type );
135        }
136
137        const ast::UnionInstType * previsit( const ast::UnionInstType * type ) {
138                assert( location );
139                return validateGeneric( *location, type );
140        }
141
142        // Check parameter and bitfield combinations:
143        bool insideSized = false;
144        void previsit( const ast::StructDecl * decl ) {
145                if ( isSizedPolymorphic( decl ) && !insideSized ) {
146                        GuardValue( insideSized ) = true;
147                }
148        }
149
150        void previsit( const ast::UnionDecl * decl ) {
151                if ( isSizedPolymorphic( decl ) && !insideSized ) {
152                        GuardValue( insideSized ) = true;
153                }
154        }
155
156        void previsit( const ast::ObjectDecl * decl ) {
157                if ( insideSized && decl->bitfieldWidth ) {
158                        SemanticError( decl->location, decl,
159                                "Cannot have bitfields inside a sized polymorphic structure." );
160                }
161        }
162};
163
164// --------------------------------------------------------------------------
165
166struct TranslateDimensionCore :
167                public WithNoIdSymbolTable, public ast::WithGuards {
168
169        // SUIT: Struct- or Union- InstType
170        // Situational awareness:
171        // array( float, [[currentExpr]]     )  has  visitingChildOfSUIT == true
172        // array( float, [[currentExpr]] - 1 )  has  visitingChildOfSUIT == false
173        // size_t x =    [[currentExpr]]        has  visitingChildOfSUIT == false
174        bool nextVisitedNodeIsChildOfSUIT = false;
175        bool visitingChildOfSUIT = false;
176        void changeState_ChildOfSUIT( bool newValue ) {
177                GuardValue( visitingChildOfSUIT ) = nextVisitedNodeIsChildOfSUIT;
178                GuardValue( nextVisitedNodeIsChildOfSUIT ) = newValue;
179        }
180
181        void previsit( const ast::StructInstType * ) {
182                changeState_ChildOfSUIT( true );
183        }
184        void previsit( const ast::UnionInstType * ) {
185                changeState_ChildOfSUIT( true );
186        }
187        void previsit( const ast::Node * ) {
188                changeState_ChildOfSUIT( false );
189        }
190
191        const ast::TypeDecl * postvisit( const ast::TypeDecl * decl );
192        const ast::Expr * postvisit( const ast::DimensionExpr * expr );
193        const ast::Expr * postvisit( const ast::Expr * expr );
194        const ast::Expr * postvisit( const ast::TypeExpr * expr );
195};
196
197const ast::TypeDecl * TranslateDimensionCore::postvisit(
198                const ast::TypeDecl * decl ) {
199        if ( decl->kind == ast::TypeDecl::Dimension ) {
200                auto mutDecl = ast::mutate( decl );
201                mutDecl->kind = ast::TypeDecl::Dtype;
202                if ( !isReservedTysysIdOnlyName( mutDecl->name ) ) {
203                        mutDecl->sized = true;
204                }
205                return mutDecl;
206        }
207        return decl;
208}
209
210// Passing values as dimension arguments:  array( float,     7 )  -> array( float, char[             7 ] )
211// Consuming dimension parameters:         size_t x =    N - 1 ;  -> size_t x =          sizeof(N) - 1   ;
212// Intertwined reality:                    array( float, N     )  -> array( float,              N        )
213//                                         array( float, N - 1 )  -> array( float, char[ sizeof(N) - 1 ] )
214// Intertwined case 1 is not just an optimization.
215// Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in:
216//   forall([N]) void f( array(float, N) & );
217//   array(float, 7) a;
218//   f(a);
219const ast::Expr * TranslateDimensionCore::postvisit(
220                const ast::DimensionExpr * expr ) {
221        // Expression `expr` is an occurrence of N in LHS of above examples.
222        // Look up the name that `expr` references.
223        // If we are in a struct body, then this reference can be to an entry of
224        // the stuct's forall list.
225        // Whether or not we are in a struct body, this reference can be to an
226        // entry of a containing function's forall list.
227        // If we are in a struct body, then the stuct's forall declarations are
228        // innermost (functions don't occur in structs).
229        // Thus, a potential struct's declaration is highest priority.
230        // A struct's forall declarations are already renamed with _generic_ suffix.
231        // Try that name variant first.
232
233        std::string useName = "__" + expr->name + "_generic_";
234        ast::TypeDecl * namedParamDecl = const_cast<ast::TypeDecl *>(
235                strict_dynamic_cast<const ast::TypeDecl *, nullptr >(
236                        symtab.lookupType( useName ) ) );
237
238        if ( !namedParamDecl ) {
239                useName = expr->name;
240                namedParamDecl = const_cast<ast::TypeDecl *>( strict_dynamic_cast<const ast::TypeDecl *, nullptr >( symtab.lookupType( useName ) ) );
241        }
242
243        // Expect to find it always.
244        // A misspelled name would have been parsed as an identifier.
245        assertf( namedParamDecl, "Type-system-managed value name not found in symbol table" );
246
247        auto * refToDecl = new ast::TypeInstType( useName, namedParamDecl );
248
249        if ( visitingChildOfSUIT ) {
250                // As in postvisit( Expr * ), topmost expression needs a TypeExpr
251                // wrapper. But avoid ArrayType-Sizeof.
252                return new ast::TypeExpr( expr->location, refToDecl );
253        } else {
254                // the N occurrence is being used directly as a runtime value,
255                // if we are in a type instantiation, then the N is within a bigger value computation
256                return new ast::SizeofExpr( expr->location, refToDecl );
257        }
258}
259
260const ast::Expr * TranslateDimensionCore::postvisit(
261                const ast::Expr * expr ) {
262        // This expression is used as an argument to instantiate a type.
263        if ( visitingChildOfSUIT ) {
264                // DimensionExpr and TypeExpr should not reach here.
265                return new ast::TypeExpr( expr->location,
266                        new ast::ArrayType(
267                                new ast::BasicType( ast::BasicType::Char ),
268                                expr,
269                                ast::VariableLen,
270                                ast::DynamicDim
271                        )
272                );
273        }
274        return expr;
275}
276
277const ast::Expr * TranslateDimensionCore::postvisit(
278                const ast::TypeExpr * expr ) {
279        // Does nothing, except prevents matching ast::Expr (above).
280        return expr;
281}
282
283} // namespace
284
285void fillGenericParameters( ast::TranslationUnit & translationUnit ) {
286        ast::Pass<ValidateGenericParamsCore>::run( translationUnit );
287}
288
289void translateDimensionParameters( ast::TranslationUnit & translationUnit ) {
290        ast::Pass<TranslateDimensionCore>::run( translationUnit );
291}
292
293} // namespace Validate
294
295// Local Variables: //
296// tab-width: 4 //
297// mode: c++ //
298// compile-command: "make install" //
299// End: //
Note: See TracBrowser for help on using the repository browser.