Home | History | Annotate | Download | only in IR
      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"
     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 
     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 
     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 
     69 void Mangler::getNameWithPrefix(raw_ostream &OS, const Twine &GVName,
     70                                 const DataLayout &DL) {
     71   return getNameWithPrefixImpl(OS, GVName, DL, Default);
     72 }
     73 
     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 
     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.
     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 
    112 void Mangler::getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV,
    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;
    150   if (!DL.hasMicrosoftFastStdCallMangling() &&
    151       CC != CallingConv::X86_VectorCall)
    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 
    178 void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
    179                                 const GlobalValue *GV,
    180                                 bool CannotUsePrivateLabel) const {
    181   raw_svector_ostream OS(OutName);
    182   getNameWithPrefix(OS, GV, CannotUsePrivateLabel);
    183 }
    184 
    185 void llvm::emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV,
    186                                         const Triple &TT, Mangler &Mangler) {
    187   if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
    188     return;
    189 
    190   if (TT.isKnownWindowsMSVCEnvironment())
    191     OS << " /EXPORT:";
    192   else
    193     OS << " -export:";
    194 
    195   if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
    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()) {
    209     if (TT.isKnownWindowsMSVCEnvironment())
    210       OS << ",DATA";
    211     else
    212       OS << ",data";
    213   }
    214 }
    215 
    216 void llvm::emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV,
    217                                       const Triple &T, Mangler &M) {
    218   if (!T.isKnownWindowsMSVCEnvironment())
    219     return;
    220 
    221   OS << " /INCLUDE:";
    222   M.getNameWithPrefix(OS, GV, false);
    223 }
    224 
    225