source: src/SymTab/Mangler.cc @ fc263b5

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumwith_gc
Last change on this file since fc263b5 was 3f024c9, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Mangle function pointers the same as functions to prevent function/function-pointer overloading

  • Property mode set to 100644
File size: 14.1 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 "SynTree/Declaration.h"    // for TypeDecl, DeclarationWithType
30#include "SynTree/Expression.h"     // for TypeExpr, Expression, operator<<
31#include "SynTree/Type.h"           // for Type, ReferenceToType, Type::Fora...
32
33namespace SymTab {
34        namespace Mangler {
35                namespace {
36                        /// Mangles names to a unique C identifier
37                        struct Mangler : public WithShortCircuiting, public WithVisitorRef<Mangler>, public WithGuards {
38                                Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams );
39                                Mangler( const Mangler & ) = delete;
40
41                                void previsit( BaseSyntaxNode * ) { visit_children = false; }
42
43                                void postvisit( ObjectDecl * declaration );
44                                void postvisit( FunctionDecl * declaration );
45                                void postvisit( TypeDecl * declaration );
46
47                                void postvisit( VoidType * voidType );
48                                void postvisit( BasicType * basicType );
49                                void postvisit( PointerType * pointerType );
50                                void postvisit( ArrayType * arrayType );
51                                void postvisit( ReferenceType * refType );
52                                void postvisit( FunctionType * functionType );
53                                void postvisit( StructInstType * aggregateUseType );
54                                void postvisit( UnionInstType * aggregateUseType );
55                                void postvisit( EnumInstType * aggregateUseType );
56                                void postvisit( TypeInstType * aggregateUseType );
57                                void postvisit( TraitInstType * inst );
58                                void postvisit( TupleType * tupleType );
59                                void postvisit( VarArgsType * varArgsType );
60                                void postvisit( ZeroType * zeroType );
61                                void postvisit( OneType * oneType );
62
63                                std::string get_mangleName() { return mangleName.str(); }
64                          private:
65                                std::ostringstream mangleName;  ///< Mangled name being constructed
66                                typedef std::map< std::string, std::pair< int, int > > VarMapType;
67                                VarMapType varNums;             ///< Map of type variables to indices
68                                int nextVarNum;                 ///< Next type variable index
69                                bool isTopLevel;                ///< Is the Mangler at the top level
70                                bool mangleOverridable;         ///< Specially mangle overridable built-in methods
71                                bool typeMode;                  ///< Produce a unique mangled name for a type
72                                bool mangleGenericParams;       ///< Include generic parameters in name mangling if true
73                                bool inFunctionType = false;    ///< Include type qualifiers if false.
74
75                                void mangleDecl( DeclarationWithType *declaration );
76                                void mangleRef( ReferenceToType *refType, std::string prefix );
77
78                                void printQualifiers( Type *type );
79                        }; // Mangler
80                } // namespace
81
82                std::string mangle( BaseSyntaxNode * decl, bool mangleOverridable, bool typeMode, bool mangleGenericParams ) {
83                        PassVisitor<Mangler> mangler( mangleOverridable, typeMode, mangleGenericParams );
84                        maybeAccept( decl, mangler );
85                        return mangler.pass.get_mangleName();
86                }
87
88                std::string mangleType( Type * ty ) {
89                        PassVisitor<Mangler> mangler( false, true, true );
90                        maybeAccept( ty, mangler );
91                        return mangler.pass.get_mangleName();
92                }
93
94                std::string mangleConcrete( Type * ty ) {
95                        PassVisitor<Mangler> mangler( false, false, false );
96                        maybeAccept( ty, mangler );
97                        return mangler.pass.get_mangleName();
98                }
99
100                namespace {
101                        Mangler::Mangler( bool mangleOverridable, bool typeMode, bool mangleGenericParams )
102                                : nextVarNum( 0 ), isTopLevel( true ), mangleOverridable( mangleOverridable ), typeMode( typeMode ), mangleGenericParams( mangleGenericParams ) {}
103
104                        void Mangler::mangleDecl( DeclarationWithType * declaration ) {
105                                bool wasTopLevel = isTopLevel;
106                                if ( isTopLevel ) {
107                                        varNums.clear();
108                                        nextVarNum = 0;
109                                        isTopLevel = false;
110                                } // if
111                                mangleName << "__";
112                                CodeGen::OperatorInfo opInfo;
113                                if ( operatorLookup( declaration->get_name(), opInfo ) ) {
114                                        mangleName << opInfo.outputName;
115                                } else {
116                                        mangleName << declaration->get_name();
117                                } // if
118                                mangleName << "__";
119                                maybeAccept( declaration->get_type(), *visitor );
120                                if ( mangleOverridable && LinkageSpec::isOverridable( declaration->get_linkage() ) ) {
121                                        // want to be able to override autogenerated and intrinsic routines,
122                                        // so they need a different name mangling
123                                        if ( declaration->get_linkage() == LinkageSpec::AutoGen ) {
124                                                mangleName << "autogen__";
125                                        } else if ( declaration->get_linkage() == LinkageSpec::Intrinsic ) {
126                                                mangleName << "intrinsic__";
127                                        } else {
128                                                // if we add another kind of overridable function, this has to change
129                                                assert( false && "unknown overrideable linkage" );
130                                        } // if
131                                }
132                                isTopLevel = wasTopLevel;
133                        }
134
135                        void Mangler::postvisit( ObjectDecl * declaration ) {
136                                mangleDecl( declaration );
137                        }
138
139                        void Mangler::postvisit( FunctionDecl * declaration ) {
140                                mangleDecl( declaration );
141                        }
142
143                        void Mangler::postvisit( VoidType * voidType ) {
144                                printQualifiers( voidType );
145                                mangleName << "v";
146                        }
147
148                        void Mangler::postvisit( BasicType * basicType ) {
149                                static const char *btLetter[] = {
150                                        "b",    // Bool
151                                        "c",    // Char
152                                        "Sc",   // SignedChar
153                                        "Uc",   // UnsignedChar
154                                        "s",    // ShortSignedInt
155                                        "Us",   // ShortUnsignedInt
156                                        "i",    // SignedInt
157                                        "Ui",   // UnsignedInt
158                                        "l",    // LongSignedInt
159                                        "Ul",   // LongUnsignedInt
160                                        "q",    // LongLongSignedInt
161                                        "Uq",   // LongLongUnsignedInt
162                                        "f",    // Float
163                                        "d",    // Double
164                                        "r",    // LongDouble
165                                        "Xf",   // FloatComplex
166                                        "Xd",   // DoubleComplex
167                                        "Xr",   // LongDoubleComplex
168                                        "If",   // FloatImaginary
169                                        "Id",   // DoubleImaginary
170                                        "Ir",   // LongDoubleImaginary
171                                        "w",    // SignedInt128
172                                        "Uw",   // UnsignedInt128
173                                };
174
175                                printQualifiers( basicType );
176                                mangleName << btLetter[ basicType->get_kind() ];
177                        }
178
179                        void Mangler::postvisit( PointerType * pointerType ) {
180                                printQualifiers( pointerType );
181                                // mangle void (*f)() and void f() to the same name to prevent overloading on functions and function pointers
182                                if ( ! dynamic_cast<FunctionType *>( pointerType->base ) ) mangleName << "P";
183                                maybeAccept( pointerType->base, *visitor );
184                        }
185
186                        void Mangler::postvisit( ArrayType * arrayType ) {
187                                // TODO: encode dimension
188                                printQualifiers( arrayType );
189                                mangleName << "A0";
190                                maybeAccept( arrayType->base, *visitor );
191                        }
192
193                        void Mangler::postvisit( ReferenceType * refType ) {
194                                // don't print prefix (e.g. 'R') for reference types so that references and non-references do not overload.
195                                // Further, do not print the qualifiers for a reference type (but do run printQualifers because of TypeDecls, etc.),
196                                // by pretending every reference type is a function parameter.
197                                GuardValue( inFunctionType );
198                                inFunctionType = true;
199                                printQualifiers( refType );
200                                maybeAccept( refType->base, *visitor );
201                        }
202
203                        namespace {
204                                inline std::list< Type* > getTypes( const std::list< DeclarationWithType* > decls ) {
205                                        std::list< Type* > ret;
206                                        std::transform( decls.begin(), decls.end(), std::back_inserter( ret ),
207                                                                        std::mem_fun( &DeclarationWithType::get_type ) );
208                                        return ret;
209                                }
210                        }
211
212                        void Mangler::postvisit( FunctionType * functionType ) {
213                                printQualifiers( functionType );
214                                mangleName << "F";
215                                // turn on inFunctionType so that printQualifiers does not print most qualifiers for function parameters,
216                                // since qualifiers on outermost parameter type do not differentiate function types, e.g.,
217                                // void (*)(const int) and void (*)(int) are the same type, but void (*)(const int *) and void (*)(int *) are different
218                                GuardValue( inFunctionType );
219                                inFunctionType = true;
220                                std::list< Type* > returnTypes = getTypes( functionType->get_returnVals() );
221                                acceptAll( returnTypes, *visitor );
222                                mangleName << "_";
223                                std::list< Type* > paramTypes = getTypes( functionType->get_parameters() );
224                                acceptAll( paramTypes, *visitor );
225                                mangleName << "_";
226                        }
227
228                        void Mangler::mangleRef( ReferenceToType * refType, std::string prefix ) {
229                                printQualifiers( refType );
230
231                                mangleName << ( refType->get_name().length() + prefix.length() ) << prefix << refType->get_name();
232
233                                if ( mangleGenericParams ) {
234                                        std::list< Expression* >& params = refType->get_parameters();
235                                        if ( ! params.empty() ) {
236                                                mangleName << "_";
237                                                for ( std::list< Expression* >::const_iterator param = params.begin(); param != params.end(); ++param ) {
238                                                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
239                                                        assertf(paramType, "Aggregate parameters should be type expressions: %s", toString(*param).c_str());
240                                                        maybeAccept( paramType->get_type(), *visitor );
241                                                }
242                                                mangleName << "_";
243                                        }
244                                }
245                        }
246
247                        void Mangler::postvisit( StructInstType * aggregateUseType ) {
248                                mangleRef( aggregateUseType, "s" );
249                        }
250
251                        void Mangler::postvisit( UnionInstType * aggregateUseType ) {
252                                mangleRef( aggregateUseType, "u" );
253                        }
254
255                        void Mangler::postvisit( EnumInstType * aggregateUseType ) {
256                                mangleRef( aggregateUseType, "e" );
257                        }
258
259                        void Mangler::postvisit( TypeInstType * typeInst ) {
260                                VarMapType::iterator varNum = varNums.find( typeInst->get_name() );
261                                if ( varNum == varNums.end() ) {
262                                        mangleRef( typeInst, "t" );
263                                } else {
264                                        printQualifiers( typeInst );
265                                        std::ostringstream numStream;
266                                        numStream << varNum->second.first;
267                                        switch ( (TypeDecl::Kind )varNum->second.second ) {
268                                          case TypeDecl::Dtype:
269                                                mangleName << "d";
270                                                break;
271                                          case TypeDecl::Ftype:
272                                                mangleName << "f";
273                                                break;
274                                                case TypeDecl::Ttype:
275                                                mangleName << "tVARGS";
276                                                break;
277                                                default:
278                                                assert( false );
279                                        } // switch
280                                        mangleName << numStream.str();
281                                } // if
282                        }
283
284                        void Mangler::postvisit( TraitInstType * inst ) {
285                                printQualifiers( inst );
286                                mangleName << "_Y" << inst->name << "_";
287                        }
288
289                        void Mangler::postvisit( TupleType * tupleType ) {
290                                printQualifiers( tupleType );
291                                mangleName << "T";
292                                acceptAll( tupleType->types, *visitor );
293                                mangleName << "_";
294                        }
295
296                        void Mangler::postvisit( VarArgsType * varArgsType ) {
297                                printQualifiers( varArgsType );
298                                mangleName << "VARGS";
299                        }
300
301                        void Mangler::postvisit( ZeroType * ) {
302                                mangleName << "Z";
303                        }
304
305                        void Mangler::postvisit( OneType * ) {
306                                mangleName << "O";
307                        }
308
309                        void Mangler::postvisit( TypeDecl * decl ) {
310                                static const char *typePrefix[] = { "BT", "BD", "BF" };
311                                mangleName << typePrefix[ decl->get_kind() ] << ( decl->name.length() + 1 ) << decl->name;
312                        }
313
314                        __attribute__((unused)) void printVarMap( const std::map< std::string, std::pair< int, int > > &varMap, std::ostream &os ) {
315                                for ( std::map< std::string, std::pair< int, int > >::const_iterator i = varMap.begin(); i != varMap.end(); ++i ) {
316                                        os << i->first << "(" << i->second.first << "/" << i->second.second << ")" << std::endl;
317                                } // for
318                        }
319
320                        void Mangler::printQualifiers( Type * type ) {
321                                // skip if not including qualifiers
322                                if ( typeMode ) return;
323                                if ( ! type->get_forall().empty() ) {
324                                        std::list< std::string > assertionNames;
325                                        int tcount = 0, dcount = 0, fcount = 0, vcount = 0;
326                                        mangleName << "A";
327                                        for ( Type::ForallList::iterator i = type->forall.begin(); i != type->forall.end(); ++i ) {
328                                                switch ( (*i)->get_kind() ) {
329                                                  case TypeDecl::Dtype:
330                                                        dcount++;
331                                                        break;
332                                                  case TypeDecl::Ftype:
333                                                        fcount++;
334                                                        break;
335                                                  case TypeDecl::Ttype:
336                                                        vcount++;
337                                                        break;
338                                                  default:
339                                                        assert( false );
340                                                } // switch
341                                                varNums[ (*i)->name ] = std::pair< int, int >( nextVarNum++, (int)(*i)->get_kind() );
342                                                for ( std::list< DeclarationWithType* >::iterator assert = (*i)->assertions.begin(); assert != (*i)->assertions.end(); ++assert ) {
343                                                        PassVisitor<Mangler> sub_mangler( mangleOverridable, typeMode, mangleGenericParams );
344                                                        sub_mangler.pass.nextVarNum = nextVarNum;
345                                                        sub_mangler.pass.isTopLevel = false;
346                                                        sub_mangler.pass.varNums = varNums;
347                                                        (*assert)->accept( sub_mangler );
348                                                        assertionNames.push_back( sub_mangler.pass.mangleName.str() );
349                                                } // for
350                                        } // for
351                                        mangleName << tcount << "_" << dcount << "_" << fcount << "_" << vcount << "_";
352                                        std::copy( assertionNames.begin(), assertionNames.end(), std::ostream_iterator< std::string >( mangleName, "" ) );
353                                        mangleName << "_";
354                                } // if
355                                if ( ! inFunctionType ) {
356                                        // these qualifiers do not distinguish the outermost type of a function parameter
357                                        if ( type->get_const() ) {
358                                                mangleName << "C";
359                                        } // if
360                                        if ( type->get_volatile() ) {
361                                                mangleName << "V";
362                                        } // if
363                                        // Removed due to restrict not affecting function compatibility in GCC
364                                        // if ( type->get_isRestrict() ) {
365                                        //      mangleName << "E";
366                                        // } // if
367                                        if ( type->get_atomic() ) {
368                                                mangleName << "A";
369                                        } // if
370                                }
371                                if ( type->get_mutex() ) {
372                                        mangleName << "M";
373                                } // if
374                                if ( type->get_lvalue() ) {
375                                        // mangle based on whether the type is lvalue, so that the resolver can differentiate lvalues and rvalues
376                                        mangleName << "L";
377                                }
378
379                                if ( inFunctionType ) {
380                                        // turn off inFunctionType so that types can be differentiated for nested qualifiers
381                                        GuardValue( inFunctionType );
382                                        inFunctionType = false;
383                                }
384                        }
385                }       // namespace
386        } // namespace Mangler
387} // namespace SymTab
388
389// Local Variables: //
390// tab-width: 4 //
391// mode: c++ //
392// compile-command: "make install" //
393// End: //
Note: See TracBrowser for help on using the repository browser.