add new isSingleStringRef()/getSingleStringRef() methods to twine,
[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   StringRef Name;
192   if (GVName.isSingleStringRef())
193     Name = GVName.getSingleStringRef();
194   else {
195     GVName.toVector(TmpData);
196     Name = TmpData.str();
197   }
198   assert(!Name.empty() && "getNameWithPrefix requires non-empty name");
199   
200   // If the global name is not led with \1, add the appropriate prefixes.
201   if (Name[0] != '\1') {
202     if (PrefixTy == Mangler::Private)
203       OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
204     else if (PrefixTy == Mangler::LinkerPrivate)
205       OutName.append(LinkerPrivatePrefix,
206                      LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));
207     
208     if (Prefix[0] == 0)
209       ; // Common noop, no prefix.
210     else if (Prefix[1] == 0)
211       OutName.push_back(Prefix[0]);  // Common, one character prefix.
212     else
213       OutName.append(Prefix, Prefix+strlen(Prefix)); // Arbitrary prefix.
214   } else {
215     Name = Name.substr(1);
216   }
217   
218   OutName.append(Name.begin(), Name.end());
219 }
220
221
222 /// getNameWithPrefix - Fill OutName with the name of the appropriate prefix
223 /// and the specified global variable's name.  If the global variable doesn't
224 /// have a name, this fills in a unique name for the global.
225 void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
226                                 const GlobalValue *GV,
227                                 bool isImplicitlyPrivate) {
228   // If this global has a name, handle it simply.
229   if (GV->hasName()) {
230     ManglerPrefixTy PrefixTy = Mangler::Default;
231     if (GV->hasPrivateLinkage() || isImplicitlyPrivate)
232       PrefixTy = Mangler::Private;
233     else if (GV->hasLinkerPrivateLinkage())
234       PrefixTy = Mangler::LinkerPrivate;
235     
236     return getNameWithPrefix(OutName, GV->getName(), PrefixTy);
237   }
238   
239   // If the global variable doesn't have a name, return a unique name for the
240   // global based on a numbering.
241   
242   // Anonymous names always get prefixes.
243   if (GV->hasPrivateLinkage() || isImplicitlyPrivate)
244     OutName.append(PrivatePrefix, PrivatePrefix+strlen(PrivatePrefix));
245   else if (GV->hasLinkerPrivateLinkage())
246     OutName.append(LinkerPrivatePrefix,
247                    LinkerPrivatePrefix+strlen(LinkerPrivatePrefix));;
248   OutName.append(Prefix, Prefix+strlen(Prefix));
249   
250   // Get the ID for the global, assigning a new one if we haven't got one
251   // already.
252   unsigned &ID = AnonGlobalIDs[GV];
253   if (ID == 0) ID = NextAnonGlobalID++;
254   
255   // Must mangle the global into a unique ID.
256   raw_svector_ostream(OutName) << "__unnamed_" << ID;
257 }
258
259
260 Mangler::Mangler(Module &M, const char *prefix, const char *privatePrefix,
261                  const char *linkerPrivatePrefix)
262   : Prefix(prefix), PrivatePrefix(privatePrefix),
263     LinkerPrivatePrefix(linkerPrivatePrefix), UseQuotes(false),
264     SymbolsCanStartWithDigit(false), NextAnonGlobalID(1) {
265   std::fill(AcceptableChars, array_endof(AcceptableChars), 0);
266
267   // Letters and numbers are acceptable.
268   for (unsigned char X = 'a'; X <= 'z'; ++X)
269     markCharAcceptable(X);
270   for (unsigned char X = 'A'; X <= 'Z'; ++X)
271     markCharAcceptable(X);
272   for (unsigned char X = '0'; X <= '9'; ++X)
273     markCharAcceptable(X);
274   
275   // These chars are acceptable.
276   markCharAcceptable('_');
277   markCharAcceptable('$');
278   markCharAcceptable('.');
279   markCharAcceptable('@');
280 }