1 //===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
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
7 //===----------------------------------------------------------------------===//
9 // Unified name mangler for assembly backends.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/Mangler.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringExtras.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/IR/Module.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/TargetParser/Triple.h"
27 enum ManglerPrefixTy
{
28 Default
, ///< Emit default string before each symbol.
29 Private
, ///< Emit "private" prefix before each symbol.
30 LinkerPrivate
///< Emit "linker private" prefix before each symbol.
34 static void getNameWithPrefixImpl(raw_ostream
&OS
, const Twine
&GVName
,
35 ManglerPrefixTy PrefixTy
,
36 const DataLayout
&DL
, char Prefix
) {
37 SmallString
<256> TmpData
;
38 StringRef Name
= GVName
.toStringRef(TmpData
);
39 assert(!Name
.empty() && "getNameWithPrefix requires non-empty name");
41 // No need to do anything special if the global has the special "do not
42 // mangle" flag in the name.
43 if (Name
[0] == '\1') {
48 if (DL
.doNotMangleLeadingQuestionMark() && Name
[0] == '?')
51 if (PrefixTy
== Private
)
52 OS
<< DL
.getPrivateGlobalPrefix();
53 else if (PrefixTy
== LinkerPrivate
)
54 OS
<< DL
.getLinkerPrivateGlobalPrefix();
59 // If this is a simple string that doesn't need escaping, just append it.
63 static void getNameWithPrefixImpl(raw_ostream
&OS
, const Twine
&GVName
,
65 ManglerPrefixTy PrefixTy
) {
66 char Prefix
= DL
.getGlobalPrefix();
67 return getNameWithPrefixImpl(OS
, GVName
, PrefixTy
, DL
, Prefix
);
70 void Mangler::getNameWithPrefix(raw_ostream
&OS
, const Twine
&GVName
,
71 const DataLayout
&DL
) {
72 return getNameWithPrefixImpl(OS
, GVName
, DL
, Default
);
75 void Mangler::getNameWithPrefix(SmallVectorImpl
<char> &OutName
,
76 const Twine
&GVName
, const DataLayout
&DL
) {
77 raw_svector_ostream
OS(OutName
);
78 char Prefix
= DL
.getGlobalPrefix();
79 return getNameWithPrefixImpl(OS
, GVName
, Default
, DL
, Prefix
);
82 static bool hasByteCountSuffix(CallingConv::ID CC
) {
84 case CallingConv::X86_FastCall
:
85 case CallingConv::X86_StdCall
:
86 case CallingConv::X86_VectorCall
:
93 /// Microsoft fastcall and stdcall functions require a suffix on their name
94 /// indicating the number of words of arguments they take.
95 static void addByteCountSuffix(raw_ostream
&OS
, const Function
*F
,
96 const DataLayout
&DL
) {
97 // Calculate arguments size total.
98 unsigned ArgWords
= 0;
100 const unsigned PtrSize
= DL
.getPointerSize();
102 for (const Argument
&A
: F
->args()) {
103 // For the purposes of the byte count suffix, structs returned by pointer
104 // do not count as function arguments.
105 if (A
.hasStructRetAttr())
108 // 'Dereference' type in case of byval or inalloca parameter attribute.
109 uint64_t AllocSize
= A
.hasPassPointeeByValueCopyAttr() ?
110 A
.getPassPointeeByValueCopySize(DL
) :
111 DL
.getTypeAllocSize(A
.getType());
113 // Size should be aligned to pointer size.
114 ArgWords
+= alignTo(AllocSize
, PtrSize
);
117 OS
<< '@' << ArgWords
;
120 void Mangler::getNameWithPrefix(raw_ostream
&OS
, const GlobalValue
*GV
,
121 bool CannotUsePrivateLabel
) const {
122 ManglerPrefixTy PrefixTy
= Default
;
123 assert(GV
!= nullptr && "Invalid Global Value");
124 if (GV
->hasPrivateLinkage()) {
125 if (CannotUsePrivateLabel
)
126 PrefixTy
= LinkerPrivate
;
131 const DataLayout
&DL
= GV
->getDataLayout();
132 if (!GV
->hasName()) {
133 // Get the ID for the global, assigning a new one if we haven't got one
135 unsigned &ID
= AnonGlobalIDs
[GV
];
137 ID
= AnonGlobalIDs
.size();
139 // Must mangle the global into a unique ID.
140 getNameWithPrefixImpl(OS
, "__unnamed_" + Twine(ID
), DL
, PrefixTy
);
144 StringRef Name
= GV
->getName();
145 char Prefix
= DL
.getGlobalPrefix();
147 // Mangle functions with Microsoft calling conventions specially. Only do
148 // this mangling for x86_64 vectorcall and 32-bit x86.
149 const Function
*MSFunc
= dyn_cast_or_null
<Function
>(GV
->getAliaseeObject());
151 // Don't add byte count suffixes when '\01' or '?' are in the first
153 if (Name
.starts_with("\01") ||
154 (DL
.doNotMangleLeadingQuestionMark() && Name
.starts_with("?")))
158 MSFunc
? MSFunc
->getCallingConv() : (unsigned)CallingConv::C
;
159 if (!DL
.hasMicrosoftFastStdCallMangling() &&
160 CC
!= CallingConv::X86_VectorCall
)
163 if (CC
== CallingConv::X86_FastCall
)
164 Prefix
= '@'; // fastcall functions have an @ prefix instead of _.
165 else if (CC
== CallingConv::X86_VectorCall
)
166 Prefix
= '\0'; // vectorcall functions have no prefix.
169 getNameWithPrefixImpl(OS
, Name
, PrefixTy
, DL
, Prefix
);
174 // If we are supposed to add a microsoft-style suffix for stdcall, fastcall,
175 // or vectorcall, add it. These functions have a suffix of @N where N is the
176 // cumulative byte size of all of the parameters to the function in decimal.
177 if (CC
== CallingConv::X86_VectorCall
)
178 OS
<< '@'; // vectorcall functions use a double @ suffix.
179 FunctionType
*FT
= MSFunc
->getFunctionType();
180 if (hasByteCountSuffix(CC
) &&
181 // "Pure" variadic functions do not receive @0 suffix.
182 (!FT
->isVarArg() || FT
->getNumParams() == 0 ||
183 (FT
->getNumParams() == 1 && MSFunc
->hasStructRetAttr())))
184 addByteCountSuffix(OS
, MSFunc
, DL
);
187 void Mangler::getNameWithPrefix(SmallVectorImpl
<char> &OutName
,
188 const GlobalValue
*GV
,
189 bool CannotUsePrivateLabel
) const {
190 raw_svector_ostream
OS(OutName
);
191 getNameWithPrefix(OS
, GV
, CannotUsePrivateLabel
);
194 // Check if the name needs quotes to be safe for the linker to interpret.
195 static bool canBeUnquotedInDirective(char C
) {
196 return isAlnum(C
) || C
== '_' || C
== '@' || C
== '#';
199 static bool canBeUnquotedInDirective(StringRef Name
) {
203 // If any of the characters in the string is an unacceptable character, force
205 for (char C
: Name
) {
206 if (!canBeUnquotedInDirective(C
))
213 void llvm::emitLinkerFlagsForGlobalCOFF(raw_ostream
&OS
, const GlobalValue
*GV
,
214 const Triple
&TT
, Mangler
&Mangler
) {
215 if (GV
->hasDLLExportStorageClass() && !GV
->isDeclaration()) {
217 if (TT
.isWindowsMSVCEnvironment())
222 bool NeedQuotes
= GV
->hasName() && !canBeUnquotedInDirective(GV
->getName());
225 if (TT
.isWindowsGNUEnvironment() || TT
.isWindowsCygwinEnvironment()) {
227 raw_string_ostream
FlagOS(Flag
);
228 Mangler
.getNameWithPrefix(FlagOS
, GV
, false);
230 if (Flag
[0] == GV
->getDataLayout().getGlobalPrefix())
231 OS
<< Flag
.substr(1);
235 Mangler
.getNameWithPrefix(OS
, GV
, false);
237 if (TT
.isWindowsArm64EC()) {
238 // Use EXPORTAS for mangled ARM64EC symbols.
239 // FIXME: During LTO, we're invoked prior to the EC lowering pass,
240 // so symbols are not yet mangled. Emitting the unmangled name
241 // typically functions correctly; the linker can resolve the export
242 // with the demangled alias.
243 if (std::optional
<std::string
> demangledName
=
244 getArm64ECDemangledFunctionName(GV
->getName()))
245 OS
<< ",EXPORTAS," << *demangledName
;
250 if (!GV
->getValueType()->isFunctionTy()) {
251 if (TT
.isWindowsMSVCEnvironment())
257 if (GV
->hasHiddenVisibility() && !GV
->isDeclaration() && TT
.isOSCygMing()) {
259 OS
<< " -exclude-symbols:";
261 bool NeedQuotes
= GV
->hasName() && !canBeUnquotedInDirective(GV
->getName());
266 raw_string_ostream
FlagOS(Flag
);
267 Mangler
.getNameWithPrefix(FlagOS
, GV
, false);
269 if (Flag
[0] == GV
->getDataLayout().getGlobalPrefix())
270 OS
<< Flag
.substr(1);
279 void llvm::emitLinkerFlagsForUsedCOFF(raw_ostream
&OS
, const GlobalValue
*GV
,
280 const Triple
&T
, Mangler
&M
) {
281 if (!T
.isWindowsMSVCEnvironment())
285 bool NeedQuotes
= GV
->hasName() && !canBeUnquotedInDirective(GV
->getName());
288 M
.getNameWithPrefix(OS
, GV
, false);
293 std::optional
<std::string
> llvm::getArm64ECMangledFunctionName(StringRef Name
) {
294 bool IsCppFn
= Name
[0] == '?';
295 if (IsCppFn
&& Name
.contains("$$h"))
297 if (!IsCppFn
&& Name
[0] == '#')
300 StringRef Prefix
= "$$h";
301 size_t InsertIdx
= 0;
303 InsertIdx
= Name
.find("@@");
304 size_t ThreeAtSignsIdx
= Name
.find("@@@");
305 if (InsertIdx
!= std::string::npos
&& InsertIdx
!= ThreeAtSignsIdx
) {
308 InsertIdx
= Name
.find("@");
309 if (InsertIdx
!= std::string::npos
)
316 return std::optional
<std::string
>(
317 (Name
.substr(0, InsertIdx
) + Prefix
+ Name
.substr(InsertIdx
)).str());
320 std::optional
<std::string
>
321 llvm::getArm64ECDemangledFunctionName(StringRef Name
) {
323 return std::optional
<std::string
>(Name
.substr(1));
327 std::pair
<StringRef
, StringRef
> Pair
= Name
.split("$$h");
328 if (Pair
.second
.empty())
330 return std::optional
<std::string
>((Pair
.first
+ Pair
.second
).str());