ugh, my last patch just sped up a method and changed all the clients
[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 is distributed under the University of Illinois Open Source
6 // 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/Function.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Support/raw_ostream.h"
21 using namespace llvm;
22
23 static char HexDigit(int V) {
24   return V < 10 ? V+'0' : V+'A'-10;
25 }
26
27 static void MangleLetter(SmallVectorImpl<char> &OutName, unsigned char C) {
28   OutName.push_back('_');
29   OutName.push_back(HexDigit(C >> 4));
30   OutName.push_back(HexDigit(C & 15));
31   OutName.push_back('_');
32 }
33
34 /// makeNameProper - We don't want identifier names non-C-identifier characters
35 /// in them, so mangle them as appropriate.
36 ///
37 /// FIXME: This is deprecated, new code should use getNameWithPrefix and use
38 /// MCSymbol printing to handle quotes or not etc.
39 ///
40 void Mangler::makeNameProper(SmallVectorImpl<char> &OutName,
41                              const Twine &TheName,
42                              ManglerPrefixTy PrefixTy) {
43   SmallString<256> TmpData;
44   TheName.toVector(TmpData);
45   StringRef X = TmpData.str();
46   assert(!X.empty() && "Cannot mangle empty strings");
47   
48   if (!UseQuotes) {
49     // If X does not start with (char)1, add the prefix.
50     StringRef::iterator I = X.begin();
51     if (*I == 1) {
52       ++I;  // Skip over the no-prefix marker.
53     } else {
54       if (PrefixTy == Mangler::Private)
55         OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
56       else if (PrefixTy == Mangler::LinkerPrivate)
57         OutName.append(LinkerPrivatePrefix,
58                        LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));
59       OutName.append(Prefix, Prefix+strlen(Prefix));
60     }
61     
62     // Mangle the first letter specially, don't allow numbers unless the target
63     // explicitly allows them.
64     if (!SymbolsCanStartWithDigit && *I >= '0' && *I <= '9')
65       MangleLetter(OutName, *I++);
66
67     for (StringRef::iterator E = X.end(); I != E; ++I) {
68       if (!isCharAcceptable(*I))
69         MangleLetter(OutName, *I);
70       else
71         OutName.push_back(*I);
72     }
73     return;
74   }
75
76   bool NeedPrefix = true;
77   bool NeedQuotes = false;
78   StringRef::iterator I = X.begin();
79   if (*I == 1) {
80     NeedPrefix = false;
81     ++I;  // Skip over the marker.
82   }
83
84   // If the first character is a number, we need quotes.
85   if (*I >= '0' && *I <= '9')
86     NeedQuotes = true;
87     
88   // Do an initial scan of the string, checking to see if we need quotes or
89   // to escape a '"' or not.
90   if (!NeedQuotes)
91     for (StringRef::iterator E = X.end(); I != E; ++I)
92       if (!isCharAcceptable(*I)) {
93         NeedQuotes = true;
94         break;
95       }
96     
97   // In the common case, we don't need quotes.  Handle this quickly.
98   if (!NeedQuotes) {
99     if (!NeedPrefix) {
100       OutName.append(X.begin()+1, X.end());   // Strip off the \001.
101       return;
102     }
103
104     if (PrefixTy == Mangler::Private)
105       OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
106     else if (PrefixTy == Mangler::LinkerPrivate)
107       OutName.append(LinkerPrivatePrefix,
108                      LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));
109     
110     if (Prefix[0] == 0)
111       ; // Common noop, no prefix.
112     else if (Prefix[1] == 0)
113       OutName.push_back(Prefix[0]);  // Common, one character prefix.
114     else
115       OutName.append(Prefix, Prefix+strlen(Prefix)); // Arbitrary prefix.
116     OutName.append(X.begin(), X.end());
117     return;
118   }
119
120   // Add leading quote.
121   OutName.push_back('"');
122   
123   // Add prefixes unless disabled.
124   if (NeedPrefix) {
125     if (PrefixTy == Mangler::Private)
126       OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
127     else if (PrefixTy == Mangler::LinkerPrivate)
128       OutName.append(LinkerPrivatePrefix,
129                      LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));
130     OutName.append(Prefix, Prefix+strlen(Prefix));
131   }
132   
133   // Add the piece that we already scanned through.
134   OutName.append(X.begin(), I);
135   
136   // Otherwise, construct the string the expensive way.
137   for (StringRef::iterator E = X.end(); I != E; ++I) {
138     if (*I == '"') {
139       const char *Quote = "_QQ_";
140       OutName.append(Quote, Quote+4);
141     } else if (*I == '\n') {
142       const char *Newline = "_NL_";
143       OutName.append(Newline, Newline+4);
144     } else
145       OutName.push_back(*I);
146   }
147
148   // Add trailing quote.
149   OutName.push_back('"');
150 }
151
152 /// getMangledName - Returns the mangled name of V, an LLVM Value,
153 /// in the current module.  If 'Suffix' is specified, the name ends with the
154 /// specified suffix.  If 'ForcePrivate' is specified, the label is specified
155 /// to have a private label prefix.
156 ///
157 /// FIXME: This is deprecated, new code should use getNameWithPrefix and use
158 /// MCSymbol printing to handle quotes or not etc.
159 ///
160 std::string Mangler::getMangledName(const GlobalValue *GV, const char *Suffix,
161                                     bool ForcePrivate) {
162   assert((!isa<Function>(GV) || !cast<Function>(GV)->isIntrinsic()) &&
163          "Intrinsic functions cannot be mangled by Mangler");
164
165   ManglerPrefixTy PrefixTy =
166     (GV->hasPrivateLinkage() || ForcePrivate) ? Mangler::Private :
167       GV->hasLinkerPrivateLinkage() ? Mangler::LinkerPrivate : Mangler::Default;
168
169   SmallString<128> Result;
170   if (GV->hasName()) {
171     makeNameProper(Result, GV->getNameStr() + Suffix, PrefixTy);
172     return Result.str().str();
173   }
174   
175   // Get the ID for the global, assigning a new one if we haven't got one
176   // already.
177   unsigned &ID = AnonGlobalIDs[GV];
178   if (ID == 0) ID = NextAnonGlobalID++;
179   
180   // Must mangle the global into a unique ID.
181   makeNameProper(Result, "__unnamed_" + utostr(ID) + Suffix, PrefixTy);
182   return Result.str().str();
183 }
184
185 /// getNameWithPrefix - Fill OutName with the name of the appropriate prefix
186 /// and the specified name as the global variable name.  GVName must not be
187 /// empty.
188 void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
189                                 const Twine &GVName, ManglerPrefixTy PrefixTy) {
190   SmallString<256> TmpData;
191   GVName.toVector(TmpData);
192   StringRef Name = TmpData.str();
193   assert(!Name.empty() && "getNameWithPrefix requires non-empty name");
194   
195   // If the global name is not led with \1, add the appropriate prefixes.
196   if (Name[0] != '\1') {
197     if (PrefixTy == Mangler::Private)
198       OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
199     else if (PrefixTy == Mangler::LinkerPrivate)
200       OutName.append(LinkerPrivatePrefix,
201                      LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));
202     
203     if (Prefix[0] == 0)
204       ; // Common noop, no prefix.
205     else if (Prefix[1] == 0)
206       OutName.push_back(Prefix[0]);  // Common, one character prefix.
207     else
208       OutName.append(Prefix, Prefix+strlen(Prefix)); // Arbitrary prefix.
209   } else {
210     Name = Name.substr(1);
211   }
212   
213   OutName.append(Name.begin(), Name.end());
214 }
215
216
217 /// getNameWithPrefix - Fill OutName with the name of the appropriate prefix
218 /// and the specified global variable's name.  If the global variable doesn't
219 /// have a name, this fills in a unique name for the global.
220 void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
221                                 const GlobalValue *GV,
222                                 bool isImplicitlyPrivate) {
223   // If this global has a name, handle it simply.
224   if (GV->hasName()) {
225     ManglerPrefixTy PrefixTy = Mangler::Default;
226     if (GV->hasPrivateLinkage() || isImplicitlyPrivate)
227       PrefixTy = Mangler::Private;
228     else if (GV->hasLinkerPrivateLinkage())
229       PrefixTy = Mangler::LinkerPrivate;
230     
231     return getNameWithPrefix(OutName, GV->getName(), PrefixTy);
232   }
233   
234   // If the global variable doesn't have a name, return a unique name for the
235   // global based on a numbering.
236   
237   // Anonymous names always get prefixes.
238   if (GV->hasPrivateLinkage() || isImplicitlyPrivate)
239     OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
240   else if (GV->hasLinkerPrivateLinkage())
241     OutName.append(LinkerPrivatePrefix,
242                    LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));;
243   OutName.append(Prefix, Prefix+strlen(Prefix));
244   
245   // Get the ID for the global, assigning a new one if we haven't got one
246   // already.
247   unsigned &ID = AnonGlobalIDs[GV];
248   if (ID == 0) ID = NextAnonGlobalID++;
249   
250   // Must mangle the global into a unique ID.
251   raw_svector_ostream(OutName) << "__unnamed_" << ID;
252 }
253
254
255 Mangler::Mangler(Module &M, const char *prefix, const char *privatePrefix,
256                  const char *linkerPrivatePrefix)
257   : Prefix(prefix), PrivatePrefix(privatePrefix),
258     LinkerPrivatePrefix(linkerPrivatePrefix), UseQuotes(false),
259     SymbolsCanStartWithDigit(false), NextAnonGlobalID(1) {
260   std::fill(AcceptableChars, array_endof(AcceptableChars), 0);
261
262   // Letters and numbers are acceptable.
263   for (unsigned char X = 'a'; X <= 'z'; ++X)
264     markCharAcceptable(X);
265   for (unsigned char X = 'A'; X <= 'Z'; ++X)
266     markCharAcceptable(X);
267   for (unsigned char X = '0'; X <= '9'; ++X)
268     markCharAcceptable(X);
269   
270   // These chars are acceptable.
271   markCharAcceptable('_');
272   markCharAcceptable('$');
273   markCharAcceptable('.');
274   markCharAcceptable('@');
275 }