Decl.cpp 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130
  1. //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Decl subclasses.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/Decl.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/Attr.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/PrettyPrinter.h"
  24. #include "clang/AST/Stmt.h"
  25. #include "clang/AST/TypeLoc.h"
  26. #include "clang/Basic/Builtins.h"
  27. #include "clang/Basic/IdentifierTable.h"
  28. #include "clang/Basic/Module.h"
  29. #include "clang/Basic/Specifiers.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Frontend/FrontendDiagnostic.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include <algorithm>
  34. using namespace clang;
  35. Decl *clang::getPrimaryMergedDecl(Decl *D) {
  36. return D->getASTContext().getPrimaryMergedDecl(D);
  37. }
  38. // Defined here so that it can be inlined into its direct callers.
  39. bool Decl::isOutOfLine() const {
  40. return !getLexicalDeclContext()->Equals(getDeclContext());
  41. }
  42. TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
  43. : Decl(TranslationUnit, nullptr, SourceLocation()),
  44. DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
  45. Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
  46. }
  47. //===----------------------------------------------------------------------===//
  48. // NamedDecl Implementation
  49. //===----------------------------------------------------------------------===//
  50. // Visibility rules aren't rigorously externally specified, but here
  51. // are the basic principles behind what we implement:
  52. //
  53. // 1. An explicit visibility attribute is generally a direct expression
  54. // of the user's intent and should be honored. Only the innermost
  55. // visibility attribute applies. If no visibility attribute applies,
  56. // global visibility settings are considered.
  57. //
  58. // 2. There is one caveat to the above: on or in a template pattern,
  59. // an explicit visibility attribute is just a default rule, and
  60. // visibility can be decreased by the visibility of template
  61. // arguments. But this, too, has an exception: an attribute on an
  62. // explicit specialization or instantiation causes all the visibility
  63. // restrictions of the template arguments to be ignored.
  64. //
  65. // 3. A variable that does not otherwise have explicit visibility can
  66. // be restricted by the visibility of its type.
  67. //
  68. // 4. A visibility restriction is explicit if it comes from an
  69. // attribute (or something like it), not a global visibility setting.
  70. // When emitting a reference to an external symbol, visibility
  71. // restrictions are ignored unless they are explicit.
  72. //
  73. // 5. When computing the visibility of a non-type, including a
  74. // non-type member of a class, only non-type visibility restrictions
  75. // are considered: the 'visibility' attribute, global value-visibility
  76. // settings, and a few special cases like __private_extern.
  77. //
  78. // 6. When computing the visibility of a type, including a type member
  79. // of a class, only type visibility restrictions are considered:
  80. // the 'type_visibility' attribute and global type-visibility settings.
  81. // However, a 'visibility' attribute counts as a 'type_visibility'
  82. // attribute on any declaration that only has the former.
  83. //
  84. // The visibility of a "secondary" entity, like a template argument,
  85. // is computed using the kind of that entity, not the kind of the
  86. // primary entity for which we are computing visibility. For example,
  87. // the visibility of a specialization of either of these templates:
  88. // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
  89. // template <class T, bool (&compare)(T, X)> class matcher;
  90. // is restricted according to the type visibility of the argument 'T',
  91. // the type visibility of 'bool(&)(T,X)', and the value visibility of
  92. // the argument function 'compare'. That 'has_match' is a value
  93. // and 'matcher' is a type only matters when looking for attributes
  94. // and settings from the immediate context.
  95. const unsigned IgnoreExplicitVisibilityBit = 2;
  96. const unsigned IgnoreAllVisibilityBit = 4;
  97. /// Kinds of LV computation. The linkage side of the computation is
  98. /// always the same, but different things can change how visibility is
  99. /// computed.
  100. enum LVComputationKind {
  101. /// Do an LV computation for, ultimately, a type.
  102. /// Visibility may be restricted by type visibility settings and
  103. /// the visibility of template arguments.
  104. LVForType = NamedDecl::VisibilityForType,
  105. /// Do an LV computation for, ultimately, a non-type declaration.
  106. /// Visibility may be restricted by value visibility settings and
  107. /// the visibility of template arguments.
  108. LVForValue = NamedDecl::VisibilityForValue,
  109. /// Do an LV computation for, ultimately, a type that already has
  110. /// some sort of explicit visibility. Visibility may only be
  111. /// restricted by the visibility of template arguments.
  112. LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
  113. /// Do an LV computation for, ultimately, a non-type declaration
  114. /// that already has some sort of explicit visibility. Visibility
  115. /// may only be restricted by the visibility of template arguments.
  116. LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
  117. /// Do an LV computation when we only care about the linkage.
  118. LVForLinkageOnly =
  119. LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
  120. };
  121. /// Does this computation kind permit us to consider additional
  122. /// visibility settings from attributes and the like?
  123. static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
  124. return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
  125. }
  126. /// Given an LVComputationKind, return one of the same type/value sort
  127. /// that records that it already has explicit visibility.
  128. static LVComputationKind
  129. withExplicitVisibilityAlready(LVComputationKind oldKind) {
  130. LVComputationKind newKind =
  131. static_cast<LVComputationKind>(unsigned(oldKind) |
  132. IgnoreExplicitVisibilityBit);
  133. assert(oldKind != LVForType || newKind == LVForExplicitType);
  134. assert(oldKind != LVForValue || newKind == LVForExplicitValue);
  135. assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
  136. assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
  137. return newKind;
  138. }
  139. static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
  140. LVComputationKind kind) {
  141. assert(!hasExplicitVisibilityAlready(kind) &&
  142. "asking for explicit visibility when we shouldn't be");
  143. return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
  144. }
  145. /// Is the given declaration a "type" or a "value" for the purposes of
  146. /// visibility computation?
  147. static bool usesTypeVisibility(const NamedDecl *D) {
  148. return isa<TypeDecl>(D) ||
  149. isa<ClassTemplateDecl>(D) ||
  150. isa<ObjCInterfaceDecl>(D);
  151. }
  152. /// Does the given declaration have member specialization information,
  153. /// and if so, is it an explicit specialization?
  154. template <class T> static typename
  155. std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
  156. isExplicitMemberSpecialization(const T *D) {
  157. if (const MemberSpecializationInfo *member =
  158. D->getMemberSpecializationInfo()) {
  159. return member->isExplicitSpecialization();
  160. }
  161. return false;
  162. }
  163. /// For templates, this question is easier: a member template can't be
  164. /// explicitly instantiated, so there's a single bit indicating whether
  165. /// or not this is an explicit member specialization.
  166. static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
  167. return D->isMemberSpecialization();
  168. }
  169. /// Given a visibility attribute, return the explicit visibility
  170. /// associated with it.
  171. template <class T>
  172. static Visibility getVisibilityFromAttr(const T *attr) {
  173. switch (attr->getVisibility()) {
  174. case T::Default:
  175. return DefaultVisibility;
  176. case T::Hidden:
  177. return HiddenVisibility;
  178. case T::Protected:
  179. return ProtectedVisibility;
  180. }
  181. llvm_unreachable("bad visibility kind");
  182. }
  183. /// Return the explicit visibility of the given declaration.
  184. static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
  185. NamedDecl::ExplicitVisibilityKind kind) {
  186. // If we're ultimately computing the visibility of a type, look for
  187. // a 'type_visibility' attribute before looking for 'visibility'.
  188. if (kind == NamedDecl::VisibilityForType) {
  189. if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
  190. return getVisibilityFromAttr(A);
  191. }
  192. }
  193. // If this declaration has an explicit visibility attribute, use it.
  194. if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
  195. return getVisibilityFromAttr(A);
  196. }
  197. // If we're on Mac OS X, an 'availability' for Mac OS X attribute
  198. // implies visibility(default).
  199. if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
  200. for (const auto *A : D->specific_attrs<AvailabilityAttr>())
  201. if (A->getPlatform()->getName().equals("macosx"))
  202. return DefaultVisibility;
  203. }
  204. return None;
  205. }
  206. static LinkageInfo
  207. getLVForType(const Type &T, LVComputationKind computation) {
  208. if (computation == LVForLinkageOnly)
  209. return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
  210. return T.getLinkageAndVisibility();
  211. }
  212. /// \brief Get the most restrictive linkage for the types in the given
  213. /// template parameter list. For visibility purposes, template
  214. /// parameters are part of the signature of a template.
  215. static LinkageInfo
  216. getLVForTemplateParameterList(const TemplateParameterList *Params,
  217. LVComputationKind computation) {
  218. LinkageInfo LV;
  219. for (const NamedDecl *P : *Params) {
  220. // Template type parameters are the most common and never
  221. // contribute to visibility, pack or not.
  222. if (isa<TemplateTypeParmDecl>(P))
  223. continue;
  224. // Non-type template parameters can be restricted by the value type, e.g.
  225. // template <enum X> class A { ... };
  226. // We have to be careful here, though, because we can be dealing with
  227. // dependent types.
  228. if (const NonTypeTemplateParmDecl *NTTP =
  229. dyn_cast<NonTypeTemplateParmDecl>(P)) {
  230. // Handle the non-pack case first.
  231. if (!NTTP->isExpandedParameterPack()) {
  232. if (!NTTP->getType()->isDependentType()) {
  233. LV.merge(getLVForType(*NTTP->getType(), computation));
  234. }
  235. continue;
  236. }
  237. // Look at all the types in an expanded pack.
  238. for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
  239. QualType type = NTTP->getExpansionType(i);
  240. if (!type->isDependentType())
  241. LV.merge(type->getLinkageAndVisibility());
  242. }
  243. continue;
  244. }
  245. // Template template parameters can be restricted by their
  246. // template parameters, recursively.
  247. const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P);
  248. // Handle the non-pack case first.
  249. if (!TTP->isExpandedParameterPack()) {
  250. LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
  251. computation));
  252. continue;
  253. }
  254. // Look at all expansions in an expanded pack.
  255. for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
  256. i != n; ++i) {
  257. LV.merge(getLVForTemplateParameterList(
  258. TTP->getExpansionTemplateParameters(i), computation));
  259. }
  260. }
  261. return LV;
  262. }
  263. /// getLVForDecl - Get the linkage and visibility for the given declaration.
  264. static LinkageInfo getLVForDecl(const NamedDecl *D,
  265. LVComputationKind computation);
  266. static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
  267. const Decl *Ret = nullptr;
  268. const DeclContext *DC = D->getDeclContext();
  269. while (DC->getDeclKind() != Decl::TranslationUnit) {
  270. if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
  271. Ret = cast<Decl>(DC);
  272. DC = DC->getParent();
  273. }
  274. return Ret;
  275. }
  276. /// \brief Get the most restrictive linkage for the types and
  277. /// declarations in the given template argument list.
  278. ///
  279. /// Note that we don't take an LVComputationKind because we always
  280. /// want to honor the visibility of template arguments in the same way.
  281. static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
  282. LVComputationKind computation) {
  283. LinkageInfo LV;
  284. for (const TemplateArgument &Arg : Args) {
  285. switch (Arg.getKind()) {
  286. case TemplateArgument::Null:
  287. case TemplateArgument::Integral:
  288. case TemplateArgument::Expression:
  289. continue;
  290. case TemplateArgument::Type:
  291. LV.merge(getLVForType(*Arg.getAsType(), computation));
  292. continue;
  293. case TemplateArgument::Declaration:
  294. if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
  295. assert(!usesTypeVisibility(ND));
  296. LV.merge(getLVForDecl(ND, computation));
  297. }
  298. continue;
  299. case TemplateArgument::NullPtr:
  300. LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
  301. continue;
  302. case TemplateArgument::Template:
  303. case TemplateArgument::TemplateExpansion:
  304. if (TemplateDecl *Template =
  305. Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
  306. LV.merge(getLVForDecl(Template, computation));
  307. continue;
  308. case TemplateArgument::Pack:
  309. LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
  310. continue;
  311. }
  312. llvm_unreachable("bad template argument kind");
  313. }
  314. return LV;
  315. }
  316. static LinkageInfo
  317. getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
  318. LVComputationKind computation) {
  319. return getLVForTemplateArgumentList(TArgs.asArray(), computation);
  320. }
  321. static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
  322. const FunctionTemplateSpecializationInfo *specInfo) {
  323. // Include visibility from the template parameters and arguments
  324. // only if this is not an explicit instantiation or specialization
  325. // with direct explicit visibility. (Implicit instantiations won't
  326. // have a direct attribute.)
  327. if (!specInfo->isExplicitInstantiationOrSpecialization())
  328. return true;
  329. return !fn->hasAttr<VisibilityAttr>();
  330. }
  331. /// Merge in template-related linkage and visibility for the given
  332. /// function template specialization.
  333. ///
  334. /// We don't need a computation kind here because we can assume
  335. /// LVForValue.
  336. ///
  337. /// \param[out] LV the computation to use for the parent
  338. static void
  339. mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
  340. const FunctionTemplateSpecializationInfo *specInfo,
  341. LVComputationKind computation) {
  342. bool considerVisibility =
  343. shouldConsiderTemplateVisibility(fn, specInfo);
  344. // Merge information from the template parameters.
  345. FunctionTemplateDecl *temp = specInfo->getTemplate();
  346. LinkageInfo tempLV =
  347. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  348. LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
  349. // Merge information from the template arguments.
  350. const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
  351. LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
  352. LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
  353. }
  354. /// Does the given declaration have a direct visibility attribute
  355. /// that would match the given rules?
  356. static bool hasDirectVisibilityAttribute(const NamedDecl *D,
  357. LVComputationKind computation) {
  358. switch (computation) {
  359. case LVForType:
  360. case LVForExplicitType:
  361. if (D->hasAttr<TypeVisibilityAttr>())
  362. return true;
  363. // fallthrough
  364. case LVForValue:
  365. case LVForExplicitValue:
  366. if (D->hasAttr<VisibilityAttr>())
  367. return true;
  368. return false;
  369. case LVForLinkageOnly:
  370. return false;
  371. }
  372. llvm_unreachable("bad visibility computation kind");
  373. }
  374. /// Should we consider visibility associated with the template
  375. /// arguments and parameters of the given class template specialization?
  376. static bool shouldConsiderTemplateVisibility(
  377. const ClassTemplateSpecializationDecl *spec,
  378. LVComputationKind computation) {
  379. // Include visibility from the template parameters and arguments
  380. // only if this is not an explicit instantiation or specialization
  381. // with direct explicit visibility (and note that implicit
  382. // instantiations won't have a direct attribute).
  383. //
  384. // Furthermore, we want to ignore template parameters and arguments
  385. // for an explicit specialization when computing the visibility of a
  386. // member thereof with explicit visibility.
  387. //
  388. // This is a bit complex; let's unpack it.
  389. //
  390. // An explicit class specialization is an independent, top-level
  391. // declaration. As such, if it or any of its members has an
  392. // explicit visibility attribute, that must directly express the
  393. // user's intent, and we should honor it. The same logic applies to
  394. // an explicit instantiation of a member of such a thing.
  395. // Fast path: if this is not an explicit instantiation or
  396. // specialization, we always want to consider template-related
  397. // visibility restrictions.
  398. if (!spec->isExplicitInstantiationOrSpecialization())
  399. return true;
  400. // This is the 'member thereof' check.
  401. if (spec->isExplicitSpecialization() &&
  402. hasExplicitVisibilityAlready(computation))
  403. return false;
  404. return !hasDirectVisibilityAttribute(spec, computation);
  405. }
  406. /// Merge in template-related linkage and visibility for the given
  407. /// class template specialization.
  408. static void mergeTemplateLV(LinkageInfo &LV,
  409. const ClassTemplateSpecializationDecl *spec,
  410. LVComputationKind computation) {
  411. bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
  412. // Merge information from the template parameters, but ignore
  413. // visibility if we're only considering template arguments.
  414. ClassTemplateDecl *temp = spec->getSpecializedTemplate();
  415. LinkageInfo tempLV =
  416. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  417. LV.mergeMaybeWithVisibility(tempLV,
  418. considerVisibility && !hasExplicitVisibilityAlready(computation));
  419. // Merge information from the template arguments. We ignore
  420. // template-argument visibility if we've got an explicit
  421. // instantiation with a visibility attribute.
  422. const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
  423. LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
  424. if (considerVisibility)
  425. LV.mergeVisibility(argsLV);
  426. LV.mergeExternalVisibility(argsLV);
  427. }
  428. /// Should we consider visibility associated with the template
  429. /// arguments and parameters of the given variable template
  430. /// specialization? As usual, follow class template specialization
  431. /// logic up to initialization.
  432. static bool shouldConsiderTemplateVisibility(
  433. const VarTemplateSpecializationDecl *spec,
  434. LVComputationKind computation) {
  435. // Include visibility from the template parameters and arguments
  436. // only if this is not an explicit instantiation or specialization
  437. // with direct explicit visibility (and note that implicit
  438. // instantiations won't have a direct attribute).
  439. if (!spec->isExplicitInstantiationOrSpecialization())
  440. return true;
  441. // An explicit variable specialization is an independent, top-level
  442. // declaration. As such, if it has an explicit visibility attribute,
  443. // that must directly express the user's intent, and we should honor
  444. // it.
  445. if (spec->isExplicitSpecialization() &&
  446. hasExplicitVisibilityAlready(computation))
  447. return false;
  448. return !hasDirectVisibilityAttribute(spec, computation);
  449. }
  450. /// Merge in template-related linkage and visibility for the given
  451. /// variable template specialization. As usual, follow class template
  452. /// specialization logic up to initialization.
  453. static void mergeTemplateLV(LinkageInfo &LV,
  454. const VarTemplateSpecializationDecl *spec,
  455. LVComputationKind computation) {
  456. bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
  457. // Merge information from the template parameters, but ignore
  458. // visibility if we're only considering template arguments.
  459. VarTemplateDecl *temp = spec->getSpecializedTemplate();
  460. LinkageInfo tempLV =
  461. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  462. LV.mergeMaybeWithVisibility(tempLV,
  463. considerVisibility && !hasExplicitVisibilityAlready(computation));
  464. // Merge information from the template arguments. We ignore
  465. // template-argument visibility if we've got an explicit
  466. // instantiation with a visibility attribute.
  467. const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
  468. LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
  469. if (considerVisibility)
  470. LV.mergeVisibility(argsLV);
  471. LV.mergeExternalVisibility(argsLV);
  472. }
  473. static bool useInlineVisibilityHidden(const NamedDecl *D) {
  474. #if 1 // HLSL Change Starts
  475. return false;
  476. #else
  477. // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
  478. const LangOptions &Opts = D->getASTContext().getLangOpts();
  479. if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
  480. return false;
  481. const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  482. if (!FD)
  483. return false;
  484. TemplateSpecializationKind TSK = TSK_Undeclared;
  485. if (FunctionTemplateSpecializationInfo *spec
  486. = FD->getTemplateSpecializationInfo()) {
  487. TSK = spec->getTemplateSpecializationKind();
  488. } else if (MemberSpecializationInfo *MSI =
  489. FD->getMemberSpecializationInfo()) {
  490. TSK = MSI->getTemplateSpecializationKind();
  491. }
  492. const FunctionDecl *Def = nullptr;
  493. // InlineVisibilityHidden only applies to definitions, and
  494. // isInlined() only gives meaningful answers on definitions
  495. // anyway.
  496. return TSK != TSK_ExplicitInstantiationDeclaration &&
  497. TSK != TSK_ExplicitInstantiationDefinition &&
  498. FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
  499. #endif // HLSL Change Ends
  500. }
  501. template <typename T> static bool isFirstInExternCContext(T *D) {
  502. const T *First = D->getFirstDecl();
  503. return First->isInExternCContext();
  504. }
  505. static bool isSingleLineLanguageLinkage(const Decl &D) {
  506. if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
  507. if (!SD->hasBraces())
  508. return true;
  509. return false;
  510. }
  511. static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
  512. LVComputationKind computation) {
  513. assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
  514. "Not a name having namespace scope");
  515. ASTContext &Context = D->getASTContext();
  516. // C++ [basic.link]p3:
  517. // A name having namespace scope (3.3.6) has internal linkage if it
  518. // is the name of
  519. // - an object, reference, function or function template that is
  520. // explicitly declared static; or,
  521. // (This bullet corresponds to C99 6.2.2p3.)
  522. if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
  523. // Explicitly declared static.
  524. if (Var->getStorageClass() == SC_Static)
  525. return LinkageInfo::internal();
  526. // - a non-volatile object or reference that is explicitly declared const
  527. // or constexpr and neither explicitly declared extern nor previously
  528. // declared to have external linkage; or (there is no equivalent in C99)
  529. if (Context.getLangOpts().CPlusPlus &&
  530. Var->getType().isConstQualified() &&
  531. !Context.getLangOpts().HLSL && // HLSL Change -Initializer used on a global 'const' variable will be ignored for hlsl.
  532. !Var->getType().isVolatileQualified()) {
  533. const VarDecl *PrevVar = Var->getPreviousDecl();
  534. if (PrevVar)
  535. return getLVForDecl(PrevVar, computation);
  536. if (Var->getStorageClass() != SC_Extern &&
  537. Var->getStorageClass() != SC_PrivateExtern &&
  538. !isSingleLineLanguageLinkage(*Var))
  539. return LinkageInfo::internal();
  540. }
  541. for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
  542. PrevVar = PrevVar->getPreviousDecl()) {
  543. if (PrevVar->getStorageClass() == SC_PrivateExtern &&
  544. Var->getStorageClass() == SC_None)
  545. return PrevVar->getLinkageAndVisibility();
  546. // Explicitly declared static.
  547. if (PrevVar->getStorageClass() == SC_Static)
  548. return LinkageInfo::internal();
  549. }
  550. } else if (const FunctionDecl *Function = D->getAsFunction()) {
  551. // C++ [temp]p4:
  552. // A non-member function template can have internal linkage; any
  553. // other template name shall have external linkage.
  554. // Explicitly declared static.
  555. if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
  556. return LinkageInfo(InternalLinkage, DefaultVisibility, false);
  557. } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
  558. // - a data member of an anonymous union.
  559. const VarDecl *VD = IFD->getVarDecl();
  560. assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
  561. return getLVForNamespaceScopeDecl(VD, computation);
  562. }
  563. assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
  564. if (D->isInAnonymousNamespace()) {
  565. const VarDecl *Var = dyn_cast<VarDecl>(D);
  566. const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
  567. if ((!Var || !isFirstInExternCContext(Var)) &&
  568. (!Func || !isFirstInExternCContext(Func)))
  569. return LinkageInfo::uniqueExternal();
  570. }
  571. // Set up the defaults.
  572. // C99 6.2.2p5:
  573. // If the declaration of an identifier for an object has file
  574. // scope and no storage-class specifier, its linkage is
  575. // external.
  576. LinkageInfo LV;
  577. if (!hasExplicitVisibilityAlready(computation)) {
  578. if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
  579. LV.mergeVisibility(*Vis, true);
  580. } else {
  581. // If we're declared in a namespace with a visibility attribute,
  582. // use that namespace's visibility, and it still counts as explicit.
  583. for (const DeclContext *DC = D->getDeclContext();
  584. !isa<TranslationUnitDecl>(DC);
  585. DC = DC->getParent()) {
  586. const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
  587. if (!ND) continue;
  588. if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
  589. LV.mergeVisibility(*Vis, true);
  590. break;
  591. }
  592. }
  593. }
  594. // Add in global settings if the above didn't give us direct visibility.
  595. if (!LV.isVisibilityExplicit()) {
  596. // Use global type/value visibility as appropriate.
  597. Visibility globalVisibility;
  598. if (computation == LVForValue) {
  599. globalVisibility = Context.getLangOpts().getValueVisibilityMode();
  600. } else {
  601. assert(computation == LVForType);
  602. globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
  603. }
  604. LV.mergeVisibility(globalVisibility, /*explicit*/ false);
  605. // If we're paying attention to global visibility, apply
  606. // -finline-visibility-hidden if this is an inline method.
  607. if (useInlineVisibilityHidden(D))
  608. LV.mergeVisibility(HiddenVisibility, true);
  609. }
  610. }
  611. // C++ [basic.link]p4:
  612. // A name having namespace scope has external linkage if it is the
  613. // name of
  614. //
  615. // - an object or reference, unless it has internal linkage; or
  616. if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
  617. // GCC applies the following optimization to variables and static
  618. // data members, but not to functions:
  619. //
  620. // Modify the variable's LV by the LV of its type unless this is
  621. // C or extern "C". This follows from [basic.link]p9:
  622. // A type without linkage shall not be used as the type of a
  623. // variable or function with external linkage unless
  624. // - the entity has C language linkage, or
  625. // - the entity is declared within an unnamed namespace, or
  626. // - the entity is not used or is defined in the same
  627. // translation unit.
  628. // and [basic.link]p10:
  629. // ...the types specified by all declarations referring to a
  630. // given variable or function shall be identical...
  631. // C does not have an equivalent rule.
  632. //
  633. // Ignore this if we've got an explicit attribute; the user
  634. // probably knows what they're doing.
  635. //
  636. // Note that we don't want to make the variable non-external
  637. // because of this, but unique-external linkage suits us.
  638. if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
  639. LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
  640. if (TypeLV.getLinkage() != ExternalLinkage)
  641. return LinkageInfo::uniqueExternal();
  642. if (!LV.isVisibilityExplicit())
  643. LV.mergeVisibility(TypeLV);
  644. }
  645. if (Var->getStorageClass() == SC_PrivateExtern)
  646. LV.mergeVisibility(HiddenVisibility, true);
  647. // Note that Sema::MergeVarDecl already takes care of implementing
  648. // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
  649. // to do it here.
  650. // As per function and class template specializations (below),
  651. // consider LV for the template and template arguments. We're at file
  652. // scope, so we do not need to worry about nested specializations.
  653. if (const VarTemplateSpecializationDecl *spec
  654. = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
  655. mergeTemplateLV(LV, spec, computation);
  656. }
  657. // - a function, unless it has internal linkage; or
  658. } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  659. // In theory, we can modify the function's LV by the LV of its
  660. // type unless it has C linkage (see comment above about variables
  661. // for justification). In practice, GCC doesn't do this, so it's
  662. // just too painful to make work.
  663. if (Function->getStorageClass() == SC_PrivateExtern)
  664. LV.mergeVisibility(HiddenVisibility, true);
  665. // Note that Sema::MergeCompatibleFunctionDecls already takes care of
  666. // merging storage classes and visibility attributes, so we don't have to
  667. // look at previous decls in here.
  668. // In C++, then if the type of the function uses a type with
  669. // unique-external linkage, it's not legally usable from outside
  670. // this translation unit. However, we should use the C linkage
  671. // rules instead for extern "C" declarations.
  672. if (Context.getLangOpts().CPlusPlus &&
  673. !Function->isInExternCContext()) {
  674. // Only look at the type-as-written. If this function has an auto-deduced
  675. // return type, we can't compute the linkage of that type because it could
  676. // require looking at the linkage of this function, and we don't need this
  677. // for correctness because the type is not part of the function's
  678. // signature.
  679. // FIXME: This is a hack. We should be able to solve this circularity and
  680. // the one in getLVForClassMember for Functions some other way.
  681. QualType TypeAsWritten = Function->getType();
  682. if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
  683. TypeAsWritten = TSI->getType();
  684. if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
  685. return LinkageInfo::uniqueExternal();
  686. }
  687. // Consider LV from the template and the template arguments.
  688. // We're at file scope, so we do not need to worry about nested
  689. // specializations.
  690. if (FunctionTemplateSpecializationInfo *specInfo
  691. = Function->getTemplateSpecializationInfo()) {
  692. mergeTemplateLV(LV, Function, specInfo, computation);
  693. }
  694. // - a named class (Clause 9), or an unnamed class defined in a
  695. // typedef declaration in which the class has the typedef name
  696. // for linkage purposes (7.1.3); or
  697. // - a named enumeration (7.2), or an unnamed enumeration
  698. // defined in a typedef declaration in which the enumeration
  699. // has the typedef name for linkage purposes (7.1.3); or
  700. } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
  701. // Unnamed tags have no linkage.
  702. if (!Tag->hasNameForLinkage())
  703. return LinkageInfo::none();
  704. // If this is a class template specialization, consider the
  705. // linkage of the template and template arguments. We're at file
  706. // scope, so we do not need to worry about nested specializations.
  707. if (const ClassTemplateSpecializationDecl *spec
  708. = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
  709. mergeTemplateLV(LV, spec, computation);
  710. }
  711. // - an enumerator belonging to an enumeration with external linkage;
  712. } else if (isa<EnumConstantDecl>(D)) {
  713. LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
  714. computation);
  715. if (!isExternalFormalLinkage(EnumLV.getLinkage()))
  716. return LinkageInfo::none();
  717. LV.merge(EnumLV);
  718. // - a template, unless it is a function template that has
  719. // internal linkage (Clause 14);
  720. } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
  721. bool considerVisibility = !hasExplicitVisibilityAlready(computation);
  722. LinkageInfo tempLV =
  723. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  724. LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
  725. // - a namespace (7.3), unless it is declared within an unnamed
  726. // namespace.
  727. } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
  728. return LV;
  729. // By extension, we assign external linkage to Objective-C
  730. // interfaces.
  731. } else if (isa<ObjCInterfaceDecl>(D)) {
  732. // fallout
  733. // Everything not covered here has no linkage.
  734. } else {
  735. // FIXME: A typedef declaration has linkage if it gives a type a name for
  736. // linkage purposes.
  737. return LinkageInfo::none();
  738. }
  739. // If we ended up with non-external linkage, visibility should
  740. // always be default.
  741. if (LV.getLinkage() != ExternalLinkage)
  742. return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
  743. return LV;
  744. }
  745. static LinkageInfo getLVForClassMember(const NamedDecl *D,
  746. LVComputationKind computation) {
  747. // Only certain class members have linkage. Note that fields don't
  748. // really have linkage, but it's convenient to say they do for the
  749. // purposes of calculating linkage of pointer-to-data-member
  750. // template arguments.
  751. //
  752. // Templates also don't officially have linkage, but since we ignore
  753. // the C++ standard and look at template arguments when determining
  754. // linkage and visibility of a template specialization, we might hit
  755. // a template template argument that way. If we do, we need to
  756. // consider its linkage.
  757. if (!(isa<CXXMethodDecl>(D) ||
  758. isa<VarDecl>(D) ||
  759. isa<FieldDecl>(D) ||
  760. isa<IndirectFieldDecl>(D) ||
  761. isa<TagDecl>(D) ||
  762. isa<TemplateDecl>(D)))
  763. return LinkageInfo::none();
  764. LinkageInfo LV;
  765. // If we have an explicit visibility attribute, merge that in.
  766. if (!hasExplicitVisibilityAlready(computation)) {
  767. if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
  768. LV.mergeVisibility(*Vis, true);
  769. // If we're paying attention to global visibility, apply
  770. // -finline-visibility-hidden if this is an inline method.
  771. //
  772. // Note that we do this before merging information about
  773. // the class visibility.
  774. if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
  775. LV.mergeVisibility(HiddenVisibility, true);
  776. }
  777. // If this class member has an explicit visibility attribute, the only
  778. // thing that can change its visibility is the template arguments, so
  779. // only look for them when processing the class.
  780. LVComputationKind classComputation = computation;
  781. if (LV.isVisibilityExplicit())
  782. classComputation = withExplicitVisibilityAlready(computation);
  783. LinkageInfo classLV =
  784. getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
  785. // If the class already has unique-external linkage, we can't improve.
  786. if (classLV.getLinkage() == UniqueExternalLinkage)
  787. return LinkageInfo::uniqueExternal();
  788. if (!isExternallyVisible(classLV.getLinkage()))
  789. return LinkageInfo::none();
  790. // Otherwise, don't merge in classLV yet, because in certain cases
  791. // we need to completely ignore the visibility from it.
  792. // Specifically, if this decl exists and has an explicit attribute.
  793. const NamedDecl *explicitSpecSuppressor = nullptr;
  794. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  795. // If the type of the function uses a type with unique-external
  796. // linkage, it's not legally usable from outside this translation unit.
  797. // But only look at the type-as-written. If this function has an
  798. // auto-deduced return type, we can't compute the linkage of that type
  799. // because it could require looking at the linkage of this function, and we
  800. // don't need this for correctness because the type is not part of the
  801. // function's signature.
  802. // FIXME: This is a hack. We should be able to solve this circularity and
  803. // the one in getLVForNamespaceScopeDecl for Functions some other way.
  804. {
  805. QualType TypeAsWritten = MD->getType();
  806. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  807. TypeAsWritten = TSI->getType();
  808. if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
  809. return LinkageInfo::uniqueExternal();
  810. }
  811. // If this is a method template specialization, use the linkage for
  812. // the template parameters and arguments.
  813. if (FunctionTemplateSpecializationInfo *spec
  814. = MD->getTemplateSpecializationInfo()) {
  815. mergeTemplateLV(LV, MD, spec, computation);
  816. if (spec->isExplicitSpecialization()) {
  817. explicitSpecSuppressor = MD;
  818. } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
  819. explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
  820. }
  821. } else if (isExplicitMemberSpecialization(MD)) {
  822. explicitSpecSuppressor = MD;
  823. }
  824. } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  825. if (const ClassTemplateSpecializationDecl *spec
  826. = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
  827. mergeTemplateLV(LV, spec, computation);
  828. if (spec->isExplicitSpecialization()) {
  829. explicitSpecSuppressor = spec;
  830. } else {
  831. const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
  832. if (isExplicitMemberSpecialization(temp)) {
  833. explicitSpecSuppressor = temp->getTemplatedDecl();
  834. }
  835. }
  836. } else if (isExplicitMemberSpecialization(RD)) {
  837. explicitSpecSuppressor = RD;
  838. }
  839. // Static data members.
  840. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  841. // HLSL Change: Make static data member internal linkage. This is to avoid confusion between global constant buffer
  842. if (VD->getStorageClass() == StorageClass::SC_Static)
  843. LV.setLinkage(Linkage::InternalLinkage);
  844. if (const VarTemplateSpecializationDecl *spec
  845. = dyn_cast<VarTemplateSpecializationDecl>(VD))
  846. mergeTemplateLV(LV, spec, computation);
  847. // Modify the variable's linkage by its type, but ignore the
  848. // type's visibility unless it's a definition.
  849. LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
  850. if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
  851. LV.mergeVisibility(typeLV);
  852. LV.mergeExternalVisibility(typeLV);
  853. if (isExplicitMemberSpecialization(VD)) {
  854. explicitSpecSuppressor = VD;
  855. }
  856. // Template members.
  857. } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
  858. bool considerVisibility =
  859. (!LV.isVisibilityExplicit() &&
  860. !classLV.isVisibilityExplicit() &&
  861. !hasExplicitVisibilityAlready(computation));
  862. LinkageInfo tempLV =
  863. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  864. LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
  865. if (const RedeclarableTemplateDecl *redeclTemp =
  866. dyn_cast<RedeclarableTemplateDecl>(temp)) {
  867. if (isExplicitMemberSpecialization(redeclTemp)) {
  868. explicitSpecSuppressor = temp->getTemplatedDecl();
  869. }
  870. }
  871. }
  872. // We should never be looking for an attribute directly on a template.
  873. assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
  874. // If this member is an explicit member specialization, and it has
  875. // an explicit attribute, ignore visibility from the parent.
  876. bool considerClassVisibility = true;
  877. if (explicitSpecSuppressor &&
  878. // optimization: hasDVA() is true only with explicit visibility.
  879. LV.isVisibilityExplicit() &&
  880. classLV.getVisibility() != DefaultVisibility &&
  881. hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
  882. considerClassVisibility = false;
  883. }
  884. // Finally, merge in information from the class.
  885. LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
  886. return LV;
  887. }
  888. void NamedDecl::anchor() { }
  889. static LinkageInfo computeLVForDecl(const NamedDecl *D,
  890. LVComputationKind computation);
  891. bool NamedDecl::isLinkageValid() const {
  892. if (!hasCachedLinkage())
  893. return true;
  894. return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
  895. getCachedLinkage();
  896. }
  897. ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
  898. StringRef name = getName();
  899. if (name.empty()) return SFF_None;
  900. if (name.front() == 'C')
  901. if (name == "CFStringCreateWithFormat" ||
  902. name == "CFStringCreateWithFormatAndArguments" ||
  903. name == "CFStringAppendFormat" ||
  904. name == "CFStringAppendFormatAndArguments")
  905. return SFF_CFString;
  906. return SFF_None;
  907. }
  908. Linkage NamedDecl::getLinkageInternal() const {
  909. // We don't care about visibility here, so ask for the cheapest
  910. // possible visibility analysis.
  911. return getLVForDecl(this, LVForLinkageOnly).getLinkage();
  912. }
  913. LinkageInfo NamedDecl::getLinkageAndVisibility() const {
  914. LVComputationKind computation =
  915. (usesTypeVisibility(this) ? LVForType : LVForValue);
  916. return getLVForDecl(this, computation);
  917. }
  918. static Optional<Visibility>
  919. getExplicitVisibilityAux(const NamedDecl *ND,
  920. NamedDecl::ExplicitVisibilityKind kind,
  921. bool IsMostRecent) {
  922. assert(!IsMostRecent || ND == ND->getMostRecentDecl());
  923. // Check the declaration itself first.
  924. if (Optional<Visibility> V = getVisibilityOf(ND, kind))
  925. return V;
  926. // If this is a member class of a specialization of a class template
  927. // and the corresponding decl has explicit visibility, use that.
  928. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
  929. CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
  930. if (InstantiatedFrom)
  931. return getVisibilityOf(InstantiatedFrom, kind);
  932. }
  933. // If there wasn't explicit visibility there, and this is a
  934. // specialization of a class template, check for visibility
  935. // on the pattern.
  936. if (const ClassTemplateSpecializationDecl *spec
  937. = dyn_cast<ClassTemplateSpecializationDecl>(ND))
  938. return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
  939. kind);
  940. // Use the most recent declaration.
  941. if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
  942. const NamedDecl *MostRecent = ND->getMostRecentDecl();
  943. if (MostRecent != ND)
  944. return getExplicitVisibilityAux(MostRecent, kind, true);
  945. }
  946. if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
  947. if (Var->isStaticDataMember()) {
  948. VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
  949. if (InstantiatedFrom)
  950. return getVisibilityOf(InstantiatedFrom, kind);
  951. }
  952. if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
  953. return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
  954. kind);
  955. return None;
  956. }
  957. // Also handle function template specializations.
  958. if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
  959. // If the function is a specialization of a template with an
  960. // explicit visibility attribute, use that.
  961. if (FunctionTemplateSpecializationInfo *templateInfo
  962. = fn->getTemplateSpecializationInfo())
  963. return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
  964. kind);
  965. // If the function is a member of a specialization of a class template
  966. // and the corresponding decl has explicit visibility, use that.
  967. FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
  968. if (InstantiatedFrom)
  969. return getVisibilityOf(InstantiatedFrom, kind);
  970. return None;
  971. }
  972. // The visibility of a template is stored in the templated decl.
  973. if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
  974. return getVisibilityOf(TD->getTemplatedDecl(), kind);
  975. return None;
  976. }
  977. Optional<Visibility>
  978. NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
  979. return getExplicitVisibilityAux(this, kind, false);
  980. }
  981. static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
  982. LVComputationKind computation) {
  983. // This lambda has its linkage/visibility determined by its owner.
  984. if (ContextDecl) {
  985. if (isa<ParmVarDecl>(ContextDecl))
  986. DC = ContextDecl->getDeclContext()->getRedeclContext();
  987. else
  988. return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
  989. }
  990. if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
  991. return getLVForDecl(ND, computation);
  992. return LinkageInfo::external();
  993. }
  994. static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
  995. LVComputationKind computation) {
  996. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  997. if (Function->isInAnonymousNamespace() &&
  998. !Function->isInExternCContext())
  999. return LinkageInfo::uniqueExternal();
  1000. // This is a "void f();" which got merged with a file static.
  1001. if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
  1002. return LinkageInfo::internal();
  1003. LinkageInfo LV;
  1004. if (!hasExplicitVisibilityAlready(computation)) {
  1005. if (Optional<Visibility> Vis =
  1006. getExplicitVisibility(Function, computation))
  1007. LV.mergeVisibility(*Vis, true);
  1008. }
  1009. // Note that Sema::MergeCompatibleFunctionDecls already takes care of
  1010. // merging storage classes and visibility attributes, so we don't have to
  1011. // look at previous decls in here.
  1012. return LV;
  1013. }
  1014. if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
  1015. if (Var->hasExternalStorage()) {
  1016. if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
  1017. return LinkageInfo::uniqueExternal();
  1018. LinkageInfo LV;
  1019. if (Var->getStorageClass() == SC_PrivateExtern)
  1020. LV.mergeVisibility(HiddenVisibility, true);
  1021. else if (!hasExplicitVisibilityAlready(computation)) {
  1022. if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
  1023. LV.mergeVisibility(*Vis, true);
  1024. }
  1025. if (const VarDecl *Prev = Var->getPreviousDecl()) {
  1026. LinkageInfo PrevLV = getLVForDecl(Prev, computation);
  1027. if (PrevLV.getLinkage())
  1028. LV.setLinkage(PrevLV.getLinkage());
  1029. LV.mergeVisibility(PrevLV);
  1030. }
  1031. return LV;
  1032. }
  1033. if (!Var->isStaticLocal())
  1034. return LinkageInfo::none();
  1035. }
  1036. ASTContext &Context = D->getASTContext();
  1037. if (!Context.getLangOpts().CPlusPlus)
  1038. return LinkageInfo::none();
  1039. const Decl *OuterD = getOutermostFuncOrBlockContext(D);
  1040. if (!OuterD)
  1041. return LinkageInfo::none();
  1042. LinkageInfo LV;
  1043. if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
  1044. if (!BD->getBlockManglingNumber())
  1045. return LinkageInfo::none();
  1046. LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
  1047. BD->getBlockManglingContextDecl(), computation);
  1048. } else {
  1049. const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
  1050. if (!FD->isInlined() &&
  1051. !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
  1052. return LinkageInfo::none();
  1053. LV = getLVForDecl(FD, computation);
  1054. }
  1055. if (!isExternallyVisible(LV.getLinkage()))
  1056. return LinkageInfo::none();
  1057. return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
  1058. LV.isVisibilityExplicit());
  1059. }
  1060. static inline const CXXRecordDecl*
  1061. getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
  1062. const CXXRecordDecl *Ret = Record;
  1063. while (Record && Record->isLambda()) {
  1064. Ret = Record;
  1065. if (!Record->getParent()) break;
  1066. // Get the Containing Class of this Lambda Class
  1067. Record = dyn_cast_or_null<CXXRecordDecl>(
  1068. Record->getParent()->getParent());
  1069. }
  1070. return Ret;
  1071. }
  1072. static LinkageInfo computeLVForDecl(const NamedDecl *D,
  1073. LVComputationKind computation) {
  1074. // Objective-C: treat all Objective-C declarations as having external
  1075. // linkage.
  1076. switch (D->getKind()) {
  1077. default:
  1078. break;
  1079. case Decl::ParmVar:
  1080. return LinkageInfo::none();
  1081. case Decl::TemplateTemplateParm: // count these as external
  1082. case Decl::NonTypeTemplateParm:
  1083. case Decl::ObjCAtDefsField:
  1084. case Decl::ObjCCategory:
  1085. case Decl::ObjCCategoryImpl:
  1086. case Decl::ObjCCompatibleAlias:
  1087. case Decl::ObjCImplementation:
  1088. case Decl::ObjCMethod:
  1089. case Decl::ObjCProperty:
  1090. case Decl::ObjCPropertyImpl:
  1091. case Decl::ObjCProtocol:
  1092. return LinkageInfo::external();
  1093. case Decl::CXXRecord: {
  1094. const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
  1095. if (Record->isLambda()) {
  1096. if (!Record->getLambdaManglingNumber()) {
  1097. // This lambda has no mangling number, so it's internal.
  1098. return LinkageInfo::internal();
  1099. }
  1100. // This lambda has its linkage/visibility determined:
  1101. // - either by the outermost lambda if that lambda has no mangling
  1102. // number.
  1103. // - or by the parent of the outer most lambda
  1104. // This prevents infinite recursion in settings such as nested lambdas
  1105. // used in NSDMI's, for e.g.
  1106. // struct L {
  1107. // int t{};
  1108. // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
  1109. // };
  1110. const CXXRecordDecl *OuterMostLambda =
  1111. getOutermostEnclosingLambda(Record);
  1112. if (!OuterMostLambda->getLambdaManglingNumber())
  1113. return LinkageInfo::internal();
  1114. return getLVForClosure(
  1115. OuterMostLambda->getDeclContext()->getRedeclContext(),
  1116. OuterMostLambda->getLambdaContextDecl(), computation);
  1117. }
  1118. break;
  1119. }
  1120. }
  1121. // Handle linkage for namespace-scope names.
  1122. if (D->getDeclContext()->getRedeclContext()->isFileContext())
  1123. return getLVForNamespaceScopeDecl(D, computation);
  1124. // C++ [basic.link]p5:
  1125. // In addition, a member function, static data member, a named
  1126. // class or enumeration of class scope, or an unnamed class or
  1127. // enumeration defined in a class-scope typedef declaration such
  1128. // that the class or enumeration has the typedef name for linkage
  1129. // purposes (7.1.3), has external linkage if the name of the class
  1130. // has external linkage.
  1131. if (D->getDeclContext()->isRecord())
  1132. return getLVForClassMember(D, computation);
  1133. // C++ [basic.link]p6:
  1134. // The name of a function declared in block scope and the name of
  1135. // an object declared by a block scope extern declaration have
  1136. // linkage. If there is a visible declaration of an entity with
  1137. // linkage having the same name and type, ignoring entities
  1138. // declared outside the innermost enclosing namespace scope, the
  1139. // block scope declaration declares that same entity and receives
  1140. // the linkage of the previous declaration. If there is more than
  1141. // one such matching entity, the program is ill-formed. Otherwise,
  1142. // if no matching entity is found, the block scope entity receives
  1143. // external linkage.
  1144. if (D->getDeclContext()->isFunctionOrMethod())
  1145. return getLVForLocalDecl(D, computation);
  1146. // C++ [basic.link]p6:
  1147. // Names not covered by these rules have no linkage.
  1148. return LinkageInfo::none();
  1149. }
  1150. namespace clang {
  1151. class LinkageComputer {
  1152. public:
  1153. static LinkageInfo getLVForDecl(const NamedDecl *D,
  1154. LVComputationKind computation) {
  1155. if (computation == LVForLinkageOnly && D->hasCachedLinkage())
  1156. return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
  1157. LinkageInfo LV = computeLVForDecl(D, computation);
  1158. if (D->hasCachedLinkage())
  1159. assert(D->getCachedLinkage() == LV.getLinkage());
  1160. D->setCachedLinkage(LV.getLinkage());
  1161. #ifndef NDEBUG
  1162. // In C (because of gnu inline) and in c++ with microsoft extensions an
  1163. // static can follow an extern, so we can have two decls with different
  1164. // linkages.
  1165. const LangOptions &Opts = D->getASTContext().getLangOpts();
  1166. (void)(Opts); // HLSL Change - this only has static consts referenced
  1167. if (!Opts.CPlusPlus || Opts.MicrosoftExt)
  1168. return LV;
  1169. // We have just computed the linkage for this decl. By induction we know
  1170. // that all other computed linkages match, check that the one we just
  1171. // computed also does.
  1172. NamedDecl *Old = nullptr;
  1173. for (auto I : D->redecls()) {
  1174. NamedDecl *T = cast<NamedDecl>(I);
  1175. if (T == D)
  1176. continue;
  1177. if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
  1178. Old = T;
  1179. break;
  1180. }
  1181. }
  1182. assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
  1183. #endif
  1184. return LV;
  1185. }
  1186. };
  1187. }
  1188. static LinkageInfo getLVForDecl(const NamedDecl *D,
  1189. LVComputationKind computation) {
  1190. return clang::LinkageComputer::getLVForDecl(D, computation);
  1191. }
  1192. std::string NamedDecl::getQualifiedNameAsString() const {
  1193. std::string QualName;
  1194. llvm::raw_string_ostream OS(QualName);
  1195. printQualifiedName(OS, getASTContext().getPrintingPolicy());
  1196. return OS.str();
  1197. }
  1198. void NamedDecl::printQualifiedName(raw_ostream &OS) const {
  1199. printQualifiedName(OS, getASTContext().getPrintingPolicy());
  1200. }
  1201. void NamedDecl::printQualifiedName(raw_ostream &OS,
  1202. const PrintingPolicy &P) const {
  1203. const DeclContext *Ctx = getDeclContext();
  1204. if (Ctx->isFunctionOrMethod()) {
  1205. printName(OS);
  1206. return;
  1207. }
  1208. typedef SmallVector<const DeclContext *, 8> ContextsTy;
  1209. ContextsTy Contexts;
  1210. // Collect contexts.
  1211. while (Ctx && isa<NamedDecl>(Ctx)) {
  1212. Contexts.push_back(Ctx);
  1213. Ctx = Ctx->getParent();
  1214. }
  1215. for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
  1216. I != E; ++I) {
  1217. if (const ClassTemplateSpecializationDecl *Spec
  1218. = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
  1219. OS << Spec->getName();
  1220. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  1221. TemplateSpecializationType::PrintTemplateArgumentList(OS,
  1222. TemplateArgs.data(),
  1223. TemplateArgs.size(),
  1224. P);
  1225. } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
  1226. if (P.SuppressUnwrittenScope &&
  1227. (ND->isAnonymousNamespace() || ND->isInline()))
  1228. continue;
  1229. if (ND->isAnonymousNamespace())
  1230. OS << "(anonymous namespace)";
  1231. else
  1232. OS << *ND;
  1233. } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
  1234. if (!RD->getIdentifier())
  1235. OS << "(anonymous " << RD->getKindName() << ')';
  1236. else
  1237. OS << *RD;
  1238. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  1239. const FunctionProtoType *FT = nullptr;
  1240. if (FD->hasWrittenPrototype())
  1241. FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
  1242. OS << *FD << '(';
  1243. if (FT) {
  1244. unsigned NumParams = FD->getNumParams();
  1245. for (unsigned i = 0; i < NumParams; ++i) {
  1246. if (i)
  1247. OS << ", ";
  1248. OS << FD->getParamDecl(i)->getType().stream(P);
  1249. }
  1250. if (FT->isVariadic()) {
  1251. if (NumParams > 0)
  1252. OS << ", ";
  1253. OS << "...";
  1254. }
  1255. }
  1256. OS << ')';
  1257. } else {
  1258. OS << *cast<NamedDecl>(*I);
  1259. }
  1260. OS << "::";
  1261. }
  1262. if (getDeclName())
  1263. OS << *this;
  1264. else
  1265. OS << "(anonymous)";
  1266. }
  1267. void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
  1268. const PrintingPolicy &Policy,
  1269. bool Qualified) const {
  1270. if (Qualified)
  1271. printQualifiedName(OS, Policy);
  1272. else
  1273. printName(OS);
  1274. }
  1275. static bool isKindReplaceableBy(Decl::Kind OldK, Decl::Kind NewK) {
  1276. // For method declarations, we never replace.
  1277. if (ObjCMethodDecl::classofKind(NewK))
  1278. return false;
  1279. if (OldK == NewK)
  1280. return true;
  1281. // A compatibility alias for a class can be replaced by an interface.
  1282. if (ObjCCompatibleAliasDecl::classofKind(OldK) &&
  1283. ObjCInterfaceDecl::classofKind(NewK))
  1284. return true;
  1285. // A typedef-declaration, alias-declaration, or Objective-C class declaration
  1286. // can replace another declaration of the same type. Semantic analysis checks
  1287. // that we have matching types.
  1288. if ((TypedefNameDecl::classofKind(OldK) ||
  1289. ObjCInterfaceDecl::classofKind(OldK)) &&
  1290. (TypedefNameDecl::classofKind(NewK) ||
  1291. ObjCInterfaceDecl::classofKind(NewK)))
  1292. return true;
  1293. // Otherwise, a kind mismatch implies that the declaration is not replaced.
  1294. return false;
  1295. }
  1296. template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
  1297. return true;
  1298. }
  1299. static bool isRedeclarableImpl(...) { return false; }
  1300. static bool isRedeclarable(Decl::Kind K) {
  1301. switch (K) {
  1302. #define DECL(Type, Base) \
  1303. case Decl::Type: \
  1304. return isRedeclarableImpl((Type##Decl *)nullptr);
  1305. #define ABSTRACT_DECL(DECL)
  1306. #include "clang/AST/DeclNodes.inc"
  1307. }
  1308. llvm_unreachable("unknown decl kind");
  1309. }
  1310. bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
  1311. assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
  1312. // Never replace one imported declaration with another; we need both results
  1313. // when re-exporting.
  1314. if (OldD->isFromASTFile() && isFromASTFile())
  1315. return false;
  1316. if (!isKindReplaceableBy(OldD->getKind(), getKind()))
  1317. return false;
  1318. // Inline namespaces can give us two declarations with the same
  1319. // name and kind in the same scope but different contexts; we should
  1320. // keep both declarations in this case.
  1321. if (!this->getDeclContext()->getRedeclContext()->Equals(
  1322. OldD->getDeclContext()->getRedeclContext()))
  1323. return false;
  1324. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
  1325. // For function declarations, we keep track of redeclarations.
  1326. // FIXME: This returns false for functions that should in fact be replaced.
  1327. // Instead, perform some kind of type check?
  1328. if (FD->getPreviousDecl() != OldD)
  1329. return false;
  1330. // For function templates, the underlying function declarations are linked.
  1331. if (const FunctionTemplateDecl *FunctionTemplate =
  1332. dyn_cast<FunctionTemplateDecl>(this))
  1333. return FunctionTemplate->getTemplatedDecl()->declarationReplaces(
  1334. cast<FunctionTemplateDecl>(OldD)->getTemplatedDecl());
  1335. // Using shadow declarations can be overloaded on their target declarations
  1336. // if they introduce functions.
  1337. // FIXME: If our target replaces the old target, can we replace the old
  1338. // shadow declaration?
  1339. if (auto *USD = dyn_cast<UsingShadowDecl>(this))
  1340. if (USD->getTargetDecl() != cast<UsingShadowDecl>(OldD)->getTargetDecl())
  1341. return false;
  1342. // Using declarations can be overloaded if they introduce functions.
  1343. if (auto *UD = dyn_cast<UsingDecl>(this)) {
  1344. ASTContext &Context = getASTContext();
  1345. return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
  1346. Context.getCanonicalNestedNameSpecifier(
  1347. cast<UsingDecl>(OldD)->getQualifier());
  1348. }
  1349. if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
  1350. ASTContext &Context = getASTContext();
  1351. return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
  1352. Context.getCanonicalNestedNameSpecifier(
  1353. cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
  1354. }
  1355. // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
  1356. // We want to keep it, unless it nominates same namespace.
  1357. if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
  1358. return UD->getNominatedNamespace()->getOriginalNamespace() ==
  1359. cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
  1360. ->getOriginalNamespace();
  1361. if (!IsKnownNewer && isRedeclarable(getKind())) {
  1362. // Check whether this is actually newer than OldD. We want to keep the
  1363. // newer declaration. This loop will usually only iterate once, because
  1364. // OldD is usually the previous declaration.
  1365. for (auto D : redecls()) {
  1366. if (D == OldD)
  1367. break;
  1368. // If we reach the canonical declaration, then OldD is not actually older
  1369. // than this one.
  1370. //
  1371. // FIXME: In this case, we should not add this decl to the lookup table.
  1372. if (D->isCanonicalDecl())
  1373. return false;
  1374. }
  1375. }
  1376. // It's a newer declaration of the same kind of declaration in the same scope,
  1377. // and not an overload: we want this decl instead of the existing one.
  1378. return true;
  1379. }
  1380. bool NamedDecl::hasLinkage() const {
  1381. return getFormalLinkage() != NoLinkage;
  1382. }
  1383. NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
  1384. NamedDecl *ND = this;
  1385. while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
  1386. ND = UD->getTargetDecl();
  1387. if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
  1388. return AD->getClassInterface();
  1389. return ND;
  1390. }
  1391. bool NamedDecl::isCXXInstanceMember() const {
  1392. if (!isCXXClassMember())
  1393. return false;
  1394. const NamedDecl *D = this;
  1395. if (isa<UsingShadowDecl>(D))
  1396. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  1397. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
  1398. return true;
  1399. if (const CXXMethodDecl *MD =
  1400. dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
  1401. return MD->isInstance();
  1402. return false;
  1403. }
  1404. //===----------------------------------------------------------------------===//
  1405. // DeclaratorDecl Implementation
  1406. //===----------------------------------------------------------------------===//
  1407. template <typename DeclT>
  1408. static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
  1409. if (decl->getNumTemplateParameterLists() > 0)
  1410. return decl->getTemplateParameterList(0)->getTemplateLoc();
  1411. else
  1412. return decl->getInnerLocStart();
  1413. }
  1414. SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
  1415. TypeSourceInfo *TSI = getTypeSourceInfo();
  1416. if (TSI) return TSI->getTypeLoc().getBeginLoc();
  1417. return SourceLocation();
  1418. }
  1419. void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
  1420. if (QualifierLoc) {
  1421. // Make sure the extended decl info is allocated.
  1422. if (!hasExtInfo()) {
  1423. // Save (non-extended) type source info pointer.
  1424. TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
  1425. // Allocate external info struct.
  1426. DeclInfo = new (getASTContext()) ExtInfo;
  1427. // Restore savedTInfo into (extended) decl info.
  1428. getExtInfo()->TInfo = savedTInfo;
  1429. }
  1430. // Set qualifier info.
  1431. getExtInfo()->QualifierLoc = QualifierLoc;
  1432. } else {
  1433. // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
  1434. if (hasExtInfo()) {
  1435. if (getExtInfo()->NumTemplParamLists == 0) {
  1436. // Save type source info pointer.
  1437. TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
  1438. // Deallocate the extended decl info.
  1439. getASTContext().Deallocate(getExtInfo());
  1440. // Restore savedTInfo into (non-extended) decl info.
  1441. DeclInfo = savedTInfo;
  1442. }
  1443. else
  1444. getExtInfo()->QualifierLoc = QualifierLoc;
  1445. }
  1446. }
  1447. }
  1448. void
  1449. DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
  1450. unsigned NumTPLists,
  1451. TemplateParameterList **TPLists) {
  1452. assert(NumTPLists > 0);
  1453. // Make sure the extended decl info is allocated.
  1454. if (!hasExtInfo()) {
  1455. // Save (non-extended) type source info pointer.
  1456. TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
  1457. // Allocate external info struct.
  1458. DeclInfo = new (getASTContext()) ExtInfo;
  1459. // Restore savedTInfo into (extended) decl info.
  1460. getExtInfo()->TInfo = savedTInfo;
  1461. }
  1462. // Set the template parameter lists info.
  1463. getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
  1464. }
  1465. SourceLocation DeclaratorDecl::getOuterLocStart() const {
  1466. return getTemplateOrInnerLocStart(this);
  1467. }
  1468. namespace {
  1469. // Helper function: returns true if QT is or contains a type
  1470. // having a postfix component.
  1471. bool typeIsPostfix(clang::QualType QT) {
  1472. while (true) {
  1473. const Type* T = QT.getTypePtr();
  1474. switch (T->getTypeClass()) {
  1475. default:
  1476. return false;
  1477. case Type::Pointer:
  1478. QT = cast<PointerType>(T)->getPointeeType();
  1479. break;
  1480. case Type::BlockPointer:
  1481. QT = cast<BlockPointerType>(T)->getPointeeType();
  1482. break;
  1483. case Type::MemberPointer:
  1484. QT = cast<MemberPointerType>(T)->getPointeeType();
  1485. break;
  1486. case Type::LValueReference:
  1487. case Type::RValueReference:
  1488. QT = cast<ReferenceType>(T)->getPointeeType();
  1489. break;
  1490. case Type::PackExpansion:
  1491. QT = cast<PackExpansionType>(T)->getPattern();
  1492. break;
  1493. case Type::Paren:
  1494. case Type::ConstantArray:
  1495. case Type::DependentSizedArray:
  1496. case Type::IncompleteArray:
  1497. case Type::VariableArray:
  1498. case Type::FunctionProto:
  1499. case Type::FunctionNoProto:
  1500. return true;
  1501. }
  1502. }
  1503. }
  1504. } // namespace
  1505. SourceRange DeclaratorDecl::getSourceRange() const {
  1506. SourceLocation RangeEnd = getLocation();
  1507. if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
  1508. // If the declaration has no name or the type extends past the name take the
  1509. // end location of the type.
  1510. if (!getDeclName() || typeIsPostfix(TInfo->getType()))
  1511. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  1512. }
  1513. return SourceRange(getOuterLocStart(), RangeEnd);
  1514. }
  1515. void
  1516. QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
  1517. unsigned NumTPLists,
  1518. TemplateParameterList **TPLists) {
  1519. assert((NumTPLists == 0 || TPLists != nullptr) &&
  1520. "Empty array of template parameters with positive size!");
  1521. // Free previous template parameters (if any).
  1522. if (NumTemplParamLists > 0) {
  1523. Context.Deallocate(TemplParamLists);
  1524. TemplParamLists = nullptr;
  1525. NumTemplParamLists = 0;
  1526. }
  1527. // Set info on matched template parameter lists (if any).
  1528. if (NumTPLists > 0) {
  1529. TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
  1530. NumTemplParamLists = NumTPLists;
  1531. std::copy(TPLists, TPLists + NumTPLists, TemplParamLists);
  1532. }
  1533. }
  1534. //===----------------------------------------------------------------------===//
  1535. // VarDecl Implementation
  1536. //===----------------------------------------------------------------------===//
  1537. const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
  1538. switch (SC) {
  1539. case SC_None: break;
  1540. case SC_Auto: return "auto";
  1541. case SC_Extern: return "extern";
  1542. case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
  1543. case SC_PrivateExtern: return "__private_extern__";
  1544. case SC_Register: return "register";
  1545. case SC_Static: return "static";
  1546. }
  1547. llvm_unreachable("Invalid storage class");
  1548. }
  1549. VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
  1550. SourceLocation StartLoc, SourceLocation IdLoc,
  1551. IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
  1552. StorageClass SC)
  1553. : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
  1554. redeclarable_base(C), Init() {
  1555. static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
  1556. "VarDeclBitfields too large!");
  1557. static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
  1558. "ParmVarDeclBitfields too large!");
  1559. static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
  1560. "NonParmVarDeclBitfields too large!");
  1561. AllBits = 0;
  1562. VarDeclBits.SClass = SC;
  1563. // Everything else is implicitly initialized to false.
  1564. }
  1565. VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
  1566. SourceLocation StartL, SourceLocation IdL,
  1567. IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
  1568. StorageClass S) {
  1569. return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
  1570. }
  1571. VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  1572. return new (C, ID)
  1573. VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
  1574. QualType(), nullptr, SC_None);
  1575. }
  1576. void VarDecl::setStorageClass(StorageClass SC) {
  1577. assert(isLegalForVariable(SC));
  1578. VarDeclBits.SClass = SC;
  1579. }
  1580. VarDecl::TLSKind VarDecl::getTLSKind() const {
  1581. switch (VarDeclBits.TSCSpec) {
  1582. case TSCS_unspecified:
  1583. if (!hasAttr<ThreadAttr>() &&
  1584. !(getASTContext().getLangOpts().OpenMPUseTLS &&
  1585. getASTContext().getTargetInfo().isTLSSupported() &&
  1586. hasAttr<OMPThreadPrivateDeclAttr>()))
  1587. return TLS_None;
  1588. return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
  1589. LangOptions::MSVC2015)) ||
  1590. hasAttr<OMPThreadPrivateDeclAttr>())
  1591. ? TLS_Dynamic
  1592. : TLS_Static;
  1593. case TSCS___thread: // Fall through.
  1594. case TSCS__Thread_local:
  1595. return TLS_Static;
  1596. case TSCS_thread_local:
  1597. return TLS_Dynamic;
  1598. }
  1599. llvm_unreachable("Unknown thread storage class specifier!");
  1600. }
  1601. SourceRange VarDecl::getSourceRange() const {
  1602. if (const Expr *Init = getInit()) {
  1603. SourceLocation InitEnd = Init->getLocEnd();
  1604. // If Init is implicit, ignore its source range and fallback on
  1605. // DeclaratorDecl::getSourceRange() to handle postfix elements.
  1606. if (InitEnd.isValid() && InitEnd != getLocation())
  1607. return SourceRange(getOuterLocStart(), InitEnd);
  1608. }
  1609. return DeclaratorDecl::getSourceRange();
  1610. }
  1611. template<typename T>
  1612. static LanguageLinkage getDeclLanguageLinkage(const T &D) {
  1613. // C++ [dcl.link]p1: All function types, function names with external linkage,
  1614. // and variable names with external linkage have a language linkage.
  1615. if (!D.hasExternalFormalLinkage())
  1616. return NoLanguageLinkage;
  1617. // Language linkage is a C++ concept, but saying that everything else in C has
  1618. // C language linkage fits the implementation nicely.
  1619. ASTContext &Context = D.getASTContext();
  1620. if (!Context.getLangOpts().CPlusPlus)
  1621. return CLanguageLinkage;
  1622. // C++ [dcl.link]p4: A C language linkage is ignored in determining the
  1623. // language linkage of the names of class members and the function type of
  1624. // class member functions.
  1625. const DeclContext *DC = D.getDeclContext();
  1626. if (DC->isRecord())
  1627. return CXXLanguageLinkage;
  1628. // If the first decl is in an extern "C" context, any other redeclaration
  1629. // will have C language linkage. If the first one is not in an extern "C"
  1630. // context, we would have reported an error for any other decl being in one.
  1631. if (isFirstInExternCContext(&D))
  1632. return CLanguageLinkage;
  1633. return CXXLanguageLinkage;
  1634. }
  1635. template<typename T>
  1636. static bool isDeclExternC(const T &D) {
  1637. // Since the context is ignored for class members, they can only have C++
  1638. // language linkage or no language linkage.
  1639. const DeclContext *DC = D.getDeclContext();
  1640. if (DC->isRecord()) {
  1641. assert(D.getASTContext().getLangOpts().CPlusPlus);
  1642. return false;
  1643. }
  1644. return D.getLanguageLinkage() == CLanguageLinkage;
  1645. }
  1646. LanguageLinkage VarDecl::getLanguageLinkage() const {
  1647. return getDeclLanguageLinkage(*this);
  1648. }
  1649. bool VarDecl::isExternC() const {
  1650. return isDeclExternC(*this);
  1651. }
  1652. bool VarDecl::isInExternCContext() const {
  1653. return getLexicalDeclContext()->isExternCContext();
  1654. }
  1655. bool VarDecl::isInExternCXXContext() const {
  1656. return getLexicalDeclContext()->isExternCXXContext();
  1657. }
  1658. VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
  1659. VarDecl::DefinitionKind
  1660. VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
  1661. // C++ [basic.def]p2:
  1662. // A declaration is a definition unless [...] it contains the 'extern'
  1663. // specifier or a linkage-specification and neither an initializer [...],
  1664. // it declares a static data member in a class declaration [...].
  1665. // C++1y [temp.expl.spec]p15:
  1666. // An explicit specialization of a static data member or an explicit
  1667. // specialization of a static data member template is a definition if the
  1668. // declaration includes an initializer; otherwise, it is a declaration.
  1669. //
  1670. // FIXME: How do you declare (but not define) a partial specialization of
  1671. // a static data member template outside the containing class?
  1672. if (isStaticDataMember()) {
  1673. if (isOutOfLine() &&
  1674. (hasInit() ||
  1675. // If the first declaration is out-of-line, this may be an
  1676. // instantiation of an out-of-line partial specialization of a variable
  1677. // template for which we have not yet instantiated the initializer.
  1678. (getFirstDecl()->isOutOfLine()
  1679. ? getTemplateSpecializationKind() == TSK_Undeclared
  1680. : getTemplateSpecializationKind() !=
  1681. TSK_ExplicitSpecialization) ||
  1682. isa<VarTemplatePartialSpecializationDecl>(this)))
  1683. return Definition;
  1684. else
  1685. return DeclarationOnly;
  1686. }
  1687. // C99 6.7p5:
  1688. // A definition of an identifier is a declaration for that identifier that
  1689. // [...] causes storage to be reserved for that object.
  1690. // Note: that applies for all non-file-scope objects.
  1691. // C99 6.9.2p1:
  1692. // If the declaration of an identifier for an object has file scope and an
  1693. // initializer, the declaration is an external definition for the identifier
  1694. if (hasInit())
  1695. return Definition;
  1696. if (hasAttr<AliasAttr>())
  1697. return Definition;
  1698. if (const auto *SAA = getAttr<SelectAnyAttr>())
  1699. if (!SAA->isInherited())
  1700. return Definition;
  1701. // A variable template specialization (other than a static data member
  1702. // template or an explicit specialization) is a declaration until we
  1703. // instantiate its initializer.
  1704. if (isa<VarTemplateSpecializationDecl>(this) &&
  1705. getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  1706. return DeclarationOnly;
  1707. if (!getASTContext().getLangOpts().HLSL) // HLSL Change - take extern as define to match fxc.
  1708. if (hasExternalStorage())
  1709. return DeclarationOnly;
  1710. // [dcl.link] p7:
  1711. // A declaration directly contained in a linkage-specification is treated
  1712. // as if it contains the extern specifier for the purpose of determining
  1713. // the linkage of the declared name and whether it is a definition.
  1714. if (isSingleLineLanguageLinkage(*this))
  1715. return DeclarationOnly;
  1716. // C99 6.9.2p2:
  1717. // A declaration of an object that has file scope without an initializer,
  1718. // and without a storage class specifier or the scs 'static', constitutes
  1719. // a tentative definition.
  1720. // No such thing in C++.
  1721. if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
  1722. return TentativeDefinition;
  1723. // What's left is (in C, block-scope) declarations without initializers or
  1724. // external storage. These are definitions.
  1725. return Definition;
  1726. }
  1727. VarDecl *VarDecl::getActingDefinition() {
  1728. DefinitionKind Kind = isThisDeclarationADefinition();
  1729. if (Kind != TentativeDefinition)
  1730. return nullptr;
  1731. VarDecl *LastTentative = nullptr;
  1732. VarDecl *First = getFirstDecl();
  1733. for (auto I : First->redecls()) {
  1734. Kind = I->isThisDeclarationADefinition();
  1735. if (Kind == Definition)
  1736. return nullptr;
  1737. else if (Kind == TentativeDefinition)
  1738. LastTentative = I;
  1739. }
  1740. return LastTentative;
  1741. }
  1742. VarDecl *VarDecl::getDefinition(ASTContext &C) {
  1743. VarDecl *First = getFirstDecl();
  1744. for (auto I : First->redecls()) {
  1745. if (I->isThisDeclarationADefinition(C) == Definition)
  1746. return I;
  1747. }
  1748. return nullptr;
  1749. }
  1750. VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
  1751. DefinitionKind Kind = DeclarationOnly;
  1752. const VarDecl *First = getFirstDecl();
  1753. for (auto I : First->redecls()) {
  1754. Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
  1755. if (Kind == Definition)
  1756. break;
  1757. }
  1758. return Kind;
  1759. }
  1760. const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
  1761. for (auto I : redecls()) {
  1762. if (auto Expr = I->getInit()) {
  1763. D = I;
  1764. return Expr;
  1765. }
  1766. }
  1767. return nullptr;
  1768. }
  1769. bool VarDecl::isOutOfLine() const {
  1770. if (Decl::isOutOfLine())
  1771. return true;
  1772. if (!isStaticDataMember())
  1773. return false;
  1774. // If this static data member was instantiated from a static data member of
  1775. // a class template, check whether that static data member was defined
  1776. // out-of-line.
  1777. if (VarDecl *VD = getInstantiatedFromStaticDataMember())
  1778. return VD->isOutOfLine();
  1779. return false;
  1780. }
  1781. VarDecl *VarDecl::getOutOfLineDefinition() {
  1782. if (!isStaticDataMember())
  1783. return nullptr;
  1784. for (auto RD : redecls()) {
  1785. if (RD->getLexicalDeclContext()->isFileContext())
  1786. return RD;
  1787. }
  1788. return nullptr;
  1789. }
  1790. void VarDecl::setInit(Expr *I) {
  1791. if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
  1792. Eval->~EvaluatedStmt();
  1793. getASTContext().Deallocate(Eval);
  1794. }
  1795. Init = I;
  1796. }
  1797. bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
  1798. const LangOptions &Lang = C.getLangOpts();
  1799. (void)(Lang); // HLSL Change - this object is only accessed through static consts
  1800. // HLSL Change: non-static globals are constant buffer variables that look
  1801. // like const globals, but cannot be used in constant expressions.
  1802. if (Lang.HLSL && hasGlobalStorage() && getStorageClass() != SC_Static)
  1803. return false;
  1804. if (!Lang.CPlusPlus)
  1805. return false;
  1806. // In C++11, any variable of reference type can be used in a constant
  1807. // expression if it is initialized by a constant expression.
  1808. if (Lang.CPlusPlus11 && getType()->isReferenceType())
  1809. return true;
  1810. // Only const objects can be used in constant expressions in C++. C++98 does
  1811. // not require the variable to be non-volatile, but we consider this to be a
  1812. // defect.
  1813. if (!getType().isConstQualified() || getType().isVolatileQualified())
  1814. return false;
  1815. // In C++, const, non-volatile variables of integral or enumeration types
  1816. // can be used in constant expressions.
  1817. if (getType()->isIntegralOrEnumerationType())
  1818. return true;
  1819. // Additionally, in C++11, non-volatile constexpr variables can be used in
  1820. // constant expressions.
  1821. return Lang.CPlusPlus11 && isConstexpr();
  1822. }
  1823. /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
  1824. /// form, which contains extra information on the evaluated value of the
  1825. /// initializer.
  1826. EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
  1827. EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
  1828. if (!Eval) {
  1829. Stmt *S = Init.get<Stmt *>();
  1830. // Note: EvaluatedStmt contains an APValue, which usually holds
  1831. // resources not allocated from the ASTContext. We need to do some
  1832. // work to avoid leaking those, but we do so in VarDecl::evaluateValue
  1833. // where we can detect whether there's anything to clean up or not.
  1834. Eval = new (getASTContext()) EvaluatedStmt;
  1835. Eval->Value = S;
  1836. Init = Eval;
  1837. }
  1838. return Eval;
  1839. }
  1840. APValue *VarDecl::evaluateValue() const {
  1841. SmallVector<PartialDiagnosticAt, 8> Notes;
  1842. return evaluateValue(Notes);
  1843. }
  1844. namespace {
  1845. // Destroy an APValue that was allocated in an ASTContext.
  1846. void DestroyAPValue(void* UntypedValue) {
  1847. static_cast<APValue*>(UntypedValue)->~APValue();
  1848. }
  1849. } // namespace
  1850. APValue *VarDecl::evaluateValue(
  1851. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  1852. EvaluatedStmt *Eval = ensureEvaluatedStmt();
  1853. // We only produce notes indicating why an initializer is non-constant the
  1854. // first time it is evaluated. FIXME: The notes won't always be emitted the
  1855. // first time we try evaluation, so might not be produced at all.
  1856. if (Eval->WasEvaluated)
  1857. return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
  1858. const Expr *Init = cast<Expr>(Eval->Value);
  1859. assert(!Init->isValueDependent());
  1860. if (Eval->IsEvaluating) {
  1861. // FIXME: Produce a diagnostic for self-initialization.
  1862. Eval->CheckedICE = true;
  1863. Eval->IsICE = false;
  1864. return nullptr;
  1865. }
  1866. Eval->IsEvaluating = true;
  1867. bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
  1868. this, Notes);
  1869. // Ensure the computed APValue is cleaned up later if evaluation succeeded,
  1870. // or that it's empty (so that there's nothing to clean up) if evaluation
  1871. // failed.
  1872. if (!Result)
  1873. Eval->Evaluated = APValue();
  1874. else if (Eval->Evaluated.needsCleanup())
  1875. getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
  1876. Eval->IsEvaluating = false;
  1877. Eval->WasEvaluated = true;
  1878. // In C++11, we have determined whether the initializer was a constant
  1879. // expression as a side-effect.
  1880. if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
  1881. Eval->CheckedICE = true;
  1882. Eval->IsICE = Result && Notes.empty();
  1883. }
  1884. return Result ? &Eval->Evaluated : nullptr;
  1885. }
  1886. bool VarDecl::checkInitIsICE() const {
  1887. // Initializers of weak variables are never ICEs.
  1888. if (isWeak())
  1889. return false;
  1890. EvaluatedStmt *Eval = ensureEvaluatedStmt();
  1891. if (Eval->CheckedICE)
  1892. // We have already checked whether this subexpression is an
  1893. // integral constant expression.
  1894. return Eval->IsICE;
  1895. const Expr *Init = cast<Expr>(Eval->Value);
  1896. assert(!Init->isValueDependent());
  1897. // In C++11, evaluate the initializer to check whether it's a constant
  1898. // expression.
  1899. if (getASTContext().getLangOpts().CPlusPlus11) {
  1900. SmallVector<PartialDiagnosticAt, 8> Notes;
  1901. evaluateValue(Notes);
  1902. return Eval->IsICE;
  1903. }
  1904. // It's an ICE whether or not the definition we found is
  1905. // out-of-line. See DR 721 and the discussion in Clang PR
  1906. // 6206 for details.
  1907. if (Eval->CheckingICE)
  1908. return false;
  1909. Eval->CheckingICE = true;
  1910. Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
  1911. Eval->CheckingICE = false;
  1912. Eval->CheckedICE = true;
  1913. return Eval->IsICE;
  1914. }
  1915. VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
  1916. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  1917. return cast<VarDecl>(MSI->getInstantiatedFrom());
  1918. return nullptr;
  1919. }
  1920. TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
  1921. if (const VarTemplateSpecializationDecl *Spec =
  1922. dyn_cast<VarTemplateSpecializationDecl>(this))
  1923. return Spec->getSpecializationKind();
  1924. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  1925. return MSI->getTemplateSpecializationKind();
  1926. return TSK_Undeclared;
  1927. }
  1928. SourceLocation VarDecl::getPointOfInstantiation() const {
  1929. if (const VarTemplateSpecializationDecl *Spec =
  1930. dyn_cast<VarTemplateSpecializationDecl>(this))
  1931. return Spec->getPointOfInstantiation();
  1932. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  1933. return MSI->getPointOfInstantiation();
  1934. return SourceLocation();
  1935. }
  1936. VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
  1937. return getASTContext().getTemplateOrSpecializationInfo(this)
  1938. .dyn_cast<VarTemplateDecl *>();
  1939. }
  1940. void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
  1941. getASTContext().setTemplateOrSpecializationInfo(this, Template);
  1942. }
  1943. MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
  1944. if (isStaticDataMember())
  1945. // FIXME: Remove ?
  1946. // return getASTContext().getInstantiatedFromStaticDataMember(this);
  1947. return getASTContext().getTemplateOrSpecializationInfo(this)
  1948. .dyn_cast<MemberSpecializationInfo *>();
  1949. return nullptr;
  1950. }
  1951. void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  1952. SourceLocation PointOfInstantiation) {
  1953. assert((isa<VarTemplateSpecializationDecl>(this) ||
  1954. getMemberSpecializationInfo()) &&
  1955. "not a variable or static data member template specialization");
  1956. if (VarTemplateSpecializationDecl *Spec =
  1957. dyn_cast<VarTemplateSpecializationDecl>(this)) {
  1958. Spec->setSpecializationKind(TSK);
  1959. if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
  1960. Spec->getPointOfInstantiation().isInvalid())
  1961. Spec->setPointOfInstantiation(PointOfInstantiation);
  1962. }
  1963. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
  1964. MSI->setTemplateSpecializationKind(TSK);
  1965. if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
  1966. MSI->getPointOfInstantiation().isInvalid())
  1967. MSI->setPointOfInstantiation(PointOfInstantiation);
  1968. }
  1969. }
  1970. void
  1971. VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
  1972. TemplateSpecializationKind TSK) {
  1973. assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
  1974. "Previous template or instantiation?");
  1975. getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
  1976. }
  1977. //===----------------------------------------------------------------------===//
  1978. // ParmVarDecl Implementation
  1979. //===----------------------------------------------------------------------===//
  1980. ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
  1981. SourceLocation StartLoc,
  1982. SourceLocation IdLoc, IdentifierInfo *Id,
  1983. QualType T, TypeSourceInfo *TInfo,
  1984. StorageClass S, Expr *DefArg,
  1985. hlsl::ParameterModifier ParamMod) {
  1986. return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
  1987. S, DefArg, ParamMod);
  1988. }
  1989. QualType ParmVarDecl::getOriginalType() const {
  1990. TypeSourceInfo *TSI = getTypeSourceInfo();
  1991. QualType T = TSI ? TSI->getType() : getType();
  1992. if (const DecayedType *DT = dyn_cast<DecayedType>(T))
  1993. return DT->getOriginalType();
  1994. return T;
  1995. }
  1996. ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  1997. return new (C, ID)
  1998. ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
  1999. nullptr, QualType(), nullptr, SC_None, nullptr, hlsl::ParameterModifier());
  2000. }
  2001. SourceRange ParmVarDecl::getSourceRange() const {
  2002. if (!hasInheritedDefaultArg()) {
  2003. SourceRange ArgRange = getDefaultArgRange();
  2004. if (ArgRange.isValid())
  2005. return SourceRange(getOuterLocStart(), ArgRange.getEnd());
  2006. }
  2007. // DeclaratorDecl considers the range of postfix types as overlapping with the
  2008. // declaration name, but this is not the case with parameters in ObjC methods.
  2009. if (isa<ObjCMethodDecl>(getDeclContext()))
  2010. return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
  2011. return DeclaratorDecl::getSourceRange();
  2012. }
  2013. Expr *ParmVarDecl::getDefaultArg() {
  2014. assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
  2015. assert(!hasUninstantiatedDefaultArg() &&
  2016. "Default argument is not yet instantiated!");
  2017. Expr *Arg = getInit();
  2018. if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
  2019. return E->getSubExpr();
  2020. return Arg;
  2021. }
  2022. SourceRange ParmVarDecl::getDefaultArgRange() const {
  2023. if (const Expr *E = getInit())
  2024. return E->getSourceRange();
  2025. if (hasUninstantiatedDefaultArg())
  2026. return getUninstantiatedDefaultArg()->getSourceRange();
  2027. return SourceRange();
  2028. }
  2029. bool ParmVarDecl::isParameterPack() const {
  2030. return isa<PackExpansionType>(getType());
  2031. }
  2032. void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
  2033. getASTContext().setParameterIndex(this, parameterIndex);
  2034. ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
  2035. }
  2036. unsigned ParmVarDecl::getParameterIndexLarge() const {
  2037. return getASTContext().getParameterIndex(this);
  2038. }
  2039. // HLSL Change Begins
  2040. void ParmVarDecl::updateOutParamToRefType(ASTContext &C) {
  2041. // Aggregate type will be indirect param convert to pointer type.
  2042. // So don't update to ReferenceType.
  2043. if ((!getType()->isArrayType() && !getType()->isRecordType()) ||
  2044. hlsl::IsHLSLVecMatType(getType()))
  2045. setType(C.getLValueReferenceType(getType(), false));
  2046. // Add restrict to out param.
  2047. QualType QT = getType();
  2048. QT.addRestrict();
  2049. setType(QT);
  2050. }
  2051. // HLSL Change Ends
  2052. //===----------------------------------------------------------------------===//
  2053. // FunctionDecl Implementation
  2054. //===----------------------------------------------------------------------===//
  2055. void FunctionDecl::getNameForDiagnostic(
  2056. raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
  2057. NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
  2058. const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
  2059. if (TemplateArgs)
  2060. TemplateSpecializationType::PrintTemplateArgumentList(
  2061. OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
  2062. }
  2063. bool FunctionDecl::isVariadic() const {
  2064. if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
  2065. return FT->isVariadic();
  2066. return false;
  2067. }
  2068. bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
  2069. for (auto I : redecls()) {
  2070. if (I->Body || I->IsLateTemplateParsed) {
  2071. Definition = I;
  2072. return true;
  2073. }
  2074. }
  2075. return false;
  2076. }
  2077. bool FunctionDecl::hasTrivialBody() const
  2078. {
  2079. Stmt *S = getBody();
  2080. if (!S) {
  2081. // Since we don't have a body for this function, we don't know if it's
  2082. // trivial or not.
  2083. return false;
  2084. }
  2085. if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
  2086. return true;
  2087. return false;
  2088. }
  2089. bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
  2090. for (auto I : redecls()) {
  2091. if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
  2092. I->hasAttr<AliasAttr>()) {
  2093. Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
  2094. return true;
  2095. }
  2096. }
  2097. return false;
  2098. }
  2099. Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
  2100. if (!hasBody(Definition))
  2101. return nullptr;
  2102. if (Definition->Body)
  2103. return Definition->Body.get(getASTContext().getExternalSource());
  2104. return nullptr;
  2105. }
  2106. void FunctionDecl::setBody(Stmt *B) {
  2107. Body = B;
  2108. if (B)
  2109. EndRangeLoc = B->getLocEnd();
  2110. }
  2111. void FunctionDecl::setPure(bool P) {
  2112. IsPure = P;
  2113. if (P)
  2114. if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
  2115. Parent->markedVirtualFunctionPure();
  2116. }
  2117. template<std::size_t Len>
  2118. static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
  2119. IdentifierInfo *II = ND->getIdentifier();
  2120. return II && II->isStr(Str);
  2121. }
  2122. bool FunctionDecl::isMain() const {
  2123. const TranslationUnitDecl *tunit =
  2124. dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
  2125. return tunit &&
  2126. !tunit->getASTContext().getLangOpts().Freestanding &&
  2127. isNamed(this, "main");
  2128. }
  2129. bool FunctionDecl::isMSVCRTEntryPoint() const {
  2130. const TranslationUnitDecl *TUnit =
  2131. dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
  2132. if (!TUnit)
  2133. return false;
  2134. // Even though we aren't really targeting MSVCRT if we are freestanding,
  2135. // semantic analysis for these functions remains the same.
  2136. // MSVCRT entry points only exist on MSVCRT targets.
  2137. if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
  2138. return false;
  2139. // Nameless functions like constructors cannot be entry points.
  2140. if (!getIdentifier())
  2141. return false;
  2142. return llvm::StringSwitch<bool>(getName())
  2143. .Cases("main", // an ANSI console app
  2144. "wmain", // a Unicode console App
  2145. "WinMain", // an ANSI GUI app
  2146. "wWinMain", // a Unicode GUI app
  2147. "DllMain", // a DLL
  2148. true)
  2149. .Default(false);
  2150. }
  2151. bool FunctionDecl::isReservedGlobalPlacementOperator() const {
  2152. assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
  2153. assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
  2154. getDeclName().getCXXOverloadedOperator() == OO_Delete ||
  2155. getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
  2156. getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
  2157. if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
  2158. return false;
  2159. const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
  2160. if (proto->getNumParams() != 2 || proto->isVariadic())
  2161. return false;
  2162. ASTContext &Context =
  2163. cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
  2164. ->getASTContext();
  2165. // The result type and first argument type are constant across all
  2166. // these operators. The second argument must be exactly void*.
  2167. return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
  2168. }
  2169. bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
  2170. if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
  2171. return false;
  2172. if (getDeclName().getCXXOverloadedOperator() != OO_New &&
  2173. getDeclName().getCXXOverloadedOperator() != OO_Delete &&
  2174. getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
  2175. getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
  2176. return false;
  2177. if (isa<CXXRecordDecl>(getDeclContext()))
  2178. return false;
  2179. // This can only fail for an invalid 'operator new' declaration.
  2180. if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
  2181. return false;
  2182. const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
  2183. if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
  2184. return false;
  2185. // If this is a single-parameter function, it must be a replaceable global
  2186. // allocation or deallocation function.
  2187. if (FPT->getNumParams() == 1)
  2188. return true;
  2189. // Otherwise, we're looking for a second parameter whose type is
  2190. // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
  2191. QualType Ty = FPT->getParamType(1);
  2192. ASTContext &Ctx = getASTContext();
  2193. if (Ctx.getLangOpts().SizedDeallocation &&
  2194. Ctx.hasSameType(Ty, Ctx.getSizeType()))
  2195. return true;
  2196. if (!Ty->isReferenceType())
  2197. return false;
  2198. Ty = Ty->getPointeeType();
  2199. if (Ty.getCVRQualifiers() != Qualifiers::Const)
  2200. return false;
  2201. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  2202. return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
  2203. }
  2204. LanguageLinkage FunctionDecl::getLanguageLinkage() const {
  2205. return getDeclLanguageLinkage(*this);
  2206. }
  2207. bool FunctionDecl::isExternC() const {
  2208. return isDeclExternC(*this);
  2209. }
  2210. bool FunctionDecl::isInExternCContext() const {
  2211. return getLexicalDeclContext()->isExternCContext();
  2212. }
  2213. bool FunctionDecl::isInExternCXXContext() const {
  2214. return getLexicalDeclContext()->isExternCXXContext();
  2215. }
  2216. bool FunctionDecl::isGlobal() const {
  2217. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
  2218. return Method->isStatic();
  2219. if (getCanonicalDecl()->getStorageClass() == SC_Static)
  2220. return false;
  2221. for (const DeclContext *DC = getDeclContext();
  2222. DC->isNamespace();
  2223. DC = DC->getParent()) {
  2224. if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
  2225. if (!Namespace->getDeclName())
  2226. return false;
  2227. break;
  2228. }
  2229. }
  2230. return true;
  2231. }
  2232. bool FunctionDecl::isNoReturn() const {
  2233. return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
  2234. hasAttr<C11NoReturnAttr>() ||
  2235. getType()->getAs<FunctionType>()->getNoReturnAttr();
  2236. }
  2237. void
  2238. FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
  2239. redeclarable_base::setPreviousDecl(PrevDecl);
  2240. if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
  2241. FunctionTemplateDecl *PrevFunTmpl
  2242. = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
  2243. assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
  2244. FunTmpl->setPreviousDecl(PrevFunTmpl);
  2245. }
  2246. if (PrevDecl && PrevDecl->IsInline)
  2247. IsInline = true;
  2248. }
  2249. FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
  2250. /// \brief Returns a value indicating whether this function
  2251. /// corresponds to a builtin function.
  2252. ///
  2253. /// The function corresponds to a built-in function if it is
  2254. /// declared at translation scope or within an extern "C" block and
  2255. /// its name matches with the name of a builtin. The returned value
  2256. /// will be 0 for functions that do not correspond to a builtin, a
  2257. /// value of type \c Builtin::ID if in the target-independent range
  2258. /// \c [1,Builtin::First), or a target-specific builtin value.
  2259. unsigned FunctionDecl::getBuiltinID() const {
  2260. if (!getIdentifier())
  2261. return 0;
  2262. unsigned BuiltinID = getIdentifier()->getBuiltinID();
  2263. if (!BuiltinID)
  2264. return 0;
  2265. ASTContext &Context = getASTContext();
  2266. if (Context.getLangOpts().CPlusPlus) {
  2267. const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
  2268. getFirstDecl()->getDeclContext());
  2269. // In C++, the first declaration of a builtin is always inside an implicit
  2270. // extern "C".
  2271. // FIXME: A recognised library function may not be directly in an extern "C"
  2272. // declaration, for instance "extern "C" { namespace std { decl } }".
  2273. if (!LinkageDecl) {
  2274. if (BuiltinID == Builtin::BI__GetExceptionInfo &&
  2275. Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  2276. isInStdNamespace())
  2277. return Builtin::BI__GetExceptionInfo;
  2278. return 0;
  2279. }
  2280. if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
  2281. return 0;
  2282. }
  2283. // If the function is marked "overloadable", it has a different mangled name
  2284. // and is not the C library function.
  2285. if (hasAttr<OverloadableAttr>())
  2286. return 0;
  2287. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  2288. return BuiltinID;
  2289. // This function has the name of a known C library
  2290. // function. Determine whether it actually refers to the C library
  2291. // function or whether it just has the same name.
  2292. // If this is a static function, it's not a builtin.
  2293. if (getStorageClass() == SC_Static)
  2294. return 0;
  2295. return BuiltinID;
  2296. }
  2297. /// getNumParams - Return the number of parameters this function must have
  2298. /// based on its FunctionType. This is the length of the ParamInfo array
  2299. /// after it has been created.
  2300. unsigned FunctionDecl::getNumParams() const {
  2301. const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
  2302. return FPT ? FPT->getNumParams() : 0;
  2303. }
  2304. void FunctionDecl::setParams(ASTContext &C,
  2305. ArrayRef<ParmVarDecl *> NewParamInfo) {
  2306. assert(!ParamInfo && "Already has param info!");
  2307. assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
  2308. // Zero params -> null pointer.
  2309. if (!NewParamInfo.empty()) {
  2310. ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
  2311. std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
  2312. }
  2313. }
  2314. void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
  2315. assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
  2316. if (!NewDecls.empty()) {
  2317. NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
  2318. std::copy(NewDecls.begin(), NewDecls.end(), A);
  2319. DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
  2320. // Move declarations introduced in prototype to the function context.
  2321. for (auto I : NewDecls) {
  2322. DeclContext *DC = I->getDeclContext();
  2323. // Forward-declared reference to an enumeration is not added to
  2324. // declaration scope, so skip declaration that is absent from its
  2325. // declaration contexts.
  2326. if (DC->containsDecl(I)) {
  2327. DC->removeDecl(I);
  2328. I->setDeclContext(this);
  2329. addDecl(I);
  2330. }
  2331. }
  2332. }
  2333. }
  2334. /// getMinRequiredArguments - Returns the minimum number of arguments
  2335. /// needed to call this function. This may be fewer than the number of
  2336. /// function parameters, if some of the parameters have default
  2337. /// arguments (in C++) or are parameter packs (C++11).
  2338. unsigned FunctionDecl::getMinRequiredArguments() const {
  2339. if (!getASTContext().getLangOpts().CPlusPlus)
  2340. return getNumParams();
  2341. unsigned NumRequiredArgs = 0;
  2342. for (auto *Param : params())
  2343. if (!Param->isParameterPack() && !Param->hasDefaultArg())
  2344. ++NumRequiredArgs;
  2345. return NumRequiredArgs;
  2346. }
  2347. /// \brief The combination of the extern and inline keywords under MSVC forces
  2348. /// the function to be required.
  2349. ///
  2350. /// Note: This function assumes that we will only get called when isInlined()
  2351. /// would return true for this FunctionDecl.
  2352. bool FunctionDecl::isMSExternInline() const {
  2353. assert(isInlined() && "expected to get called on an inlined function!");
  2354. const ASTContext &Context = getASTContext();
  2355. if (!Context.getLangOpts().MSVCCompat && !hasAttr<DLLExportAttr>())
  2356. return false;
  2357. for (const FunctionDecl *FD = getMostRecentDecl(); FD;
  2358. FD = FD->getPreviousDecl())
  2359. if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
  2360. return true;
  2361. return false;
  2362. }
  2363. static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
  2364. if (Redecl->getStorageClass() != SC_Extern)
  2365. return false;
  2366. for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
  2367. FD = FD->getPreviousDecl())
  2368. if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
  2369. return false;
  2370. return true;
  2371. }
  2372. static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
  2373. // Only consider file-scope declarations in this test.
  2374. if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
  2375. return false;
  2376. // Only consider explicit declarations; the presence of a builtin for a
  2377. // libcall shouldn't affect whether a definition is externally visible.
  2378. if (Redecl->isImplicit())
  2379. return false;
  2380. if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
  2381. return true; // Not an inline definition
  2382. return false;
  2383. }
  2384. /// \brief For a function declaration in C or C++, determine whether this
  2385. /// declaration causes the definition to be externally visible.
  2386. ///
  2387. /// For instance, this determines if adding the current declaration to the set
  2388. /// of redeclarations of the given functions causes
  2389. /// isInlineDefinitionExternallyVisible to change from false to true.
  2390. bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
  2391. assert(!doesThisDeclarationHaveABody() &&
  2392. "Must have a declaration without a body.");
  2393. ASTContext &Context = getASTContext();
  2394. if (Context.getLangOpts().MSVCCompat) {
  2395. const FunctionDecl *Definition;
  2396. if (hasBody(Definition) && Definition->isInlined() &&
  2397. redeclForcesDefMSVC(this))
  2398. return true;
  2399. }
  2400. if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
  2401. // With GNU inlining, a declaration with 'inline' but not 'extern', forces
  2402. // an externally visible definition.
  2403. //
  2404. // FIXME: What happens if gnu_inline gets added on after the first
  2405. // declaration?
  2406. if (!isInlineSpecified() || getStorageClass() == SC_Extern)
  2407. return false;
  2408. const FunctionDecl *Prev = this;
  2409. bool FoundBody = false;
  2410. while ((Prev = Prev->getPreviousDecl())) {
  2411. FoundBody |= Prev->Body.isValid();
  2412. if (Prev->Body) {
  2413. // If it's not the case that both 'inline' and 'extern' are
  2414. // specified on the definition, then it is always externally visible.
  2415. if (!Prev->isInlineSpecified() ||
  2416. Prev->getStorageClass() != SC_Extern)
  2417. return false;
  2418. } else if (Prev->isInlineSpecified() &&
  2419. Prev->getStorageClass() != SC_Extern) {
  2420. return false;
  2421. }
  2422. }
  2423. return FoundBody;
  2424. }
  2425. if (Context.getLangOpts().CPlusPlus)
  2426. return false;
  2427. // C99 6.7.4p6:
  2428. // [...] If all of the file scope declarations for a function in a
  2429. // translation unit include the inline function specifier without extern,
  2430. // then the definition in that translation unit is an inline definition.
  2431. if (isInlineSpecified() && getStorageClass() != SC_Extern)
  2432. return false;
  2433. const FunctionDecl *Prev = this;
  2434. bool FoundBody = false;
  2435. while ((Prev = Prev->getPreviousDecl())) {
  2436. FoundBody |= Prev->Body.isValid();
  2437. if (RedeclForcesDefC99(Prev))
  2438. return false;
  2439. }
  2440. return FoundBody;
  2441. }
  2442. SourceRange FunctionDecl::getReturnTypeSourceRange() const {
  2443. const TypeSourceInfo *TSI = getTypeSourceInfo();
  2444. if (!TSI)
  2445. return SourceRange();
  2446. FunctionTypeLoc FTL =
  2447. TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
  2448. if (!FTL)
  2449. return SourceRange();
  2450. // Skip self-referential return types.
  2451. const SourceManager &SM = getASTContext().getSourceManager();
  2452. SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
  2453. SourceLocation Boundary = getNameInfo().getLocStart();
  2454. if (RTRange.isInvalid() || Boundary.isInvalid() ||
  2455. !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
  2456. return SourceRange();
  2457. return RTRange;
  2458. }
  2459. bool FunctionDecl::hasUnusedResultAttr() const {
  2460. QualType RetType = getReturnType();
  2461. if (RetType->isRecordType()) {
  2462. const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
  2463. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(this);
  2464. if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() &&
  2465. !(MD && MD->getCorrespondingMethodInClass(Ret, true)))
  2466. return true;
  2467. }
  2468. return hasAttr<WarnUnusedResultAttr>();
  2469. }
  2470. /// \brief For an inline function definition in C, or for a gnu_inline function
  2471. /// in C++, determine whether the definition will be externally visible.
  2472. ///
  2473. /// Inline function definitions are always available for inlining optimizations.
  2474. /// However, depending on the language dialect, declaration specifiers, and
  2475. /// attributes, the definition of an inline function may or may not be
  2476. /// "externally" visible to other translation units in the program.
  2477. ///
  2478. /// In C99, inline definitions are not externally visible by default. However,
  2479. /// if even one of the global-scope declarations is marked "extern inline", the
  2480. /// inline definition becomes externally visible (C99 6.7.4p6).
  2481. ///
  2482. /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
  2483. /// definition, we use the GNU semantics for inline, which are nearly the
  2484. /// opposite of C99 semantics. In particular, "inline" by itself will create
  2485. /// an externally visible symbol, but "extern inline" will not create an
  2486. /// externally visible symbol.
  2487. bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
  2488. assert(doesThisDeclarationHaveABody() && "Must have the function definition");
  2489. assert(isInlined() && "Function must be inline");
  2490. ASTContext &Context = getASTContext();
  2491. if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
  2492. // Note: If you change the logic here, please change
  2493. // doesDeclarationForceExternallyVisibleDefinition as well.
  2494. //
  2495. // If it's not the case that both 'inline' and 'extern' are
  2496. // specified on the definition, then this inline definition is
  2497. // externally visible.
  2498. if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
  2499. return true;
  2500. // If any declaration is 'inline' but not 'extern', then this definition
  2501. // is externally visible.
  2502. for (auto Redecl : redecls()) {
  2503. if (Redecl->isInlineSpecified() &&
  2504. Redecl->getStorageClass() != SC_Extern)
  2505. return true;
  2506. }
  2507. return false;
  2508. }
  2509. // The rest of this function is C-only.
  2510. assert(!Context.getLangOpts().CPlusPlus &&
  2511. "should not use C inline rules in C++");
  2512. // C99 6.7.4p6:
  2513. // [...] If all of the file scope declarations for a function in a
  2514. // translation unit include the inline function specifier without extern,
  2515. // then the definition in that translation unit is an inline definition.
  2516. for (auto Redecl : redecls()) {
  2517. if (RedeclForcesDefC99(Redecl))
  2518. return true;
  2519. }
  2520. // C99 6.7.4p6:
  2521. // An inline definition does not provide an external definition for the
  2522. // function, and does not forbid an external definition in another
  2523. // translation unit.
  2524. return false;
  2525. }
  2526. /// getOverloadedOperator - Which C++ overloaded operator this
  2527. /// function represents, if any.
  2528. OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
  2529. if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  2530. return getDeclName().getCXXOverloadedOperator();
  2531. else
  2532. return OO_None;
  2533. }
  2534. /// getLiteralIdentifier - The literal suffix identifier this function
  2535. /// represents, if any.
  2536. const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
  2537. if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
  2538. return getDeclName().getCXXLiteralIdentifier();
  2539. else
  2540. return nullptr;
  2541. }
  2542. FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
  2543. if (TemplateOrSpecialization.isNull())
  2544. return TK_NonTemplate;
  2545. if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
  2546. return TK_FunctionTemplate;
  2547. if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
  2548. return TK_MemberSpecialization;
  2549. if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
  2550. return TK_FunctionTemplateSpecialization;
  2551. if (TemplateOrSpecialization.is
  2552. <DependentFunctionTemplateSpecializationInfo*>())
  2553. return TK_DependentFunctionTemplateSpecialization;
  2554. llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
  2555. }
  2556. FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
  2557. if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
  2558. return cast<FunctionDecl>(Info->getInstantiatedFrom());
  2559. return nullptr;
  2560. }
  2561. void
  2562. FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
  2563. FunctionDecl *FD,
  2564. TemplateSpecializationKind TSK) {
  2565. assert(TemplateOrSpecialization.isNull() &&
  2566. "Member function is already a specialization");
  2567. MemberSpecializationInfo *Info
  2568. = new (C) MemberSpecializationInfo(FD, TSK);
  2569. TemplateOrSpecialization = Info;
  2570. }
  2571. bool FunctionDecl::isImplicitlyInstantiable() const {
  2572. // If the function is invalid, it can't be implicitly instantiated.
  2573. if (isInvalidDecl())
  2574. return false;
  2575. switch (getTemplateSpecializationKind()) {
  2576. case TSK_Undeclared:
  2577. case TSK_ExplicitInstantiationDefinition:
  2578. return false;
  2579. case TSK_ImplicitInstantiation:
  2580. return true;
  2581. // It is possible to instantiate TSK_ExplicitSpecialization kind
  2582. // if the FunctionDecl has a class scope specialization pattern.
  2583. case TSK_ExplicitSpecialization:
  2584. return getClassScopeSpecializationPattern() != nullptr;
  2585. case TSK_ExplicitInstantiationDeclaration:
  2586. // Handled below.
  2587. break;
  2588. }
  2589. // Find the actual template from which we will instantiate.
  2590. const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
  2591. bool HasPattern = false;
  2592. if (PatternDecl)
  2593. HasPattern = PatternDecl->hasBody(PatternDecl);
  2594. // C++0x [temp.explicit]p9:
  2595. // Except for inline functions, other explicit instantiation declarations
  2596. // have the effect of suppressing the implicit instantiation of the entity
  2597. // to which they refer.
  2598. if (!HasPattern || !PatternDecl)
  2599. return true;
  2600. return PatternDecl->isInlined();
  2601. }
  2602. bool FunctionDecl::isTemplateInstantiation() const {
  2603. switch (getTemplateSpecializationKind()) {
  2604. case TSK_Undeclared:
  2605. case TSK_ExplicitSpecialization:
  2606. return false;
  2607. case TSK_ImplicitInstantiation:
  2608. case TSK_ExplicitInstantiationDeclaration:
  2609. case TSK_ExplicitInstantiationDefinition:
  2610. return true;
  2611. }
  2612. llvm_unreachable("All TSK values handled.");
  2613. }
  2614. FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
  2615. // Handle class scope explicit specialization special case.
  2616. if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  2617. return getClassScopeSpecializationPattern();
  2618. // If this is a generic lambda call operator specialization, its
  2619. // instantiation pattern is always its primary template's pattern
  2620. // even if its primary template was instantiated from another
  2621. // member template (which happens with nested generic lambdas).
  2622. // Since a lambda's call operator's body is transformed eagerly,
  2623. // we don't have to go hunting for a prototype definition template
  2624. // (i.e. instantiated-from-member-template) to use as an instantiation
  2625. // pattern.
  2626. if (isGenericLambdaCallOperatorSpecialization(
  2627. dyn_cast<CXXMethodDecl>(this))) {
  2628. assert(getPrimaryTemplate() && "A generic lambda specialization must be "
  2629. "generated from a primary call operator "
  2630. "template");
  2631. assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
  2632. "A generic lambda call operator template must always have a body - "
  2633. "even if instantiated from a prototype (i.e. as written) member "
  2634. "template");
  2635. return getPrimaryTemplate()->getTemplatedDecl();
  2636. }
  2637. if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
  2638. while (Primary->getInstantiatedFromMemberTemplate()) {
  2639. // If we have hit a point where the user provided a specialization of
  2640. // this template, we're done looking.
  2641. if (Primary->isMemberSpecialization())
  2642. break;
  2643. Primary = Primary->getInstantiatedFromMemberTemplate();
  2644. }
  2645. return Primary->getTemplatedDecl();
  2646. }
  2647. return getInstantiatedFromMemberFunction();
  2648. }
  2649. FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
  2650. if (FunctionTemplateSpecializationInfo *Info
  2651. = TemplateOrSpecialization
  2652. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  2653. return Info->Template.getPointer();
  2654. }
  2655. return nullptr;
  2656. }
  2657. FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
  2658. return getASTContext().getClassScopeSpecializationPattern(this);
  2659. }
  2660. const TemplateArgumentList *
  2661. FunctionDecl::getTemplateSpecializationArgs() const {
  2662. if (FunctionTemplateSpecializationInfo *Info
  2663. = TemplateOrSpecialization
  2664. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  2665. return Info->TemplateArguments;
  2666. }
  2667. return nullptr;
  2668. }
  2669. const ASTTemplateArgumentListInfo *
  2670. FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
  2671. if (FunctionTemplateSpecializationInfo *Info
  2672. = TemplateOrSpecialization
  2673. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  2674. return Info->TemplateArgumentsAsWritten;
  2675. }
  2676. return nullptr;
  2677. }
  2678. void
  2679. FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
  2680. FunctionTemplateDecl *Template,
  2681. const TemplateArgumentList *TemplateArgs,
  2682. void *InsertPos,
  2683. TemplateSpecializationKind TSK,
  2684. const TemplateArgumentListInfo *TemplateArgsAsWritten,
  2685. SourceLocation PointOfInstantiation) {
  2686. assert(TSK != TSK_Undeclared &&
  2687. "Must specify the type of function template specialization");
  2688. FunctionTemplateSpecializationInfo *Info
  2689. = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
  2690. if (!Info)
  2691. Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
  2692. TemplateArgs,
  2693. TemplateArgsAsWritten,
  2694. PointOfInstantiation);
  2695. TemplateOrSpecialization = Info;
  2696. Template->addSpecialization(Info, InsertPos);
  2697. }
  2698. void
  2699. FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
  2700. const UnresolvedSetImpl &Templates,
  2701. const TemplateArgumentListInfo &TemplateArgs) {
  2702. assert(TemplateOrSpecialization.isNull());
  2703. size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
  2704. Size += Templates.size() * sizeof(FunctionTemplateDecl*);
  2705. Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
  2706. void *Buffer = Context.Allocate(Size);
  2707. DependentFunctionTemplateSpecializationInfo *Info =
  2708. new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
  2709. TemplateArgs);
  2710. TemplateOrSpecialization = Info;
  2711. }
  2712. DependentFunctionTemplateSpecializationInfo::
  2713. DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
  2714. const TemplateArgumentListInfo &TArgs)
  2715. : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
  2716. static_assert(sizeof(*this) % llvm::AlignOf<void *>::Alignment == 0,
  2717. "Trailing data is unaligned!");
  2718. d.NumTemplates = Ts.size();
  2719. d.NumArgs = TArgs.size();
  2720. FunctionTemplateDecl **TsArray =
  2721. const_cast<FunctionTemplateDecl**>(getTemplates());
  2722. for (unsigned I = 0, E = Ts.size(); I != E; ++I)
  2723. TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
  2724. TemplateArgumentLoc *ArgsArray =
  2725. const_cast<TemplateArgumentLoc*>(getTemplateArgs());
  2726. for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
  2727. new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
  2728. }
  2729. TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
  2730. // For a function template specialization, query the specialization
  2731. // information object.
  2732. FunctionTemplateSpecializationInfo *FTSInfo
  2733. = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
  2734. if (FTSInfo)
  2735. return FTSInfo->getTemplateSpecializationKind();
  2736. MemberSpecializationInfo *MSInfo
  2737. = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
  2738. if (MSInfo)
  2739. return MSInfo->getTemplateSpecializationKind();
  2740. return TSK_Undeclared;
  2741. }
  2742. void
  2743. FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  2744. SourceLocation PointOfInstantiation) {
  2745. if (FunctionTemplateSpecializationInfo *FTSInfo
  2746. = TemplateOrSpecialization.dyn_cast<
  2747. FunctionTemplateSpecializationInfo*>()) {
  2748. FTSInfo->setTemplateSpecializationKind(TSK);
  2749. if (TSK != TSK_ExplicitSpecialization &&
  2750. PointOfInstantiation.isValid() &&
  2751. FTSInfo->getPointOfInstantiation().isInvalid())
  2752. FTSInfo->setPointOfInstantiation(PointOfInstantiation);
  2753. } else if (MemberSpecializationInfo *MSInfo
  2754. = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
  2755. MSInfo->setTemplateSpecializationKind(TSK);
  2756. if (TSK != TSK_ExplicitSpecialization &&
  2757. PointOfInstantiation.isValid() &&
  2758. MSInfo->getPointOfInstantiation().isInvalid())
  2759. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2760. } else
  2761. llvm_unreachable("Function cannot have a template specialization kind");
  2762. }
  2763. SourceLocation FunctionDecl::getPointOfInstantiation() const {
  2764. if (FunctionTemplateSpecializationInfo *FTSInfo
  2765. = TemplateOrSpecialization.dyn_cast<
  2766. FunctionTemplateSpecializationInfo*>())
  2767. return FTSInfo->getPointOfInstantiation();
  2768. else if (MemberSpecializationInfo *MSInfo
  2769. = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
  2770. return MSInfo->getPointOfInstantiation();
  2771. return SourceLocation();
  2772. }
  2773. bool FunctionDecl::isOutOfLine() const {
  2774. if (Decl::isOutOfLine())
  2775. return true;
  2776. // If this function was instantiated from a member function of a
  2777. // class template, check whether that member function was defined out-of-line.
  2778. if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
  2779. const FunctionDecl *Definition;
  2780. if (FD->hasBody(Definition))
  2781. return Definition->isOutOfLine();
  2782. }
  2783. // If this function was instantiated from a function template,
  2784. // check whether that function template was defined out-of-line.
  2785. if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
  2786. const FunctionDecl *Definition;
  2787. if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
  2788. return Definition->isOutOfLine();
  2789. }
  2790. return false;
  2791. }
  2792. SourceRange FunctionDecl::getSourceRange() const {
  2793. return SourceRange(getOuterLocStart(), EndRangeLoc);
  2794. }
  2795. unsigned FunctionDecl::getMemoryFunctionKind() const {
  2796. IdentifierInfo *FnInfo = getIdentifier();
  2797. if (!FnInfo)
  2798. return 0;
  2799. // Builtin handling.
  2800. switch (getBuiltinID()) {
  2801. case Builtin::BI__builtin_memset:
  2802. case Builtin::BI__builtin___memset_chk:
  2803. case Builtin::BImemset:
  2804. return Builtin::BImemset;
  2805. case Builtin::BI__builtin_memcpy:
  2806. case Builtin::BI__builtin___memcpy_chk:
  2807. case Builtin::BImemcpy:
  2808. return Builtin::BImemcpy;
  2809. case Builtin::BI__builtin_memmove:
  2810. case Builtin::BI__builtin___memmove_chk:
  2811. case Builtin::BImemmove:
  2812. return Builtin::BImemmove;
  2813. case Builtin::BIstrlcpy:
  2814. case Builtin::BI__builtin___strlcpy_chk:
  2815. return Builtin::BIstrlcpy;
  2816. case Builtin::BIstrlcat:
  2817. case Builtin::BI__builtin___strlcat_chk:
  2818. return Builtin::BIstrlcat;
  2819. case Builtin::BI__builtin_memcmp:
  2820. case Builtin::BImemcmp:
  2821. return Builtin::BImemcmp;
  2822. case Builtin::BI__builtin_strncpy:
  2823. case Builtin::BI__builtin___strncpy_chk:
  2824. case Builtin::BIstrncpy:
  2825. return Builtin::BIstrncpy;
  2826. case Builtin::BI__builtin_strncmp:
  2827. case Builtin::BIstrncmp:
  2828. return Builtin::BIstrncmp;
  2829. case Builtin::BI__builtin_strncasecmp:
  2830. case Builtin::BIstrncasecmp:
  2831. return Builtin::BIstrncasecmp;
  2832. case Builtin::BI__builtin_strncat:
  2833. case Builtin::BI__builtin___strncat_chk:
  2834. case Builtin::BIstrncat:
  2835. return Builtin::BIstrncat;
  2836. case Builtin::BI__builtin_strndup:
  2837. case Builtin::BIstrndup:
  2838. return Builtin::BIstrndup;
  2839. case Builtin::BI__builtin_strlen:
  2840. case Builtin::BIstrlen:
  2841. return Builtin::BIstrlen;
  2842. default:
  2843. if (isExternC()) {
  2844. if (FnInfo->isStr("memset"))
  2845. return Builtin::BImemset;
  2846. else if (FnInfo->isStr("memcpy"))
  2847. return Builtin::BImemcpy;
  2848. else if (FnInfo->isStr("memmove"))
  2849. return Builtin::BImemmove;
  2850. else if (FnInfo->isStr("memcmp"))
  2851. return Builtin::BImemcmp;
  2852. else if (FnInfo->isStr("strncpy"))
  2853. return Builtin::BIstrncpy;
  2854. else if (FnInfo->isStr("strncmp"))
  2855. return Builtin::BIstrncmp;
  2856. else if (FnInfo->isStr("strncasecmp"))
  2857. return Builtin::BIstrncasecmp;
  2858. else if (FnInfo->isStr("strncat"))
  2859. return Builtin::BIstrncat;
  2860. else if (FnInfo->isStr("strndup"))
  2861. return Builtin::BIstrndup;
  2862. else if (FnInfo->isStr("strlen"))
  2863. return Builtin::BIstrlen;
  2864. }
  2865. break;
  2866. }
  2867. return 0;
  2868. }
  2869. //===----------------------------------------------------------------------===//
  2870. // FieldDecl Implementation
  2871. //===----------------------------------------------------------------------===//
  2872. FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
  2873. SourceLocation StartLoc, SourceLocation IdLoc,
  2874. IdentifierInfo *Id, QualType T,
  2875. TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
  2876. InClassInitStyle InitStyle) {
  2877. return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
  2878. BW, Mutable, InitStyle);
  2879. }
  2880. FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2881. return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
  2882. SourceLocation(), nullptr, QualType(), nullptr,
  2883. nullptr, false, ICIS_NoInit);
  2884. }
  2885. bool FieldDecl::isAnonymousStructOrUnion() const {
  2886. if (!isImplicit() || getDeclName())
  2887. return false;
  2888. if (const RecordType *Record = getType()->getAs<RecordType>())
  2889. return Record->getDecl()->isAnonymousStructOrUnion();
  2890. return false;
  2891. }
  2892. unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
  2893. assert(isBitField() && "not a bitfield");
  2894. Expr *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
  2895. return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
  2896. }
  2897. unsigned FieldDecl::getFieldIndex() const {
  2898. const FieldDecl *Canonical = getCanonicalDecl();
  2899. if (Canonical != this)
  2900. return Canonical->getFieldIndex();
  2901. if (CachedFieldIndex) return CachedFieldIndex - 1;
  2902. unsigned Index = 0;
  2903. const RecordDecl *RD = getParent();
  2904. for (auto *Field : RD->fields()) {
  2905. Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
  2906. ++Index;
  2907. }
  2908. assert(CachedFieldIndex && "failed to find field in parent");
  2909. return CachedFieldIndex - 1;
  2910. }
  2911. SourceRange FieldDecl::getSourceRange() const {
  2912. switch (InitStorage.getInt()) {
  2913. // All three of these cases store an optional Expr*.
  2914. case ISK_BitWidthOrNothing:
  2915. case ISK_InClassCopyInit:
  2916. case ISK_InClassListInit:
  2917. if (const Expr *E = static_cast<const Expr *>(InitStorage.getPointer()))
  2918. return SourceRange(getInnerLocStart(), E->getLocEnd());
  2919. // FALLTHROUGH
  2920. case ISK_CapturedVLAType:
  2921. return DeclaratorDecl::getSourceRange();
  2922. }
  2923. llvm_unreachable("bad init storage kind");
  2924. }
  2925. void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
  2926. assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
  2927. "capturing type in non-lambda or captured record.");
  2928. assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
  2929. InitStorage.getPointer() == nullptr &&
  2930. "bit width, initializer or captured type already set");
  2931. InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
  2932. ISK_CapturedVLAType);
  2933. }
  2934. //===----------------------------------------------------------------------===//
  2935. // TagDecl Implementation
  2936. //===----------------------------------------------------------------------===//
  2937. SourceLocation TagDecl::getOuterLocStart() const {
  2938. return getTemplateOrInnerLocStart(this);
  2939. }
  2940. SourceRange TagDecl::getSourceRange() const {
  2941. SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
  2942. return SourceRange(getOuterLocStart(), E);
  2943. }
  2944. TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
  2945. void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
  2946. NamedDeclOrQualifier = TDD;
  2947. if (const Type *T = getTypeForDecl()) {
  2948. (void)T;
  2949. assert(T->isLinkageValid());
  2950. }
  2951. assert(isLinkageValid());
  2952. }
  2953. void TagDecl::startDefinition() {
  2954. IsBeingDefined = true;
  2955. if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
  2956. struct CXXRecordDecl::DefinitionData *Data =
  2957. new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
  2958. for (auto I : redecls())
  2959. cast<CXXRecordDecl>(I)->DefinitionData = Data;
  2960. }
  2961. }
  2962. void TagDecl::completeDefinition() {
  2963. assert((!isa<CXXRecordDecl>(this) ||
  2964. cast<CXXRecordDecl>(this)->hasDefinition()) &&
  2965. "definition completed but not started");
  2966. IsCompleteDefinition = true;
  2967. IsBeingDefined = false;
  2968. if (ASTMutationListener *L = getASTMutationListener())
  2969. L->CompletedTagDefinition(this);
  2970. }
  2971. TagDecl *TagDecl::getDefinition() const {
  2972. if (isCompleteDefinition())
  2973. return const_cast<TagDecl *>(this);
  2974. // If it's possible for us to have an out-of-date definition, check now.
  2975. if (MayHaveOutOfDateDef) {
  2976. if (IdentifierInfo *II = getIdentifier()) {
  2977. if (II->isOutOfDate()) {
  2978. updateOutOfDate(*II);
  2979. }
  2980. }
  2981. }
  2982. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
  2983. return CXXRD->getDefinition();
  2984. for (auto R : redecls())
  2985. if (R->isCompleteDefinition())
  2986. return R;
  2987. return nullptr;
  2988. }
  2989. void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
  2990. if (QualifierLoc) {
  2991. // Make sure the extended qualifier info is allocated.
  2992. if (!hasExtInfo())
  2993. NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
  2994. // Set qualifier info.
  2995. getExtInfo()->QualifierLoc = QualifierLoc;
  2996. } else {
  2997. // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
  2998. if (hasExtInfo()) {
  2999. if (getExtInfo()->NumTemplParamLists == 0) {
  3000. getASTContext().Deallocate(getExtInfo());
  3001. NamedDeclOrQualifier = (TypedefNameDecl*)nullptr;
  3002. }
  3003. else
  3004. getExtInfo()->QualifierLoc = QualifierLoc;
  3005. }
  3006. }
  3007. }
  3008. void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
  3009. unsigned NumTPLists,
  3010. TemplateParameterList **TPLists) {
  3011. assert(NumTPLists > 0);
  3012. // Make sure the extended decl info is allocated.
  3013. if (!hasExtInfo())
  3014. // Allocate external info struct.
  3015. NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
  3016. // Set the template parameter lists info.
  3017. getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
  3018. }
  3019. //===----------------------------------------------------------------------===//
  3020. // EnumDecl Implementation
  3021. //===----------------------------------------------------------------------===//
  3022. void EnumDecl::anchor() { }
  3023. EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
  3024. SourceLocation StartLoc, SourceLocation IdLoc,
  3025. IdentifierInfo *Id,
  3026. EnumDecl *PrevDecl, bool IsScoped,
  3027. bool IsScopedUsingClassTag, bool IsFixed) {
  3028. EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
  3029. IsScoped, IsScopedUsingClassTag,
  3030. IsFixed);
  3031. Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
  3032. C.getTypeDeclType(Enum, PrevDecl);
  3033. return Enum;
  3034. }
  3035. EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3036. EnumDecl *Enum =
  3037. new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
  3038. nullptr, nullptr, false, false, false);
  3039. Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
  3040. return Enum;
  3041. }
  3042. SourceRange EnumDecl::getIntegerTypeRange() const {
  3043. if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
  3044. return TI->getTypeLoc().getSourceRange();
  3045. return SourceRange();
  3046. }
  3047. void EnumDecl::completeDefinition(QualType NewType,
  3048. QualType NewPromotionType,
  3049. unsigned NumPositiveBits,
  3050. unsigned NumNegativeBits) {
  3051. assert(!isCompleteDefinition() && "Cannot redefine enums!");
  3052. if (!IntegerType)
  3053. IntegerType = NewType.getTypePtr();
  3054. PromotionType = NewPromotionType;
  3055. setNumPositiveBits(NumPositiveBits);
  3056. setNumNegativeBits(NumNegativeBits);
  3057. TagDecl::completeDefinition();
  3058. }
  3059. TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
  3060. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  3061. return MSI->getTemplateSpecializationKind();
  3062. return TSK_Undeclared;
  3063. }
  3064. void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  3065. SourceLocation PointOfInstantiation) {
  3066. MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
  3067. assert(MSI && "Not an instantiated member enumeration?");
  3068. MSI->setTemplateSpecializationKind(TSK);
  3069. if (TSK != TSK_ExplicitSpecialization &&
  3070. PointOfInstantiation.isValid() &&
  3071. MSI->getPointOfInstantiation().isInvalid())
  3072. MSI->setPointOfInstantiation(PointOfInstantiation);
  3073. }
  3074. EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
  3075. if (SpecializationInfo)
  3076. return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
  3077. return nullptr;
  3078. }
  3079. void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
  3080. TemplateSpecializationKind TSK) {
  3081. assert(!SpecializationInfo && "Member enum is already a specialization");
  3082. SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
  3083. }
  3084. //===----------------------------------------------------------------------===//
  3085. // RecordDecl Implementation
  3086. //===----------------------------------------------------------------------===//
  3087. RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
  3088. DeclContext *DC, SourceLocation StartLoc,
  3089. SourceLocation IdLoc, IdentifierInfo *Id,
  3090. RecordDecl *PrevDecl)
  3091. : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
  3092. HasFlexibleArrayMember = false;
  3093. AnonymousStructOrUnion = false;
  3094. HasObjectMember = false;
  3095. HasVolatileMember = false;
  3096. LoadedFieldsFromExternalStorage = false;
  3097. assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
  3098. }
  3099. RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
  3100. SourceLocation StartLoc, SourceLocation IdLoc,
  3101. IdentifierInfo *Id, RecordDecl* PrevDecl) {
  3102. RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
  3103. StartLoc, IdLoc, Id, PrevDecl);
  3104. R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
  3105. C.getTypeDeclType(R, PrevDecl);
  3106. return R;
  3107. }
  3108. RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
  3109. RecordDecl *R =
  3110. new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
  3111. SourceLocation(), nullptr, nullptr);
  3112. R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
  3113. return R;
  3114. }
  3115. bool RecordDecl::isInjectedClassName() const {
  3116. return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
  3117. cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
  3118. }
  3119. bool RecordDecl::isLambda() const {
  3120. if (auto RD = dyn_cast<CXXRecordDecl>(this))
  3121. return RD->isLambda();
  3122. return false;
  3123. }
  3124. bool RecordDecl::isCapturedRecord() const {
  3125. return hasAttr<CapturedRecordAttr>();
  3126. }
  3127. void RecordDecl::setCapturedRecord() {
  3128. addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
  3129. }
  3130. RecordDecl::field_iterator RecordDecl::field_begin() const {
  3131. if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
  3132. LoadFieldsFromExternalStorage();
  3133. return field_iterator(decl_iterator(FirstDecl));
  3134. }
  3135. /// completeDefinition - Notes that the definition of this type is now
  3136. /// complete.
  3137. void RecordDecl::completeDefinition() {
  3138. assert(!isCompleteDefinition() && "Cannot redefine record!");
  3139. TagDecl::completeDefinition();
  3140. }
  3141. /// isMsStruct - Get whether or not this record uses ms_struct layout.
  3142. /// This which can be turned on with an attribute, pragma, or the
  3143. /// -mms-bitfields command-line option.
  3144. bool RecordDecl::isMsStruct(const ASTContext &C) const {
  3145. return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
  3146. }
  3147. static bool isFieldOrIndirectField(Decl::Kind K) {
  3148. return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
  3149. }
  3150. void RecordDecl::LoadFieldsFromExternalStorage() const {
  3151. ExternalASTSource *Source = getASTContext().getExternalSource();
  3152. assert(hasExternalLexicalStorage() && Source && "No external storage?");
  3153. // Notify that we have a RecordDecl doing some initialization.
  3154. ExternalASTSource::Deserializing TheFields(Source);
  3155. SmallVector<Decl*, 64> Decls;
  3156. LoadedFieldsFromExternalStorage = true;
  3157. switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
  3158. Decls)) {
  3159. case ELR_Success:
  3160. break;
  3161. case ELR_AlreadyLoaded:
  3162. case ELR_Failure:
  3163. return;
  3164. }
  3165. #ifndef NDEBUG
  3166. // Check that all decls we got were FieldDecls.
  3167. for (unsigned i=0, e=Decls.size(); i != e; ++i)
  3168. assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
  3169. #endif
  3170. if (Decls.empty())
  3171. return;
  3172. std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
  3173. /*FieldsAlreadyLoaded=*/false);
  3174. }
  3175. bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
  3176. ASTContext &Context = getASTContext();
  3177. if (!Context.getLangOpts().Sanitize.hasOneOf(
  3178. SanitizerKind::Address | SanitizerKind::KernelAddress) ||
  3179. !Context.getLangOpts().SanitizeAddressFieldPadding)
  3180. return false;
  3181. const auto &Blacklist = Context.getSanitizerBlacklist();
  3182. const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this);
  3183. // We may be able to relax some of these requirements.
  3184. int ReasonToReject = -1;
  3185. if (!CXXRD || CXXRD->isExternCContext())
  3186. ReasonToReject = 0; // is not C++.
  3187. else if (CXXRD->hasAttr<PackedAttr>())
  3188. ReasonToReject = 1; // is packed.
  3189. else if (CXXRD->isUnion())
  3190. ReasonToReject = 2; // is a union.
  3191. else if (CXXRD->isTriviallyCopyable())
  3192. ReasonToReject = 3; // is trivially copyable.
  3193. else if (CXXRD->hasTrivialDestructor())
  3194. ReasonToReject = 4; // has trivial destructor.
  3195. else if (CXXRD->isStandardLayout())
  3196. ReasonToReject = 5; // is standard layout.
  3197. else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
  3198. ReasonToReject = 6; // is in a blacklisted file.
  3199. else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
  3200. "field-padding"))
  3201. ReasonToReject = 7; // is blacklisted.
  3202. if (EmitRemark) {
  3203. if (ReasonToReject >= 0)
  3204. Context.getDiagnostics().Report(
  3205. getLocation(),
  3206. diag::remark_sanitize_address_insert_extra_padding_rejected)
  3207. << getQualifiedNameAsString() << ReasonToReject;
  3208. else
  3209. Context.getDiagnostics().Report(
  3210. getLocation(),
  3211. diag::remark_sanitize_address_insert_extra_padding_accepted)
  3212. << getQualifiedNameAsString();
  3213. }
  3214. return ReasonToReject < 0;
  3215. }
  3216. const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
  3217. for (const auto *I : fields()) {
  3218. if (I->getIdentifier())
  3219. return I;
  3220. if (const RecordType *RT = I->getType()->getAs<RecordType>())
  3221. if (const FieldDecl *NamedDataMember =
  3222. RT->getDecl()->findFirstNamedDataMember())
  3223. return NamedDataMember;
  3224. }
  3225. // We didn't find a named data member.
  3226. return nullptr;
  3227. }
  3228. //===----------------------------------------------------------------------===//
  3229. // BlockDecl Implementation
  3230. //===----------------------------------------------------------------------===//
  3231. void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
  3232. assert(!ParamInfo && "Already has param info!");
  3233. // Zero params -> null pointer.
  3234. if (!NewParamInfo.empty()) {
  3235. NumParams = NewParamInfo.size();
  3236. ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
  3237. std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
  3238. }
  3239. }
  3240. void BlockDecl::setCaptures(ASTContext &Context,
  3241. const Capture *begin,
  3242. const Capture *end,
  3243. bool capturesCXXThis) {
  3244. CapturesCXXThis = capturesCXXThis;
  3245. if (begin == end) {
  3246. NumCaptures = 0;
  3247. Captures = nullptr;
  3248. return;
  3249. }
  3250. NumCaptures = end - begin;
  3251. // Avoid new Capture[] because we don't want to provide a default
  3252. // constructor.
  3253. size_t allocationSize = NumCaptures * sizeof(Capture);
  3254. void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
  3255. memcpy(buffer, begin, allocationSize);
  3256. Captures = static_cast<Capture*>(buffer);
  3257. }
  3258. bool BlockDecl::capturesVariable(const VarDecl *variable) const {
  3259. for (const auto &I : captures())
  3260. // Only auto vars can be captured, so no redeclaration worries.
  3261. if (I.getVariable() == variable)
  3262. return true;
  3263. return false;
  3264. }
  3265. SourceRange BlockDecl::getSourceRange() const {
  3266. return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
  3267. }
  3268. //===----------------------------------------------------------------------===//
  3269. // Other Decl Allocation/Deallocation Method Implementations
  3270. //===----------------------------------------------------------------------===//
  3271. void TranslationUnitDecl::anchor() { }
  3272. TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
  3273. return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
  3274. }
  3275. void ExternCContextDecl::anchor() { }
  3276. ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
  3277. TranslationUnitDecl *DC) {
  3278. return new (C, DC) ExternCContextDecl(DC);
  3279. }
  3280. void LabelDecl::anchor() { }
  3281. LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
  3282. SourceLocation IdentL, IdentifierInfo *II) {
  3283. return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
  3284. }
  3285. LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
  3286. SourceLocation IdentL, IdentifierInfo *II,
  3287. SourceLocation GnuLabelL) {
  3288. assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
  3289. return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
  3290. }
  3291. LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3292. return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
  3293. SourceLocation());
  3294. }
  3295. void LabelDecl::setMSAsmLabel(StringRef Name) {
  3296. char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
  3297. memcpy(Buffer, Name.data(), Name.size());
  3298. Buffer[Name.size()] = '\0';
  3299. MSAsmName = Buffer;
  3300. }
  3301. void ValueDecl::anchor() { }
  3302. bool ValueDecl::isWeak() const {
  3303. for (const auto *I : attrs())
  3304. if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
  3305. return true;
  3306. return isWeakImported();
  3307. }
  3308. void ImplicitParamDecl::anchor() { }
  3309. ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
  3310. SourceLocation IdLoc,
  3311. IdentifierInfo *Id,
  3312. QualType Type) {
  3313. return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
  3314. }
  3315. ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
  3316. unsigned ID) {
  3317. return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
  3318. QualType());
  3319. }
  3320. FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
  3321. SourceLocation StartLoc,
  3322. const DeclarationNameInfo &NameInfo,
  3323. QualType T, TypeSourceInfo *TInfo,
  3324. StorageClass SC,
  3325. bool isInlineSpecified,
  3326. bool hasWrittenPrototype,
  3327. bool isConstexprSpecified) {
  3328. FunctionDecl *New =
  3329. new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
  3330. SC, isInlineSpecified, isConstexprSpecified);
  3331. New->HasWrittenPrototype = hasWrittenPrototype;
  3332. return New;
  3333. }
  3334. FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3335. return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
  3336. DeclarationNameInfo(), QualType(), nullptr,
  3337. SC_None, false, false);
  3338. }
  3339. BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
  3340. return new (C, DC) BlockDecl(DC, L);
  3341. }
  3342. BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3343. return new (C, ID) BlockDecl(nullptr, SourceLocation());
  3344. }
  3345. CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
  3346. unsigned NumParams) {
  3347. return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
  3348. CapturedDecl(DC, NumParams);
  3349. }
  3350. CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  3351. unsigned NumParams) {
  3352. return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
  3353. CapturedDecl(nullptr, NumParams);
  3354. }
  3355. EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
  3356. SourceLocation L,
  3357. IdentifierInfo *Id, QualType T,
  3358. Expr *E, const llvm::APSInt &V) {
  3359. return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
  3360. }
  3361. EnumConstantDecl *
  3362. EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3363. return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
  3364. QualType(), nullptr, llvm::APSInt());
  3365. }
  3366. void IndirectFieldDecl::anchor() { }
  3367. IndirectFieldDecl *
  3368. IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
  3369. IdentifierInfo *Id, QualType T, NamedDecl **CH,
  3370. unsigned CHS) {
  3371. return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
  3372. }
  3373. IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
  3374. unsigned ID) {
  3375. return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
  3376. DeclarationName(), QualType(), nullptr,
  3377. 0);
  3378. }
  3379. SourceRange EnumConstantDecl::getSourceRange() const {
  3380. SourceLocation End = getLocation();
  3381. if (Init)
  3382. End = Init->getLocEnd();
  3383. return SourceRange(getLocation(), End);
  3384. }
  3385. void TypeDecl::anchor() { }
  3386. TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
  3387. SourceLocation StartLoc, SourceLocation IdLoc,
  3388. IdentifierInfo *Id, TypeSourceInfo *TInfo) {
  3389. return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
  3390. }
  3391. void TypedefNameDecl::anchor() { }
  3392. TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
  3393. if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
  3394. auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
  3395. auto *ThisTypedef = this;
  3396. if (AnyRedecl && OwningTypedef) {
  3397. OwningTypedef = OwningTypedef->getCanonicalDecl();
  3398. ThisTypedef = ThisTypedef->getCanonicalDecl();
  3399. }
  3400. if (OwningTypedef == ThisTypedef)
  3401. return TT->getDecl();
  3402. }
  3403. return nullptr;
  3404. }
  3405. TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3406. return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
  3407. nullptr, nullptr);
  3408. }
  3409. TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
  3410. SourceLocation StartLoc,
  3411. SourceLocation IdLoc, IdentifierInfo *Id,
  3412. TypeSourceInfo *TInfo) {
  3413. return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
  3414. }
  3415. TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3416. return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
  3417. SourceLocation(), nullptr, nullptr);
  3418. }
  3419. SourceRange TypedefDecl::getSourceRange() const {
  3420. SourceLocation RangeEnd = getLocation();
  3421. if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
  3422. if (typeIsPostfix(TInfo->getType()))
  3423. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  3424. }
  3425. return SourceRange(getLocStart(), RangeEnd);
  3426. }
  3427. SourceRange TypeAliasDecl::getSourceRange() const {
  3428. SourceLocation RangeEnd = getLocStart();
  3429. if (TypeSourceInfo *TInfo = getTypeSourceInfo())
  3430. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  3431. return SourceRange(getLocStart(), RangeEnd);
  3432. }
  3433. void FileScopeAsmDecl::anchor() { }
  3434. FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
  3435. StringLiteral *Str,
  3436. SourceLocation AsmLoc,
  3437. SourceLocation RParenLoc) {
  3438. return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
  3439. }
  3440. FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
  3441. unsigned ID) {
  3442. return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
  3443. SourceLocation());
  3444. }
  3445. void EmptyDecl::anchor() {}
  3446. EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
  3447. return new (C, DC) EmptyDecl(DC, L);
  3448. }
  3449. EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3450. return new (C, ID) EmptyDecl(nullptr, SourceLocation());
  3451. }
  3452. //===----------------------------------------------------------------------===//
  3453. // ImportDecl Implementation
  3454. //===----------------------------------------------------------------------===//
  3455. /// \brief Retrieve the number of module identifiers needed to name the given
  3456. /// module.
  3457. static unsigned getNumModuleIdentifiers(Module *Mod) {
  3458. unsigned Result = 1;
  3459. while (Mod->Parent) {
  3460. Mod = Mod->Parent;
  3461. ++Result;
  3462. }
  3463. return Result;
  3464. }
  3465. ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
  3466. Module *Imported,
  3467. ArrayRef<SourceLocation> IdentifierLocs)
  3468. : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
  3469. NextLocalImport()
  3470. {
  3471. assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
  3472. SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
  3473. memcpy(StoredLocs, IdentifierLocs.data(),
  3474. IdentifierLocs.size() * sizeof(SourceLocation));
  3475. }
  3476. ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
  3477. Module *Imported, SourceLocation EndLoc)
  3478. : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
  3479. NextLocalImport()
  3480. {
  3481. *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
  3482. }
  3483. ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
  3484. SourceLocation StartLoc, Module *Imported,
  3485. ArrayRef<SourceLocation> IdentifierLocs) {
  3486. return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
  3487. ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
  3488. }
  3489. ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
  3490. SourceLocation StartLoc,
  3491. Module *Imported,
  3492. SourceLocation EndLoc) {
  3493. ImportDecl *Import =
  3494. new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
  3495. Imported, EndLoc);
  3496. Import->setImplicit();
  3497. return Import;
  3498. }
  3499. ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  3500. unsigned NumLocations) {
  3501. return new (C, ID, NumLocations * sizeof(SourceLocation))
  3502. ImportDecl(EmptyShell());
  3503. }
  3504. ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
  3505. if (!ImportedAndComplete.getInt())
  3506. return None;
  3507. const SourceLocation *StoredLocs
  3508. = reinterpret_cast<const SourceLocation *>(this + 1);
  3509. return llvm::makeArrayRef(StoredLocs,
  3510. getNumModuleIdentifiers(getImportedModule()));
  3511. }
  3512. SourceRange ImportDecl::getSourceRange() const {
  3513. if (!ImportedAndComplete.getInt())
  3514. return SourceRange(getLocation(),
  3515. *reinterpret_cast<const SourceLocation *>(this + 1));
  3516. return SourceRange(getLocation(), getIdentifierLocs().back());
  3517. }