source: src/SymTab/Mangler.cc @ ff5caaf

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resnenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since ff5caaf was ff5caaf, checked in by Aaron Moss <a3moss@…>, 6 years ago

Add environment-based-replacement mode to Mangler

  • Property mode set to 100644
File size: 17.2 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// Mangler.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:40:29 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon Sep 25 15:49:26 2017
13// Update Count     : 23
14//
15#include "Mangler.h"
16
17#include <algorithm>                     // for copy, transform
18#include <cassert>                       // for assert, assertf
19#include <functional>                    // for const_mem_fun_t, mem_fun
20#include <iterator>                      // for ostream_iterator, back_insert_ite...
21#include <list>                          // for _List_iterator, list, _List_const...
22#include <string>                        // for string, char_traits, operator<<
23
24#include "CodeGen/OperatorTable.h"       // for OperatorInfo, operatorLookup
25#include "Common/PassVisitor.h"
26#include "Common/SemanticError.h"        // for SemanticError
27#include "Common/utility.h"              // for toString
28#include "Parser/LinkageSpec.h"          // for Spec, isOverridable, AutoGen, Int...
29#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
30#include "SynTree/Declaration.h"         // for TypeDecl, DeclarationWithType
31#include "SynTree/Expression.h"          // for TypeExpr, Expression, operator<<
32#include "SynTree/Type.h"                // for Type, ReferenceToType, Type::Fora...
33
34namespace SymTab {
35        namespace Mangler {
36                namespace {
37                        /// Mangles names to a unique C identifier
38                        struct Mangler : public WithShortCircuiting, public WithVisitorRef<Mangler>, public WithGuards {
39                                Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams );
40                                Mangler( const ResolvExpr::TypeEnvironment& env );
41                                Mangler( const Mangler & ) = delete;
42
43                                void previsit( BaseSyntaxNode * ) { visit_children = false; }
44
45                                void postvisit( ObjectDecl * declaration );
46                                void postvisit( FunctionDecl * declaration );
47                                void postvisit( TypeDecl * declaration );
48
49                                void postvisit( VoidType * voidType );
50                                void postvisit( BasicType * basicType );
51                                void postvisit( PointerType * pointerType );
52                                void postvisit( ArrayType * arrayType );
53                                void postvisit( ReferenceType * refType );
54                                void postvisit( FunctionType * functionType );
55                                void postvisit( StructInstType * aggregateUseType );
56                                void postvisit( UnionInstType * aggregateUseType );
57                                void postvisit( EnumInstType * aggregateUseType );
58                                void postvisit( TypeInstType * aggregateUseType );
59                                void postvisit( TraitInstType * inst );
60                                void postvisit( TupleType * tupleType );
61                                void postvisit( VarArgsType * varArgsType );
62                                void postvisit( ZeroType * zeroType );
63                                void postvisit( OneType * oneType );
64                                void postvisit( QualifiedType * qualType );
65
66                                std::string get_mangleName() { return mangleName.str(); }
67                          private:
68                                std::ostringstream mangleName;  ///< Mangled name being constructed
69                                typedef std::map< std::string, std::pair< std::string, int > > VarMapType;
70                                VarMapType varNums;             ///< Map of type variables to indices
71                                const ResolvExpr::TypeEnvironment* env;  ///< optional environment for substitutions
72                                int nextVarNum;                 ///< Next type variable index
73                                bool isTopLevel;                ///< Is the Mangler at the top level
74                                bool mangleOverridable;         ///< Specially mangle overridable built-in methods
75                                bool typeMode;                  ///< Produce a unique mangled name for a type
76                                bool mangleGenericParams;       ///< Include generic parameters in name mangling if true
77                                bool inFunctionType = false;    ///< Include type qualifiers if false.
78                                bool inQualifiedType = false;   ///< Add start/end delimiters around qualified type
79
80                                Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams, 
81                                        int nextVarNum, const ResolvExpr::TypeEnvironment* env, 
82                                        const VarMapType& varNums );
83
84                                void mangleDecl( DeclarationWithType *declaration );
85                                void mangleRef( ReferenceToType *refType, std::string prefix );
86
87                                void printQualifiers( Type *type );
88                        }; // Mangler
89                } // namespace
90
91                std::string mangle( BaseSyntaxNode * decl, bool mangleOverridable, bool typeMode, bool mangleGenericParams ) {
92                        PassVisitor<Mangler> mangler( mangleOverridable, typeMode, mangleGenericParams );
93                        maybeAccept( decl, mangler );
94                        return mangler.pass.get_mangleName();
95                }
96
97                std::string mangleType( Type * ty ) {
98                        PassVisitor<Mangler> mangler( false, true, true );
99                        maybeAccept( ty, mangler );
100                        return mangler.pass.get_mangleName();
101                }
102
103                std::string mangleConcrete( Type * ty ) {
104                        PassVisitor<Mangler> mangler( false, false, false );
105                        maybeAccept( ty, mangler );
106                        return mangler.pass.get_mangleName();
107                }
108
109                std::string mangleAssnKey( DeclarationWithType* decl, 
110                                const ResolvExpr::TypeEnvironment& env ) {
111                        PassVisitor<Mangler> mangler( env );
112                        maybeAccept( decl, mangler );
113                        return mangler.pass.get_mangleName();
114                }
115
116                namespace {
117                        Mangler::Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams )
118                                : nextVarNum( 0 ), env(nullptr), isTopLevel( true ), 
119                                mangleOverridable( mangleOverridable ), typeMode( typeMode ), 
120                                mangleGenericParams( mangleGenericParams ) {}
121                       
122                        Mangler::Mangler( const ResolvExpr::TypeEnvironment& env )
123                                : nextVarNum( 0 ), env( &env ), isTopLevel( true ), mangleOverridable( false ),
124                                typeMode( false ), mangleGenericParams( true ) {}
125                       
126                        Mangler::Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams, 
127                                int nextVarNum, const ResolvExpr::TypeEnvironment* env, 
128                                const VarMapType& varNums )
129                                : nextVarNum( nextVarNum ), varNums( varNums ), env( env ), isTopLevel( false ), 
130                                mangleOverridable( mangleOverridable ), typeMode( typeMode ), 
131                                mangleGenericParams( mangleGenericParams ) {}
132
133                        void Mangler::mangleDecl( DeclarationWithType * declaration ) {
134                                bool wasTopLevel = isTopLevel;
135                                if ( isTopLevel ) {
136                                        varNums.clear();
137                                        nextVarNum = 0;
138                                        isTopLevel = false;
139                                } // if
140                                mangleName << Encoding::manglePrefix;
141                                CodeGen::OperatorInfo opInfo;
142                                if ( operatorLookup( declaration->get_name(), opInfo ) ) {
143                                        mangleName << opInfo.outputName.size() << opInfo.outputName;
144                                } else {
145                                        mangleName << declaration->name.size() << declaration->name;
146                                } // if
147                                maybeAccept( declaration->get_type(), *visitor );
148                                if ( mangleOverridable && LinkageSpec::isOverridable( declaration->get_linkage() ) ) {
149                                        // want to be able to override autogenerated and intrinsic routines,
150                                        // so they need a different name mangling
151                                        if ( declaration->get_linkage() == LinkageSpec::AutoGen ) {
152                                                mangleName << Encoding::autogen;
153                                        } else if ( declaration->get_linkage() == LinkageSpec::Intrinsic ) {
154                                                mangleName << Encoding::intrinsic;
155                                        } else {
156                                                // if we add another kind of overridable function, this has to change
157                                                assert( false && "unknown overrideable linkage" );
158                                        } // if
159                                }
160                                isTopLevel = wasTopLevel;
161                        }
162
163                        void Mangler::postvisit( ObjectDecl * declaration ) {
164                                mangleDecl( declaration );
165                        }
166
167                        void Mangler::postvisit( FunctionDecl * declaration ) {
168                                mangleDecl( declaration );
169                        }
170
171                        void Mangler::postvisit( VoidType * voidType ) {
172                                printQualifiers( voidType );
173                                mangleName << Encoding::void_t;
174                        }
175
176                        void Mangler::postvisit( BasicType * basicType ) {
177                                printQualifiers( basicType );
178                                assertf( basicType->get_kind() < BasicType::NUMBER_OF_BASIC_TYPES, "Unhandled basic type: %d", basicType->get_kind() );
179                                mangleName << Encoding::basicTypes[ basicType->get_kind() ];
180                        }
181
182                        void Mangler::postvisit( PointerType * pointerType ) {
183                                printQualifiers( pointerType );
184                                // mangle void (*f)() and void f() to the same name to prevent overloading on functions and function pointers
185                                if ( ! dynamic_cast<FunctionType *>( pointerType->base ) ) mangleName << Encoding::pointer;
186                                maybeAccept( pointerType->base, *visitor );
187                        }
188
189                        void Mangler::postvisit( ArrayType * arrayType ) {
190                                // TODO: encode dimension
191                                printQualifiers( arrayType );
192                                mangleName << Encoding::array << "0";
193                                maybeAccept( arrayType->base, *visitor );
194                        }
195
196                        void Mangler::postvisit( ReferenceType * refType ) {
197                                // don't print prefix (e.g. 'R') for reference types so that references and non-references do not overload.
198                                // Further, do not print the qualifiers for a reference type (but do run printQualifers because of TypeDecls, etc.),
199                                // by pretending every reference type is a function parameter.
200                                GuardValue( inFunctionType );
201                                inFunctionType = true;
202                                printQualifiers( refType );
203                                maybeAccept( refType->base, *visitor );
204                        }
205
206                        namespace {
207                                inline std::list< Type* > getTypes( const std::list< DeclarationWithType* > decls ) {
208                                        std::list< Type* > ret;
209                                        std::transform( decls.begin(), decls.end(), std::back_inserter( ret ),
210                                                                        std::mem_fun( &DeclarationWithType::get_type ) );
211                                        return ret;
212                                }
213                        }
214
215                        void Mangler::postvisit( FunctionType * functionType ) {
216                                printQualifiers( functionType );
217                                mangleName << Encoding::function;
218                                // turn on inFunctionType so that printQualifiers does not print most qualifiers for function parameters,
219                                // since qualifiers on outermost parameter type do not differentiate function types, e.g.,
220                                // void (*)(const int) and void (*)(int) are the same type, but void (*)(const int *) and void (*)(int *) are different
221                                GuardValue( inFunctionType );
222                                inFunctionType = true;
223                                std::list< Type* > returnTypes = getTypes( functionType->returnVals );
224                                if (returnTypes.empty()) mangleName << Encoding::void_t;
225                                else acceptAll( returnTypes, *visitor );
226                                mangleName << "_";
227                                std::list< Type* > paramTypes = getTypes( functionType->parameters );
228                                acceptAll( paramTypes, *visitor );
229                                mangleName << "_";
230                        }
231
232                        void Mangler::mangleRef( ReferenceToType * refType, std::string prefix ) {
233                                printQualifiers( refType );
234
235                                mangleName << prefix << refType->name.length() << refType->name;
236
237                                if ( mangleGenericParams ) {
238                                        std::list< Expression* >& params = refType->parameters;
239                                        if ( ! params.empty() ) {
240                                                mangleName << "_";
241                                                for ( std::list< Expression* >::const_iterator param = params.begin(); param != params.end(); ++param ) {
242                                                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
243                                                        assertf(paramType, "Aggregate parameters should be type expressions: %s", toCString(*param));
244                                                        maybeAccept( paramType->type, *visitor );
245                                                }
246                                                mangleName << "_";
247                                        }
248                                }
249                        }
250
251                        void Mangler::postvisit( StructInstType * aggregateUseType ) {
252                                mangleRef( aggregateUseType, Encoding::struct_t );
253                        }
254
255                        void Mangler::postvisit( UnionInstType * aggregateUseType ) {
256                                mangleRef( aggregateUseType, Encoding::union_t );
257                        }
258
259                        void Mangler::postvisit( EnumInstType * aggregateUseType ) {
260                                mangleRef( aggregateUseType, Encoding::enum_t );
261                        }
262
263                        void Mangler::postvisit( TypeInstType * typeInst ) {
264                                VarMapType::iterator varNum = varNums.find( typeInst->get_name() );
265                                if ( varNum == varNums.end() ) {
266                                        mangleRef( typeInst, Encoding::type );
267                                } else {
268                                        printQualifiers( typeInst );
269                                        // Note: Can't use name here, since type variable names do not actually disambiguate a function, e.g.
270                                        //   forall(dtype T) void f(T);
271                                        //   forall(dtype S) void f(S);
272                                        // are equivalent and should mangle the same way. This is accomplished by numbering the type variables when they
273                                        // are first found and prefixing with the appropriate encoding for the type class.
274                                        assertf( varNum->second.second < TypeDecl::NUMBER_OF_KINDS, "Unhandled type variable kind: %d", varNum->second.second );
275                                        mangleName << Encoding::typeVariables[varNum->second.second] << varNum->second.first;
276                                } // if
277                        }
278
279                        void Mangler::postvisit( TraitInstType * inst ) {
280                                printQualifiers( inst );
281                                mangleName << inst->name.size() << inst->name;
282                        }
283
284                        void Mangler::postvisit( TupleType * tupleType ) {
285                                printQualifiers( tupleType );
286                                mangleName << Encoding::tuple << tupleType->types.size();
287                                acceptAll( tupleType->types, *visitor );
288                        }
289
290                        void Mangler::postvisit( VarArgsType * varArgsType ) {
291                                printQualifiers( varArgsType );
292                                static const std::string vargs = "__builtin_va_list";
293                                mangleName << Encoding::type << vargs.size() << vargs;
294                        }
295
296                        void Mangler::postvisit( ZeroType * ) {
297                                mangleName << Encoding::zero;
298                        }
299
300                        void Mangler::postvisit( OneType * ) {
301                                mangleName << Encoding::one;
302                        }
303
304                        void Mangler::postvisit( QualifiedType * qualType ) {
305                                bool inqual = inQualifiedType;
306                                if (! inqual ) {
307                                        // N marks the start of a qualified type
308                                        inQualifiedType = true;
309                                        mangleName << Encoding::qualifiedTypeStart;
310                                }
311                                maybeAccept( qualType->parent, *visitor );
312                                maybeAccept( qualType->child, *visitor );
313                                if ( ! inqual ) {
314                                        // E marks the end of a qualified type
315                                        inQualifiedType = false;
316                                        mangleName << Encoding::qualifiedTypeEnd;
317                                }
318                        }
319
320                        void Mangler::postvisit( TypeDecl * decl ) {
321                                // TODO: is there any case where mangling a TypeDecl makes sense? If so, this code needs to be
322                                // fixed to ensure that two TypeDecls mangle to the same name when they are the same type and vice versa.
323                                // Note: The current scheme may already work correctly for this case, I have not thought about this deeply
324                                // and the case has not yet come up in practice. Alternatively, if not then this code can be removed
325                                // aside from the assert false.
326                                assertf(false, "Mangler should not visit typedecl: %s", toCString(decl));
327                                assertf( decl->get_kind() < TypeDecl::NUMBER_OF_KINDS, "Unhandled type variable kind: %d", decl->get_kind() );
328                                mangleName << Encoding::typeVariables[ decl->get_kind() ] << ( decl->name.length() ) << decl->name;
329                        }
330
331                        __attribute__((unused)) void printVarMap( const std::map< std::string, std::pair< int, int > > &varMap, std::ostream &os ) {
332                                for ( std::map< std::string, std::pair< int, int > >::const_iterator i = varMap.begin(); i != varMap.end(); ++i ) {
333                                        os << i->first << "(" << i->second.first << "/" << i->second.second << ")" << std::endl;
334                                } // for
335                        }
336
337                        void Mangler::printQualifiers( Type * type ) {
338                                // skip if not including qualifiers
339                                if ( typeMode ) return;
340                                if ( ! type->get_forall().empty() ) {
341                                        std::list< std::string > assertionNames;
342                                        int dcount = 0, fcount = 0, vcount = 0, acount = 0;
343                                        mangleName << Encoding::forall;
344                                        for ( Type::ForallList::iterator i = type->forall.begin(); i != type->forall.end(); ++i ) {
345                                                switch ( (*i)->get_kind() ) {
346                                                  case TypeDecl::Dtype:
347                                                        dcount++;
348                                                        break;
349                                                  case TypeDecl::Ftype:
350                                                        fcount++;
351                                                        break;
352                                                  case TypeDecl::Ttype:
353                                                        vcount++;
354                                                        break;
355                                                  default:
356                                                        assert( false );
357                                                } // switch
358                                                std::string varName;
359                                                // replace type with substitution name if environment is available and bound
360                                                if ( env ) {
361                                                        const EqvClass* varClass = env->lookup( (*i)->name );
362                                                        if ( varClass && varClass->type ) {
363                                                                PassVisitor<Mangler> sub_mangler(
364                                                                        mangleOverridable, typeMode, mangleGenericParams, nextVarNum, 
365                                                                        env, varNums );
366                                                                varClass->type->accept( sub_mangler );
367                                                                varName = std::string{"%"} + sub_mangler.pass.get_mangleName();
368                                                        }
369                                                }
370                                                // otherwise just give type numeric name
371                                                if ( varName.empty() ) {
372                                                        varName = std::to_string( nextVarNum++ );
373                                                }
374                                                varNums[ (*i)->name ] = std::make_pair( varName, (int)(*i)->get_kind() );
375                                                for ( std::list< DeclarationWithType* >::iterator assert = (*i)->assertions.begin(); assert != (*i)->assertions.end(); ++assert ) {
376                                                        PassVisitor<Mangler> sub_mangler( 
377                                                                mangleOverridable, typeMode, mangleGenericParams, nextVarNum, env, 
378                                                                varNums );
379                                                        (*assert)->accept( sub_mangler );
380                                                        assertionNames.push_back( sub_mangler.pass.get_mangleName() );
381                                                        acount++;
382                                                } // for
383                                        } // for
384                                        mangleName << dcount << "_" << fcount << "_" << vcount << "_" << acount << "_";
385                                        std::copy( assertionNames.begin(), assertionNames.end(), std::ostream_iterator< std::string >( mangleName, "" ) );
386                                        mangleName << "_";
387                                } // if
388                                if ( ! inFunctionType ) {
389                                        // these qualifiers do not distinguish the outermost type of a function parameter
390                                        if ( type->get_const() ) {
391                                                mangleName << Encoding::qualifiers.at(Type::Const);
392                                        } // if
393                                        if ( type->get_volatile() ) {
394                                                mangleName << Encoding::qualifiers.at(Type::Volatile);
395                                        } // if
396                                        // Removed due to restrict not affecting function compatibility in GCC
397                                        // if ( type->get_isRestrict() ) {
398                                        //      mangleName << "E";
399                                        // } // if
400                                        if ( type->get_atomic() ) {
401                                                mangleName << Encoding::qualifiers.at(Type::Atomic);
402                                        } // if
403                                }
404                                if ( type->get_mutex() ) {
405                                        mangleName << Encoding::qualifiers.at(Type::Mutex);
406                                } // if
407                                if ( type->get_lvalue() ) {
408                                        // mangle based on whether the type is lvalue, so that the resolver can differentiate lvalues and rvalues
409                                        mangleName << Encoding::qualifiers.at(Type::Lvalue);
410                                }
411
412                                if ( inFunctionType ) {
413                                        // turn off inFunctionType so that types can be differentiated for nested qualifiers
414                                        GuardValue( inFunctionType );
415                                        inFunctionType = false;
416                                }
417                        }
418                }       // namespace
419        } // namespace Mangler
420} // namespace SymTab
421
422// Local Variables: //
423// tab-width: 4 //
424// mode: c++ //
425// compile-command: "make install" //
426// End: //
Note: See TracBrowser for help on using the repository browser.