ItaniumMangle.cpp 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139
  1. //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
  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. // Implements C++ name mangling according to the Itanium C++ ABI,
  11. // which is used in GCC 3.2 and newer (and many compilers that are
  12. // ABI-compatible with GCC):
  13. //
  14. // http://mentorembedded.github.io/cxx-abi/abi.html#mangling
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "clang/AST/Mangle.h"
  18. #include "clang/AST/ASTContext.h"
  19. #include "clang/AST/Attr.h"
  20. #include "clang/AST/Decl.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/Expr.h"
  25. #include "clang/AST/ExprCXX.h"
  26. #include "clang/AST/ExprObjC.h"
  27. #include "clang/AST/TypeLoc.h"
  28. #include "clang/Basic/ABI.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "llvm/ADT/StringExtras.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. // //
  35. ///////////////////////////////////////////////////////////////////////////////
  36. #define MANGLE_CHECKER 0
  37. #if MANGLE_CHECKER
  38. #include <cxxabi.h>
  39. #endif
  40. using namespace clang;
  41. namespace {
  42. /// Retrieve the declaration context that should be used when mangling the given
  43. /// declaration.
  44. static const DeclContext *getEffectiveDeclContext(const Decl *D) {
  45. // The ABI assumes that lambda closure types that occur within
  46. // default arguments live in the context of the function. However, due to
  47. // the way in which Clang parses and creates function declarations, this is
  48. // not the case: the lambda closure type ends up living in the context
  49. // where the function itself resides, because the function declaration itself
  50. // had not yet been created. Fix the context here.
  51. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  52. if (RD->isLambda())
  53. if (ParmVarDecl *ContextParam
  54. = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
  55. return ContextParam->getDeclContext();
  56. }
  57. // Perform the same check for block literals.
  58. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  59. if (ParmVarDecl *ContextParam
  60. = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
  61. return ContextParam->getDeclContext();
  62. }
  63. const DeclContext *DC = D->getDeclContext();
  64. if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
  65. return getEffectiveDeclContext(CD);
  66. if (const auto *VD = dyn_cast<VarDecl>(D))
  67. if (VD->isExternC())
  68. return VD->getASTContext().getTranslationUnitDecl();
  69. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  70. if (FD->isExternC())
  71. return FD->getASTContext().getTranslationUnitDecl();
  72. return DC;
  73. }
  74. static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
  75. return getEffectiveDeclContext(cast<Decl>(DC));
  76. }
  77. static bool isLocalContainerContext(const DeclContext *DC) {
  78. return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
  79. }
  80. static const RecordDecl *GetLocalClassDecl(const Decl *D) {
  81. const DeclContext *DC = getEffectiveDeclContext(D);
  82. while (!DC->isNamespace() && !DC->isTranslationUnit()) {
  83. if (isLocalContainerContext(DC))
  84. return dyn_cast<RecordDecl>(D);
  85. D = cast<Decl>(DC);
  86. DC = getEffectiveDeclContext(D);
  87. }
  88. return nullptr;
  89. }
  90. static const FunctionDecl *getStructor(const FunctionDecl *fn) {
  91. if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
  92. return ftd->getTemplatedDecl();
  93. return fn;
  94. }
  95. static const NamedDecl *getStructor(const NamedDecl *decl) {
  96. const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
  97. return (fn ? getStructor(fn) : decl);
  98. }
  99. static bool isLambda(const NamedDecl *ND) {
  100. const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
  101. if (!Record)
  102. return false;
  103. return Record->isLambda();
  104. }
  105. static const unsigned UnknownArity = ~0U;
  106. class ItaniumMangleContextImpl : public ItaniumMangleContext {
  107. typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
  108. llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
  109. llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
  110. public:
  111. explicit ItaniumMangleContextImpl(ASTContext &Context,
  112. DiagnosticsEngine &Diags)
  113. : ItaniumMangleContext(Context, Diags) {}
  114. /// @name Mangler Entry Points
  115. /// @{
  116. bool shouldMangleCXXName(const NamedDecl *D) override;
  117. bool shouldMangleStringLiteral(const StringLiteral *) override {
  118. return false;
  119. }
  120. void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
  121. void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
  122. raw_ostream &) override;
  123. void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
  124. const ThisAdjustment &ThisAdjustment,
  125. raw_ostream &) override;
  126. void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
  127. raw_ostream &) override;
  128. void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
  129. void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
  130. void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
  131. const CXXRecordDecl *Type, raw_ostream &) override;
  132. void mangleCXXRTTI(QualType T, raw_ostream &) override;
  133. void mangleCXXRTTIName(QualType T, raw_ostream &) override;
  134. void mangleTypeName(QualType T, raw_ostream &) override;
  135. void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
  136. raw_ostream &) override;
  137. void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
  138. raw_ostream &) override;
  139. void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
  140. void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
  141. void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
  142. void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
  143. void mangleDynamicAtExitDestructor(const VarDecl *D,
  144. raw_ostream &Out) override;
  145. void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
  146. raw_ostream &Out) override;
  147. void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
  148. raw_ostream &Out) override;
  149. void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
  150. void mangleItaniumThreadLocalWrapper(const VarDecl *D,
  151. raw_ostream &) override;
  152. void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
  153. void mangleCXXVTableBitSet(const CXXRecordDecl *RD, raw_ostream &) override;
  154. bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
  155. // Lambda closure types are already numbered.
  156. if (isLambda(ND))
  157. return false;
  158. // Anonymous tags are already numbered.
  159. if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
  160. if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
  161. return false;
  162. }
  163. // Use the canonical number for externally visible decls.
  164. if (ND->isExternallyVisible()) {
  165. unsigned discriminator = getASTContext().getManglingNumber(ND);
  166. if (discriminator == 1)
  167. return false;
  168. disc = discriminator - 2;
  169. return true;
  170. }
  171. // Make up a reasonable number for internal decls.
  172. unsigned &discriminator = Uniquifier[ND];
  173. if (!discriminator) {
  174. const DeclContext *DC = getEffectiveDeclContext(ND);
  175. discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
  176. }
  177. if (discriminator == 1)
  178. return false;
  179. disc = discriminator-2;
  180. return true;
  181. }
  182. /// @}
  183. };
  184. /// Manage the mangling of a single name.
  185. class CXXNameMangler {
  186. ItaniumMangleContextImpl &Context;
  187. raw_ostream &Out;
  188. /// The "structor" is the top-level declaration being mangled, if
  189. /// that's not a template specialization; otherwise it's the pattern
  190. /// for that specialization.
  191. const NamedDecl *Structor;
  192. unsigned StructorType;
  193. /// The next substitution sequence number.
  194. unsigned SeqID;
  195. class FunctionTypeDepthState {
  196. unsigned Bits;
  197. enum { InResultTypeMask = 1 };
  198. public:
  199. FunctionTypeDepthState() : Bits(0) {}
  200. /// The number of function types we're inside.
  201. unsigned getDepth() const {
  202. return Bits >> 1;
  203. }
  204. /// True if we're in the return type of the innermost function type.
  205. bool isInResultType() const {
  206. return Bits & InResultTypeMask;
  207. }
  208. FunctionTypeDepthState push() {
  209. FunctionTypeDepthState tmp = *this;
  210. Bits = (Bits & ~InResultTypeMask) + 2;
  211. return tmp;
  212. }
  213. void enterResultType() {
  214. Bits |= InResultTypeMask;
  215. }
  216. void leaveResultType() {
  217. Bits &= ~InResultTypeMask;
  218. }
  219. void pop(FunctionTypeDepthState saved) {
  220. assert(getDepth() == saved.getDepth() + 1);
  221. Bits = saved.Bits;
  222. }
  223. } FunctionTypeDepth;
  224. llvm::DenseMap<uintptr_t, unsigned> Substitutions;
  225. ASTContext &getASTContext() const { return Context.getASTContext(); }
  226. public:
  227. CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
  228. const NamedDecl *D = nullptr)
  229. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
  230. SeqID(0) {
  231. // These can't be mangled without a ctor type or dtor type.
  232. assert(!D || (!isa<CXXDestructorDecl>(D) &&
  233. !isa<CXXConstructorDecl>(D)));
  234. }
  235. CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
  236. const CXXConstructorDecl *D, CXXCtorType Type)
  237. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  238. SeqID(0) { }
  239. CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
  240. const CXXDestructorDecl *D, CXXDtorType Type)
  241. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  242. SeqID(0) { }
  243. #if MANGLE_CHECKER
  244. ~CXXNameMangler() {
  245. if (Out.str()[0] == '\01')
  246. return;
  247. int status = 0;
  248. char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
  249. assert(status == 0 && "Could not demangle mangled name!");
  250. free(result);
  251. }
  252. #endif
  253. raw_ostream &getStream() { return Out; }
  254. void mangle(const NamedDecl *D);
  255. void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
  256. void mangleNumber(const llvm::APSInt &I);
  257. void mangleNumber(int64_t Number);
  258. void mangleFloat(const llvm::APFloat &F);
  259. void mangleFunctionEncoding(const FunctionDecl *FD);
  260. void mangleSeqID(unsigned SeqID);
  261. void mangleName(const NamedDecl *ND);
  262. void mangleType(QualType T);
  263. void mangleNameOrStandardSubstitution(const NamedDecl *ND);
  264. private:
  265. bool mangleSubstitution(const NamedDecl *ND);
  266. bool mangleSubstitution(QualType T);
  267. bool mangleSubstitution(TemplateName Template);
  268. bool mangleSubstitution(uintptr_t Ptr);
  269. void mangleExistingSubstitution(QualType type);
  270. void mangleExistingSubstitution(TemplateName name);
  271. bool mangleStandardSubstitution(const NamedDecl *ND);
  272. void addSubstitution(const NamedDecl *ND) {
  273. ND = cast<NamedDecl>(ND->getCanonicalDecl());
  274. addSubstitution(reinterpret_cast<uintptr_t>(ND));
  275. }
  276. void addSubstitution(QualType T);
  277. void addSubstitution(TemplateName Template);
  278. void addSubstitution(uintptr_t Ptr);
  279. void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
  280. bool recursive = false);
  281. void mangleUnresolvedName(NestedNameSpecifier *qualifier,
  282. DeclarationName name,
  283. unsigned KnownArity = UnknownArity);
  284. void mangleName(const TemplateDecl *TD,
  285. const TemplateArgument *TemplateArgs,
  286. unsigned NumTemplateArgs);
  287. void mangleUnqualifiedName(const NamedDecl *ND) {
  288. mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
  289. }
  290. void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
  291. unsigned KnownArity);
  292. void mangleUnscopedName(const NamedDecl *ND);
  293. void mangleUnscopedTemplateName(const TemplateDecl *ND);
  294. void mangleUnscopedTemplateName(TemplateName);
  295. void mangleSourceName(const IdentifierInfo *II);
  296. void mangleLocalName(const Decl *D);
  297. void mangleBlockForPrefix(const BlockDecl *Block);
  298. void mangleUnqualifiedBlock(const BlockDecl *Block);
  299. void mangleLambda(const CXXRecordDecl *Lambda);
  300. void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
  301. bool NoFunction=false);
  302. void mangleNestedName(const TemplateDecl *TD,
  303. const TemplateArgument *TemplateArgs,
  304. unsigned NumTemplateArgs);
  305. void manglePrefix(NestedNameSpecifier *qualifier);
  306. void manglePrefix(const DeclContext *DC, bool NoFunction=false);
  307. void manglePrefix(QualType type);
  308. void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
  309. void mangleTemplatePrefix(TemplateName Template);
  310. bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
  311. StringRef Prefix = "");
  312. void mangleOperatorName(DeclarationName Name, unsigned Arity);
  313. void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
  314. void mangleQualifiers(Qualifiers Quals);
  315. void mangleRefQualifier(RefQualifierKind RefQualifier);
  316. void mangleObjCMethodName(const ObjCMethodDecl *MD);
  317. // Declare manglers for every type class.
  318. #define ABSTRACT_TYPE(CLASS, PARENT)
  319. #define NON_CANONICAL_TYPE(CLASS, PARENT)
  320. #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
  321. #include "clang/AST/TypeNodes.def"
  322. void mangleType(const TagType*);
  323. void mangleType(TemplateName);
  324. void mangleBareFunctionType(const FunctionType *T,
  325. bool MangleReturnType);
  326. void mangleNeonVectorType(const VectorType *T);
  327. void mangleAArch64NeonVectorType(const VectorType *T);
  328. void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
  329. void mangleMemberExprBase(const Expr *base, bool isArrow);
  330. void mangleMemberExpr(const Expr *base, bool isArrow,
  331. NestedNameSpecifier *qualifier,
  332. NamedDecl *firstQualifierLookup,
  333. DeclarationName name,
  334. unsigned knownArity);
  335. void mangleCastExpression(const Expr *E, StringRef CastEncoding);
  336. void mangleInitListElements(const InitListExpr *InitList);
  337. void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
  338. void mangleCXXCtorType(CXXCtorType T);
  339. void mangleCXXDtorType(CXXDtorType T);
  340. void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
  341. void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
  342. unsigned NumTemplateArgs);
  343. void mangleTemplateArgs(const TemplateArgumentList &AL);
  344. void mangleTemplateArg(TemplateArgument A);
  345. void mangleTemplateParameter(unsigned Index);
  346. void mangleFunctionParam(const ParmVarDecl *parm);
  347. };
  348. }
  349. bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
  350. const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  351. if (FD) {
  352. LanguageLinkage L = FD->getLanguageLinkage();
  353. // Overloadable functions need mangling.
  354. if (FD->hasAttr<OverloadableAttr>())
  355. return true;
  356. // "main" is not mangled.
  357. if (FD->isMain())
  358. return false;
  359. // C++ functions and those whose names are not a simple identifier need
  360. // mangling.
  361. if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
  362. return true;
  363. // C functions are not mangled.
  364. if (L == CLanguageLinkage)
  365. return false;
  366. }
  367. // Otherwise, no mangling is done outside C++ mode.
  368. if (!getASTContext().getLangOpts().CPlusPlus)
  369. return false;
  370. const VarDecl *VD = dyn_cast<VarDecl>(D);
  371. if (VD) {
  372. // C variables are not mangled.
  373. if (VD->isExternC())
  374. return false;
  375. // Variables at global scope with non-internal linkage are not mangled
  376. const DeclContext *DC = getEffectiveDeclContext(D);
  377. // Check for extern variable declared locally.
  378. if (DC->isFunctionOrMethod() && D->hasLinkage())
  379. while (!DC->isNamespace() && !DC->isTranslationUnit())
  380. DC = getEffectiveParentContext(DC);
  381. if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
  382. !isa<VarTemplateSpecializationDecl>(D))
  383. return false;
  384. }
  385. return true;
  386. }
  387. void CXXNameMangler::mangle(const NamedDecl *D) {
  388. // <mangled-name> ::= _Z <encoding>
  389. // ::= <data name>
  390. // ::= <special-name>
  391. Out << "_Z";
  392. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  393. mangleFunctionEncoding(FD);
  394. else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  395. mangleName(VD);
  396. else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  397. mangleName(IFD->getAnonField());
  398. else
  399. mangleName(cast<FieldDecl>(D));
  400. }
  401. void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
  402. // <encoding> ::= <function name> <bare-function-type>
  403. mangleName(FD);
  404. // Don't mangle in the type if this isn't a decl we should typically mangle.
  405. if (!Context.shouldMangleDeclName(FD))
  406. return;
  407. if (FD->hasAttr<EnableIfAttr>()) {
  408. FunctionTypeDepthState Saved = FunctionTypeDepth.push();
  409. Out << "Ua9enable_ifI";
  410. // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
  411. // it here.
  412. for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
  413. E = FD->getAttrs().rend();
  414. I != E; ++I) {
  415. EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
  416. if (!EIA)
  417. continue;
  418. Out << 'X';
  419. mangleExpression(EIA->getCond());
  420. Out << 'E';
  421. }
  422. Out << 'E';
  423. FunctionTypeDepth.pop(Saved);
  424. }
  425. // Whether the mangling of a function type includes the return type depends on
  426. // the context and the nature of the function. The rules for deciding whether
  427. // the return type is included are:
  428. //
  429. // 1. Template functions (names or types) have return types encoded, with
  430. // the exceptions listed below.
  431. // 2. Function types not appearing as part of a function name mangling,
  432. // e.g. parameters, pointer types, etc., have return type encoded, with the
  433. // exceptions listed below.
  434. // 3. Non-template function names do not have return types encoded.
  435. //
  436. // The exceptions mentioned in (1) and (2) above, for which the return type is
  437. // never included, are
  438. // 1. Constructors.
  439. // 2. Destructors.
  440. // 3. Conversion operator functions, e.g. operator int.
  441. bool MangleReturnType = false;
  442. if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
  443. if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
  444. isa<CXXConversionDecl>(FD)))
  445. MangleReturnType = true;
  446. // Mangle the type of the primary template.
  447. FD = PrimaryTemplate->getTemplatedDecl();
  448. }
  449. mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
  450. MangleReturnType);
  451. }
  452. static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
  453. while (isa<LinkageSpecDecl>(DC)) {
  454. DC = getEffectiveParentContext(DC);
  455. }
  456. return DC;
  457. }
  458. /// Return whether a given namespace is the 'std' namespace.
  459. static bool isStd(const NamespaceDecl *NS) {
  460. if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
  461. ->isTranslationUnit())
  462. return false;
  463. const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
  464. return II && II->isStr("std");
  465. }
  466. // isStdNamespace - Return whether a given decl context is a toplevel 'std'
  467. // namespace.
  468. static bool isStdNamespace(const DeclContext *DC) {
  469. if (!DC->isNamespace())
  470. return false;
  471. return isStd(cast<NamespaceDecl>(DC));
  472. }
  473. static const TemplateDecl *
  474. isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
  475. // Check if we have a function template.
  476. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
  477. if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
  478. TemplateArgs = FD->getTemplateSpecializationArgs();
  479. return TD;
  480. }
  481. }
  482. // Check if we have a class template.
  483. if (const ClassTemplateSpecializationDecl *Spec =
  484. dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  485. TemplateArgs = &Spec->getTemplateArgs();
  486. return Spec->getSpecializedTemplate();
  487. }
  488. // Check if we have a variable template.
  489. if (const VarTemplateSpecializationDecl *Spec =
  490. dyn_cast<VarTemplateSpecializationDecl>(ND)) {
  491. TemplateArgs = &Spec->getTemplateArgs();
  492. return Spec->getSpecializedTemplate();
  493. }
  494. return nullptr;
  495. }
  496. void CXXNameMangler::mangleName(const NamedDecl *ND) {
  497. // <name> ::= <nested-name>
  498. // ::= <unscoped-name>
  499. // ::= <unscoped-template-name> <template-args>
  500. // ::= <local-name>
  501. //
  502. const DeclContext *DC = getEffectiveDeclContext(ND);
  503. // If this is an extern variable declared locally, the relevant DeclContext
  504. // is that of the containing namespace, or the translation unit.
  505. // FIXME: This is a hack; extern variables declared locally should have
  506. // a proper semantic declaration context!
  507. if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
  508. while (!DC->isNamespace() && !DC->isTranslationUnit())
  509. DC = getEffectiveParentContext(DC);
  510. else if (GetLocalClassDecl(ND)) {
  511. mangleLocalName(ND);
  512. return;
  513. }
  514. DC = IgnoreLinkageSpecDecls(DC);
  515. if (DC->isTranslationUnit() || isStdNamespace(DC)) {
  516. // Check if we have a template.
  517. const TemplateArgumentList *TemplateArgs = nullptr;
  518. if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
  519. mangleUnscopedTemplateName(TD);
  520. mangleTemplateArgs(*TemplateArgs);
  521. return;
  522. }
  523. mangleUnscopedName(ND);
  524. return;
  525. }
  526. if (isLocalContainerContext(DC)) {
  527. mangleLocalName(ND);
  528. return;
  529. }
  530. mangleNestedName(ND, DC);
  531. }
  532. void CXXNameMangler::mangleName(const TemplateDecl *TD,
  533. const TemplateArgument *TemplateArgs,
  534. unsigned NumTemplateArgs) {
  535. const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
  536. if (DC->isTranslationUnit() || isStdNamespace(DC)) {
  537. mangleUnscopedTemplateName(TD);
  538. mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
  539. } else {
  540. mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
  541. }
  542. }
  543. void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
  544. // <unscoped-name> ::= <unqualified-name>
  545. // ::= St <unqualified-name> # ::std::
  546. if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
  547. Out << "St";
  548. mangleUnqualifiedName(ND);
  549. }
  550. void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
  551. // <unscoped-template-name> ::= <unscoped-name>
  552. // ::= <substitution>
  553. if (mangleSubstitution(ND))
  554. return;
  555. // <template-template-param> ::= <template-param>
  556. if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
  557. mangleTemplateParameter(TTP->getIndex());
  558. else
  559. mangleUnscopedName(ND->getTemplatedDecl());
  560. addSubstitution(ND);
  561. }
  562. void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
  563. // <unscoped-template-name> ::= <unscoped-name>
  564. // ::= <substitution>
  565. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  566. return mangleUnscopedTemplateName(TD);
  567. if (mangleSubstitution(Template))
  568. return;
  569. DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
  570. assert(Dependent && "Not a dependent template name?");
  571. if (const IdentifierInfo *Id = Dependent->getIdentifier())
  572. mangleSourceName(Id);
  573. else
  574. mangleOperatorName(Dependent->getOperator(), UnknownArity);
  575. addSubstitution(Template);
  576. }
  577. void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
  578. // ABI:
  579. // Floating-point literals are encoded using a fixed-length
  580. // lowercase hexadecimal string corresponding to the internal
  581. // representation (IEEE on Itanium), high-order bytes first,
  582. // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
  583. // on Itanium.
  584. // The 'without leading zeroes' thing seems to be an editorial
  585. // mistake; see the discussion on cxx-abi-dev beginning on
  586. // 2012-01-16.
  587. // Our requirements here are just barely weird enough to justify
  588. // using a custom algorithm instead of post-processing APInt::toString().
  589. llvm::APInt valueBits = f.bitcastToAPInt();
  590. unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
  591. assert(numCharacters != 0);
  592. // Allocate a buffer of the right number of characters.
  593. SmallVector<char, 20> buffer;
  594. buffer.set_size(numCharacters);
  595. // Fill the buffer left-to-right.
  596. for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
  597. // The bit-index of the next hex digit.
  598. unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
  599. // Project out 4 bits starting at 'digitIndex'.
  600. llvm::integerPart hexDigit
  601. = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
  602. hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
  603. hexDigit &= 0xF;
  604. // Map that over to a lowercase hex digit.
  605. static const char charForHex[16] = {
  606. '0', '1', '2', '3', '4', '5', '6', '7',
  607. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  608. };
  609. buffer[stringIndex] = charForHex[hexDigit];
  610. }
  611. Out.write(buffer.data(), numCharacters);
  612. }
  613. void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
  614. if (Value.isSigned() && Value.isNegative()) {
  615. Out << 'n';
  616. Value.abs().print(Out, /*signed*/ false);
  617. } else {
  618. Value.print(Out, /*signed*/ false);
  619. }
  620. }
  621. void CXXNameMangler::mangleNumber(int64_t Number) {
  622. // <number> ::= [n] <non-negative decimal integer>
  623. if (Number < 0) {
  624. Out << 'n';
  625. Number = -Number;
  626. }
  627. Out << Number;
  628. }
  629. void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
  630. // <call-offset> ::= h <nv-offset> _
  631. // ::= v <v-offset> _
  632. // <nv-offset> ::= <offset number> # non-virtual base override
  633. // <v-offset> ::= <offset number> _ <virtual offset number>
  634. // # virtual base override, with vcall offset
  635. if (!Virtual) {
  636. Out << 'h';
  637. mangleNumber(NonVirtual);
  638. Out << '_';
  639. return;
  640. }
  641. Out << 'v';
  642. mangleNumber(NonVirtual);
  643. Out << '_';
  644. mangleNumber(Virtual);
  645. Out << '_';
  646. }
  647. void CXXNameMangler::manglePrefix(QualType type) {
  648. if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
  649. if (!mangleSubstitution(QualType(TST, 0))) {
  650. mangleTemplatePrefix(TST->getTemplateName());
  651. // FIXME: GCC does not appear to mangle the template arguments when
  652. // the template in question is a dependent template name. Should we
  653. // emulate that badness?
  654. mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
  655. addSubstitution(QualType(TST, 0));
  656. }
  657. } else if (const auto *DTST =
  658. type->getAs<DependentTemplateSpecializationType>()) {
  659. if (!mangleSubstitution(QualType(DTST, 0))) {
  660. TemplateName Template = getASTContext().getDependentTemplateName(
  661. DTST->getQualifier(), DTST->getIdentifier());
  662. mangleTemplatePrefix(Template);
  663. // FIXME: GCC does not appear to mangle the template arguments when
  664. // the template in question is a dependent template name. Should we
  665. // emulate that badness?
  666. mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
  667. addSubstitution(QualType(DTST, 0));
  668. }
  669. } else {
  670. // We use the QualType mangle type variant here because it handles
  671. // substitutions.
  672. mangleType(type);
  673. }
  674. }
  675. /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
  676. ///
  677. /// \param recursive - true if this is being called recursively,
  678. /// i.e. if there is more prefix "to the right".
  679. void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
  680. bool recursive) {
  681. // x, ::x
  682. // <unresolved-name> ::= [gs] <base-unresolved-name>
  683. // T::x / decltype(p)::x
  684. // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
  685. // T::N::x /decltype(p)::N::x
  686. // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
  687. // <base-unresolved-name>
  688. // A::x, N::y, A<T>::z; "gs" means leading "::"
  689. // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
  690. // <base-unresolved-name>
  691. switch (qualifier->getKind()) {
  692. case NestedNameSpecifier::Global:
  693. Out << "gs";
  694. // We want an 'sr' unless this is the entire NNS.
  695. if (recursive)
  696. Out << "sr";
  697. // We never want an 'E' here.
  698. return;
  699. case NestedNameSpecifier::Super:
  700. llvm_unreachable("Can't mangle __super specifier");
  701. case NestedNameSpecifier::Namespace:
  702. if (qualifier->getPrefix())
  703. mangleUnresolvedPrefix(qualifier->getPrefix(),
  704. /*recursive*/ true);
  705. else
  706. Out << "sr";
  707. mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
  708. break;
  709. case NestedNameSpecifier::NamespaceAlias:
  710. if (qualifier->getPrefix())
  711. mangleUnresolvedPrefix(qualifier->getPrefix(),
  712. /*recursive*/ true);
  713. else
  714. Out << "sr";
  715. mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
  716. break;
  717. case NestedNameSpecifier::TypeSpec:
  718. case NestedNameSpecifier::TypeSpecWithTemplate: {
  719. const Type *type = qualifier->getAsType();
  720. // We only want to use an unresolved-type encoding if this is one of:
  721. // - a decltype
  722. // - a template type parameter
  723. // - a template template parameter with arguments
  724. // In all of these cases, we should have no prefix.
  725. if (qualifier->getPrefix()) {
  726. mangleUnresolvedPrefix(qualifier->getPrefix(),
  727. /*recursive*/ true);
  728. } else {
  729. // Otherwise, all the cases want this.
  730. Out << "sr";
  731. }
  732. if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
  733. return;
  734. break;
  735. }
  736. case NestedNameSpecifier::Identifier:
  737. // Member expressions can have these without prefixes.
  738. if (qualifier->getPrefix())
  739. mangleUnresolvedPrefix(qualifier->getPrefix(),
  740. /*recursive*/ true);
  741. else
  742. Out << "sr";
  743. mangleSourceName(qualifier->getAsIdentifier());
  744. break;
  745. }
  746. // If this was the innermost part of the NNS, and we fell out to
  747. // here, append an 'E'.
  748. if (!recursive)
  749. Out << 'E';
  750. }
  751. /// Mangle an unresolved-name, which is generally used for names which
  752. /// weren't resolved to specific entities.
  753. void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
  754. DeclarationName name,
  755. unsigned knownArity) {
  756. if (qualifier) mangleUnresolvedPrefix(qualifier);
  757. switch (name.getNameKind()) {
  758. // <base-unresolved-name> ::= <simple-id>
  759. case DeclarationName::Identifier:
  760. mangleSourceName(name.getAsIdentifierInfo());
  761. break;
  762. // <base-unresolved-name> ::= dn <destructor-name>
  763. case DeclarationName::CXXDestructorName:
  764. Out << "dn";
  765. mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
  766. break;
  767. // <base-unresolved-name> ::= on <operator-name>
  768. case DeclarationName::CXXConversionFunctionName:
  769. case DeclarationName::CXXLiteralOperatorName:
  770. case DeclarationName::CXXOperatorName:
  771. Out << "on";
  772. mangleOperatorName(name, knownArity);
  773. break;
  774. case DeclarationName::CXXConstructorName:
  775. llvm_unreachable("Can't mangle a constructor name!");
  776. case DeclarationName::CXXUsingDirective:
  777. llvm_unreachable("Can't mangle a using directive name!");
  778. case DeclarationName::ObjCMultiArgSelector:
  779. case DeclarationName::ObjCOneArgSelector:
  780. case DeclarationName::ObjCZeroArgSelector:
  781. llvm_unreachable("Can't mangle Objective-C selector names here!");
  782. }
  783. }
  784. void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
  785. DeclarationName Name,
  786. unsigned KnownArity) {
  787. unsigned Arity = KnownArity;
  788. // <unqualified-name> ::= <operator-name>
  789. // ::= <ctor-dtor-name>
  790. // ::= <source-name>
  791. switch (Name.getNameKind()) {
  792. case DeclarationName::Identifier: {
  793. if (Name.getAsIdentifierInfo()) {
  794. // We must avoid conflicts between internally- and externally-
  795. // linked variable and function declaration names in the same TU:
  796. // void test() { extern void foo(); }
  797. // static void foo();
  798. // This naming convention is the same as that followed by GCC,
  799. // though it shouldn't actually matter.
  800. if (ND && ND->getFormalLinkage() == InternalLinkage &&
  801. getEffectiveDeclContext(ND)->isFileContext())
  802. Out << 'L';
  803. // HLSL Change - use the 'name for IR' rather than II directly.
  804. StringRef r = ND->getNameForIR();
  805. Out << r.size() << r.data();
  806. break;
  807. }
  808. // Otherwise, an anonymous entity. We must have a declaration.
  809. assert(ND && "mangling empty name without declaration");
  810. if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
  811. if (NS->isAnonymousNamespace()) {
  812. // This is how gcc mangles these names.
  813. Out << "12_GLOBAL__N_1";
  814. break;
  815. }
  816. }
  817. if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
  818. // We must have an anonymous union or struct declaration.
  819. const RecordDecl *RD =
  820. cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
  821. // Itanium C++ ABI 5.1.2:
  822. //
  823. // For the purposes of mangling, the name of an anonymous union is
  824. // considered to be the name of the first named data member found by a
  825. // pre-order, depth-first, declaration-order walk of the data members of
  826. // the anonymous union. If there is no such data member (i.e., if all of
  827. // the data members in the union are unnamed), then there is no way for
  828. // a program to refer to the anonymous union, and there is therefore no
  829. // need to mangle its name.
  830. assert(RD->isAnonymousStructOrUnion()
  831. && "Expected anonymous struct or union!");
  832. const FieldDecl *FD = RD->findFirstNamedDataMember();
  833. // It's actually possible for various reasons for us to get here
  834. // with an empty anonymous struct / union. Fortunately, it
  835. // doesn't really matter what name we generate.
  836. if (!FD) break;
  837. assert(FD->getIdentifier() && "Data member name isn't an identifier!");
  838. mangleSourceName(FD->getIdentifier());
  839. break;
  840. }
  841. // Class extensions have no name as a category, and it's possible
  842. // for them to be the semantic parent of certain declarations
  843. // (primarily, tag decls defined within declarations). Such
  844. // declarations will always have internal linkage, so the name
  845. // doesn't really matter, but we shouldn't crash on them. For
  846. // safety, just handle all ObjC containers here.
  847. if (isa<ObjCContainerDecl>(ND))
  848. break;
  849. // We must have an anonymous struct.
  850. const TagDecl *TD = cast<TagDecl>(ND);
  851. if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
  852. assert(TD->getDeclContext() == D->getDeclContext() &&
  853. "Typedef should not be in another decl context!");
  854. assert(D->getDeclName().getAsIdentifierInfo() &&
  855. "Typedef was not named!");
  856. mangleSourceName(D->getDeclName().getAsIdentifierInfo());
  857. break;
  858. }
  859. // <unnamed-type-name> ::= <closure-type-name>
  860. //
  861. // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
  862. // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
  863. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
  864. if (Record->isLambda() && Record->getLambdaManglingNumber()) {
  865. mangleLambda(Record);
  866. break;
  867. }
  868. }
  869. if (TD->isExternallyVisible()) {
  870. unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
  871. Out << "Ut";
  872. if (UnnamedMangle > 1)
  873. Out << llvm::utostr(UnnamedMangle - 2);
  874. Out << '_';
  875. break;
  876. }
  877. // Get a unique id for the anonymous struct.
  878. unsigned AnonStructId = Context.getAnonymousStructId(TD);
  879. // Mangle it as a source name in the form
  880. // [n] $_<id>
  881. // where n is the length of the string.
  882. SmallString<8> Str;
  883. Str += "$_";
  884. Str += llvm::utostr(AnonStructId);
  885. Out << Str.size();
  886. Out << Str;
  887. break;
  888. }
  889. case DeclarationName::ObjCZeroArgSelector:
  890. case DeclarationName::ObjCOneArgSelector:
  891. case DeclarationName::ObjCMultiArgSelector:
  892. llvm_unreachable("Can't mangle Objective-C selector names here!");
  893. case DeclarationName::CXXConstructorName:
  894. if (ND == Structor)
  895. // If the named decl is the C++ constructor we're mangling, use the type
  896. // we were given.
  897. mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
  898. else
  899. // Otherwise, use the complete constructor name. This is relevant if a
  900. // class with a constructor is declared within a constructor.
  901. mangleCXXCtorType(Ctor_Complete);
  902. break;
  903. case DeclarationName::CXXDestructorName:
  904. if (ND == Structor)
  905. // If the named decl is the C++ destructor we're mangling, use the type we
  906. // were given.
  907. mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
  908. else
  909. // Otherwise, use the complete destructor name. This is relevant if a
  910. // class with a destructor is declared within a destructor.
  911. mangleCXXDtorType(Dtor_Complete);
  912. break;
  913. case DeclarationName::CXXOperatorName:
  914. if (ND && Arity == UnknownArity) {
  915. Arity = cast<FunctionDecl>(ND)->getNumParams();
  916. // If we have a member function, we need to include the 'this' pointer.
  917. if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
  918. if (!MD->isStatic())
  919. Arity++;
  920. }
  921. // FALLTHROUGH
  922. case DeclarationName::CXXConversionFunctionName:
  923. case DeclarationName::CXXLiteralOperatorName:
  924. mangleOperatorName(Name, Arity);
  925. break;
  926. case DeclarationName::CXXUsingDirective:
  927. llvm_unreachable("Can't mangle a using directive name!");
  928. }
  929. }
  930. void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
  931. // <source-name> ::= <positive length number> <identifier>
  932. // <number> ::= [n] <non-negative decimal integer>
  933. // <identifier> ::= <unqualified source code identifier>
  934. Out << II->getLength() << II->getName();
  935. }
  936. void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
  937. const DeclContext *DC,
  938. bool NoFunction) {
  939. // <nested-name>
  940. // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
  941. // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
  942. // <template-args> E
  943. Out << 'N';
  944. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
  945. Qualifiers MethodQuals =
  946. Qualifiers::fromCVRMask(Method->getTypeQualifiers());
  947. // We do not consider restrict a distinguishing attribute for overloading
  948. // purposes so we must not mangle it.
  949. MethodQuals.removeRestrict();
  950. mangleQualifiers(MethodQuals);
  951. mangleRefQualifier(Method->getRefQualifier());
  952. }
  953. // Check if we have a template.
  954. const TemplateArgumentList *TemplateArgs = nullptr;
  955. if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
  956. mangleTemplatePrefix(TD, NoFunction);
  957. mangleTemplateArgs(*TemplateArgs);
  958. }
  959. else {
  960. manglePrefix(DC, NoFunction);
  961. mangleUnqualifiedName(ND);
  962. }
  963. Out << 'E';
  964. }
  965. void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
  966. const TemplateArgument *TemplateArgs,
  967. unsigned NumTemplateArgs) {
  968. // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
  969. Out << 'N';
  970. mangleTemplatePrefix(TD);
  971. mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
  972. Out << 'E';
  973. }
  974. void CXXNameMangler::mangleLocalName(const Decl *D) {
  975. // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
  976. // := Z <function encoding> E s [<discriminator>]
  977. // <local-name> := Z <function encoding> E d [ <parameter number> ]
  978. // _ <entity name>
  979. // <discriminator> := _ <non-negative number>
  980. assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
  981. const RecordDecl *RD = GetLocalClassDecl(D);
  982. const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
  983. Out << 'Z';
  984. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
  985. mangleObjCMethodName(MD);
  986. else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
  987. mangleBlockForPrefix(BD);
  988. else
  989. mangleFunctionEncoding(cast<FunctionDecl>(DC));
  990. Out << 'E';
  991. if (RD) {
  992. // The parameter number is omitted for the last parameter, 0 for the
  993. // second-to-last parameter, 1 for the third-to-last parameter, etc. The
  994. // <entity name> will of course contain a <closure-type-name>: Its
  995. // numbering will be local to the particular argument in which it appears
  996. // -- other default arguments do not affect its encoding.
  997. const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  998. if (CXXRD->isLambda()) {
  999. if (const ParmVarDecl *Parm
  1000. = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
  1001. if (const FunctionDecl *Func
  1002. = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
  1003. Out << 'd';
  1004. unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
  1005. if (Num > 1)
  1006. mangleNumber(Num - 2);
  1007. Out << '_';
  1008. }
  1009. }
  1010. }
  1011. // Mangle the name relative to the closest enclosing function.
  1012. // equality ok because RD derived from ND above
  1013. if (D == RD) {
  1014. mangleUnqualifiedName(RD);
  1015. } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  1016. manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
  1017. mangleUnqualifiedBlock(BD);
  1018. } else {
  1019. const NamedDecl *ND = cast<NamedDecl>(D);
  1020. mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
  1021. }
  1022. } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  1023. // Mangle a block in a default parameter; see above explanation for
  1024. // lambdas.
  1025. if (const ParmVarDecl *Parm
  1026. = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
  1027. if (const FunctionDecl *Func
  1028. = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
  1029. Out << 'd';
  1030. unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
  1031. if (Num > 1)
  1032. mangleNumber(Num - 2);
  1033. Out << '_';
  1034. }
  1035. }
  1036. mangleUnqualifiedBlock(BD);
  1037. } else {
  1038. mangleUnqualifiedName(cast<NamedDecl>(D));
  1039. }
  1040. if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
  1041. unsigned disc;
  1042. if (Context.getNextDiscriminator(ND, disc)) {
  1043. if (disc < 10)
  1044. Out << '_' << disc;
  1045. else
  1046. Out << "__" << disc << '_';
  1047. }
  1048. }
  1049. }
  1050. void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
  1051. if (GetLocalClassDecl(Block)) {
  1052. mangleLocalName(Block);
  1053. return;
  1054. }
  1055. const DeclContext *DC = getEffectiveDeclContext(Block);
  1056. if (isLocalContainerContext(DC)) {
  1057. mangleLocalName(Block);
  1058. return;
  1059. }
  1060. manglePrefix(getEffectiveDeclContext(Block));
  1061. mangleUnqualifiedBlock(Block);
  1062. }
  1063. void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
  1064. if (Decl *Context = Block->getBlockManglingContextDecl()) {
  1065. if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
  1066. Context->getDeclContext()->isRecord()) {
  1067. if (const IdentifierInfo *Name
  1068. = cast<NamedDecl>(Context)->getIdentifier()) {
  1069. mangleSourceName(Name);
  1070. Out << 'M';
  1071. }
  1072. }
  1073. }
  1074. // If we have a block mangling number, use it.
  1075. unsigned Number = Block->getBlockManglingNumber();
  1076. // Otherwise, just make up a number. It doesn't matter what it is because
  1077. // the symbol in question isn't externally visible.
  1078. if (!Number)
  1079. Number = Context.getBlockId(Block, false);
  1080. Out << "Ub";
  1081. if (Number > 0)
  1082. Out << Number - 1;
  1083. Out << '_';
  1084. }
  1085. void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
  1086. // If the context of a closure type is an initializer for a class member
  1087. // (static or nonstatic), it is encoded in a qualified name with a final
  1088. // <prefix> of the form:
  1089. //
  1090. // <data-member-prefix> := <member source-name> M
  1091. //
  1092. // Technically, the data-member-prefix is part of the <prefix>. However,
  1093. // since a closure type will always be mangled with a prefix, it's easier
  1094. // to emit that last part of the prefix here.
  1095. if (Decl *Context = Lambda->getLambdaContextDecl()) {
  1096. if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
  1097. Context->getDeclContext()->isRecord()) {
  1098. if (const IdentifierInfo *Name
  1099. = cast<NamedDecl>(Context)->getIdentifier()) {
  1100. mangleSourceName(Name);
  1101. Out << 'M';
  1102. }
  1103. }
  1104. }
  1105. Out << "Ul";
  1106. const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
  1107. getAs<FunctionProtoType>();
  1108. mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
  1109. Out << "E";
  1110. // The number is omitted for the first closure type with a given
  1111. // <lambda-sig> in a given context; it is n-2 for the nth closure type
  1112. // (in lexical order) with that same <lambda-sig> and context.
  1113. //
  1114. // The AST keeps track of the number for us.
  1115. unsigned Number = Lambda->getLambdaManglingNumber();
  1116. assert(Number > 0 && "Lambda should be mangled as an unnamed class");
  1117. if (Number > 1)
  1118. mangleNumber(Number - 2);
  1119. Out << '_';
  1120. }
  1121. void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
  1122. switch (qualifier->getKind()) {
  1123. case NestedNameSpecifier::Global:
  1124. // nothing
  1125. return;
  1126. case NestedNameSpecifier::Super:
  1127. llvm_unreachable("Can't mangle __super specifier");
  1128. case NestedNameSpecifier::Namespace:
  1129. mangleName(qualifier->getAsNamespace());
  1130. return;
  1131. case NestedNameSpecifier::NamespaceAlias:
  1132. mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
  1133. return;
  1134. case NestedNameSpecifier::TypeSpec:
  1135. case NestedNameSpecifier::TypeSpecWithTemplate:
  1136. manglePrefix(QualType(qualifier->getAsType(), 0));
  1137. return;
  1138. case NestedNameSpecifier::Identifier:
  1139. // Member expressions can have these without prefixes, but that
  1140. // should end up in mangleUnresolvedPrefix instead.
  1141. assert(qualifier->getPrefix());
  1142. manglePrefix(qualifier->getPrefix());
  1143. mangleSourceName(qualifier->getAsIdentifier());
  1144. return;
  1145. }
  1146. llvm_unreachable("unexpected nested name specifier");
  1147. }
  1148. void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
  1149. // <prefix> ::= <prefix> <unqualified-name>
  1150. // ::= <template-prefix> <template-args>
  1151. // ::= <template-param>
  1152. // ::= # empty
  1153. // ::= <substitution>
  1154. DC = IgnoreLinkageSpecDecls(DC);
  1155. if (DC->isTranslationUnit())
  1156. return;
  1157. if (NoFunction && isLocalContainerContext(DC))
  1158. return;
  1159. assert(!isLocalContainerContext(DC));
  1160. const NamedDecl *ND = cast<NamedDecl>(DC);
  1161. if (mangleSubstitution(ND))
  1162. return;
  1163. // Check if we have a template.
  1164. const TemplateArgumentList *TemplateArgs = nullptr;
  1165. if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
  1166. mangleTemplatePrefix(TD);
  1167. mangleTemplateArgs(*TemplateArgs);
  1168. } else {
  1169. manglePrefix(getEffectiveDeclContext(ND), NoFunction);
  1170. mangleUnqualifiedName(ND);
  1171. }
  1172. addSubstitution(ND);
  1173. }
  1174. void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
  1175. // <template-prefix> ::= <prefix> <template unqualified-name>
  1176. // ::= <template-param>
  1177. // ::= <substitution>
  1178. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  1179. return mangleTemplatePrefix(TD);
  1180. if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
  1181. manglePrefix(Qualified->getQualifier());
  1182. if (OverloadedTemplateStorage *Overloaded
  1183. = Template.getAsOverloadedTemplate()) {
  1184. mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
  1185. UnknownArity);
  1186. return;
  1187. }
  1188. DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
  1189. assert(Dependent && "Unknown template name kind?");
  1190. if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
  1191. manglePrefix(Qualifier);
  1192. mangleUnscopedTemplateName(Template);
  1193. }
  1194. void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
  1195. bool NoFunction) {
  1196. // <template-prefix> ::= <prefix> <template unqualified-name>
  1197. // ::= <template-param>
  1198. // ::= <substitution>
  1199. // <template-template-param> ::= <template-param>
  1200. // <substitution>
  1201. if (mangleSubstitution(ND))
  1202. return;
  1203. // <template-template-param> ::= <template-param>
  1204. if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
  1205. mangleTemplateParameter(TTP->getIndex());
  1206. } else {
  1207. manglePrefix(getEffectiveDeclContext(ND), NoFunction);
  1208. mangleUnqualifiedName(ND->getTemplatedDecl());
  1209. }
  1210. addSubstitution(ND);
  1211. }
  1212. /// Mangles a template name under the production <type>. Required for
  1213. /// template template arguments.
  1214. /// <type> ::= <class-enum-type>
  1215. /// ::= <template-param>
  1216. /// ::= <substitution>
  1217. void CXXNameMangler::mangleType(TemplateName TN) {
  1218. if (mangleSubstitution(TN))
  1219. return;
  1220. TemplateDecl *TD = nullptr;
  1221. switch (TN.getKind()) {
  1222. case TemplateName::QualifiedTemplate:
  1223. TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
  1224. goto HaveDecl;
  1225. case TemplateName::Template:
  1226. TD = TN.getAsTemplateDecl();
  1227. goto HaveDecl;
  1228. HaveDecl:
  1229. if (isa<TemplateTemplateParmDecl>(TD))
  1230. mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
  1231. else
  1232. mangleName(TD);
  1233. break;
  1234. case TemplateName::OverloadedTemplate:
  1235. llvm_unreachable("can't mangle an overloaded template name as a <type>");
  1236. case TemplateName::DependentTemplate: {
  1237. const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
  1238. assert(Dependent->isIdentifier());
  1239. // <class-enum-type> ::= <name>
  1240. // <name> ::= <nested-name>
  1241. mangleUnresolvedPrefix(Dependent->getQualifier());
  1242. mangleSourceName(Dependent->getIdentifier());
  1243. break;
  1244. }
  1245. case TemplateName::SubstTemplateTemplateParm: {
  1246. // Substituted template parameters are mangled as the substituted
  1247. // template. This will check for the substitution twice, which is
  1248. // fine, but we have to return early so that we don't try to *add*
  1249. // the substitution twice.
  1250. SubstTemplateTemplateParmStorage *subst
  1251. = TN.getAsSubstTemplateTemplateParm();
  1252. mangleType(subst->getReplacement());
  1253. return;
  1254. }
  1255. case TemplateName::SubstTemplateTemplateParmPack: {
  1256. // FIXME: not clear how to mangle this!
  1257. // template <template <class> class T...> class A {
  1258. // template <template <class> class U...> void foo(B<T,U> x...);
  1259. // };
  1260. Out << "_SUBSTPACK_";
  1261. break;
  1262. }
  1263. }
  1264. addSubstitution(TN);
  1265. }
  1266. bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
  1267. StringRef Prefix) {
  1268. // Only certain other types are valid as prefixes; enumerate them.
  1269. switch (Ty->getTypeClass()) {
  1270. case Type::Builtin:
  1271. case Type::Complex:
  1272. case Type::Adjusted:
  1273. case Type::Decayed:
  1274. case Type::Pointer:
  1275. case Type::BlockPointer:
  1276. case Type::LValueReference:
  1277. case Type::RValueReference:
  1278. case Type::MemberPointer:
  1279. case Type::ConstantArray:
  1280. case Type::IncompleteArray:
  1281. case Type::VariableArray:
  1282. case Type::DependentSizedArray:
  1283. case Type::DependentSizedExtVector:
  1284. case Type::Vector:
  1285. case Type::ExtVector:
  1286. case Type::FunctionProto:
  1287. case Type::FunctionNoProto:
  1288. case Type::Paren:
  1289. case Type::Attributed:
  1290. case Type::Auto:
  1291. case Type::PackExpansion:
  1292. case Type::ObjCObject:
  1293. case Type::ObjCInterface:
  1294. case Type::ObjCObjectPointer:
  1295. case Type::Atomic:
  1296. llvm_unreachable("type is illegal as a nested name specifier");
  1297. case Type::SubstTemplateTypeParmPack:
  1298. // FIXME: not clear how to mangle this!
  1299. // template <class T...> class A {
  1300. // template <class U...> void foo(decltype(T::foo(U())) x...);
  1301. // };
  1302. Out << "_SUBSTPACK_";
  1303. break;
  1304. // <unresolved-type> ::= <template-param>
  1305. // ::= <decltype>
  1306. // ::= <template-template-param> <template-args>
  1307. // (this last is not official yet)
  1308. case Type::TypeOfExpr:
  1309. case Type::TypeOf:
  1310. case Type::Decltype:
  1311. case Type::TemplateTypeParm:
  1312. case Type::UnaryTransform:
  1313. case Type::SubstTemplateTypeParm:
  1314. unresolvedType:
  1315. // Some callers want a prefix before the mangled type.
  1316. Out << Prefix;
  1317. // This seems to do everything we want. It's not really
  1318. // sanctioned for a substituted template parameter, though.
  1319. mangleType(Ty);
  1320. // We never want to print 'E' directly after an unresolved-type,
  1321. // so we return directly.
  1322. return true;
  1323. case Type::Typedef:
  1324. mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
  1325. break;
  1326. case Type::UnresolvedUsing:
  1327. mangleSourceName(
  1328. cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
  1329. break;
  1330. case Type::Enum:
  1331. case Type::Record:
  1332. mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
  1333. break;
  1334. case Type::TemplateSpecialization: {
  1335. const TemplateSpecializationType *TST =
  1336. cast<TemplateSpecializationType>(Ty);
  1337. TemplateName TN = TST->getTemplateName();
  1338. switch (TN.getKind()) {
  1339. case TemplateName::Template:
  1340. case TemplateName::QualifiedTemplate: {
  1341. TemplateDecl *TD = TN.getAsTemplateDecl();
  1342. // If the base is a template template parameter, this is an
  1343. // unresolved type.
  1344. assert(TD && "no template for template specialization type");
  1345. if (isa<TemplateTemplateParmDecl>(TD))
  1346. goto unresolvedType;
  1347. mangleSourceName(TD->getIdentifier());
  1348. break;
  1349. }
  1350. case TemplateName::OverloadedTemplate:
  1351. case TemplateName::DependentTemplate:
  1352. llvm_unreachable("invalid base for a template specialization type");
  1353. case TemplateName::SubstTemplateTemplateParm: {
  1354. SubstTemplateTemplateParmStorage *subst =
  1355. TN.getAsSubstTemplateTemplateParm();
  1356. mangleExistingSubstitution(subst->getReplacement());
  1357. break;
  1358. }
  1359. case TemplateName::SubstTemplateTemplateParmPack: {
  1360. // FIXME: not clear how to mangle this!
  1361. // template <template <class U> class T...> class A {
  1362. // template <class U...> void foo(decltype(T<U>::foo) x...);
  1363. // };
  1364. Out << "_SUBSTPACK_";
  1365. break;
  1366. }
  1367. }
  1368. mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
  1369. break;
  1370. }
  1371. case Type::InjectedClassName:
  1372. mangleSourceName(
  1373. cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
  1374. break;
  1375. case Type::DependentName:
  1376. mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
  1377. break;
  1378. case Type::DependentTemplateSpecialization: {
  1379. const DependentTemplateSpecializationType *DTST =
  1380. cast<DependentTemplateSpecializationType>(Ty);
  1381. mangleSourceName(DTST->getIdentifier());
  1382. mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
  1383. break;
  1384. }
  1385. case Type::Elaborated:
  1386. return mangleUnresolvedTypeOrSimpleId(
  1387. cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
  1388. }
  1389. return false;
  1390. }
  1391. void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
  1392. switch (Name.getNameKind()) {
  1393. case DeclarationName::CXXConstructorName:
  1394. case DeclarationName::CXXDestructorName:
  1395. case DeclarationName::CXXUsingDirective:
  1396. case DeclarationName::Identifier:
  1397. case DeclarationName::ObjCMultiArgSelector:
  1398. case DeclarationName::ObjCOneArgSelector:
  1399. case DeclarationName::ObjCZeroArgSelector:
  1400. llvm_unreachable("Not an operator name");
  1401. case DeclarationName::CXXConversionFunctionName:
  1402. // <operator-name> ::= cv <type> # (cast)
  1403. Out << "cv";
  1404. mangleType(Name.getCXXNameType());
  1405. break;
  1406. case DeclarationName::CXXLiteralOperatorName:
  1407. Out << "li";
  1408. mangleSourceName(Name.getCXXLiteralIdentifier());
  1409. return;
  1410. case DeclarationName::CXXOperatorName:
  1411. mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
  1412. break;
  1413. }
  1414. }
  1415. void
  1416. CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
  1417. switch (OO) {
  1418. // <operator-name> ::= nw # new
  1419. case OO_New: Out << "nw"; break;
  1420. // ::= na # new[]
  1421. case OO_Array_New: Out << "na"; break;
  1422. // ::= dl # delete
  1423. case OO_Delete: Out << "dl"; break;
  1424. // ::= da # delete[]
  1425. case OO_Array_Delete: Out << "da"; break;
  1426. // ::= ps # + (unary)
  1427. // ::= pl # + (binary or unknown)
  1428. case OO_Plus:
  1429. Out << (Arity == 1? "ps" : "pl"); break;
  1430. // ::= ng # - (unary)
  1431. // ::= mi # - (binary or unknown)
  1432. case OO_Minus:
  1433. Out << (Arity == 1? "ng" : "mi"); break;
  1434. // ::= ad # & (unary)
  1435. // ::= an # & (binary or unknown)
  1436. case OO_Amp:
  1437. Out << (Arity == 1? "ad" : "an"); break;
  1438. // ::= de # * (unary)
  1439. // ::= ml # * (binary or unknown)
  1440. case OO_Star:
  1441. // Use binary when unknown.
  1442. Out << (Arity == 1? "de" : "ml"); break;
  1443. // ::= co # ~
  1444. case OO_Tilde: Out << "co"; break;
  1445. // ::= dv # /
  1446. case OO_Slash: Out << "dv"; break;
  1447. // ::= rm # %
  1448. case OO_Percent: Out << "rm"; break;
  1449. // ::= or # |
  1450. case OO_Pipe: Out << "or"; break;
  1451. // ::= eo # ^
  1452. case OO_Caret: Out << "eo"; break;
  1453. // ::= aS # =
  1454. case OO_Equal: Out << "aS"; break;
  1455. // ::= pL # +=
  1456. case OO_PlusEqual: Out << "pL"; break;
  1457. // ::= mI # -=
  1458. case OO_MinusEqual: Out << "mI"; break;
  1459. // ::= mL # *=
  1460. case OO_StarEqual: Out << "mL"; break;
  1461. // ::= dV # /=
  1462. case OO_SlashEqual: Out << "dV"; break;
  1463. // ::= rM # %=
  1464. case OO_PercentEqual: Out << "rM"; break;
  1465. // ::= aN # &=
  1466. case OO_AmpEqual: Out << "aN"; break;
  1467. // ::= oR # |=
  1468. case OO_PipeEqual: Out << "oR"; break;
  1469. // ::= eO # ^=
  1470. case OO_CaretEqual: Out << "eO"; break;
  1471. // ::= ls # <<
  1472. case OO_LessLess: Out << "ls"; break;
  1473. // ::= rs # >>
  1474. case OO_GreaterGreater: Out << "rs"; break;
  1475. // ::= lS # <<=
  1476. case OO_LessLessEqual: Out << "lS"; break;
  1477. // ::= rS # >>=
  1478. case OO_GreaterGreaterEqual: Out << "rS"; break;
  1479. // ::= eq # ==
  1480. case OO_EqualEqual: Out << "eq"; break;
  1481. // ::= ne # !=
  1482. case OO_ExclaimEqual: Out << "ne"; break;
  1483. // ::= lt # <
  1484. case OO_Less: Out << "lt"; break;
  1485. // ::= gt # >
  1486. case OO_Greater: Out << "gt"; break;
  1487. // ::= le # <=
  1488. case OO_LessEqual: Out << "le"; break;
  1489. // ::= ge # >=
  1490. case OO_GreaterEqual: Out << "ge"; break;
  1491. // ::= nt # !
  1492. case OO_Exclaim: Out << "nt"; break;
  1493. // ::= aa # &&
  1494. case OO_AmpAmp: Out << "aa"; break;
  1495. // ::= oo # ||
  1496. case OO_PipePipe: Out << "oo"; break;
  1497. // ::= pp # ++
  1498. case OO_PlusPlus: Out << "pp"; break;
  1499. // ::= mm # --
  1500. case OO_MinusMinus: Out << "mm"; break;
  1501. // ::= cm # ,
  1502. case OO_Comma: Out << "cm"; break;
  1503. // ::= pm # ->*
  1504. case OO_ArrowStar: Out << "pm"; break;
  1505. // ::= pt # ->
  1506. case OO_Arrow: Out << "pt"; break;
  1507. // ::= cl # ()
  1508. case OO_Call: Out << "cl"; break;
  1509. // ::= ix # []
  1510. case OO_Subscript: Out << "ix"; break;
  1511. // ::= qu # ?
  1512. // The conditional operator can't be overloaded, but we still handle it when
  1513. // mangling expressions.
  1514. case OO_Conditional: Out << "qu"; break;
  1515. case OO_None:
  1516. case NUM_OVERLOADED_OPERATORS:
  1517. llvm_unreachable("Not an overloaded operator");
  1518. }
  1519. }
  1520. void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
  1521. // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
  1522. if (Quals.hasRestrict())
  1523. Out << 'r';
  1524. if (Quals.hasVolatile())
  1525. Out << 'V';
  1526. if (Quals.hasConst())
  1527. Out << 'K';
  1528. if (Quals.hasAddressSpace()) {
  1529. // Address space extension:
  1530. //
  1531. // <type> ::= U <target-addrspace>
  1532. // <type> ::= U <OpenCL-addrspace>
  1533. // <type> ::= U <CUDA-addrspace>
  1534. SmallString<64> ASString;
  1535. unsigned AS = Quals.getAddressSpace();
  1536. if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
  1537. // <target-addrspace> ::= "AS" <address-space-number>
  1538. unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
  1539. ASString = "AS" + llvm::utostr_32(TargetAS);
  1540. } else {
  1541. switch (AS) {
  1542. default: llvm_unreachable("Not a language specific address space");
  1543. // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
  1544. case LangAS::opencl_global: ASString = "CLglobal"; break;
  1545. case LangAS::opencl_local: ASString = "CLlocal"; break;
  1546. case LangAS::opencl_constant: ASString = "CLconstant"; break;
  1547. // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
  1548. case LangAS::cuda_device: ASString = "CUdevice"; break;
  1549. case LangAS::cuda_constant: ASString = "CUconstant"; break;
  1550. case LangAS::cuda_shared: ASString = "CUshared"; break;
  1551. }
  1552. }
  1553. Out << 'U' << ASString.size() << ASString;
  1554. }
  1555. StringRef LifetimeName;
  1556. switch (Quals.getObjCLifetime()) {
  1557. // Objective-C ARC Extension:
  1558. //
  1559. // <type> ::= U "__strong"
  1560. // <type> ::= U "__weak"
  1561. // <type> ::= U "__autoreleasing"
  1562. case Qualifiers::OCL_None:
  1563. break;
  1564. case Qualifiers::OCL_Weak:
  1565. LifetimeName = "__weak";
  1566. break;
  1567. case Qualifiers::OCL_Strong:
  1568. LifetimeName = "__strong";
  1569. break;
  1570. case Qualifiers::OCL_Autoreleasing:
  1571. LifetimeName = "__autoreleasing";
  1572. break;
  1573. case Qualifiers::OCL_ExplicitNone:
  1574. // The __unsafe_unretained qualifier is *not* mangled, so that
  1575. // __unsafe_unretained types in ARC produce the same manglings as the
  1576. // equivalent (but, naturally, unqualified) types in non-ARC, providing
  1577. // better ABI compatibility.
  1578. //
  1579. // It's safe to do this because unqualified 'id' won't show up
  1580. // in any type signatures that need to be mangled.
  1581. break;
  1582. }
  1583. if (!LifetimeName.empty())
  1584. Out << 'U' << LifetimeName.size() << LifetimeName;
  1585. }
  1586. void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
  1587. // <ref-qualifier> ::= R # lvalue reference
  1588. // ::= O # rvalue-reference
  1589. switch (RefQualifier) {
  1590. case RQ_None:
  1591. break;
  1592. case RQ_LValue:
  1593. Out << 'R';
  1594. break;
  1595. case RQ_RValue:
  1596. Out << 'O';
  1597. break;
  1598. }
  1599. }
  1600. void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
  1601. Context.mangleObjCMethodName(MD, Out);
  1602. }
  1603. static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
  1604. if (Quals)
  1605. return true;
  1606. if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
  1607. return true;
  1608. if (Ty->isOpenCLSpecificType())
  1609. return true;
  1610. if (Ty->isBuiltinType())
  1611. return false;
  1612. return true;
  1613. }
  1614. void CXXNameMangler::mangleType(QualType T) {
  1615. // If our type is instantiation-dependent but not dependent, we mangle
  1616. // it as it was written in the source, removing any top-level sugar.
  1617. // Otherwise, use the canonical type.
  1618. //
  1619. // FIXME: This is an approximation of the instantiation-dependent name
  1620. // mangling rules, since we should really be using the type as written and
  1621. // augmented via semantic analysis (i.e., with implicit conversions and
  1622. // default template arguments) for any instantiation-dependent type.
  1623. // Unfortunately, that requires several changes to our AST:
  1624. // - Instantiation-dependent TemplateSpecializationTypes will need to be
  1625. // uniqued, so that we can handle substitutions properly
  1626. // - Default template arguments will need to be represented in the
  1627. // TemplateSpecializationType, since they need to be mangled even though
  1628. // they aren't written.
  1629. // - Conversions on non-type template arguments need to be expressed, since
  1630. // they can affect the mangling of sizeof/alignof.
  1631. if (!T->isInstantiationDependentType() || T->isDependentType())
  1632. T = T.getCanonicalType();
  1633. else {
  1634. // Desugar any types that are purely sugar.
  1635. do {
  1636. // Don't desugar through template specialization types that aren't
  1637. // type aliases. We need to mangle the template arguments as written.
  1638. if (const TemplateSpecializationType *TST
  1639. = dyn_cast<TemplateSpecializationType>(T))
  1640. if (!TST->isTypeAlias())
  1641. break;
  1642. QualType Desugared
  1643. = T.getSingleStepDesugaredType(Context.getASTContext());
  1644. if (Desugared == T)
  1645. break;
  1646. T = Desugared;
  1647. } while (true);
  1648. }
  1649. SplitQualType split = T.split();
  1650. Qualifiers quals = split.Quals;
  1651. const Type *ty = split.Ty;
  1652. bool isSubstitutable = isTypeSubstitutable(quals, ty);
  1653. if (isSubstitutable && mangleSubstitution(T))
  1654. return;
  1655. // If we're mangling a qualified array type, push the qualifiers to
  1656. // the element type.
  1657. if (quals && isa<ArrayType>(T)) {
  1658. ty = Context.getASTContext().getAsArrayType(T);
  1659. quals = Qualifiers();
  1660. // Note that we don't update T: we want to add the
  1661. // substitution at the original type.
  1662. }
  1663. if (quals) {
  1664. mangleQualifiers(quals);
  1665. // Recurse: even if the qualified type isn't yet substitutable,
  1666. // the unqualified type might be.
  1667. mangleType(QualType(ty, 0));
  1668. } else {
  1669. switch (ty->getTypeClass()) {
  1670. #define ABSTRACT_TYPE(CLASS, PARENT)
  1671. #define NON_CANONICAL_TYPE(CLASS, PARENT) \
  1672. case Type::CLASS: \
  1673. llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
  1674. return;
  1675. #define TYPE(CLASS, PARENT) \
  1676. case Type::CLASS: \
  1677. mangleType(static_cast<const CLASS##Type*>(ty)); \
  1678. break;
  1679. #include "clang/AST/TypeNodes.def"
  1680. }
  1681. }
  1682. // Add the substitution.
  1683. if (isSubstitutable)
  1684. addSubstitution(T);
  1685. }
  1686. void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
  1687. if (!mangleStandardSubstitution(ND))
  1688. mangleName(ND);
  1689. }
  1690. void CXXNameMangler::mangleType(const BuiltinType *T) {
  1691. // <type> ::= <builtin-type>
  1692. // <builtin-type> ::= v # void
  1693. // ::= w # wchar_t
  1694. // ::= b # bool
  1695. // ::= c # char
  1696. // ::= a # signed char
  1697. // ::= h # unsigned char
  1698. // ::= s # short
  1699. // ::= t # unsigned short
  1700. // ::= i # int
  1701. // ::= j # unsigned int
  1702. // ::= l # long
  1703. // ::= m # unsigned long
  1704. // ::= x # long long, __int64
  1705. // ::= y # unsigned long long, __int64
  1706. // ::= n # __int128
  1707. // ::= o # unsigned __int128
  1708. // ::= f # float
  1709. // ::= d # double
  1710. // ::= e # long double, __float80
  1711. // UNSUPPORTED: ::= g # __float128
  1712. // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
  1713. // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
  1714. // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
  1715. // ::= Dh # IEEE 754r half-precision floating point (16 bits)
  1716. // ::= Di # char32_t
  1717. // ::= Ds # char16_t
  1718. // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
  1719. // ::= u <source-name> # vendor extended type
  1720. switch (T->getKind()) {
  1721. case BuiltinType::Void: Out << 'v'; break;
  1722. case BuiltinType::Bool: Out << 'b'; break;
  1723. case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
  1724. case BuiltinType::UChar: Out << 'h'; break;
  1725. case BuiltinType::UShort: Out << 't'; break;
  1726. case BuiltinType::UInt: Out << 'j'; break;
  1727. case BuiltinType::ULong: Out << 'm'; break;
  1728. case BuiltinType::ULongLong: Out << 'y'; break;
  1729. case BuiltinType::UInt128: Out << 'o'; break;
  1730. case BuiltinType::SChar: Out << 'a'; break;
  1731. case BuiltinType::WChar_S:
  1732. case BuiltinType::WChar_U: Out << 'w'; break;
  1733. case BuiltinType::Char16: Out << "Ds"; break;
  1734. case BuiltinType::Char32: Out << "Di"; break;
  1735. case BuiltinType::Short: Out << 's'; break;
  1736. case BuiltinType::Int: Out << 'i'; break;
  1737. case BuiltinType::Long: Out << 'l'; break;
  1738. case BuiltinType::LongLong: Out << 'x'; break;
  1739. case BuiltinType::Int128: Out << 'n'; break;
  1740. case BuiltinType::Half: Out << "Dh"; break;
  1741. case BuiltinType::Float: Out << 'f'; break;
  1742. case BuiltinType::Double: Out << 'd'; break;
  1743. case BuiltinType::LongDouble:
  1744. Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
  1745. ? 'g'
  1746. : 'e');
  1747. break;
  1748. case BuiltinType::NullPtr: Out << "Dn"; break;
  1749. #define BUILTIN_TYPE(Id, SingletonId)
  1750. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  1751. case BuiltinType::Id:
  1752. #include "clang/AST/BuiltinTypes.def"
  1753. case BuiltinType::Dependent:
  1754. llvm_unreachable("mangling a placeholder type");
  1755. case BuiltinType::ObjCId: Out << "11objc_object"; break;
  1756. case BuiltinType::ObjCClass: Out << "10objc_class"; break;
  1757. case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
  1758. case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
  1759. case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
  1760. case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
  1761. case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
  1762. case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
  1763. case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
  1764. case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
  1765. case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
  1766. // HLSL Change starts
  1767. case BuiltinType::Min12Int: Out << "min12_int"; break;
  1768. case BuiltinType::LitInt: Out << "lit_int"; break;
  1769. case BuiltinType::LitFloat: Out << "lit_float"; break;
  1770. case BuiltinType::Min10Float: Out << "min10_float"; break;
  1771. case BuiltinType::Min16Float: Out << "min16_float"; break;
  1772. case BuiltinType::Min16Int: Out << "min16_int"; break;
  1773. case BuiltinType::Min16UInt: Out << "min16_uint"; break;
  1774. case BuiltinType::HalfFloat: Out << "half_float"; break;
  1775. // HLSL Change ends
  1776. }
  1777. }
  1778. // <type> ::= <function-type>
  1779. // <function-type> ::= [<CV-qualifiers>] F [Y]
  1780. // <bare-function-type> [<ref-qualifier>] E
  1781. void CXXNameMangler::mangleType(const FunctionProtoType *T) {
  1782. // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
  1783. // e.g. "const" in "int (A::*)() const".
  1784. mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
  1785. Out << 'F';
  1786. // FIXME: We don't have enough information in the AST to produce the 'Y'
  1787. // encoding for extern "C" function types.
  1788. mangleBareFunctionType(T, /*MangleReturnType=*/true);
  1789. // Mangle the ref-qualifier, if present.
  1790. mangleRefQualifier(T->getRefQualifier());
  1791. Out << 'E';
  1792. }
  1793. void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
  1794. llvm_unreachable("Can't mangle K&R function prototypes");
  1795. }
  1796. void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
  1797. bool MangleReturnType) {
  1798. // We should never be mangling something without a prototype.
  1799. const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
  1800. // Record that we're in a function type. See mangleFunctionParam
  1801. // for details on what we're trying to achieve here.
  1802. FunctionTypeDepthState saved = FunctionTypeDepth.push();
  1803. // <bare-function-type> ::= <signature type>+
  1804. if (MangleReturnType) {
  1805. FunctionTypeDepth.enterResultType();
  1806. mangleType(Proto->getReturnType());
  1807. FunctionTypeDepth.leaveResultType();
  1808. }
  1809. if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
  1810. // <builtin-type> ::= v # void
  1811. Out << 'v';
  1812. FunctionTypeDepth.pop(saved);
  1813. return;
  1814. }
  1815. for (const auto &Arg : Proto->param_types())
  1816. mangleType(Context.getASTContext().getSignatureParameterType(Arg));
  1817. FunctionTypeDepth.pop(saved);
  1818. // <builtin-type> ::= z # ellipsis
  1819. if (Proto->isVariadic())
  1820. Out << 'z';
  1821. }
  1822. // <type> ::= <class-enum-type>
  1823. // <class-enum-type> ::= <name>
  1824. void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
  1825. mangleName(T->getDecl());
  1826. }
  1827. // <type> ::= <class-enum-type>
  1828. // <class-enum-type> ::= <name>
  1829. void CXXNameMangler::mangleType(const EnumType *T) {
  1830. mangleType(static_cast<const TagType*>(T));
  1831. }
  1832. void CXXNameMangler::mangleType(const RecordType *T) {
  1833. mangleType(static_cast<const TagType*>(T));
  1834. }
  1835. void CXXNameMangler::mangleType(const TagType *T) {
  1836. mangleName(T->getDecl());
  1837. }
  1838. // <type> ::= <array-type>
  1839. // <array-type> ::= A <positive dimension number> _ <element type>
  1840. // ::= A [<dimension expression>] _ <element type>
  1841. void CXXNameMangler::mangleType(const ConstantArrayType *T) {
  1842. Out << 'A' << T->getSize() << '_';
  1843. mangleType(T->getElementType());
  1844. }
  1845. void CXXNameMangler::mangleType(const VariableArrayType *T) {
  1846. Out << 'A';
  1847. // decayed vla types (size 0) will just be skipped.
  1848. if (T->getSizeExpr())
  1849. mangleExpression(T->getSizeExpr());
  1850. Out << '_';
  1851. mangleType(T->getElementType());
  1852. }
  1853. void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
  1854. Out << 'A';
  1855. mangleExpression(T->getSizeExpr());
  1856. Out << '_';
  1857. mangleType(T->getElementType());
  1858. }
  1859. void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
  1860. Out << "A_";
  1861. mangleType(T->getElementType());
  1862. }
  1863. // <type> ::= <pointer-to-member-type>
  1864. // <pointer-to-member-type> ::= M <class type> <member type>
  1865. void CXXNameMangler::mangleType(const MemberPointerType *T) {
  1866. Out << 'M';
  1867. mangleType(QualType(T->getClass(), 0));
  1868. QualType PointeeType = T->getPointeeType();
  1869. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
  1870. mangleType(FPT);
  1871. // Itanium C++ ABI 5.1.8:
  1872. //
  1873. // The type of a non-static member function is considered to be different,
  1874. // for the purposes of substitution, from the type of a namespace-scope or
  1875. // static member function whose type appears similar. The types of two
  1876. // non-static member functions are considered to be different, for the
  1877. // purposes of substitution, if the functions are members of different
  1878. // classes. In other words, for the purposes of substitution, the class of
  1879. // which the function is a member is considered part of the type of
  1880. // function.
  1881. // Given that we already substitute member function pointers as a
  1882. // whole, the net effect of this rule is just to unconditionally
  1883. // suppress substitution on the function type in a member pointer.
  1884. // We increment the SeqID here to emulate adding an entry to the
  1885. // substitution table.
  1886. ++SeqID;
  1887. } else
  1888. mangleType(PointeeType);
  1889. }
  1890. // <type> ::= <template-param>
  1891. void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
  1892. mangleTemplateParameter(T->getIndex());
  1893. }
  1894. // <type> ::= <template-param>
  1895. void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
  1896. // FIXME: not clear how to mangle this!
  1897. // template <class T...> class A {
  1898. // template <class U...> void foo(T(*)(U) x...);
  1899. // };
  1900. Out << "_SUBSTPACK_";
  1901. }
  1902. // <type> ::= P <type> # pointer-to
  1903. void CXXNameMangler::mangleType(const PointerType *T) {
  1904. Out << 'P';
  1905. mangleType(T->getPointeeType());
  1906. }
  1907. void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
  1908. Out << 'P';
  1909. mangleType(T->getPointeeType());
  1910. }
  1911. // <type> ::= R <type> # reference-to
  1912. void CXXNameMangler::mangleType(const LValueReferenceType *T) {
  1913. Out << 'R';
  1914. mangleType(T->getPointeeType());
  1915. }
  1916. // <type> ::= O <type> # rvalue reference-to (C++0x)
  1917. void CXXNameMangler::mangleType(const RValueReferenceType *T) {
  1918. Out << 'O';
  1919. mangleType(T->getPointeeType());
  1920. }
  1921. // <type> ::= C <type> # complex pair (C 2000)
  1922. void CXXNameMangler::mangleType(const ComplexType *T) {
  1923. Out << 'C';
  1924. mangleType(T->getElementType());
  1925. }
  1926. // ARM's ABI for Neon vector types specifies that they should be mangled as
  1927. // if they are structs (to match ARM's initial implementation). The
  1928. // vector type must be one of the special types predefined by ARM.
  1929. void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
  1930. QualType EltType = T->getElementType();
  1931. assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
  1932. const char *EltName = nullptr;
  1933. if (T->getVectorKind() == VectorType::NeonPolyVector) {
  1934. switch (cast<BuiltinType>(EltType)->getKind()) {
  1935. case BuiltinType::SChar:
  1936. case BuiltinType::UChar:
  1937. EltName = "poly8_t";
  1938. break;
  1939. case BuiltinType::Short:
  1940. case BuiltinType::UShort:
  1941. EltName = "poly16_t";
  1942. break;
  1943. case BuiltinType::ULongLong:
  1944. EltName = "poly64_t";
  1945. break;
  1946. default: llvm_unreachable("unexpected Neon polynomial vector element type");
  1947. }
  1948. } else {
  1949. switch (cast<BuiltinType>(EltType)->getKind()) {
  1950. case BuiltinType::SChar: EltName = "int8_t"; break;
  1951. case BuiltinType::UChar: EltName = "uint8_t"; break;
  1952. case BuiltinType::Short: EltName = "int16_t"; break;
  1953. case BuiltinType::UShort: EltName = "uint16_t"; break;
  1954. case BuiltinType::Int: EltName = "int32_t"; break;
  1955. case BuiltinType::UInt: EltName = "uint32_t"; break;
  1956. case BuiltinType::LongLong: EltName = "int64_t"; break;
  1957. case BuiltinType::ULongLong: EltName = "uint64_t"; break;
  1958. case BuiltinType::Double: EltName = "float64_t"; break;
  1959. case BuiltinType::Float: EltName = "float32_t"; break;
  1960. case BuiltinType::Half: EltName = "float16_t";break;
  1961. default:
  1962. llvm_unreachable("unexpected Neon vector element type");
  1963. }
  1964. }
  1965. const char *BaseName = nullptr;
  1966. unsigned BitSize = (T->getNumElements() *
  1967. getASTContext().getTypeSize(EltType));
  1968. if (BitSize == 64)
  1969. BaseName = "__simd64_";
  1970. else {
  1971. assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
  1972. BaseName = "__simd128_";
  1973. }
  1974. Out << strlen(BaseName) + strlen(EltName);
  1975. Out << BaseName << EltName;
  1976. }
  1977. static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
  1978. switch (EltType->getKind()) {
  1979. case BuiltinType::SChar:
  1980. return "Int8";
  1981. case BuiltinType::Short:
  1982. return "Int16";
  1983. case BuiltinType::Int:
  1984. return "Int32";
  1985. case BuiltinType::Long:
  1986. case BuiltinType::LongLong:
  1987. return "Int64";
  1988. case BuiltinType::UChar:
  1989. return "Uint8";
  1990. case BuiltinType::UShort:
  1991. return "Uint16";
  1992. case BuiltinType::UInt:
  1993. return "Uint32";
  1994. case BuiltinType::ULong:
  1995. case BuiltinType::ULongLong:
  1996. return "Uint64";
  1997. case BuiltinType::Half:
  1998. return "Float16";
  1999. case BuiltinType::Float:
  2000. return "Float32";
  2001. case BuiltinType::Double:
  2002. return "Float64";
  2003. default:
  2004. llvm_unreachable("Unexpected vector element base type");
  2005. }
  2006. }
  2007. // AArch64's ABI for Neon vector types specifies that they should be mangled as
  2008. // the equivalent internal name. The vector type must be one of the special
  2009. // types predefined by ARM.
  2010. void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
  2011. QualType EltType = T->getElementType();
  2012. assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
  2013. unsigned BitSize =
  2014. (T->getNumElements() * getASTContext().getTypeSize(EltType));
  2015. (void)BitSize; // Silence warning.
  2016. assert((BitSize == 64 || BitSize == 128) &&
  2017. "Neon vector type not 64 or 128 bits");
  2018. StringRef EltName;
  2019. if (T->getVectorKind() == VectorType::NeonPolyVector) {
  2020. switch (cast<BuiltinType>(EltType)->getKind()) {
  2021. case BuiltinType::UChar:
  2022. EltName = "Poly8";
  2023. break;
  2024. case BuiltinType::UShort:
  2025. EltName = "Poly16";
  2026. break;
  2027. case BuiltinType::ULong:
  2028. case BuiltinType::ULongLong:
  2029. EltName = "Poly64";
  2030. break;
  2031. default:
  2032. llvm_unreachable("unexpected Neon polynomial vector element type");
  2033. }
  2034. } else
  2035. EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
  2036. std::string TypeName =
  2037. ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
  2038. Out << TypeName.length() << TypeName;
  2039. }
  2040. // GNU extension: vector types
  2041. // <type> ::= <vector-type>
  2042. // <vector-type> ::= Dv <positive dimension number> _
  2043. // <extended element type>
  2044. // ::= Dv [<dimension expression>] _ <element type>
  2045. // <extended element type> ::= <element type>
  2046. // ::= p # AltiVec vector pixel
  2047. // ::= b # Altivec vector bool
  2048. void CXXNameMangler::mangleType(const VectorType *T) {
  2049. if ((T->getVectorKind() == VectorType::NeonVector ||
  2050. T->getVectorKind() == VectorType::NeonPolyVector)) {
  2051. llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
  2052. llvm::Triple::ArchType Arch =
  2053. getASTContext().getTargetInfo().getTriple().getArch();
  2054. if ((Arch == llvm::Triple::aarch64 ||
  2055. Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
  2056. mangleAArch64NeonVectorType(T);
  2057. else
  2058. mangleNeonVectorType(T);
  2059. return;
  2060. }
  2061. Out << "Dv" << T->getNumElements() << '_';
  2062. if (T->getVectorKind() == VectorType::AltiVecPixel)
  2063. Out << 'p';
  2064. else if (T->getVectorKind() == VectorType::AltiVecBool)
  2065. Out << 'b';
  2066. else
  2067. mangleType(T->getElementType());
  2068. }
  2069. void CXXNameMangler::mangleType(const ExtVectorType *T) {
  2070. mangleType(static_cast<const VectorType*>(T));
  2071. }
  2072. void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
  2073. Out << "Dv";
  2074. mangleExpression(T->getSizeExpr());
  2075. Out << '_';
  2076. mangleType(T->getElementType());
  2077. }
  2078. void CXXNameMangler::mangleType(const PackExpansionType *T) {
  2079. // <type> ::= Dp <type> # pack expansion (C++0x)
  2080. Out << "Dp";
  2081. mangleType(T->getPattern());
  2082. }
  2083. void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
  2084. mangleSourceName(T->getDecl()->getIdentifier());
  2085. }
  2086. void CXXNameMangler::mangleType(const ObjCObjectType *T) {
  2087. // Treat __kindof as a vendor extended type qualifier.
  2088. if (T->isKindOfType())
  2089. Out << "U8__kindof";
  2090. if (!T->qual_empty()) {
  2091. // Mangle protocol qualifiers.
  2092. SmallString<64> QualStr;
  2093. llvm::raw_svector_ostream QualOS(QualStr);
  2094. QualOS << "objcproto";
  2095. for (const auto *I : T->quals()) {
  2096. StringRef name = I->getName();
  2097. QualOS << name.size() << name;
  2098. }
  2099. QualOS.flush();
  2100. Out << 'U' << QualStr.size() << QualStr;
  2101. }
  2102. mangleType(T->getBaseType());
  2103. if (T->isSpecialized()) {
  2104. // Mangle type arguments as I <type>+ E
  2105. Out << 'I';
  2106. for (auto typeArg : T->getTypeArgs())
  2107. mangleType(typeArg);
  2108. Out << 'E';
  2109. }
  2110. }
  2111. void CXXNameMangler::mangleType(const BlockPointerType *T) {
  2112. Out << "U13block_pointer";
  2113. mangleType(T->getPointeeType());
  2114. }
  2115. void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
  2116. // Mangle injected class name types as if the user had written the
  2117. // specialization out fully. It may not actually be possible to see
  2118. // this mangling, though.
  2119. mangleType(T->getInjectedSpecializationType());
  2120. }
  2121. void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
  2122. if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
  2123. mangleName(TD, T->getArgs(), T->getNumArgs());
  2124. } else {
  2125. if (mangleSubstitution(QualType(T, 0)))
  2126. return;
  2127. mangleTemplatePrefix(T->getTemplateName());
  2128. // FIXME: GCC does not appear to mangle the template arguments when
  2129. // the template in question is a dependent template name. Should we
  2130. // emulate that badness?
  2131. mangleTemplateArgs(T->getArgs(), T->getNumArgs());
  2132. addSubstitution(QualType(T, 0));
  2133. }
  2134. }
  2135. void CXXNameMangler::mangleType(const DependentNameType *T) {
  2136. // Proposal by cxx-abi-dev, 2014-03-26
  2137. // <class-enum-type> ::= <name> # non-dependent or dependent type name or
  2138. // # dependent elaborated type specifier using
  2139. // # 'typename'
  2140. // ::= Ts <name> # dependent elaborated type specifier using
  2141. // # 'struct' or 'class'
  2142. // ::= Tu <name> # dependent elaborated type specifier using
  2143. // # 'union'
  2144. // ::= Te <name> # dependent elaborated type specifier using
  2145. // # 'enum'
  2146. switch (T->getKeyword()) {
  2147. case ETK_Typename:
  2148. break;
  2149. case ETK_Struct:
  2150. case ETK_Class:
  2151. case ETK_Interface:
  2152. Out << "Ts";
  2153. break;
  2154. case ETK_Union:
  2155. Out << "Tu";
  2156. break;
  2157. case ETK_Enum:
  2158. Out << "Te";
  2159. break;
  2160. default:
  2161. llvm_unreachable("unexpected keyword for dependent type name");
  2162. }
  2163. // Typename types are always nested
  2164. Out << 'N';
  2165. manglePrefix(T->getQualifier());
  2166. mangleSourceName(T->getIdentifier());
  2167. Out << 'E';
  2168. }
  2169. void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
  2170. // Dependently-scoped template types are nested if they have a prefix.
  2171. Out << 'N';
  2172. // TODO: avoid making this TemplateName.
  2173. TemplateName Prefix =
  2174. getASTContext().getDependentTemplateName(T->getQualifier(),
  2175. T->getIdentifier());
  2176. mangleTemplatePrefix(Prefix);
  2177. // FIXME: GCC does not appear to mangle the template arguments when
  2178. // the template in question is a dependent template name. Should we
  2179. // emulate that badness?
  2180. mangleTemplateArgs(T->getArgs(), T->getNumArgs());
  2181. Out << 'E';
  2182. }
  2183. void CXXNameMangler::mangleType(const TypeOfType *T) {
  2184. // FIXME: this is pretty unsatisfactory, but there isn't an obvious
  2185. // "extension with parameters" mangling.
  2186. Out << "u6typeof";
  2187. }
  2188. void CXXNameMangler::mangleType(const TypeOfExprType *T) {
  2189. // FIXME: this is pretty unsatisfactory, but there isn't an obvious
  2190. // "extension with parameters" mangling.
  2191. Out << "u6typeof";
  2192. }
  2193. void CXXNameMangler::mangleType(const DecltypeType *T) {
  2194. Expr *E = T->getUnderlyingExpr();
  2195. // type ::= Dt <expression> E # decltype of an id-expression
  2196. // # or class member access
  2197. // ::= DT <expression> E # decltype of an expression
  2198. // This purports to be an exhaustive list of id-expressions and
  2199. // class member accesses. Note that we do not ignore parentheses;
  2200. // parentheses change the semantics of decltype for these
  2201. // expressions (and cause the mangler to use the other form).
  2202. if (isa<DeclRefExpr>(E) ||
  2203. isa<MemberExpr>(E) ||
  2204. isa<UnresolvedLookupExpr>(E) ||
  2205. isa<DependentScopeDeclRefExpr>(E) ||
  2206. isa<CXXDependentScopeMemberExpr>(E) ||
  2207. isa<UnresolvedMemberExpr>(E))
  2208. Out << "Dt";
  2209. else
  2210. Out << "DT";
  2211. mangleExpression(E);
  2212. Out << 'E';
  2213. }
  2214. void CXXNameMangler::mangleType(const UnaryTransformType *T) {
  2215. // If this is dependent, we need to record that. If not, we simply
  2216. // mangle it as the underlying type since they are equivalent.
  2217. if (T->isDependentType()) {
  2218. Out << 'U';
  2219. switch (T->getUTTKind()) {
  2220. case UnaryTransformType::EnumUnderlyingType:
  2221. Out << "3eut";
  2222. break;
  2223. }
  2224. }
  2225. mangleType(T->getUnderlyingType());
  2226. }
  2227. void CXXNameMangler::mangleType(const AutoType *T) {
  2228. QualType D = T->getDeducedType();
  2229. // <builtin-type> ::= Da # dependent auto
  2230. if (D.isNull())
  2231. Out << (T->isDecltypeAuto() ? "Dc" : "Da");
  2232. else
  2233. mangleType(D);
  2234. }
  2235. void CXXNameMangler::mangleType(const AtomicType *T) {
  2236. // <type> ::= U <source-name> <type> # vendor extended type qualifier
  2237. // (Until there's a standardized mangling...)
  2238. Out << "U7_Atomic";
  2239. mangleType(T->getValueType());
  2240. }
  2241. void CXXNameMangler::mangleIntegerLiteral(QualType T,
  2242. const llvm::APSInt &Value) {
  2243. // <expr-primary> ::= L <type> <value number> E # integer literal
  2244. Out << 'L';
  2245. mangleType(T);
  2246. if (T->isBooleanType()) {
  2247. // Boolean values are encoded as 0/1.
  2248. Out << (Value.getBoolValue() ? '1' : '0');
  2249. } else {
  2250. mangleNumber(Value);
  2251. }
  2252. Out << 'E';
  2253. }
  2254. void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
  2255. // Ignore member expressions involving anonymous unions.
  2256. while (const auto *RT = Base->getType()->getAs<RecordType>()) {
  2257. if (!RT->getDecl()->isAnonymousStructOrUnion())
  2258. break;
  2259. const auto *ME = dyn_cast<MemberExpr>(Base);
  2260. if (!ME)
  2261. break;
  2262. Base = ME->getBase();
  2263. IsArrow = ME->isArrow();
  2264. }
  2265. if (Base->isImplicitCXXThis()) {
  2266. // Note: GCC mangles member expressions to the implicit 'this' as
  2267. // *this., whereas we represent them as this->. The Itanium C++ ABI
  2268. // does not specify anything here, so we follow GCC.
  2269. Out << "dtdefpT";
  2270. } else {
  2271. Out << (IsArrow ? "pt" : "dt");
  2272. mangleExpression(Base);
  2273. }
  2274. }
  2275. /// Mangles a member expression.
  2276. void CXXNameMangler::mangleMemberExpr(const Expr *base,
  2277. bool isArrow,
  2278. NestedNameSpecifier *qualifier,
  2279. NamedDecl *firstQualifierLookup,
  2280. DeclarationName member,
  2281. unsigned arity) {
  2282. // <expression> ::= dt <expression> <unresolved-name>
  2283. // ::= pt <expression> <unresolved-name>
  2284. if (base)
  2285. mangleMemberExprBase(base, isArrow);
  2286. mangleUnresolvedName(qualifier, member, arity);
  2287. }
  2288. /// Look at the callee of the given call expression and determine if
  2289. /// it's a parenthesized id-expression which would have triggered ADL
  2290. /// otherwise.
  2291. static bool isParenthesizedADLCallee(const CallExpr *call) {
  2292. const Expr *callee = call->getCallee();
  2293. const Expr *fn = callee->IgnoreParens();
  2294. // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
  2295. // too, but for those to appear in the callee, it would have to be
  2296. // parenthesized.
  2297. if (callee == fn) return false;
  2298. // Must be an unresolved lookup.
  2299. const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
  2300. if (!lookup) return false;
  2301. assert(!lookup->requiresADL());
  2302. // Must be an unqualified lookup.
  2303. if (lookup->getQualifier()) return false;
  2304. // Must not have found a class member. Note that if one is a class
  2305. // member, they're all class members.
  2306. if (lookup->getNumDecls() > 0 &&
  2307. (*lookup->decls_begin())->isCXXClassMember())
  2308. return false;
  2309. // Otherwise, ADL would have been triggered.
  2310. return true;
  2311. }
  2312. void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
  2313. const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
  2314. Out << CastEncoding;
  2315. mangleType(ECE->getType());
  2316. mangleExpression(ECE->getSubExpr());
  2317. }
  2318. void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
  2319. if (auto *Syntactic = InitList->getSyntacticForm())
  2320. InitList = Syntactic;
  2321. for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
  2322. mangleExpression(InitList->getInit(i));
  2323. }
  2324. void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
  2325. // <expression> ::= <unary operator-name> <expression>
  2326. // ::= <binary operator-name> <expression> <expression>
  2327. // ::= <trinary operator-name> <expression> <expression> <expression>
  2328. // ::= cv <type> expression # conversion with one argument
  2329. // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
  2330. // ::= dc <type> <expression> # dynamic_cast<type> (expression)
  2331. // ::= sc <type> <expression> # static_cast<type> (expression)
  2332. // ::= cc <type> <expression> # const_cast<type> (expression)
  2333. // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
  2334. // ::= st <type> # sizeof (a type)
  2335. // ::= at <type> # alignof (a type)
  2336. // ::= <template-param>
  2337. // ::= <function-param>
  2338. // ::= sr <type> <unqualified-name> # dependent name
  2339. // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
  2340. // ::= ds <expression> <expression> # expr.*expr
  2341. // ::= sZ <template-param> # size of a parameter pack
  2342. // ::= sZ <function-param> # size of a function parameter pack
  2343. // ::= <expr-primary>
  2344. // <expr-primary> ::= L <type> <value number> E # integer literal
  2345. // ::= L <type <value float> E # floating literal
  2346. // ::= L <mangled-name> E # external name
  2347. // ::= fpT # 'this' expression
  2348. QualType ImplicitlyConvertedToType;
  2349. recurse:
  2350. switch (E->getStmtClass()) {
  2351. case Expr::NoStmtClass:
  2352. #define ABSTRACT_STMT(Type)
  2353. #define EXPR(Type, Base)
  2354. #define STMT(Type, Base) \
  2355. case Expr::Type##Class:
  2356. #include "clang/AST/StmtNodes.inc"
  2357. // fallthrough
  2358. // These all can only appear in local or variable-initialization
  2359. // contexts and so should never appear in a mangling.
  2360. case Expr::AddrLabelExprClass:
  2361. case Expr::DesignatedInitUpdateExprClass:
  2362. case Expr::ImplicitValueInitExprClass:
  2363. case Expr::NoInitExprClass:
  2364. case Expr::ParenListExprClass:
  2365. case Expr::LambdaExprClass:
  2366. case Expr::MSPropertyRefExprClass:
  2367. case Expr::TypoExprClass: // This should no longer exist in the AST by now.
  2368. llvm_unreachable("unexpected statement kind");
  2369. // FIXME: invent manglings for all these.
  2370. case Expr::BlockExprClass:
  2371. case Expr::ChooseExprClass:
  2372. case Expr::CompoundLiteralExprClass:
  2373. case Expr::DesignatedInitExprClass:
  2374. case Expr::ExtVectorElementExprClass:
  2375. case Expr::ExtMatrixElementExprClass: // HLSL Change
  2376. case Expr::HLSLVectorElementExprClass: // HLSL Change
  2377. case Expr::GenericSelectionExprClass:
  2378. case Expr::ObjCEncodeExprClass:
  2379. case Expr::ObjCIsaExprClass:
  2380. case Expr::ObjCIvarRefExprClass:
  2381. case Expr::ObjCMessageExprClass:
  2382. case Expr::ObjCPropertyRefExprClass:
  2383. case Expr::ObjCProtocolExprClass:
  2384. case Expr::ObjCSelectorExprClass:
  2385. case Expr::ObjCStringLiteralClass:
  2386. case Expr::ObjCBoxedExprClass:
  2387. case Expr::ObjCArrayLiteralClass:
  2388. case Expr::ObjCDictionaryLiteralClass:
  2389. case Expr::ObjCSubscriptRefExprClass:
  2390. case Expr::ObjCIndirectCopyRestoreExprClass:
  2391. case Expr::OffsetOfExprClass:
  2392. case Expr::PredefinedExprClass:
  2393. case Expr::ShuffleVectorExprClass:
  2394. case Expr::ConvertVectorExprClass:
  2395. case Expr::StmtExprClass:
  2396. case Expr::TypeTraitExprClass:
  2397. case Expr::ArrayTypeTraitExprClass:
  2398. case Expr::ExpressionTraitExprClass:
  2399. case Expr::VAArgExprClass:
  2400. case Expr::CUDAKernelCallExprClass:
  2401. case Expr::AsTypeExprClass:
  2402. case Expr::PseudoObjectExprClass:
  2403. case Expr::AtomicExprClass:
  2404. {
  2405. // As bad as this diagnostic is, it's better than crashing.
  2406. DiagnosticsEngine &Diags = Context.getDiags();
  2407. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2408. "cannot yet mangle expression type %0");
  2409. Diags.Report(E->getExprLoc(), DiagID)
  2410. << E->getStmtClassName() << E->getSourceRange();
  2411. break;
  2412. }
  2413. case Expr::CXXUuidofExprClass: {
  2414. const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
  2415. if (UE->isTypeOperand()) {
  2416. QualType UuidT = UE->getTypeOperand(Context.getASTContext());
  2417. Out << "u8__uuidoft";
  2418. mangleType(UuidT);
  2419. } else {
  2420. Expr *UuidExp = UE->getExprOperand();
  2421. Out << "u8__uuidofz";
  2422. mangleExpression(UuidExp, Arity);
  2423. }
  2424. break;
  2425. }
  2426. // Even gcc-4.5 doesn't mangle this.
  2427. case Expr::BinaryConditionalOperatorClass: {
  2428. DiagnosticsEngine &Diags = Context.getDiags();
  2429. unsigned DiagID =
  2430. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2431. "?: operator with omitted middle operand cannot be mangled");
  2432. Diags.Report(E->getExprLoc(), DiagID)
  2433. << E->getStmtClassName() << E->getSourceRange();
  2434. break;
  2435. }
  2436. // These are used for internal purposes and cannot be meaningfully mangled.
  2437. case Expr::OpaqueValueExprClass:
  2438. llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
  2439. case Expr::InitListExprClass: {
  2440. Out << "il";
  2441. mangleInitListElements(cast<InitListExpr>(E));
  2442. Out << "E";
  2443. break;
  2444. }
  2445. case Expr::CXXDefaultArgExprClass:
  2446. mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
  2447. break;
  2448. case Expr::CXXDefaultInitExprClass:
  2449. mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
  2450. break;
  2451. case Expr::CXXStdInitializerListExprClass:
  2452. mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
  2453. break;
  2454. case Expr::SubstNonTypeTemplateParmExprClass:
  2455. mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
  2456. Arity);
  2457. break;
  2458. case Expr::UserDefinedLiteralClass:
  2459. // We follow g++'s approach of mangling a UDL as a call to the literal
  2460. // operator.
  2461. case Expr::CXXMemberCallExprClass: // fallthrough
  2462. case Expr::CallExprClass: {
  2463. const CallExpr *CE = cast<CallExpr>(E);
  2464. // <expression> ::= cp <simple-id> <expression>* E
  2465. // We use this mangling only when the call would use ADL except
  2466. // for being parenthesized. Per discussion with David
  2467. // Vandervoorde, 2011.04.25.
  2468. if (isParenthesizedADLCallee(CE)) {
  2469. Out << "cp";
  2470. // The callee here is a parenthesized UnresolvedLookupExpr with
  2471. // no qualifier and should always get mangled as a <simple-id>
  2472. // anyway.
  2473. // <expression> ::= cl <expression>* E
  2474. } else {
  2475. Out << "cl";
  2476. }
  2477. unsigned CallArity = CE->getNumArgs();
  2478. for (const Expr *Arg : CE->arguments())
  2479. if (isa<PackExpansionExpr>(Arg))
  2480. CallArity = UnknownArity;
  2481. mangleExpression(CE->getCallee(), CallArity);
  2482. for (const Expr *Arg : CE->arguments())
  2483. mangleExpression(Arg);
  2484. Out << 'E';
  2485. break;
  2486. }
  2487. case Expr::CXXNewExprClass: {
  2488. const CXXNewExpr *New = cast<CXXNewExpr>(E);
  2489. if (New->isGlobalNew()) Out << "gs";
  2490. Out << (New->isArray() ? "na" : "nw");
  2491. for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
  2492. E = New->placement_arg_end(); I != E; ++I)
  2493. mangleExpression(*I);
  2494. Out << '_';
  2495. mangleType(New->getAllocatedType());
  2496. if (New->hasInitializer()) {
  2497. if (New->getInitializationStyle() == CXXNewExpr::ListInit)
  2498. Out << "il";
  2499. else
  2500. Out << "pi";
  2501. const Expr *Init = New->getInitializer();
  2502. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
  2503. // Directly inline the initializers.
  2504. for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
  2505. E = CCE->arg_end();
  2506. I != E; ++I)
  2507. mangleExpression(*I);
  2508. } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
  2509. for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
  2510. mangleExpression(PLE->getExpr(i));
  2511. } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
  2512. isa<InitListExpr>(Init)) {
  2513. // Only take InitListExprs apart for list-initialization.
  2514. mangleInitListElements(cast<InitListExpr>(Init));
  2515. } else
  2516. mangleExpression(Init);
  2517. }
  2518. Out << 'E';
  2519. break;
  2520. }
  2521. case Expr::CXXPseudoDestructorExprClass: {
  2522. const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
  2523. if (const Expr *Base = PDE->getBase())
  2524. mangleMemberExprBase(Base, PDE->isArrow());
  2525. NestedNameSpecifier *Qualifier = PDE->getQualifier();
  2526. QualType ScopeType;
  2527. if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
  2528. if (Qualifier) {
  2529. mangleUnresolvedPrefix(Qualifier,
  2530. /*Recursive=*/true);
  2531. mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
  2532. Out << 'E';
  2533. } else {
  2534. Out << "sr";
  2535. if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
  2536. Out << 'E';
  2537. }
  2538. } else if (Qualifier) {
  2539. mangleUnresolvedPrefix(Qualifier);
  2540. }
  2541. // <base-unresolved-name> ::= dn <destructor-name>
  2542. Out << "dn";
  2543. QualType DestroyedType = PDE->getDestroyedType();
  2544. mangleUnresolvedTypeOrSimpleId(DestroyedType);
  2545. break;
  2546. }
  2547. case Expr::MemberExprClass: {
  2548. const MemberExpr *ME = cast<MemberExpr>(E);
  2549. mangleMemberExpr(ME->getBase(), ME->isArrow(),
  2550. ME->getQualifier(), nullptr,
  2551. ME->getMemberDecl()->getDeclName(), Arity);
  2552. break;
  2553. }
  2554. case Expr::UnresolvedMemberExprClass: {
  2555. const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
  2556. mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
  2557. ME->isArrow(), ME->getQualifier(), nullptr,
  2558. ME->getMemberName(), Arity);
  2559. if (ME->hasExplicitTemplateArgs())
  2560. mangleTemplateArgs(ME->getExplicitTemplateArgs());
  2561. break;
  2562. }
  2563. case Expr::CXXDependentScopeMemberExprClass: {
  2564. const CXXDependentScopeMemberExpr *ME
  2565. = cast<CXXDependentScopeMemberExpr>(E);
  2566. mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
  2567. ME->isArrow(), ME->getQualifier(),
  2568. ME->getFirstQualifierFoundInScope(),
  2569. ME->getMember(), Arity);
  2570. if (ME->hasExplicitTemplateArgs())
  2571. mangleTemplateArgs(ME->getExplicitTemplateArgs());
  2572. break;
  2573. }
  2574. case Expr::UnresolvedLookupExprClass: {
  2575. const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
  2576. mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
  2577. // All the <unresolved-name> productions end in a
  2578. // base-unresolved-name, where <template-args> are just tacked
  2579. // onto the end.
  2580. if (ULE->hasExplicitTemplateArgs())
  2581. mangleTemplateArgs(ULE->getExplicitTemplateArgs());
  2582. break;
  2583. }
  2584. case Expr::CXXUnresolvedConstructExprClass: {
  2585. const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
  2586. unsigned N = CE->arg_size();
  2587. Out << "cv";
  2588. mangleType(CE->getType());
  2589. if (N != 1) Out << '_';
  2590. for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
  2591. if (N != 1) Out << 'E';
  2592. break;
  2593. }
  2594. case Expr::CXXConstructExprClass: {
  2595. const auto *CE = cast<CXXConstructExpr>(E);
  2596. if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
  2597. assert(
  2598. CE->getNumArgs() >= 1 &&
  2599. (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
  2600. "implicit CXXConstructExpr must have one argument");
  2601. return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
  2602. }
  2603. Out << "il";
  2604. for (auto *E : CE->arguments())
  2605. mangleExpression(E);
  2606. Out << "E";
  2607. break;
  2608. }
  2609. case Expr::CXXTemporaryObjectExprClass: {
  2610. const auto *CE = cast<CXXTemporaryObjectExpr>(E);
  2611. unsigned N = CE->getNumArgs();
  2612. bool List = CE->isListInitialization();
  2613. if (List)
  2614. Out << "tl";
  2615. else
  2616. Out << "cv";
  2617. mangleType(CE->getType());
  2618. if (!List && N != 1)
  2619. Out << '_';
  2620. if (CE->isStdInitListInitialization()) {
  2621. // We implicitly created a std::initializer_list<T> for the first argument
  2622. // of a constructor of type U in an expression of the form U{a, b, c}.
  2623. // Strip all the semantic gunk off the initializer list.
  2624. auto *SILE =
  2625. cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
  2626. auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
  2627. mangleInitListElements(ILE);
  2628. } else {
  2629. for (auto *E : CE->arguments())
  2630. mangleExpression(E);
  2631. }
  2632. if (List || N != 1)
  2633. Out << 'E';
  2634. break;
  2635. }
  2636. case Expr::CXXScalarValueInitExprClass:
  2637. Out << "cv";
  2638. mangleType(E->getType());
  2639. Out << "_E";
  2640. break;
  2641. case Expr::CXXNoexceptExprClass:
  2642. Out << "nx";
  2643. mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
  2644. break;
  2645. case Expr::UnaryExprOrTypeTraitExprClass: {
  2646. const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
  2647. if (!SAE->isInstantiationDependent()) {
  2648. // Itanium C++ ABI:
  2649. // If the operand of a sizeof or alignof operator is not
  2650. // instantiation-dependent it is encoded as an integer literal
  2651. // reflecting the result of the operator.
  2652. //
  2653. // If the result of the operator is implicitly converted to a known
  2654. // integer type, that type is used for the literal; otherwise, the type
  2655. // of std::size_t or std::ptrdiff_t is used.
  2656. QualType T = (ImplicitlyConvertedToType.isNull() ||
  2657. !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
  2658. : ImplicitlyConvertedToType;
  2659. llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
  2660. mangleIntegerLiteral(T, V);
  2661. break;
  2662. }
  2663. switch(SAE->getKind()) {
  2664. case UETT_SizeOf:
  2665. Out << 's';
  2666. break;
  2667. case UETT_AlignOf:
  2668. Out << 'a';
  2669. break;
  2670. case UETT_VecStep: {
  2671. DiagnosticsEngine &Diags = Context.getDiags();
  2672. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2673. "cannot yet mangle vec_step expression");
  2674. Diags.Report(DiagID);
  2675. return;
  2676. }
  2677. case UETT_OpenMPRequiredSimdAlign: {
  2678. DiagnosticsEngine &Diags = Context.getDiags();
  2679. unsigned DiagID = Diags.getCustomDiagID(
  2680. DiagnosticsEngine::Error,
  2681. "cannot yet mangle __builtin_omp_required_simd_align expression");
  2682. Diags.Report(DiagID);
  2683. return;
  2684. }
  2685. // HLSL Change Begins
  2686. case UETT_ArrayLength: {
  2687. DiagnosticsEngine & Diags = Context.getDiags();
  2688. unsigned DiagID = Diags.getCustomDiagID(
  2689. DiagnosticsEngine::Error,
  2690. "cannot yet mangle .Length expression");
  2691. Diags.Report(DiagID);
  2692. return;
  2693. }
  2694. // HLSL Change Begins
  2695. }
  2696. if (SAE->isArgumentType()) {
  2697. Out << 't';
  2698. mangleType(SAE->getArgumentType());
  2699. } else {
  2700. Out << 'z';
  2701. mangleExpression(SAE->getArgumentExpr());
  2702. }
  2703. break;
  2704. }
  2705. case Expr::CXXThrowExprClass: {
  2706. const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
  2707. // <expression> ::= tw <expression> # throw expression
  2708. // ::= tr # rethrow
  2709. if (TE->getSubExpr()) {
  2710. Out << "tw";
  2711. mangleExpression(TE->getSubExpr());
  2712. } else {
  2713. Out << "tr";
  2714. }
  2715. break;
  2716. }
  2717. case Expr::CXXTypeidExprClass: {
  2718. const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
  2719. // <expression> ::= ti <type> # typeid (type)
  2720. // ::= te <expression> # typeid (expression)
  2721. if (TIE->isTypeOperand()) {
  2722. Out << "ti";
  2723. mangleType(TIE->getTypeOperand(Context.getASTContext()));
  2724. } else {
  2725. Out << "te";
  2726. mangleExpression(TIE->getExprOperand());
  2727. }
  2728. break;
  2729. }
  2730. case Expr::CXXDeleteExprClass: {
  2731. const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
  2732. // <expression> ::= [gs] dl <expression> # [::] delete expr
  2733. // ::= [gs] da <expression> # [::] delete [] expr
  2734. if (DE->isGlobalDelete()) Out << "gs";
  2735. Out << (DE->isArrayForm() ? "da" : "dl");
  2736. mangleExpression(DE->getArgument());
  2737. break;
  2738. }
  2739. case Expr::UnaryOperatorClass: {
  2740. const UnaryOperator *UO = cast<UnaryOperator>(E);
  2741. mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
  2742. /*Arity=*/1);
  2743. mangleExpression(UO->getSubExpr());
  2744. break;
  2745. }
  2746. case Expr::ArraySubscriptExprClass: {
  2747. const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
  2748. // Array subscript is treated as a syntactically weird form of
  2749. // binary operator.
  2750. Out << "ix";
  2751. mangleExpression(AE->getLHS());
  2752. mangleExpression(AE->getRHS());
  2753. break;
  2754. }
  2755. case Expr::CompoundAssignOperatorClass: // fallthrough
  2756. case Expr::BinaryOperatorClass: {
  2757. const BinaryOperator *BO = cast<BinaryOperator>(E);
  2758. if (BO->getOpcode() == BO_PtrMemD)
  2759. Out << "ds";
  2760. else
  2761. mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
  2762. /*Arity=*/2);
  2763. mangleExpression(BO->getLHS());
  2764. mangleExpression(BO->getRHS());
  2765. break;
  2766. }
  2767. case Expr::ConditionalOperatorClass: {
  2768. const ConditionalOperator *CO = cast<ConditionalOperator>(E);
  2769. mangleOperatorName(OO_Conditional, /*Arity=*/3);
  2770. mangleExpression(CO->getCond());
  2771. mangleExpression(CO->getLHS(), Arity);
  2772. mangleExpression(CO->getRHS(), Arity);
  2773. break;
  2774. }
  2775. case Expr::ImplicitCastExprClass: {
  2776. ImplicitlyConvertedToType = E->getType();
  2777. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  2778. goto recurse;
  2779. }
  2780. case Expr::ObjCBridgedCastExprClass: {
  2781. // Mangle ownership casts as a vendor extended operator __bridge,
  2782. // __bridge_transfer, or __bridge_retain.
  2783. StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
  2784. Out << "v1U" << Kind.size() << Kind;
  2785. }
  2786. // Fall through to mangle the cast itself.
  2787. case Expr::CStyleCastExprClass:
  2788. mangleCastExpression(E, "cv");
  2789. break;
  2790. case Expr::CXXFunctionalCastExprClass: {
  2791. auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
  2792. // FIXME: Add isImplicit to CXXConstructExpr.
  2793. if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
  2794. if (CCE->getParenOrBraceRange().isInvalid())
  2795. Sub = CCE->getArg(0)->IgnoreImplicit();
  2796. if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
  2797. Sub = StdInitList->getSubExpr()->IgnoreImplicit();
  2798. if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
  2799. Out << "tl";
  2800. mangleType(E->getType());
  2801. mangleInitListElements(IL);
  2802. Out << "E";
  2803. } else {
  2804. mangleCastExpression(E, "cv");
  2805. }
  2806. break;
  2807. }
  2808. case Expr::CXXStaticCastExprClass:
  2809. mangleCastExpression(E, "sc");
  2810. break;
  2811. case Expr::CXXDynamicCastExprClass:
  2812. mangleCastExpression(E, "dc");
  2813. break;
  2814. case Expr::CXXReinterpretCastExprClass:
  2815. mangleCastExpression(E, "rc");
  2816. break;
  2817. case Expr::CXXConstCastExprClass:
  2818. mangleCastExpression(E, "cc");
  2819. break;
  2820. case Expr::CXXOperatorCallExprClass: {
  2821. const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
  2822. unsigned NumArgs = CE->getNumArgs();
  2823. mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
  2824. // Mangle the arguments.
  2825. for (unsigned i = 0; i != NumArgs; ++i)
  2826. mangleExpression(CE->getArg(i));
  2827. break;
  2828. }
  2829. case Expr::ParenExprClass:
  2830. mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
  2831. break;
  2832. case Expr::DeclRefExprClass: {
  2833. const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
  2834. switch (D->getKind()) {
  2835. default:
  2836. // <expr-primary> ::= L <mangled-name> E # external name
  2837. Out << 'L';
  2838. mangle(D);
  2839. Out << 'E';
  2840. break;
  2841. case Decl::ParmVar:
  2842. mangleFunctionParam(cast<ParmVarDecl>(D));
  2843. break;
  2844. case Decl::EnumConstant: {
  2845. const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
  2846. mangleIntegerLiteral(ED->getType(), ED->getInitVal());
  2847. break;
  2848. }
  2849. case Decl::NonTypeTemplateParm: {
  2850. const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
  2851. mangleTemplateParameter(PD->getIndex());
  2852. break;
  2853. }
  2854. }
  2855. break;
  2856. }
  2857. case Expr::SubstNonTypeTemplateParmPackExprClass:
  2858. // FIXME: not clear how to mangle this!
  2859. // template <unsigned N...> class A {
  2860. // template <class U...> void foo(U (&x)[N]...);
  2861. // };
  2862. Out << "_SUBSTPACK_";
  2863. break;
  2864. case Expr::FunctionParmPackExprClass: {
  2865. // FIXME: not clear how to mangle this!
  2866. const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
  2867. Out << "v110_SUBSTPACK";
  2868. mangleFunctionParam(FPPE->getParameterPack());
  2869. break;
  2870. }
  2871. case Expr::DependentScopeDeclRefExprClass: {
  2872. const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
  2873. mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
  2874. // All the <unresolved-name> productions end in a
  2875. // base-unresolved-name, where <template-args> are just tacked
  2876. // onto the end.
  2877. if (DRE->hasExplicitTemplateArgs())
  2878. mangleTemplateArgs(DRE->getExplicitTemplateArgs());
  2879. break;
  2880. }
  2881. case Expr::CXXBindTemporaryExprClass:
  2882. mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
  2883. break;
  2884. case Expr::ExprWithCleanupsClass:
  2885. mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
  2886. break;
  2887. case Expr::FloatingLiteralClass: {
  2888. const FloatingLiteral *FL = cast<FloatingLiteral>(E);
  2889. Out << 'L';
  2890. mangleType(FL->getType());
  2891. mangleFloat(FL->getValue());
  2892. Out << 'E';
  2893. break;
  2894. }
  2895. case Expr::CharacterLiteralClass:
  2896. Out << 'L';
  2897. mangleType(E->getType());
  2898. Out << cast<CharacterLiteral>(E)->getValue();
  2899. Out << 'E';
  2900. break;
  2901. // FIXME. __objc_yes/__objc_no are mangled same as true/false
  2902. case Expr::ObjCBoolLiteralExprClass:
  2903. Out << "Lb";
  2904. Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
  2905. Out << 'E';
  2906. break;
  2907. case Expr::CXXBoolLiteralExprClass:
  2908. Out << "Lb";
  2909. Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
  2910. Out << 'E';
  2911. break;
  2912. case Expr::IntegerLiteralClass: {
  2913. llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
  2914. if (E->getType()->isSignedIntegerType())
  2915. Value.setIsSigned(true);
  2916. mangleIntegerLiteral(E->getType(), Value);
  2917. break;
  2918. }
  2919. case Expr::ImaginaryLiteralClass: {
  2920. const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
  2921. // Mangle as if a complex literal.
  2922. // Proposal from David Vandevoorde, 2010.06.30.
  2923. Out << 'L';
  2924. mangleType(E->getType());
  2925. if (const FloatingLiteral *Imag =
  2926. dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
  2927. // Mangle a floating-point zero of the appropriate type.
  2928. mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
  2929. Out << '_';
  2930. mangleFloat(Imag->getValue());
  2931. } else {
  2932. Out << "0_";
  2933. llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
  2934. if (IE->getSubExpr()->getType()->isSignedIntegerType())
  2935. Value.setIsSigned(true);
  2936. mangleNumber(Value);
  2937. }
  2938. Out << 'E';
  2939. break;
  2940. }
  2941. case Expr::StringLiteralClass: {
  2942. // Revised proposal from David Vandervoorde, 2010.07.15.
  2943. Out << 'L';
  2944. assert(isa<ConstantArrayType>(E->getType()));
  2945. mangleType(E->getType());
  2946. Out << 'E';
  2947. break;
  2948. }
  2949. case Expr::GNUNullExprClass:
  2950. // FIXME: should this really be mangled the same as nullptr?
  2951. // fallthrough
  2952. case Expr::CXXNullPtrLiteralExprClass: {
  2953. Out << "LDnE";
  2954. break;
  2955. }
  2956. case Expr::PackExpansionExprClass:
  2957. Out << "sp";
  2958. mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
  2959. break;
  2960. case Expr::SizeOfPackExprClass: {
  2961. Out << "sZ";
  2962. const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
  2963. if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
  2964. mangleTemplateParameter(TTP->getIndex());
  2965. else if (const NonTypeTemplateParmDecl *NTTP
  2966. = dyn_cast<NonTypeTemplateParmDecl>(Pack))
  2967. mangleTemplateParameter(NTTP->getIndex());
  2968. else if (const TemplateTemplateParmDecl *TempTP
  2969. = dyn_cast<TemplateTemplateParmDecl>(Pack))
  2970. mangleTemplateParameter(TempTP->getIndex());
  2971. else
  2972. mangleFunctionParam(cast<ParmVarDecl>(Pack));
  2973. break;
  2974. }
  2975. case Expr::MaterializeTemporaryExprClass: {
  2976. mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
  2977. break;
  2978. }
  2979. case Expr::CXXFoldExprClass: {
  2980. auto *FE = cast<CXXFoldExpr>(E);
  2981. if (FE->isLeftFold())
  2982. Out << (FE->getInit() ? "fL" : "fl");
  2983. else
  2984. Out << (FE->getInit() ? "fR" : "fr");
  2985. if (FE->getOperator() == BO_PtrMemD)
  2986. Out << "ds";
  2987. else
  2988. mangleOperatorName(
  2989. BinaryOperator::getOverloadedOperator(FE->getOperator()),
  2990. /*Arity=*/2);
  2991. if (FE->getLHS())
  2992. mangleExpression(FE->getLHS());
  2993. if (FE->getRHS())
  2994. mangleExpression(FE->getRHS());
  2995. break;
  2996. }
  2997. case Expr::CXXThisExprClass:
  2998. Out << "fpT";
  2999. break;
  3000. }
  3001. }
  3002. /// Mangle an expression which refers to a parameter variable.
  3003. ///
  3004. /// <expression> ::= <function-param>
  3005. /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
  3006. /// <function-param> ::= fp <top-level CV-qualifiers>
  3007. /// <parameter-2 non-negative number> _ # L == 0, I > 0
  3008. /// <function-param> ::= fL <L-1 non-negative number>
  3009. /// p <top-level CV-qualifiers> _ # L > 0, I == 0
  3010. /// <function-param> ::= fL <L-1 non-negative number>
  3011. /// p <top-level CV-qualifiers>
  3012. /// <I-1 non-negative number> _ # L > 0, I > 0
  3013. ///
  3014. /// L is the nesting depth of the parameter, defined as 1 if the
  3015. /// parameter comes from the innermost function prototype scope
  3016. /// enclosing the current context, 2 if from the next enclosing
  3017. /// function prototype scope, and so on, with one special case: if
  3018. /// we've processed the full parameter clause for the innermost
  3019. /// function type, then L is one less. This definition conveniently
  3020. /// makes it irrelevant whether a function's result type was written
  3021. /// trailing or leading, but is otherwise overly complicated; the
  3022. /// numbering was first designed without considering references to
  3023. /// parameter in locations other than return types, and then the
  3024. /// mangling had to be generalized without changing the existing
  3025. /// manglings.
  3026. ///
  3027. /// I is the zero-based index of the parameter within its parameter
  3028. /// declaration clause. Note that the original ABI document describes
  3029. /// this using 1-based ordinals.
  3030. void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
  3031. unsigned parmDepth = parm->getFunctionScopeDepth();
  3032. unsigned parmIndex = parm->getFunctionScopeIndex();
  3033. // Compute 'L'.
  3034. // parmDepth does not include the declaring function prototype.
  3035. // FunctionTypeDepth does account for that.
  3036. assert(parmDepth < FunctionTypeDepth.getDepth());
  3037. unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
  3038. if (FunctionTypeDepth.isInResultType())
  3039. nestingDepth--;
  3040. if (nestingDepth == 0) {
  3041. Out << "fp";
  3042. } else {
  3043. Out << "fL" << (nestingDepth - 1) << 'p';
  3044. }
  3045. // Top-level qualifiers. We don't have to worry about arrays here,
  3046. // because parameters declared as arrays should already have been
  3047. // transformed to have pointer type. FIXME: apparently these don't
  3048. // get mangled if used as an rvalue of a known non-class type?
  3049. assert(!parm->getType()->isArrayType()
  3050. && "parameter's type is still an array type?");
  3051. mangleQualifiers(parm->getType().getQualifiers());
  3052. // Parameter index.
  3053. if (parmIndex != 0) {
  3054. Out << (parmIndex - 1);
  3055. }
  3056. Out << '_';
  3057. }
  3058. void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
  3059. // <ctor-dtor-name> ::= C1 # complete object constructor
  3060. // ::= C2 # base object constructor
  3061. //
  3062. // In addition, C5 is a comdat name with C1 and C2 in it.
  3063. switch (T) {
  3064. case Ctor_Complete:
  3065. Out << "C1";
  3066. break;
  3067. case Ctor_Base:
  3068. Out << "C2";
  3069. break;
  3070. case Ctor_Comdat:
  3071. Out << "C5";
  3072. break;
  3073. case Ctor_DefaultClosure:
  3074. case Ctor_CopyingClosure:
  3075. llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
  3076. }
  3077. }
  3078. void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
  3079. // <ctor-dtor-name> ::= D0 # deleting destructor
  3080. // ::= D1 # complete object destructor
  3081. // ::= D2 # base object destructor
  3082. //
  3083. // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
  3084. switch (T) {
  3085. case Dtor_Deleting:
  3086. Out << "D0";
  3087. break;
  3088. case Dtor_Complete:
  3089. Out << "D1";
  3090. break;
  3091. case Dtor_Base:
  3092. Out << "D2";
  3093. break;
  3094. case Dtor_Comdat:
  3095. Out << "D5";
  3096. break;
  3097. }
  3098. }
  3099. void CXXNameMangler::mangleTemplateArgs(
  3100. const ASTTemplateArgumentListInfo &TemplateArgs) {
  3101. // <template-args> ::= I <template-arg>+ E
  3102. Out << 'I';
  3103. for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
  3104. mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
  3105. Out << 'E';
  3106. }
  3107. void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
  3108. // <template-args> ::= I <template-arg>+ E
  3109. Out << 'I';
  3110. for (unsigned i = 0, e = AL.size(); i != e; ++i)
  3111. mangleTemplateArg(AL[i]);
  3112. Out << 'E';
  3113. }
  3114. void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
  3115. unsigned NumTemplateArgs) {
  3116. // <template-args> ::= I <template-arg>+ E
  3117. Out << 'I';
  3118. for (unsigned i = 0; i != NumTemplateArgs; ++i)
  3119. mangleTemplateArg(TemplateArgs[i]);
  3120. Out << 'E';
  3121. }
  3122. void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
  3123. // <template-arg> ::= <type> # type or template
  3124. // ::= X <expression> E # expression
  3125. // ::= <expr-primary> # simple expressions
  3126. // ::= J <template-arg>* E # argument pack
  3127. if (!A.isInstantiationDependent() || A.isDependent())
  3128. A = Context.getASTContext().getCanonicalTemplateArgument(A);
  3129. switch (A.getKind()) {
  3130. case TemplateArgument::Null:
  3131. llvm_unreachable("Cannot mangle NULL template argument");
  3132. case TemplateArgument::Type:
  3133. mangleType(A.getAsType());
  3134. break;
  3135. case TemplateArgument::Template:
  3136. // This is mangled as <type>.
  3137. mangleType(A.getAsTemplate());
  3138. break;
  3139. case TemplateArgument::TemplateExpansion:
  3140. // <type> ::= Dp <type> # pack expansion (C++0x)
  3141. Out << "Dp";
  3142. mangleType(A.getAsTemplateOrTemplatePattern());
  3143. break;
  3144. case TemplateArgument::Expression: {
  3145. // It's possible to end up with a DeclRefExpr here in certain
  3146. // dependent cases, in which case we should mangle as a
  3147. // declaration.
  3148. const Expr *E = A.getAsExpr()->IgnoreParens();
  3149. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3150. const ValueDecl *D = DRE->getDecl();
  3151. if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
  3152. Out << 'L';
  3153. mangle(D);
  3154. Out << 'E';
  3155. break;
  3156. }
  3157. }
  3158. Out << 'X';
  3159. mangleExpression(E);
  3160. Out << 'E';
  3161. break;
  3162. }
  3163. case TemplateArgument::Integral:
  3164. mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
  3165. break;
  3166. case TemplateArgument::Declaration: {
  3167. // <expr-primary> ::= L <mangled-name> E # external name
  3168. // Clang produces AST's where pointer-to-member-function expressions
  3169. // and pointer-to-function expressions are represented as a declaration not
  3170. // an expression. We compensate for it here to produce the correct mangling.
  3171. ValueDecl *D = A.getAsDecl();
  3172. bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
  3173. if (compensateMangling) {
  3174. Out << 'X';
  3175. mangleOperatorName(OO_Amp, 1);
  3176. }
  3177. Out << 'L';
  3178. // References to external entities use the mangled name; if the name would
  3179. // not normally be manged then mangle it as unqualified.
  3180. mangle(D);
  3181. Out << 'E';
  3182. if (compensateMangling)
  3183. Out << 'E';
  3184. break;
  3185. }
  3186. case TemplateArgument::NullPtr: {
  3187. // <expr-primary> ::= L <type> 0 E
  3188. Out << 'L';
  3189. mangleType(A.getNullPtrType());
  3190. Out << "0E";
  3191. break;
  3192. }
  3193. case TemplateArgument::Pack: {
  3194. // <template-arg> ::= J <template-arg>* E
  3195. Out << 'J';
  3196. for (const auto &P : A.pack_elements())
  3197. mangleTemplateArg(P);
  3198. Out << 'E';
  3199. }
  3200. }
  3201. }
  3202. void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
  3203. // <template-param> ::= T_ # first template parameter
  3204. // ::= T <parameter-2 non-negative number> _
  3205. if (Index == 0)
  3206. Out << "T_";
  3207. else
  3208. Out << 'T' << (Index - 1) << '_';
  3209. }
  3210. void CXXNameMangler::mangleSeqID(unsigned SeqID) {
  3211. if (SeqID == 1)
  3212. Out << '0';
  3213. else if (SeqID > 1) {
  3214. SeqID--;
  3215. // <seq-id> is encoded in base-36, using digits and upper case letters.
  3216. char Buffer[7]; // log(2**32) / log(36) ~= 7
  3217. MutableArrayRef<char> BufferRef(Buffer);
  3218. MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
  3219. for (; SeqID != 0; SeqID /= 36) {
  3220. unsigned C = SeqID % 36;
  3221. *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
  3222. }
  3223. Out.write(I.base(), I - BufferRef.rbegin());
  3224. }
  3225. Out << '_';
  3226. }
  3227. void CXXNameMangler::mangleExistingSubstitution(QualType type) {
  3228. bool result = mangleSubstitution(type);
  3229. assert(result && "no existing substitution for type");
  3230. (void) result;
  3231. }
  3232. void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
  3233. bool result = mangleSubstitution(tname);
  3234. assert(result && "no existing substitution for template name");
  3235. (void) result;
  3236. }
  3237. // <substitution> ::= S <seq-id> _
  3238. // ::= S_
  3239. bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
  3240. // Try one of the standard substitutions first.
  3241. if (mangleStandardSubstitution(ND))
  3242. return true;
  3243. ND = cast<NamedDecl>(ND->getCanonicalDecl());
  3244. return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
  3245. }
  3246. /// Determine whether the given type has any qualifiers that are relevant for
  3247. /// substitutions.
  3248. static bool hasMangledSubstitutionQualifiers(QualType T) {
  3249. Qualifiers Qs = T.getQualifiers();
  3250. return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
  3251. }
  3252. bool CXXNameMangler::mangleSubstitution(QualType T) {
  3253. if (!hasMangledSubstitutionQualifiers(T)) {
  3254. if (const RecordType *RT = T->getAs<RecordType>())
  3255. return mangleSubstitution(RT->getDecl());
  3256. }
  3257. uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
  3258. return mangleSubstitution(TypePtr);
  3259. }
  3260. bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
  3261. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  3262. return mangleSubstitution(TD);
  3263. Template = Context.getASTContext().getCanonicalTemplateName(Template);
  3264. return mangleSubstitution(
  3265. reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
  3266. }
  3267. bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
  3268. llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
  3269. if (I == Substitutions.end())
  3270. return false;
  3271. unsigned SeqID = I->second;
  3272. Out << 'S';
  3273. mangleSeqID(SeqID);
  3274. return true;
  3275. }
  3276. static bool isCharType(QualType T) {
  3277. if (T.isNull())
  3278. return false;
  3279. return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3280. T->isSpecificBuiltinType(BuiltinType::Char_U);
  3281. }
  3282. /// Returns whether a given type is a template specialization of a given name
  3283. /// with a single argument of type char.
  3284. static bool isCharSpecialization(QualType T, const char *Name) {
  3285. if (T.isNull())
  3286. return false;
  3287. const RecordType *RT = T->getAs<RecordType>();
  3288. if (!RT)
  3289. return false;
  3290. const ClassTemplateSpecializationDecl *SD =
  3291. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  3292. if (!SD)
  3293. return false;
  3294. if (!isStdNamespace(getEffectiveDeclContext(SD)))
  3295. return false;
  3296. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  3297. if (TemplateArgs.size() != 1)
  3298. return false;
  3299. if (!isCharType(TemplateArgs[0].getAsType()))
  3300. return false;
  3301. return SD->getIdentifier()->getName() == Name;
  3302. }
  3303. template <std::size_t StrLen>
  3304. static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
  3305. const char (&Str)[StrLen]) {
  3306. if (!SD->getIdentifier()->isStr(Str))
  3307. return false;
  3308. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  3309. if (TemplateArgs.size() != 2)
  3310. return false;
  3311. if (!isCharType(TemplateArgs[0].getAsType()))
  3312. return false;
  3313. if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
  3314. return false;
  3315. return true;
  3316. }
  3317. bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
  3318. // <substitution> ::= St # ::std::
  3319. if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
  3320. if (isStd(NS)) {
  3321. Out << "St";
  3322. return true;
  3323. }
  3324. }
  3325. if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
  3326. if (!isStdNamespace(getEffectiveDeclContext(TD)))
  3327. return false;
  3328. // <substitution> ::= Sa # ::std::allocator
  3329. if (TD->getIdentifier()->isStr("allocator")) {
  3330. Out << "Sa";
  3331. return true;
  3332. }
  3333. // <<substitution> ::= Sb # ::std::basic_string
  3334. if (TD->getIdentifier()->isStr("basic_string")) {
  3335. Out << "Sb";
  3336. return true;
  3337. }
  3338. }
  3339. if (const ClassTemplateSpecializationDecl *SD =
  3340. dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  3341. if (!isStdNamespace(getEffectiveDeclContext(SD)))
  3342. return false;
  3343. // <substitution> ::= Ss # ::std::basic_string<char,
  3344. // ::std::char_traits<char>,
  3345. // ::std::allocator<char> >
  3346. if (SD->getIdentifier()->isStr("basic_string")) {
  3347. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  3348. if (TemplateArgs.size() != 3)
  3349. return false;
  3350. if (!isCharType(TemplateArgs[0].getAsType()))
  3351. return false;
  3352. if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
  3353. return false;
  3354. if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
  3355. return false;
  3356. Out << "Ss";
  3357. return true;
  3358. }
  3359. // <substitution> ::= Si # ::std::basic_istream<char,
  3360. // ::std::char_traits<char> >
  3361. if (isStreamCharSpecialization(SD, "basic_istream")) {
  3362. Out << "Si";
  3363. return true;
  3364. }
  3365. // <substitution> ::= So # ::std::basic_ostream<char,
  3366. // ::std::char_traits<char> >
  3367. if (isStreamCharSpecialization(SD, "basic_ostream")) {
  3368. Out << "So";
  3369. return true;
  3370. }
  3371. // <substitution> ::= Sd # ::std::basic_iostream<char,
  3372. // ::std::char_traits<char> >
  3373. if (isStreamCharSpecialization(SD, "basic_iostream")) {
  3374. Out << "Sd";
  3375. return true;
  3376. }
  3377. }
  3378. return false;
  3379. }
  3380. void CXXNameMangler::addSubstitution(QualType T) {
  3381. if (!hasMangledSubstitutionQualifiers(T)) {
  3382. if (const RecordType *RT = T->getAs<RecordType>()) {
  3383. addSubstitution(RT->getDecl());
  3384. return;
  3385. }
  3386. }
  3387. uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
  3388. addSubstitution(TypePtr);
  3389. }
  3390. void CXXNameMangler::addSubstitution(TemplateName Template) {
  3391. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  3392. return addSubstitution(TD);
  3393. Template = Context.getASTContext().getCanonicalTemplateName(Template);
  3394. addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
  3395. }
  3396. void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
  3397. assert(!Substitutions.count(Ptr) && "Substitution already exists!");
  3398. Substitutions[Ptr] = SeqID++;
  3399. }
  3400. //
  3401. /// Mangles the name of the declaration D and emits that name to the given
  3402. /// output stream.
  3403. ///
  3404. /// If the declaration D requires a mangled name, this routine will emit that
  3405. /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
  3406. /// and this routine will return false. In this case, the caller should just
  3407. /// emit the identifier of the declaration (\c D->getIdentifier()) as its
  3408. /// name.
  3409. void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
  3410. raw_ostream &Out) {
  3411. assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
  3412. "Invalid mangleName() call, argument is not a variable or function!");
  3413. assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
  3414. "Invalid mangleName() call on 'structor decl!");
  3415. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  3416. getASTContext().getSourceManager(),
  3417. "Mangling declaration");
  3418. CXXNameMangler Mangler(*this, Out, D);
  3419. Mangler.mangle(D);
  3420. }
  3421. void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
  3422. CXXCtorType Type,
  3423. raw_ostream &Out) {
  3424. CXXNameMangler Mangler(*this, Out, D, Type);
  3425. Mangler.mangle(D);
  3426. }
  3427. void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
  3428. CXXDtorType Type,
  3429. raw_ostream &Out) {
  3430. CXXNameMangler Mangler(*this, Out, D, Type);
  3431. Mangler.mangle(D);
  3432. }
  3433. void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
  3434. raw_ostream &Out) {
  3435. CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
  3436. Mangler.mangle(D);
  3437. }
  3438. void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
  3439. raw_ostream &Out) {
  3440. CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
  3441. Mangler.mangle(D);
  3442. }
  3443. void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
  3444. const ThunkInfo &Thunk,
  3445. raw_ostream &Out) {
  3446. // <special-name> ::= T <call-offset> <base encoding>
  3447. // # base is the nominal target function of thunk
  3448. // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
  3449. // # base is the nominal target function of thunk
  3450. // # first call-offset is 'this' adjustment
  3451. // # second call-offset is result adjustment
  3452. assert(!isa<CXXDestructorDecl>(MD) &&
  3453. "Use mangleCXXDtor for destructor decls!");
  3454. CXXNameMangler Mangler(*this, Out);
  3455. Mangler.getStream() << "_ZT";
  3456. if (!Thunk.Return.isEmpty())
  3457. Mangler.getStream() << 'c';
  3458. // Mangle the 'this' pointer adjustment.
  3459. Mangler.mangleCallOffset(Thunk.This.NonVirtual,
  3460. Thunk.This.Virtual.Itanium.VCallOffsetOffset);
  3461. // Mangle the return pointer adjustment if there is one.
  3462. if (!Thunk.Return.isEmpty())
  3463. Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
  3464. Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
  3465. Mangler.mangleFunctionEncoding(MD);
  3466. }
  3467. void ItaniumMangleContextImpl::mangleCXXDtorThunk(
  3468. const CXXDestructorDecl *DD, CXXDtorType Type,
  3469. const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
  3470. // <special-name> ::= T <call-offset> <base encoding>
  3471. // # base is the nominal target function of thunk
  3472. CXXNameMangler Mangler(*this, Out, DD, Type);
  3473. Mangler.getStream() << "_ZT";
  3474. // Mangle the 'this' pointer adjustment.
  3475. Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
  3476. ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
  3477. Mangler.mangleFunctionEncoding(DD);
  3478. }
  3479. /// Returns the mangled name for a guard variable for the passed in VarDecl.
  3480. void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
  3481. raw_ostream &Out) {
  3482. // <special-name> ::= GV <object name> # Guard variable for one-time
  3483. // # initialization
  3484. CXXNameMangler Mangler(*this, Out);
  3485. Mangler.getStream() << "_ZGV";
  3486. Mangler.mangleName(D);
  3487. }
  3488. void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
  3489. raw_ostream &Out) {
  3490. // These symbols are internal in the Itanium ABI, so the names don't matter.
  3491. // Clang has traditionally used this symbol and allowed LLVM to adjust it to
  3492. // avoid duplicate symbols.
  3493. Out << "__cxx_global_var_init";
  3494. }
  3495. void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
  3496. raw_ostream &Out) {
  3497. // Prefix the mangling of D with __dtor_.
  3498. CXXNameMangler Mangler(*this, Out);
  3499. Mangler.getStream() << "__dtor_";
  3500. if (shouldMangleDeclName(D))
  3501. Mangler.mangle(D);
  3502. else
  3503. Mangler.getStream() << D->getName();
  3504. }
  3505. void ItaniumMangleContextImpl::mangleSEHFilterExpression(
  3506. const NamedDecl *EnclosingDecl, raw_ostream &Out) {
  3507. CXXNameMangler Mangler(*this, Out);
  3508. Mangler.getStream() << "__filt_";
  3509. if (shouldMangleDeclName(EnclosingDecl))
  3510. Mangler.mangle(EnclosingDecl);
  3511. else
  3512. Mangler.getStream() << EnclosingDecl->getName();
  3513. }
  3514. void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
  3515. const NamedDecl *EnclosingDecl, raw_ostream &Out) {
  3516. CXXNameMangler Mangler(*this, Out);
  3517. Mangler.getStream() << "__fin_";
  3518. if (shouldMangleDeclName(EnclosingDecl))
  3519. Mangler.mangle(EnclosingDecl);
  3520. else
  3521. Mangler.getStream() << EnclosingDecl->getName();
  3522. }
  3523. void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
  3524. raw_ostream &Out) {
  3525. // <special-name> ::= TH <object name>
  3526. CXXNameMangler Mangler(*this, Out);
  3527. Mangler.getStream() << "_ZTH";
  3528. Mangler.mangleName(D);
  3529. }
  3530. void
  3531. ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
  3532. raw_ostream &Out) {
  3533. // <special-name> ::= TW <object name>
  3534. CXXNameMangler Mangler(*this, Out);
  3535. Mangler.getStream() << "_ZTW";
  3536. Mangler.mangleName(D);
  3537. }
  3538. void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
  3539. unsigned ManglingNumber,
  3540. raw_ostream &Out) {
  3541. // We match the GCC mangling here.
  3542. // <special-name> ::= GR <object name>
  3543. CXXNameMangler Mangler(*this, Out);
  3544. Mangler.getStream() << "_ZGR";
  3545. Mangler.mangleName(D);
  3546. assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
  3547. Mangler.mangleSeqID(ManglingNumber - 1);
  3548. }
  3549. void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
  3550. raw_ostream &Out) {
  3551. // <special-name> ::= TV <type> # virtual table
  3552. CXXNameMangler Mangler(*this, Out);
  3553. Mangler.getStream() << "_ZTV";
  3554. Mangler.mangleNameOrStandardSubstitution(RD);
  3555. }
  3556. void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
  3557. raw_ostream &Out) {
  3558. // <special-name> ::= TT <type> # VTT structure
  3559. CXXNameMangler Mangler(*this, Out);
  3560. Mangler.getStream() << "_ZTT";
  3561. Mangler.mangleNameOrStandardSubstitution(RD);
  3562. }
  3563. void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
  3564. int64_t Offset,
  3565. const CXXRecordDecl *Type,
  3566. raw_ostream &Out) {
  3567. // <special-name> ::= TC <type> <offset number> _ <base type>
  3568. CXXNameMangler Mangler(*this, Out);
  3569. Mangler.getStream() << "_ZTC";
  3570. Mangler.mangleNameOrStandardSubstitution(RD);
  3571. Mangler.getStream() << Offset;
  3572. Mangler.getStream() << '_';
  3573. Mangler.mangleNameOrStandardSubstitution(Type);
  3574. }
  3575. void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
  3576. // <special-name> ::= TI <type> # typeinfo structure
  3577. assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
  3578. CXXNameMangler Mangler(*this, Out);
  3579. Mangler.getStream() << "_ZTI";
  3580. Mangler.mangleType(Ty);
  3581. }
  3582. void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
  3583. raw_ostream &Out) {
  3584. // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
  3585. CXXNameMangler Mangler(*this, Out);
  3586. Mangler.getStream() << "_ZTS";
  3587. Mangler.mangleType(Ty);
  3588. }
  3589. void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
  3590. mangleCXXRTTIName(Ty, Out);
  3591. }
  3592. void ItaniumMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
  3593. raw_ostream &Out) {
  3594. if (!RD->isExternallyVisible()) {
  3595. // This part of the identifier needs to be unique across all translation
  3596. // units in the linked program. The scheme fails if multiple translation
  3597. // units are compiled using the same relative source file path, or if
  3598. // multiple translation units are built from the same source file.
  3599. SourceManager &SM = getASTContext().getSourceManager();
  3600. Out << "[" << SM.getFileEntryForID(SM.getMainFileID())->getName() << "]";
  3601. }
  3602. CXXNameMangler Mangler(*this, Out);
  3603. Mangler.mangleType(QualType(RD->getTypeForDecl(), 0));
  3604. }
  3605. void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
  3606. llvm_unreachable("Can't mangle string literals");
  3607. }
  3608. ItaniumMangleContext *
  3609. ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
  3610. return new ItaniumMangleContextImpl(Context, Diags);
  3611. }