Make output match actual condition tested. Thanks, Duncan.
[oota-llvm.git] / lib / VMCore / Mangler.cpp
1 //===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Unified name mangler for CWriter and assembly backends.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/Mangler.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/ADT/StringExtras.h"
18 using namespace llvm;
19
20 static char HexDigit(int V) {
21   return V < 10 ? V+'0' : V+'A'-10;
22 }
23
24 static std::string MangleLetter(unsigned char C) {
25   char Result[] = { '_', HexDigit(C >> 4), HexDigit(C & 15), '_', 0 };
26   return Result;
27 }
28
29 /// makeNameProper - We don't want identifier names non-C-identifier characters
30 /// in them, so mangle them as appropriate.
31 ///
32 std::string Mangler::makeNameProper(const std::string &X, const char *Prefix) {
33   std::string Result;
34   if (X.empty()) return X;  // Empty names are uniqued by the caller.
35   
36   // If PreserveAsmNames is set, names with asm identifiers are not modified. 
37   if (PreserveAsmNames && X[0] == 1)
38     return X;
39   
40   if (!UseQuotes) {
41     // If X does not start with (char)1, add the prefix.
42     std::string::const_iterator I = X.begin();
43     if (*I != 1)
44       Result = Prefix;
45     else
46       ++I;  // Skip over the marker.
47     
48     // Mangle the first letter specially, don't allow numbers.
49     if (*I >= '0' && *I <= '9')
50       Result += MangleLetter(*I++);
51
52     for (std::string::const_iterator E = X.end(); I != E; ++I) {
53       if (!isCharAcceptable(*I))
54         Result += MangleLetter(*I);
55       else
56         Result += *I;
57     }
58   } else {
59     bool NeedsQuotes = false;
60     
61     std::string::const_iterator I = X.begin();
62     if (*I == 1)
63       ++I;  // Skip over the marker.
64
65     // If the first character is a number, we need quotes.
66     if (*I >= '0' && *I <= '9')
67       NeedsQuotes = true;
68     
69     // Do an initial scan of the string, checking to see if we need quotes or
70     // to escape a '"' or not.
71     if (!NeedsQuotes)
72       for (std::string::const_iterator E = X.end(); I != E; ++I)
73         if (!isCharAcceptable(*I)) {
74           NeedsQuotes = true;
75           break;
76         }
77     
78     // In the common case, we don't need quotes.  Handle this quickly.
79     if (!NeedsQuotes) {
80       if (*X.begin() != 1)
81         return Prefix+X;
82       else
83         return X.substr(1);
84     }
85     
86     // Otherwise, construct the string the expensive way.
87     I = X.begin();
88     
89     // If X does not start with (char)1, add the prefix.
90     if (*I != 1)
91       Result = Prefix;
92     else
93       ++I;   // Skip the marker if present.
94       
95     for (std::string::const_iterator E = X.end(); I != E; ++I) {
96       if (*I == '"')
97         Result += "_QQ_";
98       else
99         Result += *I;
100     }
101     Result = '"' + Result + '"';
102   }
103   return Result;
104 }
105
106 /// getTypeID - Return a unique ID for the specified LLVM type.
107 ///
108 unsigned Mangler::getTypeID(const Type *Ty) {
109   unsigned &E = TypeMap[Ty];
110   if (E == 0) E = ++TypeCounter;
111   return E;
112 }
113
114 std::string Mangler::getValueName(const Value *V) {
115   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
116     return getValueName(GV);
117   
118   std::string &Name = Memo[V];
119   if (!Name.empty())
120     return Name;       // Return the already-computed name for V.
121   
122   // Always mangle local names.
123   Name = "ltmp_" + utostr(Count++) + "_" + utostr(getTypeID(V->getType()));
124   return Name;
125 }
126
127
128 std::string Mangler::getValueName(const GlobalValue *GV) {
129   // Check to see whether we've already named V.
130   std::string &Name = Memo[GV];
131   if (!Name.empty())
132     return Name;       // Return the already-computed name for V.
133
134   // Name mangling occurs as follows:
135   // - If V is an intrinsic function, do not change name at all
136   // - Otherwise, mangling occurs if global collides with existing name.
137   if (isa<Function>(GV) && cast<Function>(GV)->getIntrinsicID()) {
138     Name = GV->getName(); // Is an intrinsic function
139   } else if (!GV->hasName()) {
140     // Must mangle the global into a unique ID.
141     unsigned TypeUniqueID = getTypeID(GV->getType());
142     static unsigned GlobalID = 0;
143     Name = "__unnamed_" + utostr(TypeUniqueID) + "_" + utostr(GlobalID++);
144   } else if (!MangledGlobals.count(GV)) {
145     Name = makeNameProper(GV->getName(), Prefix);
146   } else {
147     unsigned TypeUniqueID = getTypeID(GV->getType());
148     Name = "l" + utostr(TypeUniqueID) + "_" + makeNameProper(GV->getName());
149   }
150
151   return Name;
152 }
153
154 void Mangler::InsertName(GlobalValue *GV,
155                          std::map<std::string, GlobalValue*> &Names) {
156   if (!GV->hasName())   // We must mangle unnamed globals.
157     return;
158
159   // Figure out if this is already used.
160   GlobalValue *&ExistingValue = Names[GV->getName()];
161   if (!ExistingValue) {
162     ExistingValue = GV;
163   } else {
164     // If GV is external but the existing one is static, mangle the existing one
165     if ((GV->hasExternalLinkage() || GV->hasDLLImportLinkage()) &&
166         !(ExistingValue->hasExternalLinkage() || ExistingValue->hasDLLImportLinkage())) {
167       MangledGlobals.insert(ExistingValue);
168       ExistingValue = GV;
169     } else if ((GV->hasExternalLinkage() ||
170                 GV->hasDLLImportLinkage()) &&
171                (ExistingValue->hasExternalLinkage() ||
172                 ExistingValue->hasDLLImportLinkage()) &&
173                GV->isDeclaration() &&
174                ExistingValue->isDeclaration()) {
175       // If the two globals both have external inkage, and are both external,
176       // don't mangle either of them, we just have some silly type mismatch.
177     } else {
178       // Otherwise, mangle GV
179       MangledGlobals.insert(GV);
180     }
181   }
182 }
183
184
185 Mangler::Mangler(Module &M, const char *prefix)
186   : Prefix(prefix), UseQuotes(false), PreserveAsmNames(false),
187     Count(0), TypeCounter(0) {
188   std::fill(AcceptableChars, 
189           AcceptableChars+sizeof(AcceptableChars)/sizeof(AcceptableChars[0]),
190             0);
191
192   // Letters and numbers are acceptable.
193   for (unsigned char X = 'a'; X <= 'z'; ++X)
194     markCharAcceptable(X);
195   for (unsigned char X = 'A'; X <= 'Z'; ++X)
196     markCharAcceptable(X);
197   for (unsigned char X = '0'; X <= '9'; ++X)
198     markCharAcceptable(X);
199   
200   // These chars are acceptable.
201   markCharAcceptable('_');
202   markCharAcceptable('$');
203   markCharAcceptable('.');
204     
205   // Calculate which global values have names that will collide when we throw
206   // away type information.
207   std::map<std::string, GlobalValue*> Names;
208   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
209     InsertName(I, Names);
210   for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
211     InsertName(I, Names);
212 }
213
214 // Cause this file to be linked in when Support/Mangler.h is #included
215 DEFINING_FILE_FOR(Mangler)