Mangler.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. #include "llvm/IR/Mangler.h"
  13. #include "llvm/ADT/SmallString.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/ADT/Triple.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. using namespace llvm;
  23. namespace {
  24. enum ManglerPrefixTy {
  25. Default, ///< Emit default string before each symbol.
  26. Private, ///< Emit "private" prefix before each symbol.
  27. LinkerPrivate ///< Emit "linker private" prefix before each symbol.
  28. };
  29. }
  30. static void getNameWithPrefixImpl(raw_ostream &OS, const Twine &GVName,
  31. ManglerPrefixTy PrefixTy,
  32. const DataLayout &DL, char Prefix) {
  33. SmallString<256> TmpData;
  34. StringRef Name = GVName.toStringRef(TmpData);
  35. assert(!Name.empty() && "getNameWithPrefix requires non-empty name");
  36. // No need to do anything special if the global has the special "do not
  37. // mangle" flag in the name.
  38. if (Name[0] == '\1') {
  39. OS << Name.substr(1);
  40. return;
  41. }
  42. if (DL.doNotMangleLeadingQuestionMark() && Name[0] == '?')
  43. Prefix = '\0';
  44. if (PrefixTy == Private)
  45. OS << DL.getPrivateGlobalPrefix();
  46. else if (PrefixTy == LinkerPrivate)
  47. OS << DL.getLinkerPrivateGlobalPrefix();
  48. if (Prefix != '\0')
  49. OS << Prefix;
  50. // If this is a simple string that doesn't need escaping, just append it.
  51. OS << Name;
  52. }
  53. static void getNameWithPrefixImpl(raw_ostream &OS, const Twine &GVName,
  54. const DataLayout &DL,
  55. ManglerPrefixTy PrefixTy) {
  56. char Prefix = DL.getGlobalPrefix();
  57. return getNameWithPrefixImpl(OS, GVName, PrefixTy, DL, Prefix);
  58. }
  59. void Mangler::getNameWithPrefix(raw_ostream &OS, const Twine &GVName,
  60. const DataLayout &DL) {
  61. return getNameWithPrefixImpl(OS, GVName, DL, Default);
  62. }
  63. void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
  64. const Twine &GVName, const DataLayout &DL) {
  65. raw_svector_ostream OS(OutName);
  66. char Prefix = DL.getGlobalPrefix();
  67. return getNameWithPrefixImpl(OS, GVName, Default, DL, Prefix);
  68. }
  69. static bool hasByteCountSuffix(CallingConv::ID CC) {
  70. switch (CC) {
  71. case CallingConv::X86_FastCall:
  72. case CallingConv::X86_StdCall:
  73. case CallingConv::X86_VectorCall:
  74. return true;
  75. default:
  76. return false;
  77. }
  78. }
  79. /// Microsoft fastcall and stdcall functions require a suffix on their name
  80. /// indicating the number of words of arguments they take.
  81. static void addByteCountSuffix(raw_ostream &OS, const Function *F,
  82. const DataLayout &DL) {
  83. // Calculate arguments size total.
  84. unsigned ArgWords = 0;
  85. const unsigned PtrSize = DL.getPointerSize();
  86. for (const Argument &A : F->args()) {
  87. // For the purposes of the byte count suffix, structs returned by pointer
  88. // do not count as function arguments.
  89. if (A.hasStructRetAttr())
  90. continue;
  91. // 'Dereference' type in case of byval or inalloca parameter attribute.
  92. uint64_t AllocSize = A.hasPassPointeeByValueCopyAttr() ?
  93. A.getPassPointeeByValueCopySize(DL) :
  94. DL.getTypeAllocSize(A.getType());
  95. // Size should be aligned to pointer size.
  96. ArgWords += alignTo(AllocSize, PtrSize);
  97. }
  98. OS << '@' << ArgWords;
  99. }
  100. void Mangler::getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV,
  101. bool CannotUsePrivateLabel) const {
  102. ManglerPrefixTy PrefixTy = Default;
  103. if (GV->hasPrivateLinkage()) {
  104. if (CannotUsePrivateLabel)
  105. PrefixTy = LinkerPrivate;
  106. else
  107. PrefixTy = Private;
  108. }
  109. const DataLayout &DL = GV->getParent()->getDataLayout();
  110. if (!GV->hasName()) {
  111. // Get the ID for the global, assigning a new one if we haven't got one
  112. // already.
  113. unsigned &ID = AnonGlobalIDs[GV];
  114. if (ID == 0)
  115. ID = AnonGlobalIDs.size();
  116. // Must mangle the global into a unique ID.
  117. getNameWithPrefixImpl(OS, "__unnamed_" + Twine(ID), DL, PrefixTy);
  118. return;
  119. }
  120. StringRef Name = GV->getName();
  121. char Prefix = DL.getGlobalPrefix();
  122. // Mangle functions with Microsoft calling conventions specially. Only do
  123. // this mangling for x86_64 vectorcall and 32-bit x86.
  124. const Function *MSFunc = dyn_cast_or_null<Function>(GV->getAliaseeObject());
  125. // Don't add byte count suffixes when '\01' or '?' are in the first
  126. // character.
  127. if (Name.startswith("\01") ||
  128. (DL.doNotMangleLeadingQuestionMark() && Name.startswith("?")))
  129. MSFunc = nullptr;
  130. CallingConv::ID CC =
  131. MSFunc ? MSFunc->getCallingConv() : (unsigned)CallingConv::C;
  132. if (!DL.hasMicrosoftFastStdCallMangling() &&
  133. CC != CallingConv::X86_VectorCall)
  134. MSFunc = nullptr;
  135. if (MSFunc) {
  136. if (CC == CallingConv::X86_FastCall)
  137. Prefix = '@'; // fastcall functions have an @ prefix instead of _.
  138. else if (CC == CallingConv::X86_VectorCall)
  139. Prefix = '\0'; // vectorcall functions have no prefix.
  140. }
  141. getNameWithPrefixImpl(OS, Name, PrefixTy, DL, Prefix);
  142. if (!MSFunc)
  143. return;
  144. // If we are supposed to add a microsoft-style suffix for stdcall, fastcall,
  145. // or vectorcall, add it. These functions have a suffix of @N where N is the
  146. // cumulative byte size of all of the parameters to the function in decimal.
  147. if (CC == CallingConv::X86_VectorCall)
  148. OS << '@'; // vectorcall functions use a double @ suffix.
  149. FunctionType *FT = MSFunc->getFunctionType();
  150. if (hasByteCountSuffix(CC) &&
  151. // "Pure" variadic functions do not receive @0 suffix.
  152. (!FT->isVarArg() || FT->getNumParams() == 0 ||
  153. (FT->getNumParams() == 1 && MSFunc->hasStructRetAttr())))
  154. addByteCountSuffix(OS, MSFunc, DL);
  155. }
  156. void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
  157. const GlobalValue *GV,
  158. bool CannotUsePrivateLabel) const {
  159. raw_svector_ostream OS(OutName);
  160. getNameWithPrefix(OS, GV, CannotUsePrivateLabel);
  161. }
  162. // Check if the name needs quotes to be safe for the linker to interpret.
  163. static bool canBeUnquotedInDirective(char C) {
  164. return isAlnum(C) || C == '_' || C == '@';
  165. }
  166. static bool canBeUnquotedInDirective(StringRef Name) {
  167. if (Name.empty())
  168. return false;
  169. // If any of the characters in the string is an unacceptable character, force
  170. // quotes.
  171. for (char C : Name) {
  172. if (!canBeUnquotedInDirective(C))
  173. return false;
  174. }
  175. return true;
  176. }
  177. void llvm::emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV,
  178. const Triple &TT, Mangler &Mangler) {
  179. if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
  180. return;
  181. if (TT.isWindowsMSVCEnvironment())
  182. OS << " /EXPORT:";
  183. else
  184. OS << " -export:";
  185. bool NeedQuotes = GV->hasName() && !canBeUnquotedInDirective(GV->getName());
  186. if (NeedQuotes)
  187. OS << "\"";
  188. if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
  189. std::string Flag;
  190. raw_string_ostream FlagOS(Flag);
  191. Mangler.getNameWithPrefix(FlagOS, GV, false);
  192. FlagOS.flush();
  193. if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
  194. OS << Flag.substr(1);
  195. else
  196. OS << Flag;
  197. } else {
  198. Mangler.getNameWithPrefix(OS, GV, false);
  199. }
  200. if (NeedQuotes)
  201. OS << "\"";
  202. if (!GV->getValueType()->isFunctionTy()) {
  203. if (TT.isWindowsMSVCEnvironment())
  204. OS << ",DATA";
  205. else
  206. OS << ",data";
  207. }
  208. }
  209. void llvm::emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV,
  210. const Triple &T, Mangler &M) {
  211. if (!T.isWindowsMSVCEnvironment())
  212. return;
  213. OS << " /INCLUDE:";
  214. bool NeedQuotes = GV->hasName() && !canBeUnquotedInDirective(GV->getName());
  215. if (NeedQuotes)
  216. OS << "\"";
  217. M.getNameWithPrefix(OS, GV, false);
  218. if (NeedQuotes)
  219. OS << "\"";
  220. }