source: src/GenPoly/Box.cc@ 2e60a1a

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

Fix parameter names for layout functions

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