MicrosoftMangle.cpp 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826
  1. //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
  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. // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/Mangle.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/VTableBuilder.h"
  25. #include "clang/Basic/ABI.h"
  26. #include "clang/Basic/DiagnosticOptions.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/Support/MathExtras.h"
  30. using namespace clang;
  31. namespace {
  32. /// \brief Retrieve the declaration context that should be used when mangling
  33. /// the given declaration.
  34. static const DeclContext *getEffectiveDeclContext(const Decl *D) {
  35. // The ABI assumes that lambda closure types that occur within
  36. // default arguments live in the context of the function. However, due to
  37. // the way in which Clang parses and creates function declarations, this is
  38. // not the case: the lambda closure type ends up living in the context
  39. // where the function itself resides, because the function declaration itself
  40. // had not yet been created. Fix the context here.
  41. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  42. if (RD->isLambda())
  43. if (ParmVarDecl *ContextParam =
  44. dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
  45. return ContextParam->getDeclContext();
  46. }
  47. // Perform the same check for block literals.
  48. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  49. if (ParmVarDecl *ContextParam =
  50. dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
  51. return ContextParam->getDeclContext();
  52. }
  53. const DeclContext *DC = D->getDeclContext();
  54. if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
  55. return getEffectiveDeclContext(CD);
  56. return DC;
  57. }
  58. static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
  59. return getEffectiveDeclContext(cast<Decl>(DC));
  60. }
  61. static const FunctionDecl *getStructor(const NamedDecl *ND) {
  62. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  63. return FTD->getTemplatedDecl();
  64. const auto *FD = cast<FunctionDecl>(ND);
  65. if (const auto *FTD = FD->getPrimaryTemplate())
  66. return FTD->getTemplatedDecl();
  67. return FD;
  68. }
  69. static bool isLambda(const NamedDecl *ND) {
  70. const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
  71. if (!Record)
  72. return false;
  73. return Record->isLambda();
  74. }
  75. /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
  76. /// Microsoft Visual C++ ABI.
  77. class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
  78. typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
  79. llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
  80. llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
  81. llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
  82. llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
  83. llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
  84. public:
  85. MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
  86. : MicrosoftMangleContext(Context, Diags) {}
  87. bool shouldMangleCXXName(const NamedDecl *D) override;
  88. bool shouldMangleStringLiteral(const StringLiteral *SL) override;
  89. void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
  90. void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
  91. raw_ostream &) override;
  92. void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
  93. raw_ostream &) override;
  94. void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
  95. const ThisAdjustment &ThisAdjustment,
  96. raw_ostream &) override;
  97. void mangleCXXVFTable(const CXXRecordDecl *Derived,
  98. ArrayRef<const CXXRecordDecl *> BasePath,
  99. raw_ostream &Out) override;
  100. void mangleCXXVBTable(const CXXRecordDecl *Derived,
  101. ArrayRef<const CXXRecordDecl *> BasePath,
  102. raw_ostream &Out) override;
  103. void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
  104. const CXXRecordDecl *DstRD,
  105. raw_ostream &Out) override;
  106. void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
  107. uint32_t NumEntries, raw_ostream &Out) override;
  108. void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
  109. raw_ostream &Out) override;
  110. void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
  111. CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
  112. int32_t VBPtrOffset, uint32_t VBIndex,
  113. raw_ostream &Out) override;
  114. void mangleCXXCatchHandlerType(QualType T, uint32_t Flags,
  115. raw_ostream &Out) override;
  116. void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
  117. void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
  118. void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
  119. uint32_t NVOffset, int32_t VBPtrOffset,
  120. uint32_t VBTableOffset, uint32_t Flags,
  121. raw_ostream &Out) override;
  122. void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
  123. raw_ostream &Out) override;
  124. void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
  125. raw_ostream &Out) override;
  126. void
  127. mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
  128. ArrayRef<const CXXRecordDecl *> BasePath,
  129. raw_ostream &Out) override;
  130. void mangleTypeName(QualType T, raw_ostream &) override;
  131. void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
  132. raw_ostream &) override;
  133. void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
  134. raw_ostream &) override;
  135. void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
  136. raw_ostream &) override;
  137. void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
  138. void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
  139. raw_ostream &Out) override;
  140. void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
  141. void mangleDynamicAtExitDestructor(const VarDecl *D,
  142. raw_ostream &Out) override;
  143. void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
  144. raw_ostream &Out) override;
  145. void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
  146. raw_ostream &Out) override;
  147. void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
  148. void mangleCXXVTableBitSet(const CXXRecordDecl *RD,
  149. raw_ostream &Out) override;
  150. bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
  151. // Lambda closure types are already numbered.
  152. if (isLambda(ND))
  153. return false;
  154. const DeclContext *DC = getEffectiveDeclContext(ND);
  155. if (!DC->isFunctionOrMethod())
  156. return false;
  157. // Use the canonical number for externally visible decls.
  158. if (ND->isExternallyVisible()) {
  159. disc = getASTContext().getManglingNumber(ND);
  160. return true;
  161. }
  162. // Anonymous tags are already numbered.
  163. if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
  164. if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
  165. return false;
  166. }
  167. // Make up a reasonable number for internal decls.
  168. unsigned &discriminator = Uniquifier[ND];
  169. if (!discriminator)
  170. discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
  171. disc = discriminator + 1;
  172. return true;
  173. }
  174. unsigned getLambdaId(const CXXRecordDecl *RD) {
  175. assert(RD->isLambda() && "RD must be a lambda!");
  176. assert(!RD->isExternallyVisible() && "RD must not be visible!");
  177. assert(RD->getLambdaManglingNumber() == 0 &&
  178. "RD must not have a mangling number!");
  179. std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
  180. Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
  181. return Result.first->second;
  182. }
  183. private:
  184. void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
  185. };
  186. /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
  187. /// Microsoft Visual C++ ABI.
  188. class MicrosoftCXXNameMangler {
  189. MicrosoftMangleContextImpl &Context;
  190. raw_ostream &Out;
  191. /// The "structor" is the top-level declaration being mangled, if
  192. /// that's not a template specialization; otherwise it's the pattern
  193. /// for that specialization.
  194. const NamedDecl *Structor;
  195. unsigned StructorType;
  196. typedef llvm::SmallVector<std::string, 10> BackRefVec;
  197. BackRefVec NameBackReferences;
  198. typedef llvm::DenseMap<void *, unsigned> ArgBackRefMap;
  199. ArgBackRefMap TypeBackReferences;
  200. ASTContext &getASTContext() const { return Context.getASTContext(); }
  201. // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
  202. // this check into mangleQualifiers().
  203. const bool PointersAre64Bit;
  204. public:
  205. enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
  206. MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
  207. : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
  208. PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
  209. 64) {}
  210. MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
  211. const CXXConstructorDecl *D, CXXCtorType Type)
  212. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  213. PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
  214. 64) {}
  215. MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
  216. const CXXDestructorDecl *D, CXXDtorType Type)
  217. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  218. PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
  219. 64) {}
  220. raw_ostream &getStream() const { return Out; }
  221. void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
  222. void mangleName(const NamedDecl *ND);
  223. void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
  224. void mangleVariableEncoding(const VarDecl *VD);
  225. void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
  226. void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
  227. const CXXMethodDecl *MD);
  228. void mangleVirtualMemPtrThunk(
  229. const CXXMethodDecl *MD,
  230. const MicrosoftVTableContext::MethodVFTableLocation &ML);
  231. void mangleNumber(int64_t Number);
  232. void mangleType(QualType T, SourceRange Range,
  233. QualifierMangleMode QMM = QMM_Mangle);
  234. void mangleFunctionType(const FunctionType *T,
  235. const FunctionDecl *D = nullptr,
  236. bool ForceThisQuals = false);
  237. void mangleNestedName(const NamedDecl *ND);
  238. private:
  239. void mangleUnqualifiedName(const NamedDecl *ND) {
  240. mangleUnqualifiedName(ND, ND->getDeclName());
  241. }
  242. void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
  243. void mangleSourceName(StringRef Name);
  244. void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
  245. void mangleCXXDtorType(CXXDtorType T);
  246. void mangleQualifiers(Qualifiers Quals, bool IsMember);
  247. void mangleRefQualifier(RefQualifierKind RefQualifier);
  248. void manglePointerCVQualifiers(Qualifiers Quals);
  249. void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
  250. void mangleUnscopedTemplateName(const TemplateDecl *ND);
  251. void
  252. mangleTemplateInstantiationName(const TemplateDecl *TD,
  253. const TemplateArgumentList &TemplateArgs);
  254. void mangleObjCMethodName(const ObjCMethodDecl *MD);
  255. void mangleArgumentType(QualType T, SourceRange Range);
  256. // Declare manglers for every type class.
  257. #define ABSTRACT_TYPE(CLASS, PARENT)
  258. #define NON_CANONICAL_TYPE(CLASS, PARENT)
  259. #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
  260. Qualifiers Quals, \
  261. SourceRange Range);
  262. #include "clang/AST/TypeNodes.def"
  263. #undef ABSTRACT_TYPE
  264. #undef NON_CANONICAL_TYPE
  265. #undef TYPE
  266. void mangleType(const TagDecl *TD);
  267. void mangleDecayedArrayType(const ArrayType *T);
  268. void mangleArrayType(const ArrayType *T);
  269. void mangleFunctionClass(const FunctionDecl *FD);
  270. void mangleCallingConvention(CallingConv CC);
  271. void mangleCallingConvention(const FunctionType *T);
  272. void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
  273. void mangleExpression(const Expr *E);
  274. void mangleThrowSpecification(const FunctionProtoType *T);
  275. void mangleTemplateArgs(const TemplateDecl *TD,
  276. const TemplateArgumentList &TemplateArgs);
  277. void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
  278. const NamedDecl *Parm);
  279. };
  280. }
  281. bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
  282. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  283. LanguageLinkage L = FD->getLanguageLinkage();
  284. // Overloadable functions need mangling.
  285. if (FD->hasAttr<OverloadableAttr>())
  286. return true;
  287. // The ABI expects that we would never mangle "typical" user-defined entry
  288. // points regardless of visibility or freestanding-ness.
  289. //
  290. // N.B. This is distinct from asking about "main". "main" has a lot of
  291. // special rules associated with it in the standard while these
  292. // user-defined entry points are outside of the purview of the standard.
  293. // For example, there can be only one definition for "main" in a standards
  294. // compliant program; however nothing forbids the existence of wmain and
  295. // WinMain in the same translation unit.
  296. if (FD->isMSVCRTEntryPoint())
  297. return false;
  298. // C++ functions and those whose names are not a simple identifier need
  299. // mangling.
  300. if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
  301. return true;
  302. // C functions are not mangled.
  303. if (L == CLanguageLinkage)
  304. return false;
  305. }
  306. // Otherwise, no mangling is done outside C++ mode.
  307. if (!getASTContext().getLangOpts().CPlusPlus)
  308. return false;
  309. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  310. // C variables are not mangled.
  311. if (VD->isExternC())
  312. return false;
  313. // Variables at global scope with non-internal linkage are not mangled.
  314. const DeclContext *DC = getEffectiveDeclContext(D);
  315. // Check for extern variable declared locally.
  316. if (DC->isFunctionOrMethod() && D->hasLinkage())
  317. while (!DC->isNamespace() && !DC->isTranslationUnit())
  318. DC = getEffectiveParentContext(DC);
  319. if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
  320. !isa<VarTemplateSpecializationDecl>(D))
  321. return false;
  322. }
  323. return true;
  324. }
  325. bool
  326. MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
  327. return true;
  328. }
  329. void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
  330. // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
  331. // Therefore it's really important that we don't decorate the
  332. // name with leading underscores or leading/trailing at signs. So, by
  333. // default, we emit an asm marker at the start so we get the name right.
  334. // Callers can override this with a custom prefix.
  335. // <mangled-name> ::= ? <name> <type-encoding>
  336. Out << Prefix;
  337. mangleName(D);
  338. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  339. mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
  340. else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  341. mangleVariableEncoding(VD);
  342. else {
  343. // TODO: Fields? Can MSVC even mangle them?
  344. // Issue a diagnostic for now.
  345. DiagnosticsEngine &Diags = Context.getDiags();
  346. unsigned DiagID = Diags.getCustomDiagID(
  347. DiagnosticsEngine::Error, "cannot mangle this declaration yet");
  348. Diags.Report(D->getLocation(), DiagID) << D->getSourceRange();
  349. }
  350. }
  351. void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
  352. bool ShouldMangle) {
  353. // <type-encoding> ::= <function-class> <function-type>
  354. // Since MSVC operates on the type as written and not the canonical type, it
  355. // actually matters which decl we have here. MSVC appears to choose the
  356. // first, since it is most likely to be the declaration in a header file.
  357. FD = FD->getFirstDecl();
  358. // We should never ever see a FunctionNoProtoType at this point.
  359. // We don't even know how to mangle their types anyway :).
  360. const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
  361. // extern "C" functions can hold entities that must be mangled.
  362. // As it stands, these functions still need to get expressed in the full
  363. // external name. They have their class and type omitted, replaced with '9'.
  364. if (ShouldMangle) {
  365. // We would like to mangle all extern "C" functions using this additional
  366. // component but this would break compatibility with MSVC's behavior.
  367. // Instead, do this when we know that compatibility isn't important (in
  368. // other words, when it is an overloaded extern "C" funciton).
  369. if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
  370. Out << "$$J0";
  371. mangleFunctionClass(FD);
  372. mangleFunctionType(FT, FD);
  373. } else {
  374. Out << '9';
  375. }
  376. }
  377. void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
  378. // <type-encoding> ::= <storage-class> <variable-type>
  379. // <storage-class> ::= 0 # private static member
  380. // ::= 1 # protected static member
  381. // ::= 2 # public static member
  382. // ::= 3 # global
  383. // ::= 4 # static local
  384. // The first character in the encoding (after the name) is the storage class.
  385. if (VD->isStaticDataMember()) {
  386. // If it's a static member, it also encodes the access level.
  387. switch (VD->getAccess()) {
  388. default:
  389. case AS_private: Out << '0'; break;
  390. case AS_protected: Out << '1'; break;
  391. case AS_public: Out << '2'; break;
  392. }
  393. }
  394. else if (!VD->isStaticLocal())
  395. Out << '3';
  396. else
  397. Out << '4';
  398. // Now mangle the type.
  399. // <variable-type> ::= <type> <cvr-qualifiers>
  400. // ::= <type> <pointee-cvr-qualifiers> # pointers, references
  401. // Pointers and references are odd. The type of 'int * const foo;' gets
  402. // mangled as 'QAHA' instead of 'PAHB', for example.
  403. SourceRange SR = VD->getSourceRange();
  404. QualType Ty = VD->getType();
  405. if (Ty->isPointerType() || Ty->isReferenceType() ||
  406. Ty->isMemberPointerType()) {
  407. mangleType(Ty, SR, QMM_Drop);
  408. manglePointerExtQualifiers(
  409. Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
  410. if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
  411. mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
  412. // Member pointers are suffixed with a back reference to the member
  413. // pointer's class name.
  414. mangleName(MPT->getClass()->getAsCXXRecordDecl());
  415. } else
  416. mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
  417. } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
  418. // Global arrays are funny, too.
  419. mangleDecayedArrayType(AT);
  420. if (AT->getElementType()->isArrayType())
  421. Out << 'A';
  422. else
  423. mangleQualifiers(Ty.getQualifiers(), false);
  424. } else {
  425. mangleType(Ty, SR, QMM_Drop);
  426. mangleQualifiers(Ty.getQualifiers(), false);
  427. }
  428. }
  429. void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
  430. const ValueDecl *VD) {
  431. // <member-data-pointer> ::= <integer-literal>
  432. // ::= $F <number> <number>
  433. // ::= $G <number> <number> <number>
  434. int64_t FieldOffset;
  435. int64_t VBTableOffset;
  436. MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
  437. if (VD) {
  438. FieldOffset = getASTContext().getFieldOffset(VD);
  439. assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
  440. "cannot take address of bitfield");
  441. FieldOffset /= getASTContext().getCharWidth();
  442. VBTableOffset = 0;
  443. if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
  444. FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
  445. } else {
  446. FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
  447. VBTableOffset = -1;
  448. }
  449. char Code = '\0';
  450. switch (IM) {
  451. case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break;
  452. case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break;
  453. case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break;
  454. case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
  455. }
  456. Out << '$' << Code;
  457. mangleNumber(FieldOffset);
  458. // The C++ standard doesn't allow base-to-derived member pointer conversions
  459. // in template parameter contexts, so the vbptr offset of data member pointers
  460. // is always zero.
  461. if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
  462. mangleNumber(0);
  463. if (MSInheritanceAttr::hasVBTableOffsetField(IM))
  464. mangleNumber(VBTableOffset);
  465. }
  466. void
  467. MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
  468. const CXXMethodDecl *MD) {
  469. // <member-function-pointer> ::= $1? <name>
  470. // ::= $H? <name> <number>
  471. // ::= $I? <name> <number> <number>
  472. // ::= $J? <name> <number> <number> <number>
  473. MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
  474. char Code = '\0';
  475. switch (IM) {
  476. case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break;
  477. case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break;
  478. case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break;
  479. case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
  480. }
  481. // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
  482. // thunk.
  483. uint64_t NVOffset = 0;
  484. uint64_t VBTableOffset = 0;
  485. uint64_t VBPtrOffset = 0;
  486. if (MD) {
  487. Out << '$' << Code << '?';
  488. if (MD->isVirtual()) {
  489. MicrosoftVTableContext *VTContext =
  490. cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
  491. const MicrosoftVTableContext::MethodVFTableLocation &ML =
  492. VTContext->getMethodVFTableLocation(GlobalDecl(MD));
  493. mangleVirtualMemPtrThunk(MD, ML);
  494. NVOffset = ML.VFPtrOffset.getQuantity();
  495. VBTableOffset = ML.VBTableIndex * 4;
  496. if (ML.VBase) {
  497. const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
  498. VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
  499. }
  500. } else {
  501. mangleName(MD);
  502. mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
  503. }
  504. if (VBTableOffset == 0 &&
  505. IM == MSInheritanceAttr::Keyword_virtual_inheritance)
  506. NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
  507. } else {
  508. // Null single inheritance member functions are encoded as a simple nullptr.
  509. if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
  510. Out << "$0A@";
  511. return;
  512. }
  513. if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
  514. VBTableOffset = -1;
  515. Out << '$' << Code;
  516. }
  517. if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
  518. mangleNumber(static_cast<uint32_t>(NVOffset));
  519. if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
  520. mangleNumber(VBPtrOffset);
  521. if (MSInheritanceAttr::hasVBTableOffsetField(IM))
  522. mangleNumber(VBTableOffset);
  523. }
  524. void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
  525. const CXXMethodDecl *MD,
  526. const MicrosoftVTableContext::MethodVFTableLocation &ML) {
  527. // Get the vftable offset.
  528. CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
  529. getASTContext().getTargetInfo().getPointerWidth(0));
  530. uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
  531. Out << "?_9";
  532. mangleName(MD->getParent());
  533. Out << "$B";
  534. mangleNumber(OffsetInVFTable);
  535. Out << 'A';
  536. mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
  537. }
  538. void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
  539. // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
  540. // Always start with the unqualified name.
  541. mangleUnqualifiedName(ND);
  542. mangleNestedName(ND);
  543. // Terminate the whole name with an '@'.
  544. Out << '@';
  545. }
  546. void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
  547. // <non-negative integer> ::= A@ # when Number == 0
  548. // ::= <decimal digit> # when 1 <= Number <= 10
  549. // ::= <hex digit>+ @ # when Number >= 10
  550. //
  551. // <number> ::= [?] <non-negative integer>
  552. uint64_t Value = static_cast<uint64_t>(Number);
  553. if (Number < 0) {
  554. Value = -Value;
  555. Out << '?';
  556. }
  557. if (Value == 0)
  558. Out << "A@";
  559. else if (Value >= 1 && Value <= 10)
  560. Out << (Value - 1);
  561. else {
  562. // Numbers that are not encoded as decimal digits are represented as nibbles
  563. // in the range of ASCII characters 'A' to 'P'.
  564. // The number 0x123450 would be encoded as 'BCDEFA'
  565. char EncodedNumberBuffer[sizeof(uint64_t) * 2];
  566. MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
  567. MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
  568. for (; Value != 0; Value >>= 4)
  569. *I++ = 'A' + (Value & 0xf);
  570. Out.write(I.base(), I - BufferRef.rbegin());
  571. Out << '@';
  572. }
  573. }
  574. static const TemplateDecl *
  575. isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
  576. // Check if we have a function template.
  577. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  578. if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
  579. TemplateArgs = FD->getTemplateSpecializationArgs();
  580. return TD;
  581. }
  582. }
  583. // Check if we have a class template.
  584. if (const ClassTemplateSpecializationDecl *Spec =
  585. dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  586. TemplateArgs = &Spec->getTemplateArgs();
  587. return Spec->getSpecializedTemplate();
  588. }
  589. // Check if we have a variable template.
  590. if (const VarTemplateSpecializationDecl *Spec =
  591. dyn_cast<VarTemplateSpecializationDecl>(ND)) {
  592. TemplateArgs = &Spec->getTemplateArgs();
  593. return Spec->getSpecializedTemplate();
  594. }
  595. return nullptr;
  596. }
  597. void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
  598. DeclarationName Name) {
  599. // <unqualified-name> ::= <operator-name>
  600. // ::= <ctor-dtor-name>
  601. // ::= <source-name>
  602. // ::= <template-name>
  603. // Check if we have a template.
  604. const TemplateArgumentList *TemplateArgs = nullptr;
  605. if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
  606. // Function templates aren't considered for name back referencing. This
  607. // makes sense since function templates aren't likely to occur multiple
  608. // times in a symbol.
  609. // FIXME: Test alias template mangling with MSVC 2013.
  610. if (!isa<ClassTemplateDecl>(TD)) {
  611. mangleTemplateInstantiationName(TD, *TemplateArgs);
  612. Out << '@';
  613. return;
  614. }
  615. // Here comes the tricky thing: if we need to mangle something like
  616. // void foo(A::X<Y>, B::X<Y>),
  617. // the X<Y> part is aliased. However, if you need to mangle
  618. // void foo(A::X<A::Y>, A::X<B::Y>),
  619. // the A::X<> part is not aliased.
  620. // That said, from the mangler's perspective we have a structure like this:
  621. // namespace[s] -> type[ -> template-parameters]
  622. // but from the Clang perspective we have
  623. // type [ -> template-parameters]
  624. // \-> namespace[s]
  625. // What we do is we create a new mangler, mangle the same type (without
  626. // a namespace suffix) to a string using the extra mangler and then use
  627. // the mangled type name as a key to check the mangling of different types
  628. // for aliasing.
  629. llvm::SmallString<64> TemplateMangling;
  630. llvm::raw_svector_ostream Stream(TemplateMangling);
  631. MicrosoftCXXNameMangler Extra(Context, Stream);
  632. Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
  633. Stream.flush();
  634. mangleSourceName(TemplateMangling);
  635. return;
  636. }
  637. switch (Name.getNameKind()) {
  638. case DeclarationName::Identifier: {
  639. if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
  640. mangleSourceName(II->getName());
  641. break;
  642. }
  643. // Otherwise, an anonymous entity. We must have a declaration.
  644. assert(ND && "mangling empty name without declaration");
  645. if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
  646. if (NS->isAnonymousNamespace()) {
  647. Out << "?A@";
  648. break;
  649. }
  650. }
  651. if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
  652. // We must have an anonymous union or struct declaration.
  653. const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
  654. assert(RD && "expected variable decl to have a record type");
  655. // Anonymous types with no tag or typedef get the name of their
  656. // declarator mangled in. If they have no declarator, number them with
  657. // a $S prefix.
  658. llvm::SmallString<64> Name("$S");
  659. // Get a unique id for the anonymous struct.
  660. Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
  661. mangleSourceName(Name.str());
  662. break;
  663. }
  664. // We must have an anonymous struct.
  665. const TagDecl *TD = cast<TagDecl>(ND);
  666. if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
  667. assert(TD->getDeclContext() == D->getDeclContext() &&
  668. "Typedef should not be in another decl context!");
  669. assert(D->getDeclName().getAsIdentifierInfo() &&
  670. "Typedef was not named!");
  671. mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
  672. break;
  673. }
  674. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
  675. if (Record->isLambda()) {
  676. llvm::SmallString<10> Name("<lambda_");
  677. unsigned LambdaId;
  678. if (Record->getLambdaManglingNumber())
  679. LambdaId = Record->getLambdaManglingNumber();
  680. else
  681. LambdaId = Context.getLambdaId(Record);
  682. Name += llvm::utostr(LambdaId);
  683. Name += ">";
  684. mangleSourceName(Name);
  685. break;
  686. }
  687. }
  688. llvm::SmallString<64> Name("<unnamed-type-");
  689. if (TD->hasDeclaratorForAnonDecl()) {
  690. // Anonymous types with no tag or typedef get the name of their
  691. // declarator mangled in if they have one.
  692. Name += TD->getDeclaratorForAnonDecl()->getName();
  693. } else {
  694. // Otherwise, number the types using a $S prefix.
  695. Name += "$S";
  696. Name += llvm::utostr(Context.getAnonymousStructId(TD));
  697. }
  698. Name += ">";
  699. mangleSourceName(Name.str());
  700. break;
  701. }
  702. case DeclarationName::ObjCZeroArgSelector:
  703. case DeclarationName::ObjCOneArgSelector:
  704. case DeclarationName::ObjCMultiArgSelector:
  705. llvm_unreachable("Can't mangle Objective-C selector names here!");
  706. case DeclarationName::CXXConstructorName:
  707. if (Structor == getStructor(ND)) {
  708. if (StructorType == Ctor_CopyingClosure) {
  709. Out << "?_O";
  710. return;
  711. }
  712. if (StructorType == Ctor_DefaultClosure) {
  713. Out << "?_F";
  714. return;
  715. }
  716. }
  717. Out << "?0";
  718. return;
  719. case DeclarationName::CXXDestructorName:
  720. if (ND == Structor)
  721. // If the named decl is the C++ destructor we're mangling,
  722. // use the type we were given.
  723. mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
  724. else
  725. // Otherwise, use the base destructor name. This is relevant if a
  726. // class with a destructor is declared within a destructor.
  727. mangleCXXDtorType(Dtor_Base);
  728. break;
  729. case DeclarationName::CXXConversionFunctionName:
  730. // <operator-name> ::= ?B # (cast)
  731. // The target type is encoded as the return type.
  732. Out << "?B";
  733. break;
  734. case DeclarationName::CXXOperatorName:
  735. mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
  736. break;
  737. case DeclarationName::CXXLiteralOperatorName: {
  738. Out << "?__K";
  739. mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
  740. break;
  741. }
  742. case DeclarationName::CXXUsingDirective:
  743. llvm_unreachable("Can't mangle a using directive name!");
  744. }
  745. }
  746. void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
  747. // <postfix> ::= <unqualified-name> [<postfix>]
  748. // ::= <substitution> [<postfix>]
  749. const DeclContext *DC = getEffectiveDeclContext(ND);
  750. while (!DC->isTranslationUnit()) {
  751. if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
  752. unsigned Disc;
  753. if (Context.getNextDiscriminator(ND, Disc)) {
  754. Out << '?';
  755. mangleNumber(Disc);
  756. Out << '?';
  757. }
  758. }
  759. if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
  760. DiagnosticsEngine &Diags = Context.getDiags();
  761. unsigned DiagID =
  762. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  763. "cannot mangle a local inside this block yet");
  764. Diags.Report(BD->getLocation(), DiagID);
  765. // FIXME: This is completely, utterly, wrong; see ItaniumMangle
  766. // for how this should be done.
  767. Out << "__block_invoke" << Context.getBlockId(BD, false);
  768. Out << '@';
  769. continue;
  770. } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
  771. mangleObjCMethodName(Method);
  772. } else if (isa<NamedDecl>(DC)) {
  773. ND = cast<NamedDecl>(DC);
  774. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  775. mangle(FD, "?");
  776. break;
  777. } else
  778. mangleUnqualifiedName(ND);
  779. }
  780. DC = DC->getParent();
  781. }
  782. }
  783. void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
  784. // Microsoft uses the names on the case labels for these dtor variants. Clang
  785. // uses the Itanium terminology internally. Everything in this ABI delegates
  786. // towards the base dtor.
  787. switch (T) {
  788. // <operator-name> ::= ?1 # destructor
  789. case Dtor_Base: Out << "?1"; return;
  790. // <operator-name> ::= ?_D # vbase destructor
  791. case Dtor_Complete: Out << "?_D"; return;
  792. // <operator-name> ::= ?_G # scalar deleting destructor
  793. case Dtor_Deleting: Out << "?_G"; return;
  794. // <operator-name> ::= ?_E # vector deleting destructor
  795. // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
  796. // it.
  797. case Dtor_Comdat:
  798. llvm_unreachable("not expecting a COMDAT");
  799. }
  800. llvm_unreachable("Unsupported dtor type?");
  801. }
  802. void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
  803. SourceLocation Loc) {
  804. switch (OO) {
  805. // ?0 # constructor
  806. // ?1 # destructor
  807. // <operator-name> ::= ?2 # new
  808. case OO_New: Out << "?2"; break;
  809. // <operator-name> ::= ?3 # delete
  810. case OO_Delete: Out << "?3"; break;
  811. // <operator-name> ::= ?4 # =
  812. case OO_Equal: Out << "?4"; break;
  813. // <operator-name> ::= ?5 # >>
  814. case OO_GreaterGreater: Out << "?5"; break;
  815. // <operator-name> ::= ?6 # <<
  816. case OO_LessLess: Out << "?6"; break;
  817. // <operator-name> ::= ?7 # !
  818. case OO_Exclaim: Out << "?7"; break;
  819. // <operator-name> ::= ?8 # ==
  820. case OO_EqualEqual: Out << "?8"; break;
  821. // <operator-name> ::= ?9 # !=
  822. case OO_ExclaimEqual: Out << "?9"; break;
  823. // <operator-name> ::= ?A # []
  824. case OO_Subscript: Out << "?A"; break;
  825. // ?B # conversion
  826. // <operator-name> ::= ?C # ->
  827. case OO_Arrow: Out << "?C"; break;
  828. // <operator-name> ::= ?D # *
  829. case OO_Star: Out << "?D"; break;
  830. // <operator-name> ::= ?E # ++
  831. case OO_PlusPlus: Out << "?E"; break;
  832. // <operator-name> ::= ?F # --
  833. case OO_MinusMinus: Out << "?F"; break;
  834. // <operator-name> ::= ?G # -
  835. case OO_Minus: Out << "?G"; break;
  836. // <operator-name> ::= ?H # +
  837. case OO_Plus: Out << "?H"; break;
  838. // <operator-name> ::= ?I # &
  839. case OO_Amp: Out << "?I"; break;
  840. // <operator-name> ::= ?J # ->*
  841. case OO_ArrowStar: Out << "?J"; break;
  842. // <operator-name> ::= ?K # /
  843. case OO_Slash: Out << "?K"; break;
  844. // <operator-name> ::= ?L # %
  845. case OO_Percent: Out << "?L"; break;
  846. // <operator-name> ::= ?M # <
  847. case OO_Less: Out << "?M"; break;
  848. // <operator-name> ::= ?N # <=
  849. case OO_LessEqual: Out << "?N"; break;
  850. // <operator-name> ::= ?O # >
  851. case OO_Greater: Out << "?O"; break;
  852. // <operator-name> ::= ?P # >=
  853. case OO_GreaterEqual: Out << "?P"; break;
  854. // <operator-name> ::= ?Q # ,
  855. case OO_Comma: Out << "?Q"; break;
  856. // <operator-name> ::= ?R # ()
  857. case OO_Call: Out << "?R"; break;
  858. // <operator-name> ::= ?S # ~
  859. case OO_Tilde: Out << "?S"; break;
  860. // <operator-name> ::= ?T # ^
  861. case OO_Caret: Out << "?T"; break;
  862. // <operator-name> ::= ?U # |
  863. case OO_Pipe: Out << "?U"; break;
  864. // <operator-name> ::= ?V # &&
  865. case OO_AmpAmp: Out << "?V"; break;
  866. // <operator-name> ::= ?W # ||
  867. case OO_PipePipe: Out << "?W"; break;
  868. // <operator-name> ::= ?X # *=
  869. case OO_StarEqual: Out << "?X"; break;
  870. // <operator-name> ::= ?Y # +=
  871. case OO_PlusEqual: Out << "?Y"; break;
  872. // <operator-name> ::= ?Z # -=
  873. case OO_MinusEqual: Out << "?Z"; break;
  874. // <operator-name> ::= ?_0 # /=
  875. case OO_SlashEqual: Out << "?_0"; break;
  876. // <operator-name> ::= ?_1 # %=
  877. case OO_PercentEqual: Out << "?_1"; break;
  878. // <operator-name> ::= ?_2 # >>=
  879. case OO_GreaterGreaterEqual: Out << "?_2"; break;
  880. // <operator-name> ::= ?_3 # <<=
  881. case OO_LessLessEqual: Out << "?_3"; break;
  882. // <operator-name> ::= ?_4 # &=
  883. case OO_AmpEqual: Out << "?_4"; break;
  884. // <operator-name> ::= ?_5 # |=
  885. case OO_PipeEqual: Out << "?_5"; break;
  886. // <operator-name> ::= ?_6 # ^=
  887. case OO_CaretEqual: Out << "?_6"; break;
  888. // ?_7 # vftable
  889. // ?_8 # vbtable
  890. // ?_9 # vcall
  891. // ?_A # typeof
  892. // ?_B # local static guard
  893. // ?_C # string
  894. // ?_D # vbase destructor
  895. // ?_E # vector deleting destructor
  896. // ?_F # default constructor closure
  897. // ?_G # scalar deleting destructor
  898. // ?_H # vector constructor iterator
  899. // ?_I # vector destructor iterator
  900. // ?_J # vector vbase constructor iterator
  901. // ?_K # virtual displacement map
  902. // ?_L # eh vector constructor iterator
  903. // ?_M # eh vector destructor iterator
  904. // ?_N # eh vector vbase constructor iterator
  905. // ?_O # copy constructor closure
  906. // ?_P<name> # udt returning <name>
  907. // ?_Q # <unknown>
  908. // ?_R0 # RTTI Type Descriptor
  909. // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
  910. // ?_R2 # RTTI Base Class Array
  911. // ?_R3 # RTTI Class Hierarchy Descriptor
  912. // ?_R4 # RTTI Complete Object Locator
  913. // ?_S # local vftable
  914. // ?_T # local vftable constructor closure
  915. // <operator-name> ::= ?_U # new[]
  916. case OO_Array_New: Out << "?_U"; break;
  917. // <operator-name> ::= ?_V # delete[]
  918. case OO_Array_Delete: Out << "?_V"; break;
  919. case OO_Conditional: {
  920. DiagnosticsEngine &Diags = Context.getDiags();
  921. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  922. "cannot mangle this conditional operator yet");
  923. Diags.Report(Loc, DiagID);
  924. break;
  925. }
  926. case OO_None:
  927. case NUM_OVERLOADED_OPERATORS:
  928. llvm_unreachable("Not an overloaded operator");
  929. }
  930. }
  931. void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
  932. // <source name> ::= <identifier> @
  933. BackRefVec::iterator Found =
  934. std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
  935. if (Found == NameBackReferences.end()) {
  936. if (NameBackReferences.size() < 10)
  937. NameBackReferences.push_back(Name);
  938. Out << Name << '@';
  939. } else {
  940. Out << (Found - NameBackReferences.begin());
  941. }
  942. }
  943. void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
  944. Context.mangleObjCMethodName(MD, Out);
  945. }
  946. void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
  947. const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
  948. // <template-name> ::= <unscoped-template-name> <template-args>
  949. // ::= <substitution>
  950. // Always start with the unqualified name.
  951. // Templates have their own context for back references.
  952. ArgBackRefMap OuterArgsContext;
  953. BackRefVec OuterTemplateContext;
  954. NameBackReferences.swap(OuterTemplateContext);
  955. TypeBackReferences.swap(OuterArgsContext);
  956. mangleUnscopedTemplateName(TD);
  957. mangleTemplateArgs(TD, TemplateArgs);
  958. // Restore the previous back reference contexts.
  959. NameBackReferences.swap(OuterTemplateContext);
  960. TypeBackReferences.swap(OuterArgsContext);
  961. }
  962. void
  963. MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
  964. // <unscoped-template-name> ::= ?$ <unqualified-name>
  965. Out << "?$";
  966. mangleUnqualifiedName(TD);
  967. }
  968. void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
  969. bool IsBoolean) {
  970. // <integer-literal> ::= $0 <number>
  971. Out << "$0";
  972. // Make sure booleans are encoded as 0/1.
  973. if (IsBoolean && Value.getBoolValue())
  974. mangleNumber(1);
  975. else if (Value.isSigned())
  976. mangleNumber(Value.getSExtValue());
  977. else
  978. mangleNumber(Value.getZExtValue());
  979. }
  980. void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
  981. // See if this is a constant expression.
  982. llvm::APSInt Value;
  983. if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
  984. mangleIntegerLiteral(Value, E->getType()->isBooleanType());
  985. return;
  986. }
  987. // Look through no-op casts like template parameter substitutions.
  988. E = E->IgnoreParenNoopCasts(Context.getASTContext());
  989. const CXXUuidofExpr *UE = nullptr;
  990. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  991. if (UO->getOpcode() == UO_AddrOf)
  992. UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
  993. } else
  994. UE = dyn_cast<CXXUuidofExpr>(E);
  995. if (UE) {
  996. // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
  997. // const __s_GUID _GUID_{lower case UUID with underscores}
  998. StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
  999. std::string Name = "_GUID_" + Uuid.lower();
  1000. std::replace(Name.begin(), Name.end(), '-', '_');
  1001. // If we had to peek through an address-of operator, treat this like we are
  1002. // dealing with a pointer type. Otherwise, treat it like a const reference.
  1003. //
  1004. // N.B. This matches up with the handling of TemplateArgument::Declaration
  1005. // in mangleTemplateArg
  1006. if (UE == E)
  1007. Out << "$E?";
  1008. else
  1009. Out << "$1?";
  1010. Out << Name << "@@3U__s_GUID@@B";
  1011. return;
  1012. }
  1013. // As bad as this diagnostic is, it's better than crashing.
  1014. DiagnosticsEngine &Diags = Context.getDiags();
  1015. unsigned DiagID = Diags.getCustomDiagID(
  1016. DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
  1017. Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
  1018. << E->getSourceRange();
  1019. }
  1020. void MicrosoftCXXNameMangler::mangleTemplateArgs(
  1021. const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
  1022. // <template-args> ::= <template-arg>+
  1023. const TemplateParameterList *TPL = TD->getTemplateParameters();
  1024. assert(TPL->size() == TemplateArgs.size() &&
  1025. "size mismatch between args and parms!");
  1026. unsigned Idx = 0;
  1027. for (const TemplateArgument &TA : TemplateArgs.asArray())
  1028. mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
  1029. }
  1030. void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
  1031. const TemplateArgument &TA,
  1032. const NamedDecl *Parm) {
  1033. // <template-arg> ::= <type>
  1034. // ::= <integer-literal>
  1035. // ::= <member-data-pointer>
  1036. // ::= <member-function-pointer>
  1037. // ::= $E? <name> <type-encoding>
  1038. // ::= $1? <name> <type-encoding>
  1039. // ::= $0A@
  1040. // ::= <template-args>
  1041. switch (TA.getKind()) {
  1042. case TemplateArgument::Null:
  1043. llvm_unreachable("Can't mangle null template arguments!");
  1044. case TemplateArgument::TemplateExpansion:
  1045. llvm_unreachable("Can't mangle template expansion arguments!");
  1046. case TemplateArgument::Type: {
  1047. QualType T = TA.getAsType();
  1048. mangleType(T, SourceRange(), QMM_Escape);
  1049. break;
  1050. }
  1051. case TemplateArgument::Declaration: {
  1052. const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
  1053. if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
  1054. mangleMemberDataPointer(
  1055. cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
  1056. cast<ValueDecl>(ND));
  1057. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  1058. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  1059. if (MD && MD->isInstance()) {
  1060. mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
  1061. } else {
  1062. Out << "$1?";
  1063. mangleName(FD);
  1064. mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
  1065. }
  1066. } else {
  1067. mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
  1068. }
  1069. break;
  1070. }
  1071. case TemplateArgument::Integral:
  1072. mangleIntegerLiteral(TA.getAsIntegral(),
  1073. TA.getIntegralType()->isBooleanType());
  1074. break;
  1075. case TemplateArgument::NullPtr: {
  1076. QualType T = TA.getNullPtrType();
  1077. if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
  1078. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  1079. if (MPT->isMemberFunctionPointerType() && isa<ClassTemplateDecl>(TD)) {
  1080. mangleMemberFunctionPointer(RD, nullptr);
  1081. return;
  1082. }
  1083. if (MPT->isMemberDataPointer()) {
  1084. if (isa<ClassTemplateDecl>(TD)) {
  1085. mangleMemberDataPointer(RD, nullptr);
  1086. return;
  1087. }
  1088. // nullptr data pointers are always represented with a single field
  1089. // which is initialized with either 0 or -1. Why -1? Well, we need to
  1090. // distinguish the case where the data member is at offset zero in the
  1091. // record.
  1092. // However, we are free to use 0 *if* we would use multiple fields for
  1093. // non-nullptr member pointers.
  1094. if (!RD->nullFieldOffsetIsZero()) {
  1095. mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
  1096. return;
  1097. }
  1098. }
  1099. }
  1100. mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
  1101. break;
  1102. }
  1103. case TemplateArgument::Expression:
  1104. mangleExpression(TA.getAsExpr());
  1105. break;
  1106. case TemplateArgument::Pack: {
  1107. ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
  1108. if (TemplateArgs.empty()) {
  1109. if (isa<TemplateTypeParmDecl>(Parm) ||
  1110. isa<TemplateTemplateParmDecl>(Parm))
  1111. // MSVC 2015 changed the mangling for empty expanded template packs,
  1112. // use the old mangling for link compatibility for old versions.
  1113. Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
  1114. LangOptions::MSVC2015)
  1115. ? "$$V"
  1116. : "$$$V");
  1117. else if (isa<NonTypeTemplateParmDecl>(Parm))
  1118. Out << "$S";
  1119. else
  1120. llvm_unreachable("unexpected template parameter decl!");
  1121. } else {
  1122. for (const TemplateArgument &PA : TemplateArgs)
  1123. mangleTemplateArg(TD, PA, Parm);
  1124. }
  1125. break;
  1126. }
  1127. case TemplateArgument::Template: {
  1128. const NamedDecl *ND =
  1129. TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
  1130. if (const auto *TD = dyn_cast<TagDecl>(ND)) {
  1131. mangleType(TD);
  1132. } else if (isa<TypeAliasDecl>(ND)) {
  1133. Out << "$$Y";
  1134. mangleName(ND);
  1135. } else {
  1136. llvm_unreachable("unexpected template template NamedDecl!");
  1137. }
  1138. break;
  1139. }
  1140. }
  1141. }
  1142. void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
  1143. bool IsMember) {
  1144. // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
  1145. // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
  1146. // 'I' means __restrict (32/64-bit).
  1147. // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
  1148. // keyword!
  1149. // <base-cvr-qualifiers> ::= A # near
  1150. // ::= B # near const
  1151. // ::= C # near volatile
  1152. // ::= D # near const volatile
  1153. // ::= E # far (16-bit)
  1154. // ::= F # far const (16-bit)
  1155. // ::= G # far volatile (16-bit)
  1156. // ::= H # far const volatile (16-bit)
  1157. // ::= I # huge (16-bit)
  1158. // ::= J # huge const (16-bit)
  1159. // ::= K # huge volatile (16-bit)
  1160. // ::= L # huge const volatile (16-bit)
  1161. // ::= M <basis> # based
  1162. // ::= N <basis> # based const
  1163. // ::= O <basis> # based volatile
  1164. // ::= P <basis> # based const volatile
  1165. // ::= Q # near member
  1166. // ::= R # near const member
  1167. // ::= S # near volatile member
  1168. // ::= T # near const volatile member
  1169. // ::= U # far member (16-bit)
  1170. // ::= V # far const member (16-bit)
  1171. // ::= W # far volatile member (16-bit)
  1172. // ::= X # far const volatile member (16-bit)
  1173. // ::= Y # huge member (16-bit)
  1174. // ::= Z # huge const member (16-bit)
  1175. // ::= 0 # huge volatile member (16-bit)
  1176. // ::= 1 # huge const volatile member (16-bit)
  1177. // ::= 2 <basis> # based member
  1178. // ::= 3 <basis> # based const member
  1179. // ::= 4 <basis> # based volatile member
  1180. // ::= 5 <basis> # based const volatile member
  1181. // ::= 6 # near function (pointers only)
  1182. // ::= 7 # far function (pointers only)
  1183. // ::= 8 # near method (pointers only)
  1184. // ::= 9 # far method (pointers only)
  1185. // ::= _A <basis> # based function (pointers only)
  1186. // ::= _B <basis> # based function (far?) (pointers only)
  1187. // ::= _C <basis> # based method (pointers only)
  1188. // ::= _D <basis> # based method (far?) (pointers only)
  1189. // ::= _E # block (Clang)
  1190. // <basis> ::= 0 # __based(void)
  1191. // ::= 1 # __based(segment)?
  1192. // ::= 2 <name> # __based(name)
  1193. // ::= 3 # ?
  1194. // ::= 4 # ?
  1195. // ::= 5 # not really based
  1196. bool HasConst = Quals.hasConst(),
  1197. HasVolatile = Quals.hasVolatile();
  1198. if (!IsMember) {
  1199. if (HasConst && HasVolatile) {
  1200. Out << 'D';
  1201. } else if (HasVolatile) {
  1202. Out << 'C';
  1203. } else if (HasConst) {
  1204. Out << 'B';
  1205. } else {
  1206. Out << 'A';
  1207. }
  1208. } else {
  1209. if (HasConst && HasVolatile) {
  1210. Out << 'T';
  1211. } else if (HasVolatile) {
  1212. Out << 'S';
  1213. } else if (HasConst) {
  1214. Out << 'R';
  1215. } else {
  1216. Out << 'Q';
  1217. }
  1218. }
  1219. // FIXME: For now, just drop all extension qualifiers on the floor.
  1220. }
  1221. void
  1222. MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
  1223. // <ref-qualifier> ::= G # lvalue reference
  1224. // ::= H # rvalue-reference
  1225. switch (RefQualifier) {
  1226. case RQ_None:
  1227. break;
  1228. case RQ_LValue:
  1229. Out << 'G';
  1230. break;
  1231. case RQ_RValue:
  1232. Out << 'H';
  1233. break;
  1234. }
  1235. }
  1236. void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
  1237. QualType PointeeType) {
  1238. bool HasRestrict = Quals.hasRestrict();
  1239. if (PointersAre64Bit &&
  1240. (PointeeType.isNull() || !PointeeType->isFunctionType()))
  1241. Out << 'E';
  1242. if (HasRestrict)
  1243. Out << 'I';
  1244. }
  1245. void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
  1246. // <pointer-cv-qualifiers> ::= P # no qualifiers
  1247. // ::= Q # const
  1248. // ::= R # volatile
  1249. // ::= S # const volatile
  1250. bool HasConst = Quals.hasConst(),
  1251. HasVolatile = Quals.hasVolatile();
  1252. if (HasConst && HasVolatile) {
  1253. Out << 'S';
  1254. } else if (HasVolatile) {
  1255. Out << 'R';
  1256. } else if (HasConst) {
  1257. Out << 'Q';
  1258. } else {
  1259. Out << 'P';
  1260. }
  1261. }
  1262. void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
  1263. SourceRange Range) {
  1264. // MSVC will backreference two canonically equivalent types that have slightly
  1265. // different manglings when mangled alone.
  1266. // Decayed types do not match up with non-decayed versions of the same type.
  1267. //
  1268. // e.g.
  1269. // void (*x)(void) will not form a backreference with void x(void)
  1270. void *TypePtr;
  1271. if (const auto *DT = T->getAs<DecayedType>()) {
  1272. QualType OriginalType = DT->getOriginalType();
  1273. // All decayed ArrayTypes should be treated identically; as-if they were
  1274. // a decayed IncompleteArrayType.
  1275. if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
  1276. OriginalType = getASTContext().getIncompleteArrayType(
  1277. AT->getElementType(), AT->getSizeModifier(),
  1278. AT->getIndexTypeCVRQualifiers());
  1279. TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
  1280. // If the original parameter was textually written as an array,
  1281. // instead treat the decayed parameter like it's const.
  1282. //
  1283. // e.g.
  1284. // int [] -> int * const
  1285. if (OriginalType->isArrayType())
  1286. T = T.withConst();
  1287. } else {
  1288. TypePtr = T.getCanonicalType().getAsOpaquePtr();
  1289. }
  1290. ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
  1291. if (Found == TypeBackReferences.end()) {
  1292. size_t OutSizeBefore = Out.tell();
  1293. mangleType(T, Range, QMM_Drop);
  1294. // See if it's worth creating a back reference.
  1295. // Only types longer than 1 character are considered
  1296. // and only 10 back references slots are available:
  1297. bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
  1298. if (LongerThanOneChar && TypeBackReferences.size() < 10) {
  1299. size_t Size = TypeBackReferences.size();
  1300. TypeBackReferences[TypePtr] = Size;
  1301. }
  1302. } else {
  1303. Out << Found->second;
  1304. }
  1305. }
  1306. void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
  1307. QualifierMangleMode QMM) {
  1308. // Don't use the canonical types. MSVC includes things like 'const' on
  1309. // pointer arguments to function pointers that canonicalization strips away.
  1310. T = T.getDesugaredType(getASTContext());
  1311. Qualifiers Quals = T.getLocalQualifiers();
  1312. if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
  1313. // If there were any Quals, getAsArrayType() pushed them onto the array
  1314. // element type.
  1315. if (QMM == QMM_Mangle)
  1316. Out << 'A';
  1317. else if (QMM == QMM_Escape || QMM == QMM_Result)
  1318. Out << "$$B";
  1319. mangleArrayType(AT);
  1320. return;
  1321. }
  1322. bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
  1323. T->isReferenceType() || T->isBlockPointerType();
  1324. switch (QMM) {
  1325. case QMM_Drop:
  1326. break;
  1327. case QMM_Mangle:
  1328. if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
  1329. Out << '6';
  1330. mangleFunctionType(FT);
  1331. return;
  1332. }
  1333. mangleQualifiers(Quals, false);
  1334. break;
  1335. case QMM_Escape:
  1336. if (!IsPointer && Quals) {
  1337. Out << "$$C";
  1338. mangleQualifiers(Quals, false);
  1339. }
  1340. break;
  1341. case QMM_Result:
  1342. if ((!IsPointer && Quals) || isa<TagType>(T)) {
  1343. Out << '?';
  1344. mangleQualifiers(Quals, false);
  1345. }
  1346. break;
  1347. }
  1348. const Type *ty = T.getTypePtr();
  1349. switch (ty->getTypeClass()) {
  1350. #define ABSTRACT_TYPE(CLASS, PARENT)
  1351. #define NON_CANONICAL_TYPE(CLASS, PARENT) \
  1352. case Type::CLASS: \
  1353. llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
  1354. return;
  1355. #define TYPE(CLASS, PARENT) \
  1356. case Type::CLASS: \
  1357. mangleType(cast<CLASS##Type>(ty), Quals, Range); \
  1358. break;
  1359. #include "clang/AST/TypeNodes.def"
  1360. #undef ABSTRACT_TYPE
  1361. #undef NON_CANONICAL_TYPE
  1362. #undef TYPE
  1363. }
  1364. }
  1365. void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
  1366. SourceRange Range) {
  1367. // <type> ::= <builtin-type>
  1368. // <builtin-type> ::= X # void
  1369. // ::= C # signed char
  1370. // ::= D # char
  1371. // ::= E # unsigned char
  1372. // ::= F # short
  1373. // ::= G # unsigned short (or wchar_t if it's not a builtin)
  1374. // ::= H # int
  1375. // ::= I # unsigned int
  1376. // ::= J # long
  1377. // ::= K # unsigned long
  1378. // L # <none>
  1379. // ::= M # float
  1380. // ::= N # double
  1381. // ::= O # long double (__float80 is mangled differently)
  1382. // ::= _J # long long, __int64
  1383. // ::= _K # unsigned long long, __int64
  1384. // ::= _L # __int128
  1385. // ::= _M # unsigned __int128
  1386. // ::= _N # bool
  1387. // _O # <array in parameter>
  1388. // ::= _T # __float80 (Intel)
  1389. // ::= _W # wchar_t
  1390. // ::= _Z # __float80 (Digital Mars)
  1391. switch (T->getKind()) {
  1392. case BuiltinType::Void: Out << 'X'; break;
  1393. case BuiltinType::SChar: Out << 'C'; break;
  1394. case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
  1395. case BuiltinType::UChar: Out << 'E'; break;
  1396. case BuiltinType::Short: Out << 'F'; break;
  1397. case BuiltinType::UShort: Out << 'G'; break;
  1398. case BuiltinType::Int: Out << 'H'; break;
  1399. case BuiltinType::UInt: Out << 'I'; break;
  1400. case BuiltinType::Long: Out << 'J'; break;
  1401. case BuiltinType::ULong: Out << 'K'; break;
  1402. case BuiltinType::Float: Out << 'M'; break;
  1403. case BuiltinType::LitFloat: // HLSL Change
  1404. case BuiltinType::Double: Out << 'N'; break;
  1405. // TODO: Determine size and mangle accordingly
  1406. case BuiltinType::LongDouble: Out << 'O'; break;
  1407. case BuiltinType::LitInt: // HLSL Change
  1408. case BuiltinType::LongLong: Out << "_J"; break;
  1409. case BuiltinType::ULongLong: Out << "_K"; break;
  1410. case BuiltinType::Int128: Out << "_L"; break;
  1411. case BuiltinType::UInt128: Out << "_M"; break;
  1412. case BuiltinType::Bool: Out << "_N"; break;
  1413. case BuiltinType::Char16: Out << "_S"; break;
  1414. case BuiltinType::Char32: Out << "_U"; break;
  1415. case BuiltinType::WChar_S:
  1416. case BuiltinType::WChar_U: Out << "_W"; break;
  1417. #define BUILTIN_TYPE(Id, SingletonId)
  1418. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  1419. case BuiltinType::Id:
  1420. #include "clang/AST/BuiltinTypes.def"
  1421. case BuiltinType::Dependent:
  1422. llvm_unreachable("placeholder types shouldn't get to name mangling");
  1423. case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
  1424. case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
  1425. case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
  1426. case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
  1427. case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
  1428. case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
  1429. case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
  1430. case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
  1431. case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
  1432. case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
  1433. case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
  1434. case BuiltinType::NullPtr: Out << "$$T"; break;
  1435. // HLSL Change Starts
  1436. case BuiltinType::Min10Float:
  1437. Out << "$min10f@";
  1438. break;
  1439. case BuiltinType::Min16Float:
  1440. Out << "$min16f@";
  1441. break;
  1442. case BuiltinType::Min16Int:
  1443. Out << "$min16i@";
  1444. break;
  1445. case BuiltinType::Min16UInt:
  1446. Out << "$min16ui@";
  1447. break;
  1448. case BuiltinType::HalfFloat:
  1449. Out << "$halff@";
  1450. break;
  1451. case BuiltinType::Min12Int:
  1452. Out << "$min12i@";
  1453. break;
  1454. case BuiltinType::Half:
  1455. Out << "$f16@";
  1456. break;
  1457. // HLSL Change Ends
  1458. }
  1459. }
  1460. // <type> ::= <function-type>
  1461. void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
  1462. SourceRange) {
  1463. // Structors only appear in decls, so at this point we know it's not a
  1464. // structor type.
  1465. // FIXME: This may not be lambda-friendly.
  1466. if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
  1467. Out << "$$A8@@";
  1468. mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
  1469. } else {
  1470. Out << "$$A6";
  1471. mangleFunctionType(T);
  1472. }
  1473. }
  1474. void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
  1475. Qualifiers, SourceRange) {
  1476. llvm_unreachable("Can't mangle K&R function prototypes");
  1477. }
  1478. void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
  1479. const FunctionDecl *D,
  1480. bool ForceThisQuals) {
  1481. // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
  1482. // <return-type> <argument-list> <throw-spec>
  1483. const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
  1484. SourceRange Range;
  1485. if (D) Range = D->getSourceRange();
  1486. bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
  1487. CallingConv CC = T->getCallConv();
  1488. if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
  1489. if (MD->isInstance())
  1490. HasThisQuals = true;
  1491. if (isa<CXXDestructorDecl>(MD)) {
  1492. IsStructor = true;
  1493. } else if (isa<CXXConstructorDecl>(MD)) {
  1494. IsStructor = true;
  1495. IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
  1496. StructorType == Ctor_DefaultClosure) &&
  1497. getStructor(MD) == Structor;
  1498. if (IsCtorClosure)
  1499. CC = getASTContext().getDefaultCallingConvention(
  1500. /*IsVariadic=*/false, /*IsCXXMethod=*/true);
  1501. }
  1502. }
  1503. // If this is a C++ instance method, mangle the CVR qualifiers for the
  1504. // this pointer.
  1505. if (HasThisQuals) {
  1506. Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
  1507. manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
  1508. mangleRefQualifier(Proto->getRefQualifier());
  1509. mangleQualifiers(Quals, /*IsMember=*/false);
  1510. }
  1511. mangleCallingConvention(CC);
  1512. // <return-type> ::= <type>
  1513. // ::= @ # structors (they have no declared return type)
  1514. if (IsStructor) {
  1515. if (isa<CXXDestructorDecl>(D) && D == Structor &&
  1516. StructorType == Dtor_Deleting) {
  1517. // The scalar deleting destructor takes an extra int argument.
  1518. // However, the FunctionType generated has 0 arguments.
  1519. // FIXME: This is a temporary hack.
  1520. // Maybe should fix the FunctionType creation instead?
  1521. Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
  1522. return;
  1523. }
  1524. if (IsCtorClosure) {
  1525. // Default constructor closure and copy constructor closure both return
  1526. // void.
  1527. Out << 'X';
  1528. if (StructorType == Ctor_DefaultClosure) {
  1529. // Default constructor closure always has no arguments.
  1530. Out << 'X';
  1531. } else if (StructorType == Ctor_CopyingClosure) {
  1532. // Copy constructor closure always takes an unqualified reference.
  1533. mangleArgumentType(getASTContext().getLValueReferenceType(
  1534. Proto->getParamType(0)
  1535. ->getAs<LValueReferenceType>()
  1536. ->getPointeeType(),
  1537. /*SpelledAsLValue=*/true),
  1538. Range);
  1539. Out << '@';
  1540. } else {
  1541. llvm_unreachable("unexpected constructor closure!");
  1542. }
  1543. Out << 'Z';
  1544. return;
  1545. }
  1546. Out << '@';
  1547. } else {
  1548. QualType ResultType = Proto->getReturnType();
  1549. if (const auto *AT =
  1550. dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
  1551. Out << '?';
  1552. mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
  1553. Out << '?';
  1554. mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
  1555. Out << '@';
  1556. } else {
  1557. if (ResultType->isVoidType())
  1558. ResultType = ResultType.getUnqualifiedType();
  1559. mangleType(ResultType, Range, QMM_Result);
  1560. }
  1561. }
  1562. // <argument-list> ::= X # void
  1563. // ::= <type>+ @
  1564. // ::= <type>* Z # varargs
  1565. if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
  1566. Out << 'X';
  1567. } else {
  1568. // Happens for function pointer type arguments for example.
  1569. for (const QualType &Arg : Proto->param_types())
  1570. mangleArgumentType(Arg, Range);
  1571. // <builtin-type> ::= Z # ellipsis
  1572. if (Proto->isVariadic())
  1573. Out << 'Z';
  1574. else
  1575. Out << '@';
  1576. }
  1577. mangleThrowSpecification(Proto);
  1578. }
  1579. void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
  1580. // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
  1581. // # pointer. in 64-bit mode *all*
  1582. // # 'this' pointers are 64-bit.
  1583. // ::= <global-function>
  1584. // <member-function> ::= A # private: near
  1585. // ::= B # private: far
  1586. // ::= C # private: static near
  1587. // ::= D # private: static far
  1588. // ::= E # private: virtual near
  1589. // ::= F # private: virtual far
  1590. // ::= I # protected: near
  1591. // ::= J # protected: far
  1592. // ::= K # protected: static near
  1593. // ::= L # protected: static far
  1594. // ::= M # protected: virtual near
  1595. // ::= N # protected: virtual far
  1596. // ::= Q # public: near
  1597. // ::= R # public: far
  1598. // ::= S # public: static near
  1599. // ::= T # public: static far
  1600. // ::= U # public: virtual near
  1601. // ::= V # public: virtual far
  1602. // <global-function> ::= Y # global near
  1603. // ::= Z # global far
  1604. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1605. switch (MD->getAccess()) {
  1606. case AS_none:
  1607. llvm_unreachable("Unsupported access specifier");
  1608. case AS_private:
  1609. if (MD->isStatic())
  1610. Out << 'C';
  1611. else if (MD->isVirtual())
  1612. Out << 'E';
  1613. else
  1614. Out << 'A';
  1615. break;
  1616. case AS_protected:
  1617. if (MD->isStatic())
  1618. Out << 'K';
  1619. else if (MD->isVirtual())
  1620. Out << 'M';
  1621. else
  1622. Out << 'I';
  1623. break;
  1624. case AS_public:
  1625. if (MD->isStatic())
  1626. Out << 'S';
  1627. else if (MD->isVirtual())
  1628. Out << 'U';
  1629. else
  1630. Out << 'Q';
  1631. }
  1632. } else {
  1633. Out << 'Y';
  1634. }
  1635. }
  1636. void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
  1637. // <calling-convention> ::= A # __cdecl
  1638. // ::= B # __export __cdecl
  1639. // ::= C # __pascal
  1640. // ::= D # __export __pascal
  1641. // ::= E # __thiscall
  1642. // ::= F # __export __thiscall
  1643. // ::= G # __stdcall
  1644. // ::= H # __export __stdcall
  1645. // ::= I # __fastcall
  1646. // ::= J # __export __fastcall
  1647. // ::= Q # __vectorcall
  1648. // The 'export' calling conventions are from a bygone era
  1649. // (*cough*Win16*cough*) when functions were declared for export with
  1650. // that keyword. (It didn't actually export them, it just made them so
  1651. // that they could be in a DLL and somebody from another module could call
  1652. // them.)
  1653. switch (CC) {
  1654. default:
  1655. llvm_unreachable("Unsupported CC for mangling");
  1656. case CC_X86_64Win64:
  1657. case CC_X86_64SysV:
  1658. case CC_C: Out << 'A'; break;
  1659. case CC_X86Pascal: Out << 'C'; break;
  1660. case CC_X86ThisCall: Out << 'E'; break;
  1661. case CC_X86StdCall: Out << 'G'; break;
  1662. case CC_X86FastCall: Out << 'I'; break;
  1663. case CC_X86VectorCall: Out << 'Q'; break;
  1664. }
  1665. }
  1666. void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
  1667. mangleCallingConvention(T->getCallConv());
  1668. }
  1669. void MicrosoftCXXNameMangler::mangleThrowSpecification(
  1670. const FunctionProtoType *FT) {
  1671. // <throw-spec> ::= Z # throw(...) (default)
  1672. // ::= @ # throw() or __declspec/__attribute__((nothrow))
  1673. // ::= <type>+
  1674. // NOTE: Since the Microsoft compiler ignores throw specifications, they are
  1675. // all actually mangled as 'Z'. (They're ignored because their associated
  1676. // functionality isn't implemented, and probably never will be.)
  1677. Out << 'Z';
  1678. }
  1679. void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
  1680. Qualifiers, SourceRange Range) {
  1681. // Probably should be mangled as a template instantiation; need to see what
  1682. // VC does first.
  1683. DiagnosticsEngine &Diags = Context.getDiags();
  1684. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1685. "cannot mangle this unresolved dependent type yet");
  1686. Diags.Report(Range.getBegin(), DiagID)
  1687. << Range;
  1688. }
  1689. // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
  1690. // <union-type> ::= T <name>
  1691. // <struct-type> ::= U <name>
  1692. // <class-type> ::= V <name>
  1693. // <enum-type> ::= W4 <name>
  1694. void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
  1695. SourceRange) {
  1696. mangleType(cast<TagType>(T)->getDecl());
  1697. }
  1698. void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
  1699. SourceRange) {
  1700. mangleType(cast<TagType>(T)->getDecl());
  1701. }
  1702. void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
  1703. switch (TD->getTagKind()) {
  1704. case TTK_Union:
  1705. Out << 'T';
  1706. break;
  1707. case TTK_Struct:
  1708. case TTK_Interface:
  1709. Out << 'U';
  1710. break;
  1711. case TTK_Class:
  1712. Out << 'V';
  1713. break;
  1714. case TTK_Enum:
  1715. Out << "W4";
  1716. break;
  1717. }
  1718. mangleName(TD);
  1719. }
  1720. // <type> ::= <array-type>
  1721. // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
  1722. // [Y <dimension-count> <dimension>+]
  1723. // <element-type> # as global, E is never required
  1724. // It's supposed to be the other way around, but for some strange reason, it
  1725. // isn't. Today this behavior is retained for the sole purpose of backwards
  1726. // compatibility.
  1727. void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
  1728. // This isn't a recursive mangling, so now we have to do it all in this
  1729. // one call.
  1730. manglePointerCVQualifiers(T->getElementType().getQualifiers());
  1731. mangleType(T->getElementType(), SourceRange());
  1732. }
  1733. void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
  1734. SourceRange) {
  1735. llvm_unreachable("Should have been special cased");
  1736. }
  1737. void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
  1738. SourceRange) {
  1739. llvm_unreachable("Should have been special cased");
  1740. }
  1741. void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
  1742. Qualifiers, SourceRange) {
  1743. llvm_unreachable("Should have been special cased");
  1744. }
  1745. void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
  1746. Qualifiers, SourceRange) {
  1747. llvm_unreachable("Should have been special cased");
  1748. }
  1749. void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
  1750. QualType ElementTy(T, 0);
  1751. SmallVector<llvm::APInt, 3> Dimensions;
  1752. for (;;) {
  1753. if (ElementTy->isConstantArrayType()) {
  1754. const ConstantArrayType *CAT =
  1755. getASTContext().getAsConstantArrayType(ElementTy);
  1756. Dimensions.push_back(CAT->getSize());
  1757. ElementTy = CAT->getElementType();
  1758. } else if (ElementTy->isIncompleteArrayType()) {
  1759. const IncompleteArrayType *IAT =
  1760. getASTContext().getAsIncompleteArrayType(ElementTy);
  1761. Dimensions.push_back(llvm::APInt(32, 0));
  1762. ElementTy = IAT->getElementType();
  1763. } else if (ElementTy->isVariableArrayType()) {
  1764. const VariableArrayType *VAT =
  1765. getASTContext().getAsVariableArrayType(ElementTy);
  1766. Dimensions.push_back(llvm::APInt(32, 0));
  1767. ElementTy = VAT->getElementType();
  1768. } else if (ElementTy->isDependentSizedArrayType()) {
  1769. // The dependent expression has to be folded into a constant (TODO).
  1770. const DependentSizedArrayType *DSAT =
  1771. getASTContext().getAsDependentSizedArrayType(ElementTy);
  1772. DiagnosticsEngine &Diags = Context.getDiags();
  1773. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1774. "cannot mangle this dependent-length array yet");
  1775. Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
  1776. << DSAT->getBracketsRange();
  1777. return;
  1778. } else {
  1779. break;
  1780. }
  1781. }
  1782. Out << 'Y';
  1783. // <dimension-count> ::= <number> # number of extra dimensions
  1784. mangleNumber(Dimensions.size());
  1785. for (const llvm::APInt &Dimension : Dimensions)
  1786. mangleNumber(Dimension.getLimitedValue());
  1787. mangleType(ElementTy, SourceRange(), QMM_Escape);
  1788. }
  1789. // <type> ::= <pointer-to-member-type>
  1790. // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
  1791. // <class name> <type>
  1792. void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals,
  1793. SourceRange Range) {
  1794. QualType PointeeType = T->getPointeeType();
  1795. manglePointerCVQualifiers(Quals);
  1796. manglePointerExtQualifiers(Quals, PointeeType);
  1797. if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
  1798. Out << '8';
  1799. mangleName(T->getClass()->castAs<RecordType>()->getDecl());
  1800. mangleFunctionType(FPT, nullptr, true);
  1801. } else {
  1802. mangleQualifiers(PointeeType.getQualifiers(), true);
  1803. mangleName(T->getClass()->castAs<RecordType>()->getDecl());
  1804. mangleType(PointeeType, Range, QMM_Drop);
  1805. }
  1806. }
  1807. void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
  1808. Qualifiers, SourceRange Range) {
  1809. DiagnosticsEngine &Diags = Context.getDiags();
  1810. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1811. "cannot mangle this template type parameter type yet");
  1812. Diags.Report(Range.getBegin(), DiagID)
  1813. << Range;
  1814. }
  1815. void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
  1816. Qualifiers, SourceRange Range) {
  1817. DiagnosticsEngine &Diags = Context.getDiags();
  1818. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1819. "cannot mangle this substituted parameter pack yet");
  1820. Diags.Report(Range.getBegin(), DiagID)
  1821. << Range;
  1822. }
  1823. // <type> ::= <pointer-type>
  1824. // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
  1825. // # the E is required for 64-bit non-static pointers
  1826. void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
  1827. SourceRange Range) {
  1828. QualType PointeeType = T->getPointeeType();
  1829. manglePointerCVQualifiers(Quals);
  1830. manglePointerExtQualifiers(Quals, PointeeType);
  1831. mangleType(PointeeType, Range);
  1832. }
  1833. void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
  1834. Qualifiers Quals, SourceRange Range) {
  1835. QualType PointeeType = T->getPointeeType();
  1836. manglePointerCVQualifiers(Quals);
  1837. manglePointerExtQualifiers(Quals, PointeeType);
  1838. // Object pointers never have qualifiers.
  1839. Out << 'A';
  1840. mangleType(PointeeType, Range);
  1841. }
  1842. // <type> ::= <reference-type>
  1843. // <reference-type> ::= A E? <cvr-qualifiers> <type>
  1844. // # the E is required for 64-bit non-static lvalue references
  1845. void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
  1846. Qualifiers Quals, SourceRange Range) {
  1847. QualType PointeeType = T->getPointeeType();
  1848. Out << (Quals.hasVolatile() ? 'B' : 'A');
  1849. manglePointerExtQualifiers(Quals, PointeeType);
  1850. mangleType(PointeeType, Range);
  1851. }
  1852. // <type> ::= <r-value-reference-type>
  1853. // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
  1854. // # the E is required for 64-bit non-static rvalue references
  1855. void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
  1856. Qualifiers Quals, SourceRange Range) {
  1857. QualType PointeeType = T->getPointeeType();
  1858. Out << (Quals.hasVolatile() ? "$$R" : "$$Q");
  1859. manglePointerExtQualifiers(Quals, PointeeType);
  1860. mangleType(PointeeType, Range);
  1861. }
  1862. void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
  1863. SourceRange Range) {
  1864. DiagnosticsEngine &Diags = Context.getDiags();
  1865. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1866. "cannot mangle this complex number type yet");
  1867. Diags.Report(Range.getBegin(), DiagID)
  1868. << Range;
  1869. }
  1870. void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
  1871. SourceRange Range) {
  1872. const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
  1873. assert(ET && "vectors with non-builtin elements are unsupported");
  1874. uint64_t Width = getASTContext().getTypeSize(T);
  1875. // Pattern match exactly the typedefs in our intrinsic headers. Anything that
  1876. // doesn't match the Intel types uses a custom mangling below.
  1877. bool IsBuiltin = true;
  1878. llvm::Triple::ArchType AT =
  1879. getASTContext().getTargetInfo().getTriple().getArch();
  1880. if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
  1881. if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
  1882. Out << "T__m64";
  1883. } else if (Width >= 128) {
  1884. if (ET->getKind() == BuiltinType::Float)
  1885. Out << "T__m" << Width;
  1886. else if (ET->getKind() == BuiltinType::LongLong)
  1887. Out << "T__m" << Width << 'i';
  1888. else if (ET->getKind() == BuiltinType::Double)
  1889. Out << "U__m" << Width << 'd';
  1890. else
  1891. IsBuiltin = false;
  1892. } else {
  1893. IsBuiltin = false;
  1894. }
  1895. } else {
  1896. IsBuiltin = false;
  1897. }
  1898. if (!IsBuiltin) {
  1899. // The MS ABI doesn't have a special mangling for vector types, so we define
  1900. // our own mangling to handle uses of __vector_size__ on user-specified
  1901. // types, and for extensions like __v4sf.
  1902. Out << "T__clang_vec" << T->getNumElements() << '_';
  1903. mangleType(ET, Quals, Range);
  1904. }
  1905. Out << "@@";
  1906. }
  1907. void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T, Qualifiers,
  1908. SourceRange Range) {
  1909. DiagnosticsEngine &Diags = Context.getDiags();
  1910. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1911. "cannot mangle this extended vector type yet");
  1912. Diags.Report(Range.getBegin(), DiagID)
  1913. << Range;
  1914. }
  1915. void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
  1916. Qualifiers, SourceRange Range) {
  1917. DiagnosticsEngine &Diags = Context.getDiags();
  1918. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1919. "cannot mangle this dependent-sized extended vector type yet");
  1920. Diags.Report(Range.getBegin(), DiagID)
  1921. << Range;
  1922. }
  1923. void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
  1924. SourceRange) {
  1925. // ObjC interfaces have structs underlying them.
  1926. Out << 'U';
  1927. mangleName(T->getDecl());
  1928. }
  1929. void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
  1930. SourceRange Range) {
  1931. // We don't allow overloading by different protocol qualification,
  1932. // so mangling them isn't necessary.
  1933. mangleType(T->getBaseType(), Range);
  1934. }
  1935. void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
  1936. Qualifiers Quals, SourceRange Range) {
  1937. QualType PointeeType = T->getPointeeType();
  1938. manglePointerCVQualifiers(Quals);
  1939. manglePointerExtQualifiers(Quals, PointeeType);
  1940. Out << "_E";
  1941. mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
  1942. }
  1943. void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
  1944. Qualifiers, SourceRange) {
  1945. llvm_unreachable("Cannot mangle injected class name type.");
  1946. }
  1947. void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
  1948. Qualifiers, SourceRange Range) {
  1949. DiagnosticsEngine &Diags = Context.getDiags();
  1950. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1951. "cannot mangle this template specialization type yet");
  1952. Diags.Report(Range.getBegin(), DiagID)
  1953. << Range;
  1954. }
  1955. void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
  1956. SourceRange Range) {
  1957. DiagnosticsEngine &Diags = Context.getDiags();
  1958. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1959. "cannot mangle this dependent name type yet");
  1960. Diags.Report(Range.getBegin(), DiagID)
  1961. << Range;
  1962. }
  1963. void MicrosoftCXXNameMangler::mangleType(
  1964. const DependentTemplateSpecializationType *T, Qualifiers,
  1965. SourceRange Range) {
  1966. DiagnosticsEngine &Diags = Context.getDiags();
  1967. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1968. "cannot mangle this dependent template specialization type yet");
  1969. Diags.Report(Range.getBegin(), DiagID)
  1970. << Range;
  1971. }
  1972. void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
  1973. SourceRange Range) {
  1974. DiagnosticsEngine &Diags = Context.getDiags();
  1975. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1976. "cannot mangle this pack expansion yet");
  1977. Diags.Report(Range.getBegin(), DiagID)
  1978. << Range;
  1979. }
  1980. void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
  1981. SourceRange Range) {
  1982. DiagnosticsEngine &Diags = Context.getDiags();
  1983. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1984. "cannot mangle this typeof(type) yet");
  1985. Diags.Report(Range.getBegin(), DiagID)
  1986. << Range;
  1987. }
  1988. void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
  1989. SourceRange Range) {
  1990. DiagnosticsEngine &Diags = Context.getDiags();
  1991. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1992. "cannot mangle this typeof(expression) yet");
  1993. Diags.Report(Range.getBegin(), DiagID)
  1994. << Range;
  1995. }
  1996. void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
  1997. SourceRange Range) {
  1998. DiagnosticsEngine &Diags = Context.getDiags();
  1999. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2000. "cannot mangle this decltype() yet");
  2001. Diags.Report(Range.getBegin(), DiagID)
  2002. << Range;
  2003. }
  2004. void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
  2005. Qualifiers, SourceRange Range) {
  2006. DiagnosticsEngine &Diags = Context.getDiags();
  2007. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2008. "cannot mangle this unary transform type yet");
  2009. Diags.Report(Range.getBegin(), DiagID)
  2010. << Range;
  2011. }
  2012. void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
  2013. SourceRange Range) {
  2014. assert(T->getDeducedType().isNull() && "expecting a dependent type!");
  2015. DiagnosticsEngine &Diags = Context.getDiags();
  2016. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2017. "cannot mangle this 'auto' type yet");
  2018. Diags.Report(Range.getBegin(), DiagID)
  2019. << Range;
  2020. }
  2021. void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
  2022. SourceRange Range) {
  2023. DiagnosticsEngine &Diags = Context.getDiags();
  2024. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2025. "cannot mangle this C11 atomic type yet");
  2026. Diags.Report(Range.getBegin(), DiagID)
  2027. << Range;
  2028. }
  2029. void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
  2030. raw_ostream &Out) {
  2031. assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
  2032. "Invalid mangleName() call, argument is not a variable or function!");
  2033. assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
  2034. "Invalid mangleName() call on 'structor decl!");
  2035. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  2036. getASTContext().getSourceManager(),
  2037. "Mangling declaration");
  2038. MicrosoftCXXNameMangler Mangler(*this, Out);
  2039. return Mangler.mangle(D);
  2040. }
  2041. // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
  2042. // <virtual-adjustment>
  2043. // <no-adjustment> ::= A # private near
  2044. // ::= B # private far
  2045. // ::= I # protected near
  2046. // ::= J # protected far
  2047. // ::= Q # public near
  2048. // ::= R # public far
  2049. // <static-adjustment> ::= G <static-offset> # private near
  2050. // ::= H <static-offset> # private far
  2051. // ::= O <static-offset> # protected near
  2052. // ::= P <static-offset> # protected far
  2053. // ::= W <static-offset> # public near
  2054. // ::= X <static-offset> # public far
  2055. // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
  2056. // ::= $1 <virtual-shift> <static-offset> # private far
  2057. // ::= $2 <virtual-shift> <static-offset> # protected near
  2058. // ::= $3 <virtual-shift> <static-offset> # protected far
  2059. // ::= $4 <virtual-shift> <static-offset> # public near
  2060. // ::= $5 <virtual-shift> <static-offset> # public far
  2061. // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
  2062. // <vtordisp-shift> ::= <offset-to-vtordisp>
  2063. // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
  2064. // <offset-to-vtordisp>
  2065. static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
  2066. const ThisAdjustment &Adjustment,
  2067. MicrosoftCXXNameMangler &Mangler,
  2068. raw_ostream &Out) {
  2069. if (!Adjustment.Virtual.isEmpty()) {
  2070. Out << '$';
  2071. char AccessSpec;
  2072. switch (MD->getAccess()) {
  2073. case AS_none:
  2074. llvm_unreachable("Unsupported access specifier");
  2075. case AS_private:
  2076. AccessSpec = '0';
  2077. break;
  2078. case AS_protected:
  2079. AccessSpec = '2';
  2080. break;
  2081. case AS_public:
  2082. AccessSpec = '4';
  2083. }
  2084. if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
  2085. Out << 'R' << AccessSpec;
  2086. Mangler.mangleNumber(
  2087. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
  2088. Mangler.mangleNumber(
  2089. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
  2090. Mangler.mangleNumber(
  2091. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
  2092. Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
  2093. } else {
  2094. Out << AccessSpec;
  2095. Mangler.mangleNumber(
  2096. static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
  2097. Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
  2098. }
  2099. } else if (Adjustment.NonVirtual != 0) {
  2100. switch (MD->getAccess()) {
  2101. case AS_none:
  2102. llvm_unreachable("Unsupported access specifier");
  2103. case AS_private:
  2104. Out << 'G';
  2105. break;
  2106. case AS_protected:
  2107. Out << 'O';
  2108. break;
  2109. case AS_public:
  2110. Out << 'W';
  2111. }
  2112. Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
  2113. } else {
  2114. switch (MD->getAccess()) {
  2115. case AS_none:
  2116. llvm_unreachable("Unsupported access specifier");
  2117. case AS_private:
  2118. Out << 'A';
  2119. break;
  2120. case AS_protected:
  2121. Out << 'I';
  2122. break;
  2123. case AS_public:
  2124. Out << 'Q';
  2125. }
  2126. }
  2127. }
  2128. void
  2129. MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
  2130. raw_ostream &Out) {
  2131. MicrosoftVTableContext *VTContext =
  2132. cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
  2133. const MicrosoftVTableContext::MethodVFTableLocation &ML =
  2134. VTContext->getMethodVFTableLocation(GlobalDecl(MD));
  2135. MicrosoftCXXNameMangler Mangler(*this, Out);
  2136. Mangler.getStream() << "\01?";
  2137. Mangler.mangleVirtualMemPtrThunk(MD, ML);
  2138. }
  2139. void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
  2140. const ThunkInfo &Thunk,
  2141. raw_ostream &Out) {
  2142. MicrosoftCXXNameMangler Mangler(*this, Out);
  2143. Out << "\01?";
  2144. Mangler.mangleName(MD);
  2145. mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
  2146. if (!Thunk.Return.isEmpty())
  2147. assert(Thunk.Method != nullptr &&
  2148. "Thunk info should hold the overridee decl");
  2149. const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
  2150. Mangler.mangleFunctionType(
  2151. DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
  2152. }
  2153. void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
  2154. const CXXDestructorDecl *DD, CXXDtorType Type,
  2155. const ThisAdjustment &Adjustment, raw_ostream &Out) {
  2156. // FIXME: Actually, the dtor thunk should be emitted for vector deleting
  2157. // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
  2158. // mangling manually until we support both deleting dtor types.
  2159. assert(Type == Dtor_Deleting);
  2160. MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
  2161. Out << "\01??_E";
  2162. Mangler.mangleName(DD->getParent());
  2163. mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
  2164. Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
  2165. }
  2166. void MicrosoftMangleContextImpl::mangleCXXVFTable(
  2167. const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
  2168. raw_ostream &Out) {
  2169. // <mangled-name> ::= ?_7 <class-name> <storage-class>
  2170. // <cvr-qualifiers> [<name>] @
  2171. // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
  2172. // is always '6' for vftables.
  2173. MicrosoftCXXNameMangler Mangler(*this, Out);
  2174. Mangler.getStream() << "\01??_7";
  2175. Mangler.mangleName(Derived);
  2176. Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
  2177. for (const CXXRecordDecl *RD : BasePath)
  2178. Mangler.mangleName(RD);
  2179. Mangler.getStream() << '@';
  2180. }
  2181. void MicrosoftMangleContextImpl::mangleCXXVBTable(
  2182. const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
  2183. raw_ostream &Out) {
  2184. // <mangled-name> ::= ?_8 <class-name> <storage-class>
  2185. // <cvr-qualifiers> [<name>] @
  2186. // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
  2187. // is always '7' for vbtables.
  2188. MicrosoftCXXNameMangler Mangler(*this, Out);
  2189. Mangler.getStream() << "\01??_8";
  2190. Mangler.mangleName(Derived);
  2191. Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
  2192. for (const CXXRecordDecl *RD : BasePath)
  2193. Mangler.mangleName(RD);
  2194. Mangler.getStream() << '@';
  2195. }
  2196. void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
  2197. MicrosoftCXXNameMangler Mangler(*this, Out);
  2198. Mangler.getStream() << "\01??_R0";
  2199. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  2200. Mangler.getStream() << "@8";
  2201. }
  2202. void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
  2203. raw_ostream &Out) {
  2204. MicrosoftCXXNameMangler Mangler(*this, Out);
  2205. Mangler.getStream() << '.';
  2206. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  2207. }
  2208. void MicrosoftMangleContextImpl::mangleCXXCatchHandlerType(QualType T,
  2209. uint32_t Flags,
  2210. raw_ostream &Out) {
  2211. MicrosoftCXXNameMangler Mangler(*this, Out);
  2212. Mangler.getStream() << "llvm.eh.handlertype.";
  2213. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  2214. Mangler.getStream() << '.' << Flags;
  2215. }
  2216. void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
  2217. const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
  2218. MicrosoftCXXNameMangler Mangler(*this, Out);
  2219. Mangler.getStream() << "\01??_K";
  2220. Mangler.mangleName(SrcRD);
  2221. Mangler.getStream() << "$C";
  2222. Mangler.mangleName(DstRD);
  2223. }
  2224. void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T,
  2225. bool IsConst,
  2226. bool IsVolatile,
  2227. uint32_t NumEntries,
  2228. raw_ostream &Out) {
  2229. MicrosoftCXXNameMangler Mangler(*this, Out);
  2230. Mangler.getStream() << "_TI";
  2231. if (IsConst)
  2232. Mangler.getStream() << 'C';
  2233. if (IsVolatile)
  2234. Mangler.getStream() << 'V';
  2235. Mangler.getStream() << NumEntries;
  2236. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  2237. }
  2238. void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
  2239. QualType T, uint32_t NumEntries, raw_ostream &Out) {
  2240. MicrosoftCXXNameMangler Mangler(*this, Out);
  2241. Mangler.getStream() << "_CTA";
  2242. Mangler.getStream() << NumEntries;
  2243. Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
  2244. }
  2245. void MicrosoftMangleContextImpl::mangleCXXCatchableType(
  2246. QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
  2247. uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
  2248. raw_ostream &Out) {
  2249. MicrosoftCXXNameMangler Mangler(*this, Out);
  2250. Mangler.getStream() << "_CT";
  2251. llvm::SmallString<64> RTTIMangling;
  2252. {
  2253. llvm::raw_svector_ostream Stream(RTTIMangling);
  2254. mangleCXXRTTI(T, Stream);
  2255. }
  2256. Mangler.getStream() << RTTIMangling.substr(1);
  2257. // VS2015 CTP6 omits the copy-constructor in the mangled name. This name is,
  2258. // in fact, superfluous but I'm not sure the change was made consciously.
  2259. // TODO: Revisit this when VS2015 gets released.
  2260. llvm::SmallString<64> CopyCtorMangling;
  2261. if (CD) {
  2262. llvm::raw_svector_ostream Stream(CopyCtorMangling);
  2263. mangleCXXCtor(CD, CT, Stream);
  2264. }
  2265. Mangler.getStream() << CopyCtorMangling.substr(1);
  2266. Mangler.getStream() << Size;
  2267. if (VBPtrOffset == -1) {
  2268. if (NVOffset) {
  2269. Mangler.getStream() << NVOffset;
  2270. }
  2271. } else {
  2272. Mangler.getStream() << NVOffset;
  2273. Mangler.getStream() << VBPtrOffset;
  2274. Mangler.getStream() << VBIndex;
  2275. }
  2276. }
  2277. void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
  2278. const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
  2279. uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
  2280. MicrosoftCXXNameMangler Mangler(*this, Out);
  2281. Mangler.getStream() << "\01??_R1";
  2282. Mangler.mangleNumber(NVOffset);
  2283. Mangler.mangleNumber(VBPtrOffset);
  2284. Mangler.mangleNumber(VBTableOffset);
  2285. Mangler.mangleNumber(Flags);
  2286. Mangler.mangleName(Derived);
  2287. Mangler.getStream() << "8";
  2288. }
  2289. void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
  2290. const CXXRecordDecl *Derived, raw_ostream &Out) {
  2291. MicrosoftCXXNameMangler Mangler(*this, Out);
  2292. Mangler.getStream() << "\01??_R2";
  2293. Mangler.mangleName(Derived);
  2294. Mangler.getStream() << "8";
  2295. }
  2296. void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
  2297. const CXXRecordDecl *Derived, raw_ostream &Out) {
  2298. MicrosoftCXXNameMangler Mangler(*this, Out);
  2299. Mangler.getStream() << "\01??_R3";
  2300. Mangler.mangleName(Derived);
  2301. Mangler.getStream() << "8";
  2302. }
  2303. void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
  2304. const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
  2305. raw_ostream &Out) {
  2306. // <mangled-name> ::= ?_R4 <class-name> <storage-class>
  2307. // <cvr-qualifiers> [<name>] @
  2308. // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
  2309. // is always '6' for vftables.
  2310. MicrosoftCXXNameMangler Mangler(*this, Out);
  2311. Mangler.getStream() << "\01??_R4";
  2312. Mangler.mangleName(Derived);
  2313. Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
  2314. for (const CXXRecordDecl *RD : BasePath)
  2315. Mangler.mangleName(RD);
  2316. Mangler.getStream() << '@';
  2317. }
  2318. void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
  2319. const NamedDecl *EnclosingDecl, raw_ostream &Out) {
  2320. MicrosoftCXXNameMangler Mangler(*this, Out);
  2321. // The function body is in the same comdat as the function with the handler,
  2322. // so the numbering here doesn't have to be the same across TUs.
  2323. //
  2324. // <mangled-name> ::= ?filt$ <filter-number> @0
  2325. Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
  2326. Mangler.mangleName(EnclosingDecl);
  2327. }
  2328. void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
  2329. const NamedDecl *EnclosingDecl, raw_ostream &Out) {
  2330. MicrosoftCXXNameMangler Mangler(*this, Out);
  2331. // The function body is in the same comdat as the function with the handler,
  2332. // so the numbering here doesn't have to be the same across TUs.
  2333. //
  2334. // <mangled-name> ::= ?fin$ <filter-number> @0
  2335. Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
  2336. Mangler.mangleName(EnclosingDecl);
  2337. }
  2338. void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
  2339. // This is just a made up unique string for the purposes of tbaa. undname
  2340. // does *not* know how to demangle it.
  2341. MicrosoftCXXNameMangler Mangler(*this, Out);
  2342. Mangler.getStream() << '?';
  2343. Mangler.mangleType(T, SourceRange());
  2344. }
  2345. void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
  2346. CXXCtorType Type,
  2347. raw_ostream &Out) {
  2348. MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
  2349. mangler.mangle(D);
  2350. }
  2351. void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
  2352. CXXDtorType Type,
  2353. raw_ostream &Out) {
  2354. MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
  2355. mangler.mangle(D);
  2356. }
  2357. void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
  2358. unsigned,
  2359. raw_ostream &) {
  2360. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  2361. "cannot mangle this reference temporary yet");
  2362. getDiags().Report(VD->getLocation(), DiagID);
  2363. }
  2364. void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
  2365. const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
  2366. MicrosoftCXXNameMangler Mangler(*this, Out);
  2367. Mangler.getStream() << "\01?$TSS" << GuardNum << '@';
  2368. Mangler.mangleNestedName(VD);
  2369. }
  2370. void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
  2371. raw_ostream &Out) {
  2372. // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
  2373. // ::= ?__J <postfix> @5 <scope-depth>
  2374. // ::= ?$S <guard-num> @ <postfix> @4IA
  2375. // The first mangling is what MSVC uses to guard static locals in inline
  2376. // functions. It uses a different mangling in external functions to support
  2377. // guarding more than 32 variables. MSVC rejects inline functions with more
  2378. // than 32 static locals. We don't fully implement the second mangling
  2379. // because those guards are not externally visible, and instead use LLVM's
  2380. // default renaming when creating a new guard variable.
  2381. MicrosoftCXXNameMangler Mangler(*this, Out);
  2382. bool Visible = VD->isExternallyVisible();
  2383. if (Visible) {
  2384. Mangler.getStream() << (VD->getTLSKind() ? "\01??__J" : "\01??_B");
  2385. } else {
  2386. Mangler.getStream() << "\01?$S1@";
  2387. }
  2388. unsigned ScopeDepth = 0;
  2389. if (Visible && !getNextDiscriminator(VD, ScopeDepth))
  2390. // If we do not have a discriminator and are emitting a guard variable for
  2391. // use at global scope, then mangling the nested name will not be enough to
  2392. // remove ambiguities.
  2393. Mangler.mangle(VD, "");
  2394. else
  2395. Mangler.mangleNestedName(VD);
  2396. Mangler.getStream() << (Visible ? "@5" : "@4IA");
  2397. if (ScopeDepth)
  2398. Mangler.mangleNumber(ScopeDepth);
  2399. }
  2400. void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
  2401. raw_ostream &Out,
  2402. char CharCode) {
  2403. MicrosoftCXXNameMangler Mangler(*this, Out);
  2404. Mangler.getStream() << "\01??__" << CharCode;
  2405. Mangler.mangleName(D);
  2406. if (D->isStaticDataMember()) {
  2407. Mangler.mangleVariableEncoding(D);
  2408. Mangler.getStream() << '@';
  2409. }
  2410. // This is the function class mangling. These stubs are global, non-variadic,
  2411. // cdecl functions that return void and take no args.
  2412. Mangler.getStream() << "YAXXZ";
  2413. }
  2414. void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
  2415. raw_ostream &Out) {
  2416. // <initializer-name> ::= ?__E <name> YAXXZ
  2417. mangleInitFiniStub(D, Out, 'E');
  2418. }
  2419. void
  2420. MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
  2421. raw_ostream &Out) {
  2422. // <destructor-name> ::= ?__F <name> YAXXZ
  2423. mangleInitFiniStub(D, Out, 'F');
  2424. }
  2425. void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
  2426. raw_ostream &Out) {
  2427. // <char-type> ::= 0 # char
  2428. // ::= 1 # wchar_t
  2429. // ::= ??? # char16_t/char32_t will need a mangling too...
  2430. //
  2431. // <literal-length> ::= <non-negative integer> # the length of the literal
  2432. //
  2433. // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
  2434. // # null-terminator
  2435. //
  2436. // <encoded-string> ::= <simple character> # uninteresting character
  2437. // ::= '?$' <hex digit> <hex digit> # these two nibbles
  2438. // # encode the byte for the
  2439. // # character
  2440. // ::= '?' [a-z] # \xe1 - \xfa
  2441. // ::= '?' [A-Z] # \xc1 - \xda
  2442. // ::= '?' [0-9] # [,/\:. \n\t'-]
  2443. //
  2444. // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
  2445. // <encoded-string> '@'
  2446. MicrosoftCXXNameMangler Mangler(*this, Out);
  2447. Mangler.getStream() << "\01??_C@_";
  2448. // <char-type>: The "kind" of string literal is encoded into the mangled name.
  2449. if (SL->isWide())
  2450. Mangler.getStream() << '1';
  2451. else
  2452. Mangler.getStream() << '0';
  2453. // <literal-length>: The next part of the mangled name consists of the length
  2454. // of the string.
  2455. // The StringLiteral does not consider the NUL terminator byte(s) but the
  2456. // mangling does.
  2457. // N.B. The length is in terms of bytes, not characters.
  2458. Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
  2459. // We will use the "Rocksoft^tm Model CRC Algorithm" to describe the
  2460. // properties of our CRC:
  2461. // Width : 32
  2462. // Poly : 04C11DB7
  2463. // Init : FFFFFFFF
  2464. // RefIn : True
  2465. // RefOut : True
  2466. // XorOut : 00000000
  2467. // Check : 340BC6D9
  2468. uint32_t CRC = 0xFFFFFFFFU;
  2469. auto UpdateCRC = [&CRC](char Byte) {
  2470. for (unsigned i = 0; i < 8; ++i) {
  2471. bool Bit = CRC & 0x80000000U;
  2472. if (Byte & (1U << i))
  2473. Bit = !Bit;
  2474. CRC <<= 1;
  2475. if (Bit)
  2476. CRC ^= 0x04C11DB7U;
  2477. }
  2478. };
  2479. auto GetLittleEndianByte = [&SL](unsigned Index) {
  2480. unsigned CharByteWidth = SL->getCharByteWidth();
  2481. uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
  2482. unsigned OffsetInCodeUnit = Index % CharByteWidth;
  2483. return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
  2484. };
  2485. auto GetBigEndianByte = [&SL](unsigned Index) {
  2486. unsigned CharByteWidth = SL->getCharByteWidth();
  2487. uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
  2488. unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
  2489. return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
  2490. };
  2491. // CRC all the bytes of the StringLiteral.
  2492. for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
  2493. UpdateCRC(GetLittleEndianByte(I));
  2494. // The NUL terminator byte(s) were not present earlier,
  2495. // we need to manually process those bytes into the CRC.
  2496. for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
  2497. ++NullTerminator)
  2498. UpdateCRC('\x00');
  2499. // The literature refers to the process of reversing the bits in the final CRC
  2500. // output as "reflection".
  2501. CRC = llvm::reverseBits(CRC);
  2502. // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
  2503. // scheme.
  2504. Mangler.mangleNumber(CRC);
  2505. // <encoded-string>: The mangled name also contains the first 32 _characters_
  2506. // (including null-terminator bytes) of the StringLiteral.
  2507. // Each character is encoded by splitting them into bytes and then encoding
  2508. // the constituent bytes.
  2509. auto MangleByte = [&Mangler](char Byte) {
  2510. // There are five different manglings for characters:
  2511. // - [a-zA-Z0-9_$]: A one-to-one mapping.
  2512. // - ?[a-z]: The range from \xe1 to \xfa.
  2513. // - ?[A-Z]: The range from \xc1 to \xda.
  2514. // - ?[0-9]: The set of [,/\:. \n\t'-].
  2515. // - ?$XX: A fallback which maps nibbles.
  2516. if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
  2517. Mangler.getStream() << Byte;
  2518. } else if (isLetter(Byte & 0x7f)) {
  2519. Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
  2520. } else {
  2521. const char SpecialChars[] = {',', '/', '\\', ':', '.',
  2522. ' ', '\n', '\t', '\'', '-'};
  2523. const char *Pos =
  2524. std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
  2525. if (Pos != std::end(SpecialChars)) {
  2526. Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
  2527. } else {
  2528. Mangler.getStream() << "?$";
  2529. Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
  2530. Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
  2531. }
  2532. }
  2533. };
  2534. // Enforce our 32 character max.
  2535. unsigned NumCharsToMangle = std::min(32U, SL->getLength());
  2536. for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
  2537. ++I)
  2538. if (SL->isWide())
  2539. MangleByte(GetBigEndianByte(I));
  2540. else
  2541. MangleByte(GetLittleEndianByte(I));
  2542. // Encode the NUL terminator if there is room.
  2543. if (NumCharsToMangle < 32)
  2544. for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
  2545. ++NullTerminator)
  2546. MangleByte(0);
  2547. Mangler.getStream() << '@';
  2548. }
  2549. void MicrosoftMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
  2550. raw_ostream &Out) {
  2551. if (!RD->isExternallyVisible()) {
  2552. // This part of the identifier needs to be unique across all translation
  2553. // units in the linked program. The scheme fails if multiple translation
  2554. // units are compiled using the same relative source file path, or if
  2555. // multiple translation units are built from the same source file.
  2556. SourceManager &SM = getASTContext().getSourceManager();
  2557. Out << "[" << SM.getFileEntryForID(SM.getMainFileID())->getName() << "]";
  2558. }
  2559. MicrosoftCXXNameMangler mangler(*this, Out);
  2560. mangler.mangleName(RD);
  2561. }
  2562. MicrosoftMangleContext *
  2563. MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
  2564. return new MicrosoftMangleContextImpl(Context, Diags);
  2565. }