xref: /openbsd/gnu/llvm/llvm/lib/IR/Mangler.cpp (revision d415bd75)
1 //===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Unified name mangler for assembly backends.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/Mangler.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace llvm;
24 
25 namespace {
26 enum ManglerPrefixTy {
27   Default,      ///< Emit default string before each symbol.
28   Private,      ///< Emit "private" prefix before each symbol.
29   LinkerPrivate ///< Emit "linker private" prefix before each symbol.
30 };
31 }
32 
getNameWithPrefixImpl(raw_ostream & OS,const Twine & GVName,ManglerPrefixTy PrefixTy,const DataLayout & DL,char Prefix)33 static void getNameWithPrefixImpl(raw_ostream &OS, const Twine &GVName,
34                                   ManglerPrefixTy PrefixTy,
35                                   const DataLayout &DL, char Prefix) {
36   SmallString<256> TmpData;
37   StringRef Name = GVName.toStringRef(TmpData);
38   assert(!Name.empty() && "getNameWithPrefix requires non-empty name");
39 
40   // No need to do anything special if the global has the special "do not
41   // mangle" flag in the name.
42   if (Name[0] == '\1') {
43     OS << Name.substr(1);
44     return;
45   }
46 
47   if (DL.doNotMangleLeadingQuestionMark() && Name[0] == '?')
48     Prefix = '\0';
49 
50   if (PrefixTy == Private)
51     OS << DL.getPrivateGlobalPrefix();
52   else if (PrefixTy == LinkerPrivate)
53     OS << DL.getLinkerPrivateGlobalPrefix();
54 
55   if (Prefix != '\0')
56     OS << Prefix;
57 
58   // If this is a simple string that doesn't need escaping, just append it.
59   OS << Name;
60 }
61 
getNameWithPrefixImpl(raw_ostream & OS,const Twine & GVName,const DataLayout & DL,ManglerPrefixTy PrefixTy)62 static void getNameWithPrefixImpl(raw_ostream &OS, const Twine &GVName,
63                                   const DataLayout &DL,
64                                   ManglerPrefixTy PrefixTy) {
65   char Prefix = DL.getGlobalPrefix();
66   return getNameWithPrefixImpl(OS, GVName, PrefixTy, DL, Prefix);
67 }
68 
getNameWithPrefix(raw_ostream & OS,const Twine & GVName,const DataLayout & DL)69 void Mangler::getNameWithPrefix(raw_ostream &OS, const Twine &GVName,
70                                 const DataLayout &DL) {
71   return getNameWithPrefixImpl(OS, GVName, DL, Default);
72 }
73 
getNameWithPrefix(SmallVectorImpl<char> & OutName,const Twine & GVName,const DataLayout & DL)74 void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
75                                 const Twine &GVName, const DataLayout &DL) {
76   raw_svector_ostream OS(OutName);
77   char Prefix = DL.getGlobalPrefix();
78   return getNameWithPrefixImpl(OS, GVName, Default, DL, Prefix);
79 }
80 
hasByteCountSuffix(CallingConv::ID CC)81 static bool hasByteCountSuffix(CallingConv::ID CC) {
82   switch (CC) {
83   case CallingConv::X86_FastCall:
84   case CallingConv::X86_StdCall:
85   case CallingConv::X86_VectorCall:
86     return true;
87   default:
88     return false;
89   }
90 }
91 
92 /// Microsoft fastcall and stdcall functions require a suffix on their name
93 /// indicating the number of words of arguments they take.
addByteCountSuffix(raw_ostream & OS,const Function * F,const DataLayout & DL)94 static void addByteCountSuffix(raw_ostream &OS, const Function *F,
95                                const DataLayout &DL) {
96   // Calculate arguments size total.
97   unsigned ArgWords = 0;
98 
99   const unsigned PtrSize = DL.getPointerSize();
100 
101   for (const Argument &A : F->args()) {
102     // For the purposes of the byte count suffix, structs returned by pointer
103     // do not count as function arguments.
104     if (A.hasStructRetAttr())
105       continue;
106 
107     // 'Dereference' type in case of byval or inalloca parameter attribute.
108     uint64_t AllocSize = A.hasPassPointeeByValueCopyAttr() ?
109       A.getPassPointeeByValueCopySize(DL) :
110       DL.getTypeAllocSize(A.getType());
111 
112     // Size should be aligned to pointer size.
113     ArgWords += alignTo(AllocSize, PtrSize);
114   }
115 
116   OS << '@' << ArgWords;
117 }
118 
getNameWithPrefix(raw_ostream & OS,const GlobalValue * GV,bool CannotUsePrivateLabel) const119 void Mangler::getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV,
120                                 bool CannotUsePrivateLabel) const {
121   ManglerPrefixTy PrefixTy = Default;
122   if (GV->hasPrivateLinkage()) {
123     if (CannotUsePrivateLabel)
124       PrefixTy = LinkerPrivate;
125     else
126       PrefixTy = Private;
127   }
128 
129   const DataLayout &DL = GV->getParent()->getDataLayout();
130   if (!GV->hasName()) {
131     // Get the ID for the global, assigning a new one if we haven't got one
132     // already.
133     unsigned &ID = AnonGlobalIDs[GV];
134     if (ID == 0)
135       ID = AnonGlobalIDs.size();
136 
137     // Must mangle the global into a unique ID.
138     getNameWithPrefixImpl(OS, "__unnamed_" + Twine(ID), DL, PrefixTy);
139     return;
140   }
141 
142   StringRef Name = GV->getName();
143   char Prefix = DL.getGlobalPrefix();
144 
145   // Mangle functions with Microsoft calling conventions specially.  Only do
146   // this mangling for x86_64 vectorcall and 32-bit x86.
147   const Function *MSFunc = dyn_cast_or_null<Function>(GV->getAliaseeObject());
148 
149   // Don't add byte count suffixes when '\01' or '?' are in the first
150   // character.
151   if (Name.startswith("\01") ||
152       (DL.doNotMangleLeadingQuestionMark() && Name.startswith("?")))
153     MSFunc = nullptr;
154 
155   CallingConv::ID CC =
156       MSFunc ? MSFunc->getCallingConv() : (unsigned)CallingConv::C;
157   if (!DL.hasMicrosoftFastStdCallMangling() &&
158       CC != CallingConv::X86_VectorCall)
159     MSFunc = nullptr;
160   if (MSFunc) {
161     if (CC == CallingConv::X86_FastCall)
162       Prefix = '@'; // fastcall functions have an @ prefix instead of _.
163     else if (CC == CallingConv::X86_VectorCall)
164       Prefix = '\0'; // vectorcall functions have no prefix.
165   }
166 
167   getNameWithPrefixImpl(OS, Name, PrefixTy, DL, Prefix);
168 
169   if (!MSFunc)
170     return;
171 
172   // If we are supposed to add a microsoft-style suffix for stdcall, fastcall,
173   // or vectorcall, add it.  These functions have a suffix of @N where N is the
174   // cumulative byte size of all of the parameters to the function in decimal.
175   if (CC == CallingConv::X86_VectorCall)
176     OS << '@'; // vectorcall functions use a double @ suffix.
177   FunctionType *FT = MSFunc->getFunctionType();
178   if (hasByteCountSuffix(CC) &&
179       // "Pure" variadic functions do not receive @0 suffix.
180       (!FT->isVarArg() || FT->getNumParams() == 0 ||
181        (FT->getNumParams() == 1 && MSFunc->hasStructRetAttr())))
182     addByteCountSuffix(OS, MSFunc, DL);
183 }
184 
getNameWithPrefix(SmallVectorImpl<char> & OutName,const GlobalValue * GV,bool CannotUsePrivateLabel) const185 void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
186                                 const GlobalValue *GV,
187                                 bool CannotUsePrivateLabel) const {
188   raw_svector_ostream OS(OutName);
189   getNameWithPrefix(OS, GV, CannotUsePrivateLabel);
190 }
191 
192 // Check if the name needs quotes to be safe for the linker to interpret.
canBeUnquotedInDirective(char C)193 static bool canBeUnquotedInDirective(char C) {
194   return isAlnum(C) || C == '_' || C == '@';
195 }
196 
canBeUnquotedInDirective(StringRef Name)197 static bool canBeUnquotedInDirective(StringRef Name) {
198   if (Name.empty())
199     return false;
200 
201   // If any of the characters in the string is an unacceptable character, force
202   // quotes.
203   for (char C : Name) {
204     if (!canBeUnquotedInDirective(C))
205       return false;
206   }
207 
208   return true;
209 }
210 
emitLinkerFlagsForGlobalCOFF(raw_ostream & OS,const GlobalValue * GV,const Triple & TT,Mangler & Mangler)211 void llvm::emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV,
212                                         const Triple &TT, Mangler &Mangler) {
213   if (GV->hasDLLExportStorageClass() && !GV->isDeclaration()) {
214 
215     if (TT.isWindowsMSVCEnvironment())
216       OS << " /EXPORT:";
217     else
218       OS << " -export:";
219 
220     bool NeedQuotes = GV->hasName() && !canBeUnquotedInDirective(GV->getName());
221     if (NeedQuotes)
222       OS << "\"";
223     if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
224       std::string Flag;
225       raw_string_ostream FlagOS(Flag);
226       Mangler.getNameWithPrefix(FlagOS, GV, false);
227       FlagOS.flush();
228       if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
229         OS << Flag.substr(1);
230       else
231         OS << Flag;
232     } else {
233       Mangler.getNameWithPrefix(OS, GV, false);
234     }
235     if (NeedQuotes)
236       OS << "\"";
237 
238     if (!GV->getValueType()->isFunctionTy()) {
239       if (TT.isWindowsMSVCEnvironment())
240         OS << ",DATA";
241       else
242         OS << ",data";
243     }
244   }
245   if (GV->hasHiddenVisibility() && !GV->isDeclaration() && TT.isOSCygMing()) {
246 
247     OS << " -exclude-symbols:";
248 
249     bool NeedQuotes = GV->hasName() && !canBeUnquotedInDirective(GV->getName());
250     if (NeedQuotes)
251       OS << "\"";
252 
253     std::string Flag;
254     raw_string_ostream FlagOS(Flag);
255     Mangler.getNameWithPrefix(FlagOS, GV, false);
256     FlagOS.flush();
257     if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
258       OS << Flag.substr(1);
259     else
260       OS << Flag;
261 
262     if (NeedQuotes)
263       OS << "\"";
264   }
265 }
266 
emitLinkerFlagsForUsedCOFF(raw_ostream & OS,const GlobalValue * GV,const Triple & T,Mangler & M)267 void llvm::emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV,
268                                       const Triple &T, Mangler &M) {
269   if (!T.isWindowsMSVCEnvironment())
270     return;
271 
272   OS << " /INCLUDE:";
273   bool NeedQuotes = GV->hasName() && !canBeUnquotedInDirective(GV->getName());
274   if (NeedQuotes)
275     OS << "\"";
276   M.getNameWithPrefix(OS, GV, false);
277   if (NeedQuotes)
278     OS << "\"";
279 }
280 
281