LLVM  8.0.1
Mangler.cpp
Go to the documentation of this file.
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/IR/Mangler.h"
15 #include "llvm/ADT/SmallString.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"
23 using namespace llvm;
24 
25 namespace {
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 
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)
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 
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 
70  const DataLayout &DL) {
71  return getNameWithPrefixImpl(OS, GVName, DL, Default);
72 }
73 
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 
82  switch (CC) {
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.
94 static void addByteCountSuffix(raw_ostream &OS, const Function *F,
95  const DataLayout &DL) {
96  // Calculate arguments size total.
97  unsigned ArgWords = 0;
98  for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
99  AI != AE; ++AI) {
100  Type *Ty = AI->getType();
101  // 'Dereference' type in case of byval or inalloca parameter attribute.
102  if (AI->hasByValOrInAllocaAttr())
103  Ty = cast<PointerType>(Ty)->getElementType();
104  // Size should be aligned to pointer size.
105  unsigned PtrSize = DL.getPointerSize();
106  ArgWords += alignTo(DL.getTypeAllocSize(Ty), PtrSize);
107  }
108 
109  OS << '@' << ArgWords;
110 }
111 
113  bool CannotUsePrivateLabel) const {
114  ManglerPrefixTy PrefixTy = Default;
115  if (GV->hasPrivateLinkage()) {
116  if (CannotUsePrivateLabel)
117  PrefixTy = LinkerPrivate;
118  else
119  PrefixTy = Private;
120  }
121 
122  const DataLayout &DL = GV->getParent()->getDataLayout();
123  if (!GV->hasName()) {
124  // Get the ID for the global, assigning a new one if we haven't got one
125  // already.
126  unsigned &ID = AnonGlobalIDs[GV];
127  if (ID == 0)
128  ID = AnonGlobalIDs.size();
129 
130  // Must mangle the global into a unique ID.
131  getNameWithPrefixImpl(OS, "__unnamed_" + Twine(ID), DL, PrefixTy);
132  return;
133  }
134 
135  StringRef Name = GV->getName();
136  char Prefix = DL.getGlobalPrefix();
137 
138  // Mangle functions with Microsoft calling conventions specially. Only do
139  // this mangling for x86_64 vectorcall and 32-bit x86.
140  const Function *MSFunc = dyn_cast<Function>(GV);
141 
142  // Don't add byte count suffixes when '\01' or '?' are in the first
143  // character.
144  if (Name.startswith("\01") ||
145  (DL.doNotMangleLeadingQuestionMark() && Name.startswith("?")))
146  MSFunc = nullptr;
147 
148  CallingConv::ID CC =
149  MSFunc ? MSFunc->getCallingConv() : (unsigned)CallingConv::C;
152  MSFunc = nullptr;
153  if (MSFunc) {
154  if (CC == CallingConv::X86_FastCall)
155  Prefix = '@'; // fastcall functions have an @ prefix instead of _.
156  else if (CC == CallingConv::X86_VectorCall)
157  Prefix = '\0'; // vectorcall functions have no prefix.
158  }
159 
160  getNameWithPrefixImpl(OS, Name, PrefixTy, DL, Prefix);
161 
162  if (!MSFunc)
163  return;
164 
165  // If we are supposed to add a microsoft-style suffix for stdcall, fastcall,
166  // or vectorcall, add it. These functions have a suffix of @N where N is the
167  // cumulative byte size of all of the parameters to the function in decimal.
168  if (CC == CallingConv::X86_VectorCall)
169  OS << '@'; // vectorcall functions use a double @ suffix.
170  FunctionType *FT = MSFunc->getFunctionType();
171  if (hasByteCountSuffix(CC) &&
172  // "Pure" variadic functions do not receive @0 suffix.
173  (!FT->isVarArg() || FT->getNumParams() == 0 ||
174  (FT->getNumParams() == 1 && MSFunc->hasStructRetAttr())))
175  addByteCountSuffix(OS, MSFunc, DL);
176 }
177 
179  const GlobalValue *GV,
180  bool CannotUsePrivateLabel) const {
181  raw_svector_ostream OS(OutName);
182  getNameWithPrefix(OS, GV, CannotUsePrivateLabel);
183 }
184 
186  const Triple &TT, Mangler &Mangler) {
187  if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
188  return;
189 
191  OS << " /EXPORT:";
192  else
193  OS << " -export:";
194 
196  std::string Flag;
197  raw_string_ostream FlagOS(Flag);
198  Mangler.getNameWithPrefix(FlagOS, GV, false);
199  FlagOS.flush();
200  if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
201  OS << Flag.substr(1);
202  else
203  OS << Flag;
204  } else {
205  Mangler.getNameWithPrefix(OS, GV, false);
206  }
207 
208  if (!GV->getValueType()->isFunctionTy()) {
210  OS << ",DATA";
211  else
212  OS << ",data";
213  }
214 }
215 
217  const Triple &T, Mangler &M) {
219  return;
220 
221  OS << " /INCLUDE:";
222  M.getNameWithPrefix(OS, GV, false);
223 }
224 
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
bool hasDLLExportStorageClass() const
Definition: GlobalValue.h:265
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:35
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
bool hasPrivateLinkage() const
Definition: GlobalValue.h:435
This class represents lattice values for constants.
Definition: AllocatorList.h:24
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:294
static void addByteCountSuffix(raw_ostream &OS, const Function *F, const DataLayout &DL)
Microsoft fastcall and stdcall functions require a suffix on their name indicating the number of word...
Definition: Mangler.cpp:94
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition: Twine.h:453
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:510
arg_iterator arg_end()
Definition: Function.h:680
F(f)
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:685
char getGlobalPrefix() const
Definition: DataLayout.h:280
bool isWindowsCygwinEnvironment() const
Definition: Triple.h:547
StringRef getLinkerPrivateGlobalPrefix() const
Definition: DataLayout.h:274
bool hasStructRetAttr() const
Determine if the function returns a structure through first or second pointer argument.
Definition: Function.h:579
amdgpu Simplify well known AMD library false Value Value const Twine & Name
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:371
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
bool isKnownWindowsMSVCEnvironment() const
Checks if the environment is MSVC.
Definition: Triple.h:535
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
Class to represent function types.
Definition: DerivedTypes.h:103
bool isVarArg() const
Definition: DerivedTypes.h:123
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:598
bool isWindowsGNUEnvironment() const
Definition: Triple.h:551
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:118
bool hasName() const
Definition: Value.h:251
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
Definition: DataLayout.cpp:629
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
Definition: CallingConv.h:158
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:185
arg_iterator arg_begin()
Definition: Function.h:671
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
ManglerPrefixTy
Definition: Mangler.cpp:26
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:213
Module.h This file contains the declarations for the Module class.
bool hasMicrosoftFastStdCallMangling() const
Definition: DataLayout.h:262
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:164
X86_FastCall - &#39;fast&#39; analog of X86_StdCall.
Definition: CallingConv.h:92
static bool hasByteCountSuffix(CallingConv::ID CC)
Definition: Mangler.cpp:81
static void getNameWithPrefixImpl(raw_ostream &OS, const Twine &GVName, ManglerPrefixTy PrefixTy, const DataLayout &DL, char Prefix)
Definition: Mangler.cpp:33
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:436
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:215
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Type * getValueType() const
Definition: GlobalValue.h:276
void emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &T, Mangler &M)
Definition: Mangler.cpp:216
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:206
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
X86_StdCall - stdcall is the calling conventions mostly used by the Win32 API.
Definition: CallingConv.h:87
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:483
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:112
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
bool doNotMangleLeadingQuestionMark() const
Returns true if symbols with leading question marks should not receive IR mangling.
Definition: DataLayout.h:268