source: src/GenPoly/Box.cc@ 46f6134

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors ctor deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 46f6134 was f18a711, checked in by Aaron Moss <a3moss@…>, 9 years ago

Fix bug in replacing dtype-only generics with stripped versions

  • Property mode set to 100644
File size: 96.4 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.cc --
8//
9// Author : Richard C. Bilson
10// Created On : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Wed Jun 29 21:43:03 2016
13// Update Count : 296
14//
15
16#include <algorithm>
17#include <iterator>
18#include <list>
19#include <map>
20#include <set>
21#include <stack>
22#include <string>
23#include <utility>
24#include <vector>
25#include <cassert>
26
27#include "Box.h"
28#include "DeclMutator.h"
29#include "PolyMutator.h"
30#include "FindFunction.h"
31#include "ScopedMap.h"
32#include "ScopedSet.h"
33#include "ScrubTyVars.h"
34
35#include "Parser/ParseNode.h"
36
37#include "SynTree/Constant.h"
38#include "SynTree/Declaration.h"
39#include "SynTree/Expression.h"
40#include "SynTree/Initializer.h"
41#include "SynTree/Mutator.h"
42#include "SynTree/Statement.h"
43#include "SynTree/Type.h"
44#include "SynTree/TypeSubstitution.h"
45
46#include "ResolvExpr/TypeEnvironment.h"
47#include "ResolvExpr/TypeMap.h"
48#include "ResolvExpr/typeops.h"
49
50#include "SymTab/Indexer.h"
51#include "SymTab/Mangler.h"
52
53#include "Common/SemanticError.h"
54#include "Common/UniqueName.h"
55#include "Common/utility.h"
56
57#include <ext/functional> // temporary
58
59namespace GenPoly {
60 namespace {
61 const std::list<Label> noLabels;
62
63 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
64
65 /// Adds layout-generation functions to polymorphic types
66 class LayoutFunctionBuilder : public DeclMutator {
67 unsigned int functionNesting; // current level of nested functions
68 public:
69 LayoutFunctionBuilder() : functionNesting( 0 ) {}
70
71 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
72 virtual Declaration *mutate( StructDecl *structDecl );
73 virtual Declaration *mutate( UnionDecl *unionDecl );
74 };
75
76 /// Replaces polymorphic return types with out-parameters, replaces calls to polymorphic functions with adapter calls as needed, and adds appropriate type variables to the function call
77 class Pass1 : public PolyMutator {
78 public:
79 Pass1();
80 virtual Expression *mutate( ApplicationExpr *appExpr );
81 virtual Expression *mutate( AddressExpr *addrExpr );
82 virtual Expression *mutate( UntypedExpr *expr );
83 virtual DeclarationWithType* mutate( FunctionDecl *functionDecl );
84 virtual TypeDecl *mutate( TypeDecl *typeDecl );
85 virtual Expression *mutate( CommaExpr *commaExpr );
86 virtual Expression *mutate( ConditionalExpr *condExpr );
87 virtual Statement * mutate( ReturnStmt *returnStmt );
88 virtual Type *mutate( PointerType *pointerType );
89 virtual Type * mutate( FunctionType *functionType );
90
91 virtual void doBeginScope();
92 virtual void doEndScope();
93 private:
94 /// Pass the extra type parameters from polymorphic generic arguments or return types into a function application
95 void passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes );
96 /// passes extra type parameters into a polymorphic function application
97 void passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
98 /// wraps a function application with a new temporary for the out-parameter return value
99 Expression *addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg );
100 /// Replaces all the type parameters of a generic type with their concrete equivalents under the current environment
101 void replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params );
102 /// Replaces a polymorphic type with its concrete equivalant under the current environment (returns itself if concrete).
103 /// If `doClone` is set to false, will not clone interior types
104 Type *replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone = true );
105 /// wraps a function application returning a polymorphic type with a new temporary for the out-parameter return value
106 Expression *addDynRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg );
107 Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
108 void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
109 void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
110 void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
111 /// Stores assignment operators from assertion list in local map of assignment operations
112 void findTypeOps( const std::list< TypeDecl *> &forall );
113 void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
114 FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
115 /// Replaces intrinsic operator functions with their arithmetic desugaring
116 Expression *handleIntrinsics( ApplicationExpr *appExpr );
117 /// Inserts a new temporary variable into the current scope with an auto-generated name
118 ObjectDecl *makeTemporary( Type *type );
119
120 ScopedMap< std::string, DeclarationWithType* > assignOps; ///< Currently known type variable assignment operators
121 ScopedMap< std::string, DeclarationWithType* > ctorOps; ///< Currently known type variable constructors
122 ScopedMap< std::string, DeclarationWithType* > copyOps; ///< Currently known type variable copy constructors
123 ScopedMap< std::string, DeclarationWithType* > dtorOps; ///< Currently known type variable destructors
124 ResolvExpr::TypeMap< DeclarationWithType > scopedAssignOps; ///< Currently known assignment operators
125 ResolvExpr::TypeMap< DeclarationWithType > scopedCtorOps; ///< Currently known assignment operators
126 ResolvExpr::TypeMap< DeclarationWithType > scopedCopyOps; ///< Currently known assignment operators
127 ResolvExpr::TypeMap< DeclarationWithType > scopedDtorOps; ///< Currently known assignment operators
128 ScopedMap< std::string, DeclarationWithType* > adapters; ///< Set of adapter functions in the current scope
129
130 DeclarationWithType *retval;
131 bool useRetval;
132 UniqueName tempNamer;
133 };
134
135 /// * Moves polymorphic returns in function types to pointer-type parameters
136 /// * adds type size and assertion parameters to parameter lists
137 class Pass2 : public PolyMutator {
138 public:
139 template< typename DeclClass >
140 DeclClass *handleDecl( DeclClass *decl, Type *type );
141 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
142 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
143 virtual TypeDecl *mutate( TypeDecl *typeDecl );
144 virtual TypedefDecl *mutate( TypedefDecl *typedefDecl );
145 virtual Type *mutate( PointerType *pointerType );
146 virtual Type *mutate( FunctionType *funcType );
147
148 private:
149 void addAdapters( FunctionType *functionType );
150
151 std::map< UniqueId, std::string > adapterName;
152 };
153
154 /// Replaces member and size/align/offsetof expressions on polymorphic generic types with calculated expressions.
155 /// * Replaces member expressions for polymorphic types with calculated add-field-offset-and-dereference
156 /// * Calculates polymorphic offsetof expressions from offset array
157 /// * Inserts dynamic calculation of polymorphic type layouts where needed
158 class PolyGenericCalculator : public PolyMutator {
159 public:
160 template< typename DeclClass >
161 DeclClass *handleDecl( DeclClass *decl, Type *type );
162 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
163 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
164 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
165 virtual TypeDecl *mutate( TypeDecl *objectDecl );
166 virtual Statement *mutate( DeclStmt *declStmt );
167 virtual Type *mutate( PointerType *pointerType );
168 virtual Type *mutate( FunctionType *funcType );
169 virtual Expression *mutate( MemberExpr *memberExpr );
170 virtual Expression *mutate( SizeofExpr *sizeofExpr );
171 virtual Expression *mutate( AlignofExpr *alignofExpr );
172 virtual Expression *mutate( OffsetofExpr *offsetofExpr );
173 virtual Expression *mutate( OffsetPackExpr *offsetPackExpr );
174
175 virtual void doBeginScope();
176 virtual void doEndScope();
177
178 private:
179 /// Makes a new variable in the current scope with the given name, type & optional initializer
180 ObjectDecl *makeVar( const std::string &name, Type *type, Initializer *init = 0 );
181 /// returns true if the type has a dynamic layout; such a layout will be stored in appropriately-named local variables when the function returns
182 bool findGeneric( Type *ty );
183 /// adds type parameters to the layout call; will generate the appropriate parameters if needed
184 void addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams );
185
186 /// Enters a new scope for type-variables, adding the type variables from ty
187 void beginTypeScope( Type *ty );
188 /// Exits the type-variable scope
189 void endTypeScope();
190
191 ScopedSet< std::string > knownLayouts; ///< Set of generic type layouts known in the current scope, indexed by sizeofName
192 ScopedSet< std::string > knownOffsets; ///< Set of non-generic types for which the offset array exists in the current scope, indexed by offsetofName
193 };
194
195 /// Replaces initialization of polymorphic values with alloca, declaration of dtype/ftype with appropriate void expression, and sizeof expressions of polymorphic types with the proper variable
196 class Pass3 : public PolyMutator {
197 public:
198 template< typename DeclClass >
199 DeclClass *handleDecl( DeclClass *decl, Type *type );
200 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
201 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
202 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
203 virtual TypeDecl *mutate( TypeDecl *objectDecl );
204 virtual Type *mutate( PointerType *pointerType );
205 virtual Type *mutate( FunctionType *funcType );
206 private:
207 };
208
209 } // anonymous namespace
210
211 /// version of mutateAll with special handling for translation unit so you can check the end of the prelude when debugging
212 template< typename MutatorType >
213 inline void mutateTranslationUnit( std::list< Declaration* > &translationUnit, MutatorType &mutator ) {
214 bool seenIntrinsic = false;
215 SemanticError errors;
216 for ( typename std::list< Declaration* >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
217 try {
218 if ( *i ) {
219 if ( (*i)->get_linkage() == LinkageSpec::Intrinsic ) {
220 seenIntrinsic = true;
221 } else if ( seenIntrinsic ) {
222 seenIntrinsic = false; // break on this line when debugging for end of prelude
223 }
224
225 *i = dynamic_cast< Declaration* >( (*i)->acceptMutator( mutator ) );
226 assert( *i );
227 } // if
228 } catch( SemanticError &e ) {
229 errors.append( e );
230 } // try
231 } // for
232 if ( ! errors.isEmpty() ) {
233 throw errors;
234 } // if
235 }
236
237 void box( std::list< Declaration *>& translationUnit ) {
238 LayoutFunctionBuilder layoutBuilder;
239 Pass1 pass1;
240 Pass2 pass2;
241 PolyGenericCalculator polyCalculator;
242 Pass3 pass3;
243
244 layoutBuilder.mutateDeclarationList( translationUnit );
245 mutateTranslationUnit/*All*/( translationUnit, pass1 );
246 mutateTranslationUnit/*All*/( translationUnit, pass2 );
247 mutateTranslationUnit/*All*/( translationUnit, polyCalculator );
248 mutateTranslationUnit/*All*/( translationUnit, pass3 );
249 }
250
251 ////////////////////////////////// LayoutFunctionBuilder ////////////////////////////////////////////
252
253 DeclarationWithType *LayoutFunctionBuilder::mutate( FunctionDecl *functionDecl ) {
254 functionDecl->set_functionType( maybeMutate( functionDecl->get_functionType(), *this ) );
255 mutateAll( functionDecl->get_oldDecls(), *this );
256 ++functionNesting;
257 functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
258 --functionNesting;
259 return functionDecl;
260 }
261
262 /// Get a list of type declarations that will affect a layout function
263 std::list< TypeDecl* > takeOtypeOnly( std::list< TypeDecl* > &decls ) {
264 std::list< TypeDecl * > otypeDecls;
265
266 for ( std::list< TypeDecl* >::const_iterator decl = decls.begin(); decl != decls.end(); ++decl ) {
267 if ( (*decl)->get_kind() == TypeDecl::Any ) {
268 otypeDecls.push_back( *decl );
269 }
270 }
271
272 return otypeDecls;
273 }
274
275 /// Adds parameters for otype layout to a function type
276 void addOtypeParams( FunctionType *layoutFnType, std::list< TypeDecl* > &otypeParams ) {
277 BasicType sizeAlignType( Type::Qualifiers(), BasicType::LongUnsignedInt );
278
279 for ( std::list< TypeDecl* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
280 TypeInstType paramType( Type::Qualifiers(), (*param)->get_name(), *param );
281 std::string paramName = mangleType( &paramType );
282 layoutFnType->get_parameters().push_back( new ObjectDecl( sizeofName( paramName ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
283 layoutFnType->get_parameters().push_back( new ObjectDecl( alignofName( paramName ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
284 }
285 }
286
287 /// Builds a layout function declaration
288 FunctionDecl *buildLayoutFunctionDecl( AggregateDecl *typeDecl, unsigned int functionNesting, FunctionType *layoutFnType ) {
289 // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
290 // because each unit generates copies of the default routines for each aggregate.
291 FunctionDecl *layoutDecl = new FunctionDecl(
292 layoutofName( typeDecl ), functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, layoutFnType, new CompoundStmt( noLabels ), true, false );
293 layoutDecl->fixUniqueId();
294 return layoutDecl;
295 }
296
297 /// Makes a unary operation
298 Expression *makeOp( const std::string &name, Expression *arg ) {
299 UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
300 expr->get_args().push_back( arg );
301 return expr;
302 }
303
304 /// Makes a binary operation
305 Expression *makeOp( const std::string &name, Expression *lhs, Expression *rhs ) {
306 UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
307 expr->get_args().push_back( lhs );
308 expr->get_args().push_back( rhs );
309 return expr;
310 }
311
312 /// Returns the dereference of a local pointer variable
313 Expression *derefVar( ObjectDecl *var ) {
314 return makeOp( "*?", new VariableExpr( var ) );
315 }
316
317 /// makes an if-statement with a single-expression if-block and no then block
318 Statement *makeCond( Expression *cond, Expression *ifPart ) {
319 return new IfStmt( noLabels, cond, new ExprStmt( noLabels, ifPart ), 0 );
320 }
321
322 /// makes a statement that assigns rhs to lhs if lhs < rhs
323 Statement *makeAssignMax( Expression *lhs, Expression *rhs ) {
324 return makeCond( makeOp( "?<?", lhs, rhs ), makeOp( "?=?", lhs->clone(), rhs->clone() ) );
325 }
326
327 /// makes a statement that aligns lhs to rhs (rhs should be an integer power of two)
328 Statement *makeAlignTo( Expression *lhs, Expression *rhs ) {
329 // check that the lhs is zeroed out to the level of rhs
330 Expression *ifCond = makeOp( "?&?", lhs, makeOp( "?-?", rhs, new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), "1" ) ) ) );
331 // if not aligned, increment to alignment
332 Expression *ifExpr = makeOp( "?+=?", lhs->clone(), makeOp( "?-?", rhs->clone(), ifCond->clone() ) );
333 return makeCond( ifCond, ifExpr );
334 }
335
336 /// adds an expression to a compound statement
337 void addExpr( CompoundStmt *stmts, Expression *expr ) {
338 stmts->get_kids().push_back( new ExprStmt( noLabels, expr ) );
339 }
340
341 /// adds a statement to a compound statement
342 void addStmt( CompoundStmt *stmts, Statement *stmt ) {
343 stmts->get_kids().push_back( stmt );
344 }
345
346 Declaration *LayoutFunctionBuilder::mutate( StructDecl *structDecl ) {
347 // do not generate layout function for "empty" tag structs
348 if ( structDecl->get_members().empty() ) return structDecl;
349
350 // get parameters that can change layout, exiting early if none
351 std::list< TypeDecl* > otypeParams = takeOtypeOnly( structDecl->get_parameters() );
352 if ( otypeParams.empty() ) return structDecl;
353
354 // build layout function signature
355 FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
356 BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
357 PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
358
359 ObjectDecl *sizeParam = new ObjectDecl( sizeofName( structDecl->get_name() ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
360 layoutFnType->get_parameters().push_back( sizeParam );
361 ObjectDecl *alignParam = new ObjectDecl( alignofName( structDecl->get_name() ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
362 layoutFnType->get_parameters().push_back( alignParam );
363 ObjectDecl *offsetParam = new ObjectDecl( offsetofName( structDecl->get_name() ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
364 layoutFnType->get_parameters().push_back( offsetParam );
365 addOtypeParams( layoutFnType, otypeParams );
366
367 // build function decl
368 FunctionDecl *layoutDecl = buildLayoutFunctionDecl( structDecl, functionNesting, layoutFnType );
369
370 // calculate struct layout in function body
371
372 // initialize size and alignment to 0 and 1 (will have at least one member to re-edit size
373 addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "0" ) ) ) );
374 addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
375 unsigned long n_members = 0;
376 bool firstMember = true;
377 for ( std::list< Declaration* >::const_iterator member = structDecl->get_members().begin(); member != structDecl->get_members().end(); ++member ) {
378 DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
379 assert( dwt );
380 Type *memberType = dwt->get_type();
381
382 if ( firstMember ) {
383 firstMember = false;
384 } else {
385 // make sure all members after the first (automatically aligned at 0) are properly padded for alignment
386 addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), new AlignofExpr( memberType->clone() ) ) );
387 }
388
389 // place current size in the current offset index
390 addExpr( layoutDecl->get_statements(), makeOp( "?=?", makeOp( "?[?]", new VariableExpr( offsetParam ), new ConstantExpr( Constant::from_ulong( n_members ) ) ),
391 derefVar( sizeParam ) ) );
392 ++n_members;
393
394 // add member size to current size
395 addExpr( layoutDecl->get_statements(), makeOp( "?+=?", derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
396
397 // take max of member alignment and global alignment
398 addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
399 }
400 // make sure the type is end-padded to a multiple of its alignment
401 addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
402
403 addDeclarationAfter( layoutDecl );
404 return structDecl;
405 }
406
407 Declaration *LayoutFunctionBuilder::mutate( UnionDecl *unionDecl ) {
408 // do not generate layout function for "empty" tag unions
409 if ( unionDecl->get_members().empty() ) return unionDecl;
410
411 // get parameters that can change layout, exiting early if none
412 std::list< TypeDecl* > otypeParams = takeOtypeOnly( unionDecl->get_parameters() );
413 if ( otypeParams.empty() ) return unionDecl;
414
415 // build layout function signature
416 FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
417 BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
418 PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
419
420 ObjectDecl *sizeParam = new ObjectDecl( sizeofName( unionDecl->get_name() ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
421 layoutFnType->get_parameters().push_back( sizeParam );
422 ObjectDecl *alignParam = new ObjectDecl( alignofName( unionDecl->get_name() ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
423 layoutFnType->get_parameters().push_back( alignParam );
424 addOtypeParams( layoutFnType, otypeParams );
425
426 // build function decl
427 FunctionDecl *layoutDecl = buildLayoutFunctionDecl( unionDecl, functionNesting, layoutFnType );
428
429 // calculate union layout in function body
430 addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
431 addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
432 for ( std::list< Declaration* >::const_iterator member = unionDecl->get_members().begin(); member != unionDecl->get_members().end(); ++member ) {
433 DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
434 assert( dwt );
435 Type *memberType = dwt->get_type();
436
437 // take max member size and global size
438 addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
439
440 // take max of member alignment and global alignment
441 addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
442 }
443 // make sure the type is end-padded to a multiple of its alignment
444 addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
445
446 addDeclarationAfter( layoutDecl );
447 return unionDecl;
448 }
449
450 ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
451
452 namespace {
453 std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
454 std::stringstream name;
455
456 // NOTE: this function previously used isPolyObj, which failed to produce
457 // the correct thing in some situations. It's not clear to me why this wasn't working.
458
459 // if the return type or a parameter type involved polymorphic types, then the adapter will need
460 // to take those polymorphic types as pointers. Therefore, there can be two different functions
461 // with the same mangled name, so we need to further mangle the names.
462 for ( std::list< DeclarationWithType *>::iterator retval = function->get_returnVals().begin(); retval != function->get_returnVals().end(); ++retval ) {
463 if ( isPolyType( (*retval)->get_type(), tyVars ) ) {
464 name << "P";
465 } else {
466 name << "M";
467 }
468 }
469 name << "_";
470 std::list< DeclarationWithType *> &paramList = function->get_parameters();
471 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
472 if ( isPolyType( (*arg)->get_type(), tyVars ) ) {
473 name << "P";
474 } else {
475 name << "M";
476 }
477 } // for
478 return name.str();
479 }
480
481 std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
482 return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
483 }
484
485 std::string makeAdapterName( const std::string &mangleName ) {
486 return "_adapter" + mangleName;
487 }
488
489 Pass1::Pass1() : useRetval( false ), tempNamer( "_temp" ) {}
490
491 /// Returns T if the given declaration is a function with parameter (T*) for some TypeInstType T, NULL otherwise
492 TypeInstType *isTypeInstPtrFn( DeclarationWithType *decl ) {
493 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
494 if ( funType->get_parameters().size() == 1 ) {
495 if ( PointerType *pointer = dynamic_cast< PointerType *>( funType->get_parameters().front()->get_type() ) ) {
496 if ( TypeInstType *refType = dynamic_cast< TypeInstType *>( pointer->get_base() ) ) {
497 return refType;
498 } // if
499 } // if
500 } // if
501 } // if
502 return 0;
503 }
504
505 /// Returns T if the given declaration is a function with parameters (T*, T) for some TypeInstType T, NULL otherwise
506 TypeInstType *isTypeInstPtrValFn( DeclarationWithType *decl ) {
507 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
508 if ( funType->get_parameters().size() == 2 ) {
509 if ( PointerType *pointer = dynamic_cast< PointerType *>( funType->get_parameters().front()->get_type() ) ) {
510 if ( TypeInstType *refType = dynamic_cast< TypeInstType *>( pointer->get_base() ) ) {
511 if ( TypeInstType *refType2 = dynamic_cast< TypeInstType *>( funType->get_parameters().back()->get_type() ) ) {
512 if ( refType->get_name() == refType2->get_name() ) {
513 return refType;
514 } // if
515 } // if
516 } // if
517 } // if
518 } // if
519 } // if
520 return 0;
521 }
522
523 /// Returns T if the given declaration is (*?=?)(T *, T) for some TypeInstType T (return not checked, but maybe should be), NULL otherwise
524 TypeInstType *isTypeInstAssignment( DeclarationWithType *decl ) {
525 return decl->get_name() == "?=?" ? isTypeInstPtrValFn( decl ) : 0;
526 }
527
528 /// Returns T if the given declaration is (*?{})(T *) for some TypeInstType T (return not checked, but maybe should be), NULL otherwise
529 TypeInstType *isTypeInstCtor( DeclarationWithType *decl ) {
530 return decl->get_name() == "?{}" ? isTypeInstPtrFn( decl ) : 0;
531 }
532
533 /// Returns T if the given declaration is (*?{})(T *, T) for some TypeInstType T (return not checked, but maybe should be), NULL otherwise
534 TypeInstType *isTypeInstCopy( DeclarationWithType *decl ) {
535 return decl->get_name() == "?{}" ? isTypeInstPtrValFn( decl ) : 0;
536 }
537
538 /// Returns T if the given declaration is (*^?{})(T *) for some TypeInstType T (return not checked, but maybe should be), NULL otherwise
539 TypeInstType *isTypeInstDtor( DeclarationWithType *decl ) {
540 return decl->get_name() == "^?{}" ? isTypeInstPtrFn( decl ) : 0;
541 }
542
543 /// Returns T if the given declaration is a function with parameters (T*, T) for some type T, where neither parameter is cv-qualified,
544 /// NULL otherwise
545 Type *isNoCvPtrFn( DeclarationWithType *decl ) {
546 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
547 if ( funType->get_parameters().size() == 1 ) {
548 Type::Qualifiers defaultQualifiers;
549 Type *paramType = funType->get_parameters().front()->get_type();
550 if ( paramType->get_qualifiers() != defaultQualifiers ) return 0;
551
552 if ( PointerType *pointerType = dynamic_cast< PointerType* >( paramType ) ) {
553 Type *baseType = pointerType->get_base();
554 if ( baseType->get_qualifiers() == defaultQualifiers ) {
555 return baseType;
556 } // if
557 } // if
558 } // if
559 } // if
560 return 0;
561 }
562
563 /// Returns T if the given declaration is a function with parameters (T*, T) for some type T, where neither parameter is cv-qualified,
564 /// NULL otherwise
565 Type *isNoCvPtrValFn( DeclarationWithType *decl ) {
566 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
567 if ( funType->get_parameters().size() == 2 ) {
568 Type::Qualifiers defaultQualifiers;
569 Type *paramType1 = funType->get_parameters().front()->get_type();
570 if ( paramType1->get_qualifiers() != defaultQualifiers ) return 0;
571 Type *paramType2 = funType->get_parameters().back()->get_type();
572 if ( paramType2->get_qualifiers() != defaultQualifiers ) return 0;
573
574 if ( PointerType *pointerType = dynamic_cast< PointerType* >( paramType1 ) ) {
575 Type *baseType1 = pointerType->get_base();
576 if ( baseType1->get_qualifiers() != defaultQualifiers ) return 0;
577 SymTab::Indexer dummy;
578 if ( ResolvExpr::typesCompatible( baseType1, paramType2, dummy ) ) {
579 return baseType1;
580 } // if
581 } // if
582 } // if
583 } // if
584 return 0;
585 }
586
587 /// returns T if the given declaration is: (*?=?)(T *, T) for some type T (return not checked, but maybe should be), NULL otherwise
588 /// Only picks assignments where neither parameter is cv-qualified
589 Type *isAssignment( DeclarationWithType *decl ) {
590 return decl->get_name() == "?=?" ? isNoCvPtrValFn( decl ) : 0;
591 }
592
593 /// returns T if the given declaration is: (*?{})(T *) for some type T, NULL otherwise
594 /// Only picks ctors where the parameter is not cv-qualified
595 Type *isCtor( DeclarationWithType *decl ) {
596 return decl->get_name() == "?{}" ? isNoCvPtrFn( decl ) : 0;
597 }
598
599 /// returns T if the given declaration is: (*?{})(T *, T) for some type T (return not checked, but maybe should be), NULL otherwise
600 /// Only picks copy constructors where neither parameter is cv-qualified
601 Type *isCopy( DeclarationWithType *decl ) {
602 return decl->get_name() == "?{}" ? isNoCvPtrValFn( decl ) : 0;
603 }
604
605 /// returns T if the given declaration is: (*?{})(T *) for some type T, NULL otherwise
606 /// Only picks ctors where the parameter is not cv-qualified
607 Type *isDtor( DeclarationWithType *decl ) {
608 return decl->get_name() == "^?{}" ? isNoCvPtrFn( decl ) : 0;
609 }
610
611 void Pass1::findTypeOps( const std::list< TypeDecl *> &forall ) {
612 // what if a nested function uses an assignment operator?
613 // assignOps.clear();
614 for ( std::list< TypeDecl *>::const_iterator i = forall.begin(); i != forall.end(); ++i ) {
615 for ( std::list< DeclarationWithType *>::const_iterator assert = (*i)->get_assertions().begin(); assert != (*i)->get_assertions().end(); ++assert ) {
616 std::string typeName;
617 if ( TypeInstType *typeInst = isTypeInstAssignment( *assert ) ) {
618 assignOps[ typeInst->get_name() ] = *assert;
619 } else if ( TypeInstType *typeInst = isTypeInstCtor( *assert ) ) {
620 ctorOps[ typeInst->get_name() ] = *assert;
621 } else if ( TypeInstType *typeInst = isTypeInstCopy( *assert ) ) {
622 copyOps[ typeInst->get_name() ] = *assert;
623 } else if ( TypeInstType *typeInst = isTypeInstDtor( *assert ) ) {
624 dtorOps[ typeInst->get_name() ] = *assert;
625 } // if
626 } // for
627 } // for
628 }
629
630 DeclarationWithType *Pass1::mutate( FunctionDecl *functionDecl ) {
631 // if this is a assignment function, put it in the map for this scope
632 if ( Type *paramType = isAssignment( functionDecl ) ) {
633 if ( ! dynamic_cast< TypeInstType* >( paramType ) ) {
634 scopedAssignOps.insert( paramType, functionDecl );
635 }
636 } else if ( Type *paramType = isCtor( functionDecl ) ) {
637 if ( ! dynamic_cast< TypeInstType* >( paramType ) ) {
638 scopedCtorOps.insert( paramType, functionDecl );
639 }
640 } else if ( Type *paramType = isCopy( functionDecl ) ) {
641 if ( ! dynamic_cast< TypeInstType* >( paramType ) ) {
642 scopedCopyOps.insert( paramType, functionDecl );
643 }
644 } else if ( Type *paramType = isDtor( functionDecl ) ) {
645 if ( ! dynamic_cast< TypeInstType* >( paramType ) ) {
646 scopedDtorOps.insert( paramType, functionDecl );
647 }
648 }
649
650 if ( functionDecl->get_statements() ) { // empty routine body ?
651 doBeginScope();
652 scopeTyVars.beginScope();
653 assignOps.beginScope();
654 ctorOps.beginScope();
655 copyOps.beginScope();
656 dtorOps.beginScope();
657
658 DeclarationWithType *oldRetval = retval;
659 bool oldUseRetval = useRetval;
660
661 // process polymorphic return value
662 retval = 0;
663 if ( isDynRet( functionDecl->get_functionType() ) && functionDecl->get_linkage() == LinkageSpec::Cforall ) {
664 retval = functionDecl->get_functionType()->get_returnVals().front();
665
666 // give names to unnamed return values
667 if ( retval->get_name() == "" ) {
668 retval->set_name( "_retparm" );
669 retval->set_linkage( LinkageSpec::C );
670 } // if
671 } // if
672
673 FunctionType *functionType = functionDecl->get_functionType();
674 makeTyVarMap( functionDecl->get_functionType(), scopeTyVars );
675 findTypeOps( functionDecl->get_functionType()->get_forall() );
676
677 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
678 std::list< FunctionType *> functions;
679 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
680 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
681 findFunction( (*assert)->get_type(), functions, scopeTyVars, needsAdapter );
682 } // for
683 } // for
684 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
685 findFunction( (*arg)->get_type(), functions, scopeTyVars, needsAdapter );
686 } // for
687
688 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
689 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
690 if ( adapters.find( mangleName ) == adapters.end() ) {
691 std::string adapterName = makeAdapterName( mangleName );
692 adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) ) );
693 } // if
694 } // for
695
696 functionDecl->set_statements( functionDecl->get_statements()->acceptMutator( *this ) );
697
698 scopeTyVars.endScope();
699 assignOps.endScope();
700 ctorOps.endScope();
701 copyOps.endScope();
702 dtorOps.endScope();
703 retval = oldRetval;
704 useRetval = oldUseRetval;
705 doEndScope();
706 } // if
707 return functionDecl;
708 }
709
710 TypeDecl *Pass1::mutate( TypeDecl *typeDecl ) {
711 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
712 return Mutator::mutate( typeDecl );
713 }
714
715 Expression *Pass1::mutate( CommaExpr *commaExpr ) {
716 bool oldUseRetval = useRetval;
717 useRetval = false;
718 commaExpr->set_arg1( maybeMutate( commaExpr->get_arg1(), *this ) );
719 useRetval = oldUseRetval;
720 commaExpr->set_arg2( maybeMutate( commaExpr->get_arg2(), *this ) );
721 return commaExpr;
722 }
723
724 Expression *Pass1::mutate( ConditionalExpr *condExpr ) {
725 bool oldUseRetval = useRetval;
726 useRetval = false;
727 condExpr->set_arg1( maybeMutate( condExpr->get_arg1(), *this ) );
728 useRetval = oldUseRetval;
729 condExpr->set_arg2( maybeMutate( condExpr->get_arg2(), *this ) );
730 condExpr->set_arg3( maybeMutate( condExpr->get_arg3(), *this ) );
731 return condExpr;
732
733 }
734
735 void Pass1::passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes ) {
736 Type *polyType = isPolyType( parmType, exprTyVars );
737 if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
738 std::string typeName = mangleType( polyType );
739 if ( seenTypes.count( typeName ) ) return;
740
741 arg = appExpr->get_args().insert( arg, new SizeofExpr( argBaseType->clone() ) );
742 arg++;
743 arg = appExpr->get_args().insert( arg, new AlignofExpr( argBaseType->clone() ) );
744 arg++;
745 if ( dynamic_cast< StructInstType* >( polyType ) ) {
746 if ( StructInstType *argBaseStructType = dynamic_cast< StructInstType* >( argBaseType ) ) {
747 // zero-length arrays are forbidden by C, so don't pass offset for empty struct
748 if ( ! argBaseStructType->get_baseStruct()->get_members().empty() ) {
749 arg = appExpr->get_args().insert( arg, new OffsetPackExpr( argBaseStructType->clone() ) );
750 arg++;
751 }
752 } else {
753 throw SemanticError( "Cannot pass non-struct type for generic struct" );
754 }
755 }
756
757 seenTypes.insert( typeName );
758 }
759 }
760
761 void Pass1::passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
762 // pass size/align for type variables
763 for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
764 ResolvExpr::EqvClass eqvClass;
765 assert( env );
766 if ( tyParm->second == TypeDecl::Any ) {
767 Type *concrete = env->lookup( tyParm->first );
768 if ( concrete ) {
769 arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
770 arg++;
771 arg = appExpr->get_args().insert( arg, new AlignofExpr( concrete->clone() ) );
772 arg++;
773 } else {
774 // xxx - should this be an assertion?
775 throw SemanticError( "unbound type variable: " + tyParm->first + " in application ", appExpr );
776 } // if
777 } // if
778 } // for
779
780 // add size/align for generic types to parameter list
781 if ( appExpr->get_function()->get_results().empty() ) return;
782 FunctionType *funcType = getFunctionType( appExpr->get_function()->get_results().front() );
783 assert( funcType );
784
785 std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin();
786 std::list< Expression* >::const_iterator fnArg = arg;
787 std::set< std::string > seenTypes; ///< names for generic types we've seen
788
789 // a polymorphic return type may need to be added to the argument list
790 if ( polyRetType ) {
791 Type *concRetType = replaceWithConcrete( appExpr, polyRetType );
792 passArgTypeVars( appExpr, polyRetType, concRetType, arg, exprTyVars, seenTypes );
793 }
794
795 // add type information args for presently unseen types in parameter list
796 for ( ; fnParm != funcType->get_parameters().end() && fnArg != appExpr->get_args().end(); ++fnParm, ++fnArg ) {
797 VariableExpr *fnArgBase = getBaseVar( *fnArg );
798 if ( ! fnArgBase || fnArgBase->get_results().empty() ) continue;
799 passArgTypeVars( appExpr, (*fnParm)->get_type(), fnArgBase->get_results().front(), arg, exprTyVars, seenTypes );
800 }
801 }
802
803 ObjectDecl *Pass1::makeTemporary( Type *type ) {
804 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, 0 );
805 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
806 return newObj;
807 }
808
809 Expression *Pass1::addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg ) {
810 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
811 // if ( useRetval ) {
812 // assert( retval );
813 // arg = appExpr->get_args().insert( arg, new VariableExpr( retval ) );
814 // arg++;
815 // } else {
816
817 // Create temporary to hold return value of polymorphic function and produce that temporary as a result
818 // using a comma expression. Possibly change comma expression into statement expression "{}" for multiple
819 // return values.
820 ObjectDecl *newObj = makeTemporary( retType->clone() );
821 Expression *paramExpr = new VariableExpr( newObj );
822
823 // If the type of the temporary is not polymorphic, box temporary by taking its address;
824 // otherwise the temporary is already boxed and can be used directly.
825 if ( ! isPolyType( newObj->get_type(), scopeTyVars, env ) ) {
826 paramExpr = new AddressExpr( paramExpr );
827 } // if
828 arg = appExpr->get_args().insert( arg, paramExpr ); // add argument to function call
829 arg++;
830 // Build a comma expression to call the function and emulate a normal return.
831 CommaExpr *commaExpr = new CommaExpr( appExpr, new VariableExpr( newObj ) );
832 commaExpr->set_env( appExpr->get_env() );
833 appExpr->set_env( 0 );
834 return commaExpr;
835 // } // if
836 // return appExpr;
837 }
838
839 void Pass1::replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params ) {
840 for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
841 TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
842 assert(paramType && "Aggregate parameters should be type expressions");
843 paramType->set_type( replaceWithConcrete( appExpr, paramType->get_type(), false ) );
844 }
845 }
846
847 Type *Pass1::replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone ) {
848 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
849 Type *concrete = env->lookup( typeInst->get_name() );
850 if ( concrete == 0 ) {
851 throw SemanticError( "Unbound type variable " + typeInst->get_name() + " in ", appExpr );
852 } // if
853 return concrete;
854 } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
855 if ( doClone ) {
856 structType = structType->clone();
857 }
858 replaceParametersWithConcrete( appExpr, structType->get_parameters() );
859 return structType;
860 } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
861 if ( doClone ) {
862 unionType = unionType->clone();
863 }
864 replaceParametersWithConcrete( appExpr, unionType->get_parameters() );
865 return unionType;
866 }
867 return type;
868 }
869
870 Expression *Pass1::addDynRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *dynType, std::list< Expression *>::iterator &arg ) {
871 assert( env );
872 Type *concrete = replaceWithConcrete( appExpr, dynType );
873 // add out-parameter for return value
874 return addRetParam( appExpr, function, concrete, arg );
875 }
876
877 Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
878 Expression *ret = appExpr;
879// if ( ! function->get_returnVals().empty() && isPolyType( function->get_returnVals().front()->get_type(), tyVars ) ) {
880 if ( isDynRet( function, tyVars ) ) {
881 ret = addRetParam( appExpr, function, function->get_returnVals().front()->get_type(), arg );
882 } // if
883 std::string mangleName = mangleAdapterName( function, tyVars );
884 std::string adapterName = makeAdapterName( mangleName );
885
886 // cast adaptee to void (*)(), since it may have any type inside a polymorphic function
887 Type * adapteeType = new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) );
888 appExpr->get_args().push_front( new CastExpr( appExpr->get_function(), adapteeType ) );
889 appExpr->set_function( new NameExpr( adapterName ) );
890
891 return ret;
892 }
893
894 void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
895 assert( ! arg->get_results().empty() );
896 if ( isPolyType( param, exprTyVars ) ) {
897 if ( isPolyType( arg->get_results().front() ) ) {
898 // if the argument's type is polymorphic, we don't need to box again!
899 return;
900 } else if ( arg->get_results().front()->get_isLvalue() ) {
901 // VariableExpr and MemberExpr are lvalues; need to check this isn't coming from the second arg of a comma expression though (not an lvalue)
902 // xxx - need to test that this code is still reachable
903 if ( CommaExpr *commaArg = dynamic_cast< CommaExpr* >( arg ) ) {
904 commaArg->set_arg2( new AddressExpr( commaArg->get_arg2() ) );
905 } else {
906 arg = new AddressExpr( arg );
907 }
908 } else {
909 // use type computed in unification to declare boxed variables
910 Type * newType = param->clone();
911 if ( env ) env->apply( newType );
912 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, newType, 0 );
913 newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
914 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
915 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
916 assign->get_args().push_back( new VariableExpr( newObj ) );
917 assign->get_args().push_back( arg );
918 stmtsToAdd.push_back( new ExprStmt( noLabels, assign ) );
919 arg = new AddressExpr( new VariableExpr( newObj ) );
920 } // if
921 } // if
922 }
923
924 /// cast parameters to polymorphic functions so that types are replaced with
925 /// void * if they are type parameters in the formal type.
926 /// this gets rid of warnings from gcc.
927 void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
928 if ( getFunctionType( formal ) ) {
929 Type * newType = formal->clone();
930 newType = ScrubTyVars::scrub( newType, tyVars );
931 actual = new CastExpr( actual, newType );
932 } // if
933 }
934
935 void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
936 for ( std::list< DeclarationWithType *>::const_iterator param = function->get_parameters().begin(); param != function->get_parameters().end(); ++param, ++arg ) {
937 assert( arg != appExpr->get_args().end() );
938 addCast( *arg, (*param)->get_type(), exprTyVars );
939 boxParam( (*param)->get_type(), *arg, exprTyVars );
940 } // for
941 }
942
943 void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
944 std::list< Expression *>::iterator cur = arg;
945 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
946 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
947 InferredParams::const_iterator inferParam = appExpr->get_inferParams().find( (*assert)->get_uniqueId() );
948 assert( inferParam != appExpr->get_inferParams().end() && "NOTE: Explicit casts of polymorphic functions to compatible monomorphic functions are currently unsupported" );
949 Expression *newExpr = inferParam->second.expr->clone();
950 addCast( newExpr, (*assert)->get_type(), tyVars );
951 boxParam( (*assert)->get_type(), newExpr, tyVars );
952 appExpr->get_args().insert( cur, newExpr );
953 } // for
954 } // for
955 }
956
957 void makeRetParm( FunctionType *funcType ) {
958 DeclarationWithType *retParm = funcType->get_returnVals().front();
959
960 // make a new parameter that is a pointer to the type of the old return value
961 retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
962 funcType->get_parameters().push_front( retParm );
963
964 // we don't need the return value any more
965 funcType->get_returnVals().clear();
966 }
967
968 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
969 // actually make the adapter type
970 FunctionType *adapter = adaptee->clone();
971// if ( ! adapter->get_returnVals().empty() && isPolyType( adapter->get_returnVals().front()->get_type(), tyVars ) ) {
972 if ( isDynRet( adapter, tyVars ) ) {
973 makeRetParm( adapter );
974 } // if
975 adapter->get_parameters().push_front( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
976 return adapter;
977 }
978
979 Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
980 assert( param );
981 assert( arg );
982 if ( isPolyType( realParam->get_type(), tyVars ) ) {
983 if ( ! isPolyType( arg->get_type() ) ) {
984 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
985 deref->get_args().push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
986 deref->get_results().push_back( arg->get_type()->clone() );
987 return deref;
988 } // if
989 } // if
990 return new VariableExpr( param );
991 }
992
993 void addAdapterParams( ApplicationExpr *adapteeApp, std::list< DeclarationWithType *>::iterator arg, std::list< DeclarationWithType *>::iterator param, std::list< DeclarationWithType *>::iterator paramEnd, std::list< DeclarationWithType *>::iterator realParam, const TyVarMap &tyVars ) {
994 UniqueName paramNamer( "_p" );
995 for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
996 if ( (*param)->get_name() == "" ) {
997 (*param)->set_name( paramNamer.newName() );
998 (*param)->set_linkage( LinkageSpec::C );
999 } // if
1000 adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
1001 } // for
1002 }
1003
1004 FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
1005 FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
1006 adapterType = ScrubTyVars::scrub( adapterType, tyVars );
1007 DeclarationWithType *adapteeDecl = adapterType->get_parameters().front();
1008 adapteeDecl->set_name( "_adaptee" );
1009 ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
1010 Statement *bodyStmt;
1011
1012 std::list< TypeDecl *>::iterator tyArg = realType->get_forall().begin();
1013 std::list< TypeDecl *>::iterator tyParam = adapterType->get_forall().begin();
1014 std::list< TypeDecl *>::iterator realTyParam = adaptee->get_forall().begin();
1015 for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
1016 assert( tyArg != realType->get_forall().end() );
1017 std::list< DeclarationWithType *>::iterator assertArg = (*tyArg)->get_assertions().begin();
1018 std::list< DeclarationWithType *>::iterator assertParam = (*tyParam)->get_assertions().begin();
1019 std::list< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->get_assertions().begin();
1020 for ( ; assertParam != (*tyParam)->get_assertions().end(); ++assertArg, ++assertParam, ++realAssertParam ) {
1021 assert( assertArg != (*tyArg)->get_assertions().end() );
1022 adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
1023 } // for
1024 } // for
1025
1026 std::list< DeclarationWithType *>::iterator arg = realType->get_parameters().begin();
1027 std::list< DeclarationWithType *>::iterator param = adapterType->get_parameters().begin();
1028 std::list< DeclarationWithType *>::iterator realParam = adaptee->get_parameters().begin();
1029 param++; // skip adaptee parameter in the adapter type
1030 if ( realType->get_returnVals().empty() ) {
1031 // void return
1032 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1033 bodyStmt = new ExprStmt( noLabels, adapteeApp );
1034// } else if ( isPolyType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
1035 } else if ( isDynType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
1036 // return type T
1037 if ( (*param)->get_name() == "" ) {
1038 (*param)->set_name( "_ret" );
1039 (*param)->set_linkage( LinkageSpec::C );
1040 } // if
1041 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
1042 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
1043 deref->get_args().push_back( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->get_returnVals().front()->get_type()->clone() ) ) );
1044 assign->get_args().push_back( deref );
1045 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1046 assign->get_args().push_back( adapteeApp );
1047 bodyStmt = new ExprStmt( noLabels, assign );
1048 } else {
1049 // adapter for a function that returns a monomorphic value
1050 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1051 bodyStmt = new ReturnStmt( noLabels, adapteeApp );
1052 } // if
1053 CompoundStmt *adapterBody = new CompoundStmt( noLabels );
1054 adapterBody->get_kids().push_back( bodyStmt );
1055 std::string adapterName = makeAdapterName( mangleName );
1056 return new FunctionDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, adapterType, adapterBody, false, false );
1057 }
1058
1059 void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
1060 // collect a list of function types passed as parameters or implicit parameters (assertions)
1061 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1062 std::list< FunctionType *> functions;
1063 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
1064 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
1065 findFunction( (*assert)->get_type(), functions, exprTyVars, needsAdapter );
1066 } // for
1067 } // for
1068 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1069 findFunction( (*arg)->get_type(), functions, exprTyVars, needsAdapter );
1070 } // for
1071
1072 // parameter function types for which an appropriate adapter has been generated. we cannot use the types
1073 // after applying substitutions, since two different parameter types may be unified to the same type
1074 std::set< std::string > adaptersDone;
1075
1076 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1077 FunctionType *originalFunction = (*funType)->clone();
1078 FunctionType *realFunction = (*funType)->clone();
1079 std::string mangleName = SymTab::Mangler::mangle( realFunction );
1080
1081 // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
1082 // pre-substitution parameter function type.
1083 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1084 adaptersDone.insert( adaptersDone.begin(), mangleName );
1085
1086 // apply substitution to type variables to figure out what the adapter's type should look like
1087 assert( env );
1088 env->apply( realFunction );
1089 mangleName = SymTab::Mangler::mangle( realFunction );
1090 mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
1091
1092 typedef ScopedMap< std::string, DeclarationWithType* >::iterator AdapterIter;
1093 AdapterIter adapter = adapters.find( mangleName );
1094 if ( adapter == adapters.end() ) {
1095 // adapter has not been created yet in the current scope, so define it
1096 FunctionDecl *newAdapter = makeAdapter( *funType, realFunction, mangleName, exprTyVars );
1097 std::pair< AdapterIter, bool > answer = adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
1098 adapter = answer.first;
1099 stmtsToAdd.push_back( new DeclStmt( noLabels, newAdapter ) );
1100 } // if
1101 assert( adapter != adapters.end() );
1102
1103 // add the appropriate adapter as a parameter
1104 appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
1105 } // if
1106 } // for
1107 } // passAdapters
1108
1109 Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, Type *polyType, bool isIncr ) {
1110 NameExpr *opExpr;
1111 if ( isIncr ) {
1112 opExpr = new NameExpr( "?+=?" );
1113 } else {
1114 opExpr = new NameExpr( "?-=?" );
1115 } // if
1116 UntypedExpr *addAssign = new UntypedExpr( opExpr );
1117 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
1118 addAssign->get_args().push_back( address->get_arg() );
1119 } else {
1120 addAssign->get_args().push_back( appExpr->get_args().front() );
1121 } // if
1122 addAssign->get_args().push_back( new NameExpr( sizeofName( mangleType( polyType ) ) ) );
1123 addAssign->get_results().front() = appExpr->get_results().front()->clone();
1124 if ( appExpr->get_env() ) {
1125 addAssign->set_env( appExpr->get_env() );
1126 appExpr->set_env( 0 );
1127 } // if
1128 appExpr->get_args().clear();
1129 delete appExpr;
1130 return addAssign;
1131 }
1132
1133 Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
1134 if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->get_function() ) ) {
1135 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
1136 if ( varExpr->get_var()->get_name() == "?[?]" ) {
1137 assert( ! appExpr->get_results().empty() );
1138 assert( appExpr->get_args().size() == 2 );
1139 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
1140 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
1141 assert( ! baseType1 || ! baseType2 ); // the arguments cannot both be polymorphic pointers
1142 UntypedExpr *ret = 0;
1143 if ( baseType1 || baseType2 ) { // one of the arguments is a polymorphic pointer
1144 ret = new UntypedExpr( new NameExpr( "?+?" ) );
1145 } // if
1146 if ( baseType1 ) {
1147 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1148 multiply->get_args().push_back( appExpr->get_args().back() );
1149 multiply->get_args().push_back( new SizeofExpr( baseType1->clone() ) );
1150 ret->get_args().push_back( appExpr->get_args().front() );
1151 ret->get_args().push_back( multiply );
1152 } else if ( baseType2 ) {
1153 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1154 multiply->get_args().push_back( appExpr->get_args().front() );
1155 multiply->get_args().push_back( new SizeofExpr( baseType2->clone() ) );
1156 ret->get_args().push_back( multiply );
1157 ret->get_args().push_back( appExpr->get_args().back() );
1158 } // if
1159 if ( baseType1 || baseType2 ) {
1160 ret->get_results().push_front( appExpr->get_results().front()->clone() );
1161 if ( appExpr->get_env() ) {
1162 ret->set_env( appExpr->get_env() );
1163 appExpr->set_env( 0 );
1164 } // if
1165 appExpr->get_args().clear();
1166 delete appExpr;
1167 return ret;
1168 } // if
1169 } else if ( varExpr->get_var()->get_name() == "*?" ) {
1170 assert( ! appExpr->get_results().empty() );
1171 assert( ! appExpr->get_args().empty() );
1172 if ( isPolyType( appExpr->get_results().front(), scopeTyVars, env ) ) {
1173 Expression *ret = appExpr->get_args().front();
1174 delete ret->get_results().front();
1175 ret->get_results().front() = appExpr->get_results().front()->clone();
1176 if ( appExpr->get_env() ) {
1177 ret->set_env( appExpr->get_env() );
1178 appExpr->set_env( 0 );
1179 } // if
1180 appExpr->get_args().clear();
1181 delete appExpr;
1182 return ret;
1183 } // if
1184 } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
1185 assert( ! appExpr->get_results().empty() );
1186 assert( appExpr->get_args().size() == 1 );
1187 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
1188 Type *tempType = appExpr->get_results().front()->clone();
1189 if ( env ) {
1190 env->apply( tempType );
1191 } // if
1192 ObjectDecl *newObj = makeTemporary( tempType );
1193 VariableExpr *tempExpr = new VariableExpr( newObj );
1194 UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
1195 assignExpr->get_args().push_back( tempExpr->clone() );
1196 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
1197 assignExpr->get_args().push_back( address->get_arg()->clone() );
1198 } else {
1199 assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
1200 } // if
1201 CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "?++" ) );
1202 return new CommaExpr( firstComma, tempExpr );
1203 } // if
1204 } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
1205 assert( ! appExpr->get_results().empty() );
1206 assert( appExpr->get_args().size() == 1 );
1207 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
1208 return makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "++?" );
1209 } // if
1210 } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
1211 assert( ! appExpr->get_results().empty() );
1212 assert( appExpr->get_args().size() == 2 );
1213 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
1214 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
1215 if ( baseType1 && baseType2 ) {
1216 UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
1217 divide->get_args().push_back( appExpr );
1218 divide->get_args().push_back( new SizeofExpr( baseType1->clone() ) );
1219 divide->get_results().push_front( appExpr->get_results().front()->clone() );
1220 if ( appExpr->get_env() ) {
1221 divide->set_env( appExpr->get_env() );
1222 appExpr->set_env( 0 );
1223 } // if
1224 return divide;
1225 } else if ( baseType1 ) {
1226 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1227 multiply->get_args().push_back( appExpr->get_args().back() );
1228 multiply->get_args().push_back( new SizeofExpr( baseType1->clone() ) );
1229 appExpr->get_args().back() = multiply;
1230 } else if ( baseType2 ) {
1231 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1232 multiply->get_args().push_back( appExpr->get_args().front() );
1233 multiply->get_args().push_back( new SizeofExpr( baseType2->clone() ) );
1234 appExpr->get_args().front() = multiply;
1235 } // if
1236 } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
1237 assert( ! appExpr->get_results().empty() );
1238 assert( appExpr->get_args().size() == 2 );
1239 Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env );
1240 if ( baseType ) {
1241 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1242 multiply->get_args().push_back( appExpr->get_args().back() );
1243 multiply->get_args().push_back( new SizeofExpr( baseType->clone() ) );
1244 appExpr->get_args().back() = multiply;
1245 } // if
1246 } // if
1247 return appExpr;
1248 } // if
1249 } // if
1250 return 0;
1251 }
1252
1253 Expression *Pass1::mutate( ApplicationExpr *appExpr ) {
1254 // std::cerr << "mutate appExpr: ";
1255 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
1256 // std::cerr << i->first << " ";
1257 // }
1258 // std::cerr << "\n";
1259 bool oldUseRetval = useRetval;
1260 useRetval = false;
1261 appExpr->get_function()->acceptMutator( *this );
1262 mutateAll( appExpr->get_args(), *this );
1263 useRetval = oldUseRetval;
1264
1265 assert( ! appExpr->get_function()->get_results().empty() );
1266 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1267 assert( pointer );
1268 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1269 assert( function );
1270
1271 if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
1272 return newExpr;
1273 } // if
1274
1275 Expression *ret = appExpr;
1276
1277 std::list< Expression *>::iterator arg = appExpr->get_args().begin();
1278 std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
1279
1280 TyVarMap exprTyVars( (TypeDecl::Kind)-1 );
1281 makeTyVarMap( function, exprTyVars );
1282 ReferenceToType *dynRetType = isDynRet( function, exprTyVars );
1283
1284 if ( dynRetType ) {
1285 ret = addDynRetParam( appExpr, function, dynRetType, arg );
1286 } else if ( needsAdapter( function, scopeTyVars ) ) {
1287 // std::cerr << "needs adapter: ";
1288 // printTyVarMap( std::cerr, scopeTyVars );
1289 // std::cerr << *env << std::endl;
1290 // change the application so it calls the adapter rather than the passed function
1291 ret = applyAdapter( appExpr, function, arg, scopeTyVars );
1292 } // if
1293 arg = appExpr->get_args().begin();
1294
1295 passTypeVars( appExpr, dynRetType, arg, exprTyVars );
1296 addInferredParams( appExpr, function, arg, exprTyVars );
1297
1298 arg = paramBegin;
1299
1300 boxParams( appExpr, function, arg, exprTyVars );
1301 passAdapters( appExpr, function, exprTyVars );
1302
1303 return ret;
1304 }
1305
1306 Expression *Pass1::mutate( UntypedExpr *expr ) {
1307 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1308 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1309 if ( name->get_name() == "*?" ) {
1310 Expression *ret = expr->get_args().front();
1311 expr->get_args().clear();
1312 delete expr;
1313 return ret->acceptMutator( *this );
1314 } // if
1315 } // if
1316 } // if
1317 return PolyMutator::mutate( expr );
1318 }
1319
1320 Expression *Pass1::mutate( AddressExpr *addrExpr ) {
1321 assert( ! addrExpr->get_arg()->get_results().empty() );
1322
1323 bool needs = false;
1324 if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->get_arg() ) ) {
1325 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1326 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1327 if ( name->get_name() == "*?" ) {
1328 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->get_args().front() ) ) {
1329 assert( ! appExpr->get_function()->get_results().empty() );
1330 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1331 assert( pointer );
1332 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1333 assert( function );
1334 needs = needsAdapter( function, scopeTyVars );
1335 } // if
1336 } // if
1337 } // if
1338 } // if
1339 } // if
1340 // isPolyType check needs to happen before mutating addrExpr arg, so pull it forward
1341 // out of the if condition.
1342 bool polytype = isPolyType( addrExpr->get_arg()->get_results().front(), scopeTyVars, env );
1343 addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
1344 if ( polytype || needs ) {
1345 Expression *ret = addrExpr->get_arg();
1346 delete ret->get_results().front();
1347 ret->get_results().front() = addrExpr->get_results().front()->clone();
1348 addrExpr->set_arg( 0 );
1349 delete addrExpr;
1350 return ret;
1351 } else {
1352 return addrExpr;
1353 } // if
1354 }
1355
1356 /// Wraps a function declaration in a new pointer-to-function variable expression
1357 VariableExpr *wrapFunctionDecl( DeclarationWithType *functionDecl ) {
1358 // line below cloned from FixFunction.cc
1359 // xxx - functionObj is never added to a list of declarations...
1360 ObjectDecl *functionObj = new ObjectDecl( functionDecl->get_name(), functionDecl->get_storageClass(), functionDecl->get_linkage(), 0,
1361 new PointerType( Type::Qualifiers(), functionDecl->get_type()->clone() ), 0 );
1362 functionObj->set_mangleName( functionDecl->get_mangleName() );
1363 functionObj->set_scopeLevel( functionDecl->get_scopeLevel() );
1364 return new VariableExpr( functionObj );
1365 }
1366
1367 /// Finds the operation declaration for a given type in one of the two maps
1368 DeclarationWithType* findOpForType( Type *formalType, const ScopedMap< std::string, DeclarationWithType* >& ops, ResolvExpr::TypeMap< DeclarationWithType >& scopedOps ) {
1369 if ( TypeInstType *formalTypeInstType = dynamic_cast< TypeInstType* >( formalType ) ) {
1370 ScopedMap< std::string, DeclarationWithType *>::const_iterator opIt = ops.find( formalTypeInstType->get_name() );
1371 return opIt == ops.end() ? 0 : opIt->second;
1372 } else {
1373 return scopedOps.find( formalType );
1374 }
1375 }
1376
1377 /// Adds an assertion parameter to the application expression for the actual assertion declaration valued with the assert op
1378 void addAssertionFor( ApplicationExpr *appExpr, DeclarationWithType *actualDecl, DeclarationWithType *assertOp ) {
1379 appExpr->get_inferParams()[ actualDecl->get_uniqueId() ]
1380 = ParamEntry( assertOp->get_uniqueId(), assertOp->get_type()->clone(), actualDecl->get_type()->clone(), wrapFunctionDecl( assertOp ) );
1381 }
1382
1383 Statement * Pass1::mutate( ReturnStmt *returnStmt ) {
1384 if ( retval && returnStmt->get_expr() ) {
1385 assert( ! returnStmt->get_expr()->get_results().empty() );
1386 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
1387 // if ( returnStmt->get_expr()->get_results().front()->get_isLvalue() ) {
1388 // by this point, a cast expr on a polymorphic return value is redundant
1389 while ( CastExpr *castExpr = dynamic_cast< CastExpr *>( returnStmt->get_expr() ) ) {
1390 returnStmt->set_expr( castExpr->get_arg() );
1391 returnStmt->get_expr()->set_env( castExpr->get_env() );
1392 castExpr->set_env( 0 );
1393 castExpr->set_arg( 0 );
1394 delete castExpr;
1395 } //while
1396
1397 // find assignment operator for (polymorphic) return type
1398 ApplicationExpr *assignExpr = 0;
1399 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( retval->get_type() ) ) {
1400 // find assignment operator for type variable
1401 ScopedMap< std::string, DeclarationWithType *>::const_iterator assignIter = assignOps.find( typeInst->get_name() );
1402 if ( assignIter == assignOps.end() ) {
1403 throw SemanticError( "Attempt to return dtype or ftype object in ", returnStmt->get_expr() );
1404 } // if
1405 assignExpr = new ApplicationExpr( new VariableExpr( assignIter->second ) );
1406 } else if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( retval->get_type() ) ) {
1407 // find assignment operator for generic type
1408 DeclarationWithType *functionDecl = scopedAssignOps.find( refType );
1409 if ( ! functionDecl ) {
1410 throw SemanticError( "Attempt to return dtype or ftype generic object in ", returnStmt->get_expr() );
1411 }
1412
1413 // wrap it up in an application expression
1414 assignExpr = new ApplicationExpr( wrapFunctionDecl( functionDecl ) );
1415 assignExpr->set_env( env->clone() );
1416
1417 // find each of its needed secondary assignment operators
1418 std::list< Expression* > &tyParams = refType->get_parameters();
1419 std::list< TypeDecl* > &forallParams = functionDecl->get_type()->get_forall();
1420 std::list< Expression* >::const_iterator tyIt = tyParams.begin();
1421 std::list< TypeDecl* >::const_iterator forallIt = forallParams.begin();
1422 for ( ; tyIt != tyParams.end() && forallIt != forallParams.end(); ++tyIt, ++forallIt ) {
1423 // Add appropriate mapping to assignment expression environment
1424 TypeExpr *formalTypeExpr = dynamic_cast< TypeExpr* >( *tyIt );
1425 assert( formalTypeExpr && "type parameters must be type expressions" );
1426 Type *formalType = formalTypeExpr->get_type();
1427 assignExpr->get_env()->add( (*forallIt)->get_name(), formalType );
1428
1429 // skip non-otype parameters (ftype/dtype)
1430 if ( (*forallIt)->get_kind() != TypeDecl::Any ) continue;
1431
1432 // find otype operators for formal type
1433 DeclarationWithType *assertAssign = findOpForType( formalType, assignOps, scopedAssignOps );
1434 if ( ! assertAssign ) throw SemanticError( "No assignment operation found for ", formalType );
1435
1436 DeclarationWithType *assertCtor = findOpForType( formalType, ctorOps, scopedCtorOps );
1437 if ( ! assertCtor ) throw SemanticError( "No default constructor found for ", formalType );
1438
1439 DeclarationWithType *assertCopy = findOpForType( formalType, copyOps, scopedCopyOps );
1440 if ( ! assertCopy ) throw SemanticError( "No copy constructor found for ", formalType );
1441
1442 DeclarationWithType *assertDtor = findOpForType( formalType, dtorOps, scopedDtorOps );
1443 if ( ! assertDtor ) throw SemanticError( "No destructor found for ", formalType );
1444
1445 // add inferred parameters for otype operators to assignment expression
1446 // NOTE: Code here assumes that first four assertions are assign op, ctor, copy ctor, dtor, in that order
1447 std::list< DeclarationWithType* > &asserts = (*forallIt)->get_assertions();
1448 assert( asserts.size() >= 4 && "Type param needs otype operator assertions" );
1449
1450 std::list< DeclarationWithType* >::iterator actualIt = asserts.begin();
1451 addAssertionFor( assignExpr, *actualIt, assertAssign );
1452 ++actualIt;
1453 addAssertionFor( assignExpr, *actualIt, assertCtor );
1454 ++actualIt;
1455 addAssertionFor( assignExpr, *actualIt, assertCopy );
1456 ++actualIt;
1457 addAssertionFor( assignExpr, *actualIt, assertDtor );
1458
1459 }
1460 }
1461 assert( assignExpr );
1462
1463 // replace return statement with appropriate assignment to out parameter
1464 Expression *retParm = new NameExpr( retval->get_name() );
1465 retParm->get_results().push_back( new PointerType( Type::Qualifiers(), retval->get_type()->clone() ) );
1466 assignExpr->get_args().push_back( retParm );
1467 assignExpr->get_args().push_back( returnStmt->get_expr() );
1468 stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( assignExpr ) ) );
1469 // } else {
1470 // useRetval = true;
1471 // stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( returnStmt->get_expr() ) ) );
1472 // useRetval = false;
1473 // } // if
1474 returnStmt->set_expr( 0 );
1475 } else {
1476 returnStmt->set_expr( mutateExpression( returnStmt->get_expr() ) );
1477 } // if
1478 return returnStmt;
1479 }
1480
1481 Type * Pass1::mutate( PointerType *pointerType ) {
1482 scopeTyVars.beginScope();
1483 makeTyVarMap( pointerType, scopeTyVars );
1484
1485 Type *ret = Mutator::mutate( pointerType );
1486
1487 scopeTyVars.endScope();
1488 return ret;
1489 }
1490
1491 Type * Pass1::mutate( FunctionType *functionType ) {
1492 scopeTyVars.beginScope();
1493 makeTyVarMap( functionType, scopeTyVars );
1494
1495 Type *ret = Mutator::mutate( functionType );
1496
1497 scopeTyVars.endScope();
1498 return ret;
1499 }
1500
1501 void Pass1::doBeginScope() {
1502 adapters.beginScope();
1503 scopedAssignOps.beginScope();
1504 scopedCtorOps.beginScope();
1505 scopedCopyOps.beginScope();
1506 scopedDtorOps.beginScope();
1507 }
1508
1509 void Pass1::doEndScope() {
1510 adapters.endScope();
1511 scopedAssignOps.endScope();
1512 scopedCtorOps.endScope();
1513 scopedCopyOps.endScope();
1514 scopedDtorOps.endScope();
1515 }
1516
1517////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1518
1519 void Pass2::addAdapters( FunctionType *functionType ) {
1520 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1521 std::list< FunctionType *> functions;
1522 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1523 Type *orig = (*arg)->get_type();
1524 findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1525 (*arg)->set_type( orig );
1526 }
1527 std::set< std::string > adaptersDone;
1528 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1529 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
1530 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1531 std::string adapterName = makeAdapterName( mangleName );
1532 paramList.push_front( new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) );
1533 adaptersDone.insert( adaptersDone.begin(), mangleName );
1534 }
1535 }
1536// deleteAll( functions );
1537 }
1538
1539 template< typename DeclClass >
1540 DeclClass * Pass2::handleDecl( DeclClass *decl, Type *type ) {
1541 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1542
1543 return ret;
1544 }
1545
1546 DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
1547 return handleDecl( functionDecl, functionDecl->get_functionType() );
1548 }
1549
1550 ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
1551 return handleDecl( objectDecl, objectDecl->get_type() );
1552 }
1553
1554 TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
1555 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1556 if ( typeDecl->get_base() ) {
1557 return handleDecl( typeDecl, typeDecl->get_base() );
1558 } else {
1559 return Mutator::mutate( typeDecl );
1560 }
1561 }
1562
1563 TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
1564 return handleDecl( typedefDecl, typedefDecl->get_base() );
1565 }
1566
1567 Type * Pass2::mutate( PointerType *pointerType ) {
1568 scopeTyVars.beginScope();
1569 makeTyVarMap( pointerType, scopeTyVars );
1570
1571 Type *ret = Mutator::mutate( pointerType );
1572
1573 scopeTyVars.endScope();
1574 return ret;
1575 }
1576
1577 Type *Pass2::mutate( FunctionType *funcType ) {
1578 scopeTyVars.beginScope();
1579 makeTyVarMap( funcType, scopeTyVars );
1580
1581 // move polymorphic return type to parameter list
1582 if ( isDynRet( funcType ) ) {
1583 DeclarationWithType *ret = funcType->get_returnVals().front();
1584 ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1585 funcType->get_parameters().push_front( ret );
1586 funcType->get_returnVals().pop_front();
1587 }
1588
1589 // add size/align and assertions for type parameters to parameter list
1590 std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1591 std::list< DeclarationWithType *> inferredParams;
1592 ObjectDecl newObj( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0 );
1593 ObjectDecl newPtr( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0,
1594 new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
1595 for ( std::list< TypeDecl *>::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
1596 ObjectDecl *sizeParm, *alignParm;
1597 // add all size and alignment parameters to parameter list
1598 if ( (*tyParm)->get_kind() == TypeDecl::Any ) {
1599 TypeInstType parmType( Type::Qualifiers(), (*tyParm)->get_name(), *tyParm );
1600 std::string parmName = mangleType( &parmType );
1601
1602 sizeParm = newObj.clone();
1603 sizeParm->set_name( sizeofName( parmName ) );
1604 last = funcType->get_parameters().insert( last, sizeParm );
1605 ++last;
1606
1607 alignParm = newObj.clone();
1608 alignParm->set_name( alignofName( parmName ) );
1609 last = funcType->get_parameters().insert( last, alignParm );
1610 ++last;
1611 }
1612 // move all assertions into parameter list
1613 for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
1614// *assert = (*assert)->acceptMutator( *this );
1615 inferredParams.push_back( *assert );
1616 }
1617 (*tyParm)->get_assertions().clear();
1618 }
1619
1620 // add size/align for generic parameter types to parameter list
1621 std::set< std::string > seenTypes; // sizeofName for generic types we've seen
1622 for ( std::list< DeclarationWithType* >::const_iterator fnParm = last; fnParm != funcType->get_parameters().end(); ++fnParm ) {
1623 Type *polyType = isPolyType( (*fnParm)->get_type(), scopeTyVars );
1624 if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
1625 std::string typeName = mangleType( polyType );
1626 if ( seenTypes.count( typeName ) ) continue;
1627
1628 ObjectDecl *sizeParm, *alignParm, *offsetParm;
1629 sizeParm = newObj.clone();
1630 sizeParm->set_name( sizeofName( typeName ) );
1631 last = funcType->get_parameters().insert( last, sizeParm );
1632 ++last;
1633
1634 alignParm = newObj.clone();
1635 alignParm->set_name( alignofName( typeName ) );
1636 last = funcType->get_parameters().insert( last, alignParm );
1637 ++last;
1638
1639 if ( StructInstType *polyBaseStruct = dynamic_cast< StructInstType* >( polyType ) ) {
1640 // NOTE zero-length arrays are illegal in C, so empty structs have no offset array
1641 if ( ! polyBaseStruct->get_baseStruct()->get_members().empty() ) {
1642 offsetParm = newPtr.clone();
1643 offsetParm->set_name( offsetofName( typeName ) );
1644 last = funcType->get_parameters().insert( last, offsetParm );
1645 ++last;
1646 }
1647 }
1648
1649 seenTypes.insert( typeName );
1650 }
1651 }
1652
1653 // splice assertion parameters into parameter list
1654 funcType->get_parameters().splice( last, inferredParams );
1655 addAdapters( funcType );
1656 mutateAll( funcType->get_returnVals(), *this );
1657 mutateAll( funcType->get_parameters(), *this );
1658
1659 scopeTyVars.endScope();
1660 return funcType;
1661 }
1662
1663////////////////////////////////////////// PolyGenericCalculator ////////////////////////////////////////////////////
1664
1665 void PolyGenericCalculator::beginTypeScope( Type *ty ) {
1666 scopeTyVars.beginScope();
1667 makeTyVarMap( ty, scopeTyVars );
1668 }
1669
1670 void PolyGenericCalculator::endTypeScope() {
1671 scopeTyVars.endScope();
1672 }
1673
1674 template< typename DeclClass >
1675 DeclClass * PolyGenericCalculator::handleDecl( DeclClass *decl, Type *type ) {
1676 beginTypeScope( type );
1677 knownLayouts.beginScope();
1678 knownOffsets.beginScope();
1679
1680 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1681
1682 knownOffsets.endScope();
1683 knownLayouts.endScope();
1684 endTypeScope();
1685 return ret;
1686 }
1687
1688 ObjectDecl * PolyGenericCalculator::mutate( ObjectDecl *objectDecl ) {
1689 return handleDecl( objectDecl, objectDecl->get_type() );
1690 }
1691
1692 DeclarationWithType * PolyGenericCalculator::mutate( FunctionDecl *functionDecl ) {
1693 return handleDecl( functionDecl, functionDecl->get_functionType() );
1694 }
1695
1696 TypedefDecl * PolyGenericCalculator::mutate( TypedefDecl *typedefDecl ) {
1697 return handleDecl( typedefDecl, typedefDecl->get_base() );
1698 }
1699
1700 TypeDecl * PolyGenericCalculator::mutate( TypeDecl *typeDecl ) {
1701 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1702 return Mutator::mutate( typeDecl );
1703 }
1704
1705 Type * PolyGenericCalculator::mutate( PointerType *pointerType ) {
1706 beginTypeScope( pointerType );
1707
1708 Type *ret = Mutator::mutate( pointerType );
1709
1710 endTypeScope();
1711 return ret;
1712 }
1713
1714 Type * PolyGenericCalculator::mutate( FunctionType *funcType ) {
1715 beginTypeScope( funcType );
1716
1717 // make sure that any type information passed into the function is accounted for
1718 for ( std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin(); fnParm != funcType->get_parameters().end(); ++fnParm ) {
1719 // condition here duplicates that in Pass2::mutate( FunctionType* )
1720 Type *polyType = isPolyType( (*fnParm)->get_type(), scopeTyVars );
1721 if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
1722 knownLayouts.insert( mangleType( polyType ) );
1723 }
1724 }
1725
1726 Type *ret = Mutator::mutate( funcType );
1727
1728 endTypeScope();
1729 return ret;
1730 }
1731
1732 Statement *PolyGenericCalculator::mutate( DeclStmt *declStmt ) {
1733 if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
1734 if ( findGeneric( objectDecl->get_type() ) ) {
1735 // change initialization of a polymorphic value object
1736 // to allocate storage with alloca
1737 Type *declType = objectDecl->get_type();
1738 UntypedExpr *alloc = new UntypedExpr( new NameExpr( "__builtin_alloca" ) );
1739 alloc->get_args().push_back( new NameExpr( sizeofName( mangleType( declType ) ) ) );
1740
1741 delete objectDecl->get_init();
1742
1743 std::list<Expression*> designators;
1744 objectDecl->set_init( new SingleInit( alloc, designators, false ) ); // not constructed
1745 }
1746 }
1747 return Mutator::mutate( declStmt );
1748 }
1749
1750 /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
1751 long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
1752 long i = 0;
1753 for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
1754 if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
1755
1756 if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
1757 if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
1758 || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
1759 else continue;
1760 } else return i;
1761 }
1762 return -1;
1763 }
1764
1765 /// Returns an index expression into the offset array for a type
1766 Expression *makeOffsetIndex( Type *objectType, long i ) {
1767 std::stringstream offset_namer;
1768 offset_namer << i;
1769 ConstantExpr *fieldIndex = new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), offset_namer.str() ) );
1770 UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
1771 fieldOffset->get_args().push_back( new NameExpr( offsetofName( mangleType( objectType ) ) ) );
1772 fieldOffset->get_args().push_back( fieldIndex );
1773 return fieldOffset;
1774 }
1775
1776 /// Returns an expression dereferenced n times
1777 Expression *makeDerefdVar( Expression *derefdVar, long n ) {
1778 for ( int i = 1; i < n; ++i ) {
1779 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1780 derefExpr->get_args().push_back( derefdVar );
1781 // xxx - should set results on derefExpr
1782 derefdVar = derefExpr;
1783 }
1784 return derefdVar;
1785 }
1786
1787 Expression *PolyGenericCalculator::mutate( MemberExpr *memberExpr ) {
1788 // mutate, exiting early if no longer MemberExpr
1789 Expression *expr = Mutator::mutate( memberExpr );
1790 memberExpr = dynamic_cast< MemberExpr* >( expr );
1791 if ( ! memberExpr ) return expr;
1792
1793 // get declaration for base struct, exiting early if not found
1794 int varDepth;
1795 VariableExpr *varExpr = getBaseVar( memberExpr->get_aggregate(), &varDepth );
1796 if ( ! varExpr ) return memberExpr;
1797 ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1798 if ( ! objectDecl ) return memberExpr;
1799
1800 // only mutate member expressions for polymorphic types
1801 int tyDepth;
1802 Type *objectType = hasPolyBase( objectDecl->get_type(), scopeTyVars, &tyDepth );
1803 if ( ! objectType ) return memberExpr;
1804 findGeneric( objectType ); // ensure layout for this type is available
1805
1806 // replace member expression with dynamically-computed layout expression
1807 Expression *newMemberExpr = 0;
1808 if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
1809 // look up offset index
1810 long i = findMember( memberExpr->get_member(), structType->get_baseStruct()->get_members() );
1811 if ( i == -1 ) return memberExpr;
1812
1813 // replace member expression with pointer to base plus offset
1814 UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
1815 fieldLoc->get_args().push_back( makeDerefdVar( varExpr->clone(), varDepth ) );
1816 fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
1817 newMemberExpr = fieldLoc;
1818 } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
1819 // union members are all at offset zero, so build appropriately-dereferenced variable
1820 newMemberExpr = makeDerefdVar( varExpr->clone(), varDepth );
1821 } else return memberExpr;
1822 assert( newMemberExpr );
1823
1824 Type *memberType = memberExpr->get_member()->get_type();
1825 if ( ! isPolyType( memberType, scopeTyVars ) ) {
1826 // Not all members of a polymorphic type are themselves of polymorphic type; in this case the member expression should be wrapped and dereferenced to form an lvalue
1827 CastExpr *ptrCastExpr = new CastExpr( newMemberExpr, new PointerType( Type::Qualifiers(), memberType->clone() ) );
1828 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1829 derefExpr->get_args().push_back( ptrCastExpr );
1830 newMemberExpr = derefExpr;
1831 }
1832
1833 delete memberExpr;
1834 return newMemberExpr;
1835 }
1836
1837 ObjectDecl *PolyGenericCalculator::makeVar( const std::string &name, Type *type, Initializer *init ) {
1838 ObjectDecl *newObj = new ObjectDecl( name, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, init );
1839 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
1840 return newObj;
1841 }
1842
1843 void PolyGenericCalculator::addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams ) {
1844 for ( std::list< Type* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
1845 if ( findGeneric( *param ) ) {
1846 // push size/align vars for a generic parameter back
1847 std::string paramName = mangleType( *param );
1848 layoutCall->get_args().push_back( new NameExpr( sizeofName( paramName ) ) );
1849 layoutCall->get_args().push_back( new NameExpr( alignofName( paramName ) ) );
1850 } else {
1851 layoutCall->get_args().push_back( new SizeofExpr( (*param)->clone() ) );
1852 layoutCall->get_args().push_back( new AlignofExpr( (*param)->clone() ) );
1853 }
1854 }
1855 }
1856
1857 /// returns true if any of the otype parameters have a dynamic layout and puts all otype parameters in the output list
1858 bool findGenericParams( std::list< TypeDecl* > &baseParams, std::list< Expression* > &typeParams, std::list< Type* > &out ) {
1859 bool hasDynamicLayout = false;
1860
1861 std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
1862 std::list< Expression* >::const_iterator typeParam = typeParams.begin();
1863 for ( ; baseParam != baseParams.end() && typeParam != typeParams.end(); ++baseParam, ++typeParam ) {
1864 // skip non-otype parameters
1865 if ( (*baseParam)->get_kind() != TypeDecl::Any ) continue;
1866 TypeExpr *typeExpr = dynamic_cast< TypeExpr* >( *typeParam );
1867 assert( typeExpr && "all otype parameters should be type expressions" );
1868
1869 Type *type = typeExpr->get_type();
1870 out.push_back( type );
1871 if ( isPolyType( type ) ) hasDynamicLayout = true;
1872 }
1873 assert( baseParam == baseParams.end() && typeParam == typeParams.end() );
1874
1875 return hasDynamicLayout;
1876 }
1877
1878 bool PolyGenericCalculator::findGeneric( Type *ty ) {
1879 ty = replaceTypeInst( ty, env );
1880
1881 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( ty ) ) {
1882 if ( scopeTyVars.find( typeInst->get_name() ) != scopeTyVars.end() ) {
1883 // NOTE assumes here that getting put in the scopeTyVars included having the layout variables set
1884 return true;
1885 }
1886 return false;
1887 } else if ( StructInstType *structTy = dynamic_cast< StructInstType* >( ty ) ) {
1888 // check if this type already has a layout generated for it
1889 std::string typeName = mangleType( ty );
1890 if ( knownLayouts.find( typeName ) != knownLayouts.end() ) return true;
1891
1892 // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
1893 std::list< Type* > otypeParams;
1894 if ( ! findGenericParams( *structTy->get_baseParameters(), structTy->get_parameters(), otypeParams ) ) return false;
1895
1896 // insert local variables for layout and generate call to layout function
1897 knownLayouts.insert( typeName ); // done early so as not to interfere with the later addition of parameters to the layout call
1898 Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1899
1900 int n_members = structTy->get_baseStruct()->get_members().size();
1901 if ( n_members == 0 ) {
1902 // all empty structs have the same layout - size 1, align 1
1903 makeVar( sizeofName( typeName ), layoutType, new SingleInit( new ConstantExpr( Constant::from_ulong( (unsigned long)1 ) ) ) );
1904 makeVar( alignofName( typeName ), layoutType->clone(), new SingleInit( new ConstantExpr( Constant::from_ulong( (unsigned long)1 ) ) ) );
1905 // NOTE zero-length arrays are forbidden in C, so empty structs have no offsetof array
1906 } else {
1907 ObjectDecl *sizeVar = makeVar( sizeofName( typeName ), layoutType );
1908 ObjectDecl *alignVar = makeVar( alignofName( typeName ), layoutType->clone() );
1909 ObjectDecl *offsetVar = makeVar( offsetofName( typeName ), new ArrayType( Type::Qualifiers(), layoutType->clone(), new ConstantExpr( Constant::from_int( n_members ) ), false, false ) );
1910
1911 // generate call to layout function
1912 UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( layoutofName( structTy->get_baseStruct() ) ) );
1913 layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
1914 layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
1915 layoutCall->get_args().push_back( new VariableExpr( offsetVar ) );
1916 addOtypeParamsToLayoutCall( layoutCall, otypeParams );
1917
1918 stmtsToAdd.push_back( new ExprStmt( noLabels, layoutCall ) );
1919 }
1920
1921 return true;
1922 } else if ( UnionInstType *unionTy = dynamic_cast< UnionInstType* >( ty ) ) {
1923 // check if this type already has a layout generated for it
1924 std::string typeName = mangleType( ty );
1925 if ( knownLayouts.find( typeName ) != knownLayouts.end() ) return true;
1926
1927 // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
1928 std::list< Type* > otypeParams;
1929 if ( ! findGenericParams( *unionTy->get_baseParameters(), unionTy->get_parameters(), otypeParams ) ) return false;
1930
1931 // insert local variables for layout and generate call to layout function
1932 knownLayouts.insert( typeName ); // done early so as not to interfere with the later addition of parameters to the layout call
1933 Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1934
1935 ObjectDecl *sizeVar = makeVar( sizeofName( typeName ), layoutType );
1936 ObjectDecl *alignVar = makeVar( alignofName( typeName ), layoutType->clone() );
1937
1938 // generate call to layout function
1939 UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( layoutofName( unionTy->get_baseUnion() ) ) );
1940 layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
1941 layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
1942 addOtypeParamsToLayoutCall( layoutCall, otypeParams );
1943
1944 stmtsToAdd.push_back( new ExprStmt( noLabels, layoutCall ) );
1945
1946 return true;
1947 }
1948
1949 return false;
1950 }
1951
1952 Expression *PolyGenericCalculator::mutate( SizeofExpr *sizeofExpr ) {
1953 Type *ty = sizeofExpr->get_type();
1954 if ( findGeneric( ty ) ) {
1955 Expression *ret = new NameExpr( sizeofName( mangleType( ty ) ) );
1956 delete sizeofExpr;
1957 return ret;
1958 }
1959 return sizeofExpr;
1960 }
1961
1962 Expression *PolyGenericCalculator::mutate( AlignofExpr *alignofExpr ) {
1963 Type *ty = alignofExpr->get_type();
1964 if ( findGeneric( ty ) ) {
1965 Expression *ret = new NameExpr( alignofName( mangleType( ty ) ) );
1966 delete alignofExpr;
1967 return ret;
1968 }
1969 return alignofExpr;
1970 }
1971
1972 Expression *PolyGenericCalculator::mutate( OffsetofExpr *offsetofExpr ) {
1973 // mutate, exiting early if no longer OffsetofExpr
1974 Expression *expr = Mutator::mutate( offsetofExpr );
1975 offsetofExpr = dynamic_cast< OffsetofExpr* >( expr );
1976 if ( ! offsetofExpr ) return expr;
1977
1978 // only mutate expressions for polymorphic structs/unions
1979 Type *ty = offsetofExpr->get_type();
1980 if ( ! findGeneric( ty ) ) return offsetofExpr;
1981
1982 if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
1983 // replace offsetof expression by index into offset array
1984 long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
1985 if ( i == -1 ) return offsetofExpr;
1986
1987 Expression *offsetInd = makeOffsetIndex( ty, i );
1988 delete offsetofExpr;
1989 return offsetInd;
1990 } else if ( dynamic_cast< UnionInstType* >( ty ) ) {
1991 // all union members are at offset zero
1992 delete offsetofExpr;
1993 return new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), "0" ) );
1994 } else return offsetofExpr;
1995 }
1996
1997 Expression *PolyGenericCalculator::mutate( OffsetPackExpr *offsetPackExpr ) {
1998 StructInstType *ty = offsetPackExpr->get_type();
1999
2000 Expression *ret = 0;
2001 if ( findGeneric( ty ) ) {
2002 // pull offset back from generated type information
2003 ret = new NameExpr( offsetofName( mangleType( ty ) ) );
2004 } else {
2005 std::string offsetName = offsetofName( mangleType( ty ) );
2006 if ( knownOffsets.find( offsetName ) != knownOffsets.end() ) {
2007 // use the already-generated offsets for this type
2008 ret = new NameExpr( offsetName );
2009 } else {
2010 knownOffsets.insert( offsetName );
2011
2012 std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
2013 Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
2014
2015 // build initializer list for offset array
2016 std::list< Initializer* > inits;
2017 for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
2018 DeclarationWithType *memberDecl;
2019 if ( DeclarationWithType *origMember = dynamic_cast< DeclarationWithType* >( *member ) ) {
2020 memberDecl = origMember->clone();
2021 } else {
2022 memberDecl = new ObjectDecl( (*member)->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, offsetType->clone(), 0 );
2023 }
2024 inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
2025 }
2026
2027 // build the offset array and replace the pack with a reference to it
2028 ObjectDecl *offsetArray = makeVar( offsetName, new ArrayType( Type::Qualifiers(), offsetType, new ConstantExpr( Constant::from_ulong( baseMembers.size() ) ), false, false ),
2029 new ListInit( inits ) );
2030 ret = new VariableExpr( offsetArray );
2031 }
2032 }
2033
2034 delete offsetPackExpr;
2035 return ret;
2036 }
2037
2038 void PolyGenericCalculator::doBeginScope() {
2039 knownLayouts.beginScope();
2040 knownOffsets.beginScope();
2041 }
2042
2043 void PolyGenericCalculator::doEndScope() {
2044 knownLayouts.endScope();
2045 knownOffsets.endScope();
2046 }
2047
2048////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
2049
2050 template< typename DeclClass >
2051 DeclClass * Pass3::handleDecl( DeclClass *decl, Type *type ) {
2052 scopeTyVars.beginScope();
2053 makeTyVarMap( type, scopeTyVars );
2054
2055 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
2056 ScrubTyVars::scrub( decl, scopeTyVars );
2057
2058 scopeTyVars.endScope();
2059 return ret;
2060 }
2061
2062 ObjectDecl * Pass3::mutate( ObjectDecl *objectDecl ) {
2063 return handleDecl( objectDecl, objectDecl->get_type() );
2064 }
2065
2066 DeclarationWithType * Pass3::mutate( FunctionDecl *functionDecl ) {
2067 return handleDecl( functionDecl, functionDecl->get_functionType() );
2068 }
2069
2070 TypedefDecl * Pass3::mutate( TypedefDecl *typedefDecl ) {
2071 return handleDecl( typedefDecl, typedefDecl->get_base() );
2072 }
2073
2074 TypeDecl * Pass3::mutate( TypeDecl *typeDecl ) {
2075// Initializer *init = 0;
2076// std::list< Expression *> designators;
2077// scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2078// if ( typeDecl->get_base() ) {
2079// init = new SimpleInit( new SizeofExpr( handleDecl( typeDecl, typeDecl->get_base() ) ), designators );
2080// }
2081// return new ObjectDecl( typeDecl->get_name(), Declaration::Extern, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::UnsignedInt ), init );
2082
2083 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2084 return Mutator::mutate( typeDecl );
2085 }
2086
2087 Type * Pass3::mutate( PointerType *pointerType ) {
2088 scopeTyVars.beginScope();
2089 makeTyVarMap( pointerType, scopeTyVars );
2090
2091 Type *ret = Mutator::mutate( pointerType );
2092
2093 scopeTyVars.endScope();
2094 return ret;
2095 }
2096
2097 Type * Pass3::mutate( FunctionType *functionType ) {
2098 scopeTyVars.beginScope();
2099 makeTyVarMap( functionType, scopeTyVars );
2100
2101 Type *ret = Mutator::mutate( functionType );
2102
2103 scopeTyVars.endScope();
2104 return ret;
2105 }
2106 } // anonymous namespace
2107} // namespace GenPoly
2108
2109// Local Variables: //
2110// tab-width: 4 //
2111// mode: c++ //
2112// compile-command: "make install" //
2113// End: //
Note: See TracBrowser for help on using the repository browser.