source: src/GenPoly/Box.cc@ 41a2620

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 41a2620 was 4318107, checked in by Aaron Moss <a3moss@…>, 10 years ago

Fix member expressions for polymorphic generic types where the member has pointer type

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