0fc1f2356f87a4434db5fc768a7492bcb00c017e
[oota-llvm.git] / lib / Target / 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 assembly backends.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/Mangler.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace llvm;
25
26 static char HexDigit(int V) {
27   return V < 10 ? V+'0' : V+'A'-10;
28 }
29
30 static void MangleLetter(SmallVectorImpl<char> &OutName, unsigned char C) {
31   OutName.push_back('_');
32   OutName.push_back(HexDigit(C >> 4));
33   OutName.push_back(HexDigit(C & 15));
34   OutName.push_back('_');
35 }
36
37 /// appendMangledQuotedName - On systems that support quoted symbols, we still
38 /// have to escape some (obscure) characters like " and \n which would break the
39 /// assembler's lexing.
40 static void appendMangledQuotedName(SmallVectorImpl<char> &OutName,
41                                    StringRef Str) {
42   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
43     if (Str[i] == '"' || Str[i] == '\n')
44       MangleLetter(OutName, Str[i]);
45     else
46       OutName.push_back(Str[i]);
47   }
48 }
49
50
51 /// getNameWithPrefix - Fill OutName with the name of the appropriate prefix
52 /// and the specified name as the global variable name.  GVName must not be
53 /// empty.
54 void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
55                                 const Twine &GVName, ManglerPrefixTy PrefixTy,
56                                 bool UseGlobalPrefix) {
57   SmallString<256> TmpData;
58   StringRef Name = GVName.toStringRef(TmpData);
59   assert(!Name.empty() && "getNameWithPrefix requires non-empty name");
60   
61   const MCAsmInfo *MAI = TM->getMCAsmInfo();
62   
63   // If the global name is not led with \1, add the appropriate prefixes.
64   if (Name[0] == '\1') {
65     Name = Name.substr(1);
66   } else {
67     if (PrefixTy == Mangler::Private) {
68       const char *Prefix = MAI->getPrivateGlobalPrefix();
69       OutName.append(Prefix, Prefix+strlen(Prefix));
70     } else if (PrefixTy == Mangler::LinkerPrivate) {
71       const char *Prefix = MAI->getLinkerPrivateGlobalPrefix();
72       OutName.append(Prefix, Prefix+strlen(Prefix));
73     }
74
75     if (UseGlobalPrefix) {
76       const char *Prefix = MAI->getGlobalPrefix();
77       if (Prefix[0] == 0)
78         ; // Common noop, no prefix.
79       else if (Prefix[1] == 0)
80         OutName.push_back(Prefix[0]);  // Common, one character prefix.
81       else
82         // Arbitrary length prefix.
83         OutName.append(Prefix, Prefix+strlen(Prefix));
84     }
85   }
86
87   // If this is a simple string that doesn't need escaping, just append it.
88   // Quotes can be used unless the string contains a quote or newline.
89   if (Name.find_first_of("\n\"") == StringRef::npos) {
90     OutName.append(Name.begin(), Name.end());
91     return;
92   }
93
94   // Okay, the system allows quoted strings.  We can quote most anything, the
95   // only characters that need escaping are " and \n.
96   assert(Name.find_first_of("\n\"") != StringRef::npos);
97   return appendMangledQuotedName(OutName, Name);
98 }
99
100 /// AddFastCallStdCallSuffix - Microsoft fastcall and stdcall functions require
101 /// a suffix on their name indicating the number of words of arguments they
102 /// take.
103 static void AddFastCallStdCallSuffix(SmallVectorImpl<char> &OutName,
104                                      const Function *F, const DataLayout &TD) {
105   // Calculate arguments size total.
106   unsigned ArgWords = 0;
107   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
108        AI != AE; ++AI) {
109     Type *Ty = AI->getType();
110     // 'Dereference' type in case of byval parameter attribute
111     if (AI->hasByValAttr())
112       Ty = cast<PointerType>(Ty)->getElementType();
113     // Size should be aligned to DWORD boundary
114     ArgWords += ((TD.getTypeAllocSize(Ty) + 3)/4)*4;
115   }
116   
117   raw_svector_ostream(OutName) << '@' << ArgWords;
118 }
119
120
121 /// getNameWithPrefix - Fill OutName with the name of the appropriate prefix
122 /// and the specified global variable's name.  If the global variable doesn't
123 /// have a name, this fills in a unique name for the global.
124 void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
125                                 const GlobalValue *GV, bool isImplicitlyPrivate,
126                                 bool UseGlobalPrefix) {
127   ManglerPrefixTy PrefixTy = Mangler::Default;
128   if (GV->hasPrivateLinkage() || isImplicitlyPrivate)
129     PrefixTy = Mangler::Private;
130   else if (GV->hasLinkerPrivateLinkage() || GV->hasLinkerPrivateWeakLinkage())
131     PrefixTy = Mangler::LinkerPrivate;
132   
133   // If this global has a name, handle it simply.
134   if (GV->hasName()) {
135     StringRef Name = GV->getName();
136     getNameWithPrefix(OutName, Name, PrefixTy, UseGlobalPrefix);
137     // No need to do anything else if the global has the special "do not mangle"
138     // flag in the name.
139     if (Name[0] == 1)
140       return;
141   } else {
142     // Get the ID for the global, assigning a new one if we haven't got one
143     // already.
144     unsigned &ID = AnonGlobalIDs[GV];
145     if (ID == 0) ID = NextAnonGlobalID++;
146   
147     // Must mangle the global into a unique ID.
148     getNameWithPrefix(OutName, "__unnamed_" + Twine(ID), PrefixTy,
149                       UseGlobalPrefix);
150   }
151   
152   // If we are supposed to add a microsoft-style suffix for stdcall/fastcall,
153   // add it.
154   if (TM->getMCAsmInfo()->hasMicrosoftFastStdCallMangling()) {
155     if (const Function *F = dyn_cast<Function>(GV)) {
156       CallingConv::ID CC = F->getCallingConv();
157     
158       // fastcall functions need to start with @.
159       // FIXME: This logic seems unlikely to be right.
160       if (CC == CallingConv::X86_FastCall) {
161         if (OutName[0] == '_')
162           OutName[0] = '@';
163         else
164           OutName.insert(OutName.begin(), '@');
165       }
166     
167       // fastcall and stdcall functions usually need @42 at the end to specify
168       // the argument info.
169       FunctionType *FT = F->getFunctionType();
170       if ((CC == CallingConv::X86_FastCall || CC == CallingConv::X86_StdCall) &&
171           // "Pure" variadic functions do not receive @0 suffix.
172           (!FT->isVarArg() || FT->getNumParams() == 0 ||
173            (FT->getNumParams() == 1 && F->hasStructRetAttr())))
174         AddFastCallStdCallSuffix(OutName, F, *TM->getDataLayout());
175     }
176   }
177 }