Sema.cpp 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724
  1. //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the actions class which performs semantic analysis and
  10. // builds an AST out of a parse stream.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "UsedDeclVisitor.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTDiagnostic.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclFriend.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/PrettyDeclStackTrace.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/Basic/DarwinSDKInfo.h"
  25. #include "clang/Basic/DiagnosticOptions.h"
  26. #include "clang/Basic/PartialDiagnostic.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/Stack.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/HeaderSearch.h"
  31. #include "clang/Lex/HeaderSearchOptions.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "clang/Sema/CXXFieldCollector.h"
  34. #include "clang/Sema/DelayedDiagnostic.h"
  35. #include "clang/Sema/ExternalSemaSource.h"
  36. #include "clang/Sema/Initialization.h"
  37. #include "clang/Sema/MultiplexExternalSemaSource.h"
  38. #include "clang/Sema/ObjCMethodList.h"
  39. #include "clang/Sema/RISCVIntrinsicManager.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/SemaConsumer.h"
  43. #include "clang/Sema/SemaInternal.h"
  44. #include "clang/Sema/TemplateDeduction.h"
  45. #include "clang/Sema/TemplateInstCallback.h"
  46. #include "clang/Sema/TypoCorrection.h"
  47. #include "llvm/ADT/DenseMap.h"
  48. #include "llvm/ADT/STLExtras.h"
  49. #include "llvm/ADT/SmallPtrSet.h"
  50. #include "llvm/Support/TimeProfiler.h"
  51. #include <optional>
  52. using namespace clang;
  53. using namespace sema;
  54. SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
  55. return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
  56. }
  57. ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
  58. DarwinSDKInfo *
  59. Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
  60. StringRef Platform) {
  61. auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking();
  62. if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
  63. Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
  64. << Platform;
  65. WarnedDarwinSDKInfoMissing = true;
  66. }
  67. return SDKInfo;
  68. }
  69. DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() {
  70. if (CachedDarwinSDKInfo)
  71. return CachedDarwinSDKInfo->get();
  72. auto SDKInfo = parseDarwinSDKInfo(
  73. PP.getFileManager().getVirtualFileSystem(),
  74. PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
  75. if (SDKInfo && *SDKInfo) {
  76. CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
  77. return CachedDarwinSDKInfo->get();
  78. }
  79. if (!SDKInfo)
  80. llvm::consumeError(SDKInfo.takeError());
  81. CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
  82. return nullptr;
  83. }
  84. IdentifierInfo *
  85. Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
  86. unsigned int Index) {
  87. std::string InventedName;
  88. llvm::raw_string_ostream OS(InventedName);
  89. if (!ParamName)
  90. OS << "auto:" << Index + 1;
  91. else
  92. OS << ParamName->getName() << ":auto";
  93. OS.flush();
  94. return &Context.Idents.get(OS.str());
  95. }
  96. PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
  97. const Preprocessor &PP) {
  98. PrintingPolicy Policy = Context.getPrintingPolicy();
  99. // In diagnostics, we print _Bool as bool if the latter is defined as the
  100. // former.
  101. Policy.Bool = Context.getLangOpts().Bool;
  102. if (!Policy.Bool) {
  103. if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
  104. Policy.Bool = BoolMacro->isObjectLike() &&
  105. BoolMacro->getNumTokens() == 1 &&
  106. BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
  107. }
  108. }
  109. // Shorten the data output if needed
  110. Policy.EntireContentsOfLargeArray = false;
  111. return Policy;
  112. }
  113. void Sema::ActOnTranslationUnitScope(Scope *S) {
  114. TUScope = S;
  115. PushDeclContext(S, Context.getTranslationUnitDecl());
  116. }
  117. namespace clang {
  118. namespace sema {
  119. class SemaPPCallbacks : public PPCallbacks {
  120. Sema *S = nullptr;
  121. llvm::SmallVector<SourceLocation, 8> IncludeStack;
  122. public:
  123. void set(Sema &S) { this->S = &S; }
  124. void reset() { S = nullptr; }
  125. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  126. SrcMgr::CharacteristicKind FileType,
  127. FileID PrevFID) override {
  128. if (!S)
  129. return;
  130. switch (Reason) {
  131. case EnterFile: {
  132. SourceManager &SM = S->getSourceManager();
  133. SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
  134. if (IncludeLoc.isValid()) {
  135. if (llvm::timeTraceProfilerEnabled()) {
  136. const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
  137. llvm::timeTraceProfilerBegin(
  138. "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
  139. }
  140. IncludeStack.push_back(IncludeLoc);
  141. S->DiagnoseNonDefaultPragmaAlignPack(
  142. Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,
  143. IncludeLoc);
  144. }
  145. break;
  146. }
  147. case ExitFile:
  148. if (!IncludeStack.empty()) {
  149. if (llvm::timeTraceProfilerEnabled())
  150. llvm::timeTraceProfilerEnd();
  151. S->DiagnoseNonDefaultPragmaAlignPack(
  152. Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,
  153. IncludeStack.pop_back_val());
  154. }
  155. break;
  156. default:
  157. break;
  158. }
  159. }
  160. };
  161. } // end namespace sema
  162. } // end namespace clang
  163. const unsigned Sema::MaxAlignmentExponent;
  164. const uint64_t Sema::MaximumAlignment;
  165. Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
  166. TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
  167. : ExternalSource(nullptr), CurFPFeatures(pp.getLangOpts()),
  168. LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
  169. Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
  170. CollectStats(false), CodeCompleter(CodeCompleter), CurContext(nullptr),
  171. OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
  172. MSPointerToMemberRepresentationMethod(
  173. LangOpts.getMSPointerToMemberRepresentationMethod()),
  174. VtorDispStack(LangOpts.getVtorDispMode()),
  175. AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
  176. DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
  177. CodeSegStack(nullptr), StrictGuardStackCheckStack(false),
  178. FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr),
  179. VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),
  180. IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr),
  181. LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
  182. StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
  183. StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
  184. MSVCGuidDecl(nullptr), StdSourceLocationImplDecl(nullptr),
  185. NSNumberDecl(nullptr), NSValueDecl(nullptr), NSStringDecl(nullptr),
  186. StringWithUTF8StringMethod(nullptr),
  187. ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
  188. ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
  189. DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
  190. TUKind(TUKind), NumSFINAEErrors(0),
  191. FullyCheckedComparisonCategories(
  192. static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
  193. SatisfactionCache(Context), AccessCheckingSFINAE(false),
  194. InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
  195. ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
  196. DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
  197. ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
  198. CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
  199. assert(pp.TUKind == TUKind);
  200. TUScope = nullptr;
  201. isConstantEvaluatedOverride = false;
  202. LoadedExternalKnownNamespaces = false;
  203. for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
  204. NSNumberLiteralMethods[I] = nullptr;
  205. if (getLangOpts().ObjC)
  206. NSAPIObj.reset(new NSAPI(Context));
  207. if (getLangOpts().CPlusPlus)
  208. FieldCollector.reset(new CXXFieldCollector());
  209. // Tell diagnostics how to render things from the AST library.
  210. Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
  211. // This evaluation context exists to ensure that there's always at least one
  212. // valid evaluation context available. It is never removed from the
  213. // evaluation stack.
  214. ExprEvalContexts.emplace_back(
  215. ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
  216. nullptr, ExpressionEvaluationContextRecord::EK_Other);
  217. // Initialization of data sharing attributes stack for OpenMP
  218. InitDataSharingAttributesStack();
  219. std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
  220. std::make_unique<sema::SemaPPCallbacks>();
  221. SemaPPCallbackHandler = Callbacks.get();
  222. PP.addPPCallbacks(std::move(Callbacks));
  223. SemaPPCallbackHandler->set(*this);
  224. CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
  225. }
  226. // Anchor Sema's type info to this TU.
  227. void Sema::anchor() {}
  228. void Sema::addImplicitTypedef(StringRef Name, QualType T) {
  229. DeclarationName DN = &Context.Idents.get(Name);
  230. if (IdResolver.begin(DN) == IdResolver.end())
  231. PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
  232. }
  233. void Sema::Initialize() {
  234. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  235. SC->InitializeSema(*this);
  236. // Tell the external Sema source about this Sema object.
  237. if (ExternalSemaSource *ExternalSema
  238. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  239. ExternalSema->InitializeSema(*this);
  240. // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
  241. // will not be able to merge any duplicate __va_list_tag decls correctly.
  242. VAListTagName = PP.getIdentifierInfo("__va_list_tag");
  243. if (!TUScope)
  244. return;
  245. // Initialize predefined 128-bit integer types, if needed.
  246. if (Context.getTargetInfo().hasInt128Type() ||
  247. (Context.getAuxTargetInfo() &&
  248. Context.getAuxTargetInfo()->hasInt128Type())) {
  249. // If either of the 128-bit integer types are unavailable to name lookup,
  250. // define them now.
  251. DeclarationName Int128 = &Context.Idents.get("__int128_t");
  252. if (IdResolver.begin(Int128) == IdResolver.end())
  253. PushOnScopeChains(Context.getInt128Decl(), TUScope);
  254. DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
  255. if (IdResolver.begin(UInt128) == IdResolver.end())
  256. PushOnScopeChains(Context.getUInt128Decl(), TUScope);
  257. }
  258. // Initialize predefined Objective-C types:
  259. if (getLangOpts().ObjC) {
  260. // If 'SEL' does not yet refer to any declarations, make it refer to the
  261. // predefined 'SEL'.
  262. DeclarationName SEL = &Context.Idents.get("SEL");
  263. if (IdResolver.begin(SEL) == IdResolver.end())
  264. PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
  265. // If 'id' does not yet refer to any declarations, make it refer to the
  266. // predefined 'id'.
  267. DeclarationName Id = &Context.Idents.get("id");
  268. if (IdResolver.begin(Id) == IdResolver.end())
  269. PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
  270. // Create the built-in typedef for 'Class'.
  271. DeclarationName Class = &Context.Idents.get("Class");
  272. if (IdResolver.begin(Class) == IdResolver.end())
  273. PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
  274. // Create the built-in forward declaratino for 'Protocol'.
  275. DeclarationName Protocol = &Context.Idents.get("Protocol");
  276. if (IdResolver.begin(Protocol) == IdResolver.end())
  277. PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
  278. }
  279. // Create the internal type for the *StringMakeConstantString builtins.
  280. DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
  281. if (IdResolver.begin(ConstantString) == IdResolver.end())
  282. PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
  283. // Initialize Microsoft "predefined C++ types".
  284. if (getLangOpts().MSVCCompat) {
  285. if (getLangOpts().CPlusPlus &&
  286. IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
  287. PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
  288. TUScope);
  289. addImplicitTypedef("size_t", Context.getSizeType());
  290. }
  291. // Initialize predefined OpenCL types and supported extensions and (optional)
  292. // core features.
  293. if (getLangOpts().OpenCL) {
  294. getOpenCLOptions().addSupport(
  295. Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
  296. addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
  297. addImplicitTypedef("event_t", Context.OCLEventTy);
  298. auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
  299. if (OCLCompatibleVersion >= 200) {
  300. if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
  301. addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
  302. addImplicitTypedef("queue_t", Context.OCLQueueTy);
  303. }
  304. if (getLangOpts().OpenCLPipes)
  305. addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
  306. addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
  307. addImplicitTypedef("atomic_uint",
  308. Context.getAtomicType(Context.UnsignedIntTy));
  309. addImplicitTypedef("atomic_float",
  310. Context.getAtomicType(Context.FloatTy));
  311. // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
  312. // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
  313. addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
  314. // OpenCL v2.0 s6.13.11.6:
  315. // - The atomic_long and atomic_ulong types are supported if the
  316. // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
  317. // extensions are supported.
  318. // - The atomic_double type is only supported if double precision
  319. // is supported and the cl_khr_int64_base_atomics and
  320. // cl_khr_int64_extended_atomics extensions are supported.
  321. // - If the device address space is 64-bits, the data types
  322. // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
  323. // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
  324. // cl_khr_int64_extended_atomics extensions are supported.
  325. auto AddPointerSizeDependentTypes = [&]() {
  326. auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
  327. auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
  328. auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
  329. auto AtomicPtrDiffT =
  330. Context.getAtomicType(Context.getPointerDiffType());
  331. addImplicitTypedef("atomic_size_t", AtomicSizeT);
  332. addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
  333. addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
  334. addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
  335. };
  336. if (Context.getTypeSize(Context.getSizeType()) == 32) {
  337. AddPointerSizeDependentTypes();
  338. }
  339. if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
  340. auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
  341. addImplicitTypedef("atomic_half", AtomicHalfT);
  342. }
  343. std::vector<QualType> Atomic64BitTypes;
  344. if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
  345. getLangOpts()) &&
  346. getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
  347. getLangOpts())) {
  348. if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
  349. auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
  350. addImplicitTypedef("atomic_double", AtomicDoubleT);
  351. Atomic64BitTypes.push_back(AtomicDoubleT);
  352. }
  353. auto AtomicLongT = Context.getAtomicType(Context.LongTy);
  354. auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
  355. addImplicitTypedef("atomic_long", AtomicLongT);
  356. addImplicitTypedef("atomic_ulong", AtomicULongT);
  357. if (Context.getTypeSize(Context.getSizeType()) == 64) {
  358. AddPointerSizeDependentTypes();
  359. }
  360. }
  361. }
  362. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  363. if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \
  364. addImplicitTypedef(#ExtType, Context.Id##Ty); \
  365. }
  366. #include "clang/Basic/OpenCLExtensionTypes.def"
  367. }
  368. if (Context.getTargetInfo().hasAArch64SVETypes()) {
  369. #define SVE_TYPE(Name, Id, SingletonId) \
  370. addImplicitTypedef(Name, Context.SingletonId);
  371. #include "clang/Basic/AArch64SVEACLETypes.def"
  372. }
  373. if (Context.getTargetInfo().getTriple().isPPC64()) {
  374. #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
  375. addImplicitTypedef(#Name, Context.Id##Ty);
  376. #include "clang/Basic/PPCTypes.def"
  377. #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
  378. addImplicitTypedef(#Name, Context.Id##Ty);
  379. #include "clang/Basic/PPCTypes.def"
  380. }
  381. if (Context.getTargetInfo().hasRISCVVTypes()) {
  382. #define RVV_TYPE(Name, Id, SingletonId) \
  383. addImplicitTypedef(Name, Context.SingletonId);
  384. #include "clang/Basic/RISCVVTypes.def"
  385. }
  386. if (Context.getTargetInfo().hasBuiltinMSVaList()) {
  387. DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
  388. if (IdResolver.begin(MSVaList) == IdResolver.end())
  389. PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
  390. }
  391. DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
  392. if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
  393. PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
  394. }
  395. Sema::~Sema() {
  396. assert(InstantiatingSpecializations.empty() &&
  397. "failed to clean up an InstantiatingTemplate?");
  398. if (VisContext) FreeVisContext();
  399. // Kill all the active scopes.
  400. for (sema::FunctionScopeInfo *FSI : FunctionScopes)
  401. delete FSI;
  402. // Tell the SemaConsumer to forget about us; we're going out of scope.
  403. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  404. SC->ForgetSema();
  405. // Detach from the external Sema source.
  406. if (ExternalSemaSource *ExternalSema
  407. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  408. ExternalSema->ForgetSema();
  409. // Delete cached satisfactions.
  410. std::vector<ConstraintSatisfaction *> Satisfactions;
  411. Satisfactions.reserve(Satisfactions.size());
  412. for (auto &Node : SatisfactionCache)
  413. Satisfactions.push_back(&Node);
  414. for (auto *Node : Satisfactions)
  415. delete Node;
  416. threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
  417. // Destroys data sharing attributes stack for OpenMP
  418. DestroyDataSharingAttributesStack();
  419. // Detach from the PP callback handler which outlives Sema since it's owned
  420. // by the preprocessor.
  421. SemaPPCallbackHandler->reset();
  422. }
  423. void Sema::warnStackExhausted(SourceLocation Loc) {
  424. // Only warn about this once.
  425. if (!WarnedStackExhausted) {
  426. Diag(Loc, diag::warn_stack_exhausted);
  427. WarnedStackExhausted = true;
  428. }
  429. }
  430. void Sema::runWithSufficientStackSpace(SourceLocation Loc,
  431. llvm::function_ref<void()> Fn) {
  432. clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn);
  433. }
  434. /// makeUnavailableInSystemHeader - There is an error in the current
  435. /// context. If we're still in a system header, and we can plausibly
  436. /// make the relevant declaration unavailable instead of erroring, do
  437. /// so and return true.
  438. bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
  439. UnavailableAttr::ImplicitReason reason) {
  440. // If we're not in a function, it's an error.
  441. FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
  442. if (!fn) return false;
  443. // If we're in template instantiation, it's an error.
  444. if (inTemplateInstantiation())
  445. return false;
  446. // If that function's not in a system header, it's an error.
  447. if (!Context.getSourceManager().isInSystemHeader(loc))
  448. return false;
  449. // If the function is already unavailable, it's not an error.
  450. if (fn->hasAttr<UnavailableAttr>()) return true;
  451. fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
  452. return true;
  453. }
  454. ASTMutationListener *Sema::getASTMutationListener() const {
  455. return getASTConsumer().GetASTMutationListener();
  456. }
  457. ///Registers an external source. If an external source already exists,
  458. /// creates a multiplex external source and appends to it.
  459. ///
  460. ///\param[in] E - A non-null external sema source.
  461. ///
  462. void Sema::addExternalSource(ExternalSemaSource *E) {
  463. assert(E && "Cannot use with NULL ptr");
  464. if (!ExternalSource) {
  465. ExternalSource = E;
  466. return;
  467. }
  468. if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource))
  469. Ex->AddSource(E);
  470. else
  471. ExternalSource = new MultiplexExternalSemaSource(ExternalSource.get(), E);
  472. }
  473. /// Print out statistics about the semantic analysis.
  474. void Sema::PrintStats() const {
  475. llvm::errs() << "\n*** Semantic Analysis Stats:\n";
  476. llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
  477. BumpAlloc.PrintStats();
  478. AnalysisWarnings.PrintStats();
  479. }
  480. void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
  481. QualType SrcType,
  482. SourceLocation Loc) {
  483. std::optional<NullabilityKind> ExprNullability = SrcType->getNullability();
  484. if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
  485. *ExprNullability != NullabilityKind::NullableResult))
  486. return;
  487. std::optional<NullabilityKind> TypeNullability = DstType->getNullability();
  488. if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
  489. return;
  490. Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
  491. }
  492. void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E) {
  493. // nullptr only exists from C++11 on, so don't warn on its absence earlier.
  494. if (!getLangOpts().CPlusPlus11)
  495. return;
  496. if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
  497. return;
  498. if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
  499. return;
  500. if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
  501. E->getBeginLoc()))
  502. return;
  503. // Don't diagnose the conversion from a 0 literal to a null pointer argument
  504. // in a synthesized call to operator<=>.
  505. if (!CodeSynthesisContexts.empty() &&
  506. CodeSynthesisContexts.back().Kind ==
  507. CodeSynthesisContext::RewritingOperatorAsSpaceship)
  508. return;
  509. // Ignore null pointers in defaulted comparison operators.
  510. FunctionDecl *FD = getCurFunctionDecl();
  511. if (FD && FD->isDefaulted()) {
  512. return;
  513. }
  514. // If it is a macro from system header, and if the macro name is not "NULL",
  515. // do not warn.
  516. SourceLocation MaybeMacroLoc = E->getBeginLoc();
  517. if (Diags.getSuppressSystemWarnings() &&
  518. SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
  519. !findMacroSpelling(MaybeMacroLoc, "NULL"))
  520. return;
  521. Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
  522. << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
  523. }
  524. /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
  525. /// If there is already an implicit cast, merge into the existing one.
  526. /// The result is of the given category.
  527. ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
  528. CastKind Kind, ExprValueKind VK,
  529. const CXXCastPath *BasePath,
  530. CheckedConversionKind CCK) {
  531. #ifndef NDEBUG
  532. if (VK == VK_PRValue && !E->isPRValue()) {
  533. switch (Kind) {
  534. default:
  535. llvm_unreachable(
  536. ("can't implicitly cast glvalue to prvalue with this cast "
  537. "kind: " +
  538. std::string(CastExpr::getCastKindName(Kind)))
  539. .c_str());
  540. case CK_Dependent:
  541. case CK_LValueToRValue:
  542. case CK_ArrayToPointerDecay:
  543. case CK_FunctionToPointerDecay:
  544. case CK_ToVoid:
  545. case CK_NonAtomicToAtomic:
  546. break;
  547. }
  548. }
  549. assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
  550. "can't cast prvalue to glvalue");
  551. #endif
  552. diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
  553. diagnoseZeroToNullptrConversion(Kind, E);
  554. QualType ExprTy = Context.getCanonicalType(E->getType());
  555. QualType TypeTy = Context.getCanonicalType(Ty);
  556. if (ExprTy == TypeTy)
  557. return E;
  558. if (Kind == CK_ArrayToPointerDecay) {
  559. // C++1z [conv.array]: The temporary materialization conversion is applied.
  560. // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
  561. if (getLangOpts().CPlusPlus && E->isPRValue()) {
  562. // The temporary is an lvalue in C++98 and an xvalue otherwise.
  563. ExprResult Materialized = CreateMaterializeTemporaryExpr(
  564. E->getType(), E, !getLangOpts().CPlusPlus11);
  565. if (Materialized.isInvalid())
  566. return ExprError();
  567. E = Materialized.get();
  568. }
  569. // C17 6.7.1p6 footnote 124: The implementation can treat any register
  570. // declaration simply as an auto declaration. However, whether or not
  571. // addressable storage is actually used, the address of any part of an
  572. // object declared with storage-class specifier register cannot be
  573. // computed, either explicitly(by use of the unary & operator as discussed
  574. // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
  575. // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
  576. // array declared with storage-class specifier register is sizeof.
  577. if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {
  578. if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  579. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  580. if (VD->getStorageClass() == SC_Register) {
  581. Diag(E->getExprLoc(), diag::err_typecheck_address_of)
  582. << /*register variable*/ 3 << E->getSourceRange();
  583. return ExprError();
  584. }
  585. }
  586. }
  587. }
  588. }
  589. if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
  590. if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
  591. ImpCast->setType(Ty);
  592. ImpCast->setValueKind(VK);
  593. return E;
  594. }
  595. }
  596. return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
  597. CurFPFeatureOverrides());
  598. }
  599. /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
  600. /// to the conversion from scalar type ScalarTy to the Boolean type.
  601. CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
  602. switch (ScalarTy->getScalarTypeKind()) {
  603. case Type::STK_Bool: return CK_NoOp;
  604. case Type::STK_CPointer: return CK_PointerToBoolean;
  605. case Type::STK_BlockPointer: return CK_PointerToBoolean;
  606. case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
  607. case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
  608. case Type::STK_Integral: return CK_IntegralToBoolean;
  609. case Type::STK_Floating: return CK_FloatingToBoolean;
  610. case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
  611. case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
  612. case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
  613. }
  614. llvm_unreachable("unknown scalar type kind");
  615. }
  616. /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
  617. static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
  618. if (D->getMostRecentDecl()->isUsed())
  619. return true;
  620. if (D->isExternallyVisible())
  621. return true;
  622. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  623. // If this is a function template and none of its specializations is used,
  624. // we should warn.
  625. if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
  626. for (const auto *Spec : Template->specializations())
  627. if (ShouldRemoveFromUnused(SemaRef, Spec))
  628. return true;
  629. // UnusedFileScopedDecls stores the first declaration.
  630. // The declaration may have become definition so check again.
  631. const FunctionDecl *DeclToCheck;
  632. if (FD->hasBody(DeclToCheck))
  633. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  634. // Later redecls may add new information resulting in not having to warn,
  635. // so check again.
  636. DeclToCheck = FD->getMostRecentDecl();
  637. if (DeclToCheck != FD)
  638. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  639. }
  640. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  641. // If a variable usable in constant expressions is referenced,
  642. // don't warn if it isn't used: if the value of a variable is required
  643. // for the computation of a constant expression, it doesn't make sense to
  644. // warn even if the variable isn't odr-used. (isReferenced doesn't
  645. // precisely reflect that, but it's a decent approximation.)
  646. if (VD->isReferenced() &&
  647. VD->mightBeUsableInConstantExpressions(SemaRef->Context))
  648. return true;
  649. if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
  650. // If this is a variable template and none of its specializations is used,
  651. // we should warn.
  652. for (const auto *Spec : Template->specializations())
  653. if (ShouldRemoveFromUnused(SemaRef, Spec))
  654. return true;
  655. // UnusedFileScopedDecls stores the first declaration.
  656. // The declaration may have become definition so check again.
  657. const VarDecl *DeclToCheck = VD->getDefinition();
  658. if (DeclToCheck)
  659. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  660. // Later redecls may add new information resulting in not having to warn,
  661. // so check again.
  662. DeclToCheck = VD->getMostRecentDecl();
  663. if (DeclToCheck != VD)
  664. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  665. }
  666. return false;
  667. }
  668. static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
  669. if (auto *FD = dyn_cast<FunctionDecl>(ND))
  670. return FD->isExternC();
  671. return cast<VarDecl>(ND)->isExternC();
  672. }
  673. /// Determine whether ND is an external-linkage function or variable whose
  674. /// type has no linkage.
  675. bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
  676. // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
  677. // because we also want to catch the case where its type has VisibleNoLinkage,
  678. // which does not affect the linkage of VD.
  679. return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
  680. !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
  681. !isFunctionOrVarDeclExternC(VD);
  682. }
  683. /// Obtains a sorted list of functions and variables that are undefined but
  684. /// ODR-used.
  685. void Sema::getUndefinedButUsed(
  686. SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
  687. for (const auto &UndefinedUse : UndefinedButUsed) {
  688. NamedDecl *ND = UndefinedUse.first;
  689. // Ignore attributes that have become invalid.
  690. if (ND->isInvalidDecl()) continue;
  691. // __attribute__((weakref)) is basically a definition.
  692. if (ND->hasAttr<WeakRefAttr>()) continue;
  693. if (isa<CXXDeductionGuideDecl>(ND))
  694. continue;
  695. if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
  696. // An exported function will always be emitted when defined, so even if
  697. // the function is inline, it doesn't have to be emitted in this TU. An
  698. // imported function implies that it has been exported somewhere else.
  699. continue;
  700. }
  701. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  702. if (FD->isDefined())
  703. continue;
  704. if (FD->isExternallyVisible() &&
  705. !isExternalWithNoLinkageType(FD) &&
  706. !FD->getMostRecentDecl()->isInlined() &&
  707. !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  708. continue;
  709. if (FD->getBuiltinID())
  710. continue;
  711. } else {
  712. auto *VD = cast<VarDecl>(ND);
  713. if (VD->hasDefinition() != VarDecl::DeclarationOnly)
  714. continue;
  715. if (VD->isExternallyVisible() &&
  716. !isExternalWithNoLinkageType(VD) &&
  717. !VD->getMostRecentDecl()->isInline() &&
  718. !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  719. continue;
  720. // Skip VarDecls that lack formal definitions but which we know are in
  721. // fact defined somewhere.
  722. if (VD->isKnownToBeDefined())
  723. continue;
  724. }
  725. Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
  726. }
  727. }
  728. /// checkUndefinedButUsed - Check for undefined objects with internal linkage
  729. /// or that are inline.
  730. static void checkUndefinedButUsed(Sema &S) {
  731. if (S.UndefinedButUsed.empty()) return;
  732. // Collect all the still-undefined entities with internal linkage.
  733. SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
  734. S.getUndefinedButUsed(Undefined);
  735. if (Undefined.empty()) return;
  736. for (auto Undef : Undefined) {
  737. ValueDecl *VD = cast<ValueDecl>(Undef.first);
  738. SourceLocation UseLoc = Undef.second;
  739. if (S.isExternalWithNoLinkageType(VD)) {
  740. // C++ [basic.link]p8:
  741. // A type without linkage shall not be used as the type of a variable
  742. // or function with external linkage unless
  743. // -- the entity has C language linkage
  744. // -- the entity is not odr-used or is defined in the same TU
  745. //
  746. // As an extension, accept this in cases where the type is externally
  747. // visible, since the function or variable actually can be defined in
  748. // another translation unit in that case.
  749. S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
  750. ? diag::ext_undefined_internal_type
  751. : diag::err_undefined_internal_type)
  752. << isa<VarDecl>(VD) << VD;
  753. } else if (!VD->isExternallyVisible()) {
  754. // FIXME: We can promote this to an error. The function or variable can't
  755. // be defined anywhere else, so the program must necessarily violate the
  756. // one definition rule.
  757. bool IsImplicitBase = false;
  758. if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
  759. auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
  760. if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
  761. llvm::omp::TraitProperty::
  762. implementation_extension_disable_implicit_base)) {
  763. const auto *Func = cast<FunctionDecl>(
  764. cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
  765. IsImplicitBase = BaseD->isImplicit() &&
  766. Func->getIdentifier()->isMangledOpenMPVariantName();
  767. }
  768. }
  769. if (!S.getLangOpts().OpenMP || !IsImplicitBase)
  770. S.Diag(VD->getLocation(), diag::warn_undefined_internal)
  771. << isa<VarDecl>(VD) << VD;
  772. } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
  773. (void)FD;
  774. assert(FD->getMostRecentDecl()->isInlined() &&
  775. "used object requires definition but isn't inline or internal?");
  776. // FIXME: This is ill-formed; we should reject.
  777. S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
  778. } else {
  779. assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
  780. "used var requires definition but isn't inline or internal?");
  781. S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
  782. }
  783. if (UseLoc.isValid())
  784. S.Diag(UseLoc, diag::note_used_here);
  785. }
  786. S.UndefinedButUsed.clear();
  787. }
  788. void Sema::LoadExternalWeakUndeclaredIdentifiers() {
  789. if (!ExternalSource)
  790. return;
  791. SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
  792. ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
  793. for (auto &WeakID : WeakIDs)
  794. (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
  795. }
  796. typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
  797. /// Returns true, if all methods and nested classes of the given
  798. /// CXXRecordDecl are defined in this translation unit.
  799. ///
  800. /// Should only be called from ActOnEndOfTranslationUnit so that all
  801. /// definitions are actually read.
  802. static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
  803. RecordCompleteMap &MNCComplete) {
  804. RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
  805. if (Cache != MNCComplete.end())
  806. return Cache->second;
  807. if (!RD->isCompleteDefinition())
  808. return false;
  809. bool Complete = true;
  810. for (DeclContext::decl_iterator I = RD->decls_begin(),
  811. E = RD->decls_end();
  812. I != E && Complete; ++I) {
  813. if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
  814. Complete = M->isDefined() || M->isDefaulted() ||
  815. (M->isPure() && !isa<CXXDestructorDecl>(M));
  816. else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
  817. // If the template function is marked as late template parsed at this
  818. // point, it has not been instantiated and therefore we have not
  819. // performed semantic analysis on it yet, so we cannot know if the type
  820. // can be considered complete.
  821. Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
  822. F->getTemplatedDecl()->isDefined();
  823. else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
  824. if (R->isInjectedClassName())
  825. continue;
  826. if (R->hasDefinition())
  827. Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
  828. MNCComplete);
  829. else
  830. Complete = false;
  831. }
  832. }
  833. MNCComplete[RD] = Complete;
  834. return Complete;
  835. }
  836. /// Returns true, if the given CXXRecordDecl is fully defined in this
  837. /// translation unit, i.e. all methods are defined or pure virtual and all
  838. /// friends, friend functions and nested classes are fully defined in this
  839. /// translation unit.
  840. ///
  841. /// Should only be called from ActOnEndOfTranslationUnit so that all
  842. /// definitions are actually read.
  843. static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
  844. RecordCompleteMap &RecordsComplete,
  845. RecordCompleteMap &MNCComplete) {
  846. RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
  847. if (Cache != RecordsComplete.end())
  848. return Cache->second;
  849. bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
  850. for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
  851. E = RD->friend_end();
  852. I != E && Complete; ++I) {
  853. // Check if friend classes and methods are complete.
  854. if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
  855. // Friend classes are available as the TypeSourceInfo of the FriendDecl.
  856. if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
  857. Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
  858. else
  859. Complete = false;
  860. } else {
  861. // Friend functions are available through the NamedDecl of FriendDecl.
  862. if (const FunctionDecl *FD =
  863. dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
  864. Complete = FD->isDefined();
  865. else
  866. // This is a template friend, give up.
  867. Complete = false;
  868. }
  869. }
  870. RecordsComplete[RD] = Complete;
  871. return Complete;
  872. }
  873. void Sema::emitAndClearUnusedLocalTypedefWarnings() {
  874. if (ExternalSource)
  875. ExternalSource->ReadUnusedLocalTypedefNameCandidates(
  876. UnusedLocalTypedefNameCandidates);
  877. for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
  878. if (TD->isReferenced())
  879. continue;
  880. Diag(TD->getLocation(), diag::warn_unused_local_typedef)
  881. << isa<TypeAliasDecl>(TD) << TD->getDeclName();
  882. }
  883. UnusedLocalTypedefNameCandidates.clear();
  884. }
  885. /// This is called before the very first declaration in the translation unit
  886. /// is parsed. Note that the ASTContext may have already injected some
  887. /// declarations.
  888. void Sema::ActOnStartOfTranslationUnit() {
  889. if (getLangOpts().CPlusPlusModules &&
  890. getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
  891. HandleStartOfHeaderUnit();
  892. else if (getLangOpts().ModulesTS &&
  893. (getLangOpts().getCompilingModule() ==
  894. LangOptions::CMK_ModuleInterface ||
  895. getLangOpts().getCompilingModule() == LangOptions::CMK_None)) {
  896. // We start in an implied global module fragment.
  897. SourceLocation StartOfTU =
  898. SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
  899. ActOnGlobalModuleFragmentDecl(StartOfTU);
  900. ModuleScopes.back().ImplicitGlobalModuleFragment = true;
  901. }
  902. }
  903. void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
  904. // No explicit actions are required at the end of the global module fragment.
  905. if (Kind == TUFragmentKind::Global)
  906. return;
  907. // Transfer late parsed template instantiations over to the pending template
  908. // instantiation list. During normal compilation, the late template parser
  909. // will be installed and instantiating these templates will succeed.
  910. //
  911. // If we are building a TU prefix for serialization, it is also safe to
  912. // transfer these over, even though they are not parsed. The end of the TU
  913. // should be outside of any eager template instantiation scope, so when this
  914. // AST is deserialized, these templates will not be parsed until the end of
  915. // the combined TU.
  916. PendingInstantiations.insert(PendingInstantiations.end(),
  917. LateParsedInstantiations.begin(),
  918. LateParsedInstantiations.end());
  919. LateParsedInstantiations.clear();
  920. // If DefinedUsedVTables ends up marking any virtual member functions it
  921. // might lead to more pending template instantiations, which we then need
  922. // to instantiate.
  923. DefineUsedVTables();
  924. // C++: Perform implicit template instantiations.
  925. //
  926. // FIXME: When we perform these implicit instantiations, we do not
  927. // carefully keep track of the point of instantiation (C++ [temp.point]).
  928. // This means that name lookup that occurs within the template
  929. // instantiation will always happen at the end of the translation unit,
  930. // so it will find some names that are not required to be found. This is
  931. // valid, but we could do better by diagnosing if an instantiation uses a
  932. // name that was not visible at its first point of instantiation.
  933. if (ExternalSource) {
  934. // Load pending instantiations from the external source.
  935. SmallVector<PendingImplicitInstantiation, 4> Pending;
  936. ExternalSource->ReadPendingInstantiations(Pending);
  937. for (auto PII : Pending)
  938. if (auto Func = dyn_cast<FunctionDecl>(PII.first))
  939. Func->setInstantiationIsPending(true);
  940. PendingInstantiations.insert(PendingInstantiations.begin(),
  941. Pending.begin(), Pending.end());
  942. }
  943. {
  944. llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
  945. PerformPendingInstantiations();
  946. }
  947. emitDeferredDiags();
  948. assert(LateParsedInstantiations.empty() &&
  949. "end of TU template instantiation should not create more "
  950. "late-parsed templates");
  951. // Report diagnostics for uncorrected delayed typos. Ideally all of them
  952. // should have been corrected by that time, but it is very hard to cover all
  953. // cases in practice.
  954. for (const auto &Typo : DelayedTypos) {
  955. // We pass an empty TypoCorrection to indicate no correction was performed.
  956. Typo.second.DiagHandler(TypoCorrection());
  957. }
  958. DelayedTypos.clear();
  959. }
  960. /// ActOnEndOfTranslationUnit - This is called at the very end of the
  961. /// translation unit when EOF is reached and all but the top-level scope is
  962. /// popped.
  963. void Sema::ActOnEndOfTranslationUnit() {
  964. assert(DelayedDiagnostics.getCurrentPool() == nullptr
  965. && "reached end of translation unit with a pool attached?");
  966. // If code completion is enabled, don't perform any end-of-translation-unit
  967. // work.
  968. if (PP.isCodeCompletionEnabled())
  969. return;
  970. // Complete translation units and modules define vtables and perform implicit
  971. // instantiations. PCH files do not.
  972. if (TUKind != TU_Prefix) {
  973. DiagnoseUseOfUnimplementedSelectors();
  974. ActOnEndOfTranslationUnitFragment(
  975. !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
  976. Module::PrivateModuleFragment
  977. ? TUFragmentKind::Private
  978. : TUFragmentKind::Normal);
  979. if (LateTemplateParserCleanup)
  980. LateTemplateParserCleanup(OpaqueParser);
  981. CheckDelayedMemberExceptionSpecs();
  982. } else {
  983. // If we are building a TU prefix for serialization, it is safe to transfer
  984. // these over, even though they are not parsed. The end of the TU should be
  985. // outside of any eager template instantiation scope, so when this AST is
  986. // deserialized, these templates will not be parsed until the end of the
  987. // combined TU.
  988. PendingInstantiations.insert(PendingInstantiations.end(),
  989. LateParsedInstantiations.begin(),
  990. LateParsedInstantiations.end());
  991. LateParsedInstantiations.clear();
  992. if (LangOpts.PCHInstantiateTemplates) {
  993. llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
  994. PerformPendingInstantiations();
  995. }
  996. }
  997. DiagnoseUnterminatedPragmaAlignPack();
  998. DiagnoseUnterminatedPragmaAttribute();
  999. DiagnoseUnterminatedOpenMPDeclareTarget();
  1000. // All delayed member exception specs should be checked or we end up accepting
  1001. // incompatible declarations.
  1002. assert(DelayedOverridingExceptionSpecChecks.empty());
  1003. assert(DelayedEquivalentExceptionSpecChecks.empty());
  1004. // All dllexport classes should have been processed already.
  1005. assert(DelayedDllExportClasses.empty());
  1006. assert(DelayedDllExportMemberFunctions.empty());
  1007. // Remove file scoped decls that turned out to be used.
  1008. UnusedFileScopedDecls.erase(
  1009. std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
  1010. UnusedFileScopedDecls.end(),
  1011. [this](const DeclaratorDecl *DD) {
  1012. return ShouldRemoveFromUnused(this, DD);
  1013. }),
  1014. UnusedFileScopedDecls.end());
  1015. if (TUKind == TU_Prefix) {
  1016. // Translation unit prefixes don't need any of the checking below.
  1017. if (!PP.isIncrementalProcessingEnabled())
  1018. TUScope = nullptr;
  1019. return;
  1020. }
  1021. // Check for #pragma weak identifiers that were never declared
  1022. LoadExternalWeakUndeclaredIdentifiers();
  1023. for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
  1024. if (WeakIDs.second.empty())
  1025. continue;
  1026. Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
  1027. LookupOrdinaryName);
  1028. if (PrevDecl != nullptr &&
  1029. !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
  1030. for (const auto &WI : WeakIDs.second)
  1031. Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
  1032. << "'weak'" << ExpectedVariableOrFunction;
  1033. else
  1034. for (const auto &WI : WeakIDs.second)
  1035. Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
  1036. << WeakIDs.first;
  1037. }
  1038. if (LangOpts.CPlusPlus11 &&
  1039. !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
  1040. CheckDelegatingCtorCycles();
  1041. if (!Diags.hasErrorOccurred()) {
  1042. if (ExternalSource)
  1043. ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
  1044. checkUndefinedButUsed(*this);
  1045. }
  1046. // A global-module-fragment is only permitted within a module unit.
  1047. bool DiagnosedMissingModuleDeclaration = false;
  1048. if (!ModuleScopes.empty() &&
  1049. ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment &&
  1050. !ModuleScopes.back().ImplicitGlobalModuleFragment) {
  1051. Diag(ModuleScopes.back().BeginLoc,
  1052. diag::err_module_declaration_missing_after_global_module_introducer);
  1053. DiagnosedMissingModuleDeclaration = true;
  1054. }
  1055. if (TUKind == TU_Module) {
  1056. // If we are building a module interface unit, we need to have seen the
  1057. // module declaration by now.
  1058. if (getLangOpts().getCompilingModule() ==
  1059. LangOptions::CMK_ModuleInterface &&
  1060. !isCurrentModulePurview() && !DiagnosedMissingModuleDeclaration) {
  1061. // FIXME: Make a better guess as to where to put the module declaration.
  1062. Diag(getSourceManager().getLocForStartOfFile(
  1063. getSourceManager().getMainFileID()),
  1064. diag::err_module_declaration_missing);
  1065. }
  1066. // If we are building a module, resolve all of the exported declarations
  1067. // now.
  1068. if (Module *CurrentModule = PP.getCurrentModule()) {
  1069. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  1070. SmallVector<Module *, 2> Stack;
  1071. Stack.push_back(CurrentModule);
  1072. while (!Stack.empty()) {
  1073. Module *Mod = Stack.pop_back_val();
  1074. // Resolve the exported declarations and conflicts.
  1075. // FIXME: Actually complain, once we figure out how to teach the
  1076. // diagnostic client to deal with complaints in the module map at this
  1077. // point.
  1078. ModMap.resolveExports(Mod, /*Complain=*/false);
  1079. ModMap.resolveUses(Mod, /*Complain=*/false);
  1080. ModMap.resolveConflicts(Mod, /*Complain=*/false);
  1081. // Queue the submodules, so their exports will also be resolved.
  1082. Stack.append(Mod->submodule_begin(), Mod->submodule_end());
  1083. }
  1084. }
  1085. // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
  1086. // modules when they are built, not every time they are used.
  1087. emitAndClearUnusedLocalTypedefWarnings();
  1088. }
  1089. // C++ standard modules. Diagnose cases where a function is declared inline
  1090. // in the module purview but has no definition before the end of the TU or
  1091. // the start of a Private Module Fragment (if one is present).
  1092. if (!PendingInlineFuncDecls.empty()) {
  1093. for (auto *D : PendingInlineFuncDecls) {
  1094. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1095. bool DefInPMF = false;
  1096. if (auto *FDD = FD->getDefinition()) {
  1097. assert(FDD->getOwningModule() &&
  1098. FDD->getOwningModule()->isModulePurview());
  1099. DefInPMF = FDD->getOwningModule()->isPrivateModule();
  1100. if (!DefInPMF)
  1101. continue;
  1102. }
  1103. Diag(FD->getLocation(), diag::err_export_inline_not_defined)
  1104. << DefInPMF;
  1105. // If we have a PMF it should be at the end of the ModuleScopes.
  1106. if (DefInPMF &&
  1107. ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {
  1108. Diag(ModuleScopes.back().BeginLoc,
  1109. diag::note_private_module_fragment);
  1110. }
  1111. }
  1112. }
  1113. PendingInlineFuncDecls.clear();
  1114. }
  1115. // C99 6.9.2p2:
  1116. // A declaration of an identifier for an object that has file
  1117. // scope without an initializer, and without a storage-class
  1118. // specifier or with the storage-class specifier static,
  1119. // constitutes a tentative definition. If a translation unit
  1120. // contains one or more tentative definitions for an identifier,
  1121. // and the translation unit contains no external definition for
  1122. // that identifier, then the behavior is exactly as if the
  1123. // translation unit contains a file scope declaration of that
  1124. // identifier, with the composite type as of the end of the
  1125. // translation unit, with an initializer equal to 0.
  1126. llvm::SmallSet<VarDecl *, 32> Seen;
  1127. for (TentativeDefinitionsType::iterator
  1128. T = TentativeDefinitions.begin(ExternalSource.get()),
  1129. TEnd = TentativeDefinitions.end();
  1130. T != TEnd; ++T) {
  1131. VarDecl *VD = (*T)->getActingDefinition();
  1132. // If the tentative definition was completed, getActingDefinition() returns
  1133. // null. If we've already seen this variable before, insert()'s second
  1134. // return value is false.
  1135. if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
  1136. continue;
  1137. if (const IncompleteArrayType *ArrayT
  1138. = Context.getAsIncompleteArrayType(VD->getType())) {
  1139. // Set the length of the array to 1 (C99 6.9.2p5).
  1140. Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
  1141. llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
  1142. QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One,
  1143. nullptr, ArrayType::Normal, 0);
  1144. VD->setType(T);
  1145. } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
  1146. diag::err_tentative_def_incomplete_type))
  1147. VD->setInvalidDecl();
  1148. // No initialization is performed for a tentative definition.
  1149. CheckCompleteVariableDeclaration(VD);
  1150. // Notify the consumer that we've completed a tentative definition.
  1151. if (!VD->isInvalidDecl())
  1152. Consumer.CompleteTentativeDefinition(VD);
  1153. }
  1154. for (auto *D : ExternalDeclarations) {
  1155. if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
  1156. continue;
  1157. Consumer.CompleteExternalDeclaration(D);
  1158. }
  1159. // If there were errors, disable 'unused' warnings since they will mostly be
  1160. // noise. Don't warn for a use from a module: either we should warn on all
  1161. // file-scope declarations in modules or not at all, but whether the
  1162. // declaration is used is immaterial.
  1163. if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
  1164. // Output warning for unused file scoped decls.
  1165. for (UnusedFileScopedDeclsType::iterator
  1166. I = UnusedFileScopedDecls.begin(ExternalSource.get()),
  1167. E = UnusedFileScopedDecls.end();
  1168. I != E; ++I) {
  1169. if (ShouldRemoveFromUnused(this, *I))
  1170. continue;
  1171. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  1172. const FunctionDecl *DiagD;
  1173. if (!FD->hasBody(DiagD))
  1174. DiagD = FD;
  1175. if (DiagD->isDeleted())
  1176. continue; // Deleted functions are supposed to be unused.
  1177. if (DiagD->isReferenced()) {
  1178. if (isa<CXXMethodDecl>(DiagD))
  1179. Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
  1180. << DiagD;
  1181. else {
  1182. if (FD->getStorageClass() == SC_Static &&
  1183. !FD->isInlineSpecified() &&
  1184. !SourceMgr.isInMainFile(
  1185. SourceMgr.getExpansionLoc(FD->getLocation())))
  1186. Diag(DiagD->getLocation(),
  1187. diag::warn_unneeded_static_internal_decl)
  1188. << DiagD;
  1189. else
  1190. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  1191. << /*function*/ 0 << DiagD;
  1192. }
  1193. } else {
  1194. if (FD->getDescribedFunctionTemplate())
  1195. Diag(DiagD->getLocation(), diag::warn_unused_template)
  1196. << /*function*/ 0 << DiagD;
  1197. else
  1198. Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
  1199. ? diag::warn_unused_member_function
  1200. : diag::warn_unused_function)
  1201. << DiagD;
  1202. }
  1203. } else {
  1204. const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
  1205. if (!DiagD)
  1206. DiagD = cast<VarDecl>(*I);
  1207. if (DiagD->isReferenced()) {
  1208. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  1209. << /*variable*/ 1 << DiagD;
  1210. } else if (DiagD->getType().isConstQualified()) {
  1211. const SourceManager &SM = SourceMgr;
  1212. if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
  1213. !PP.getLangOpts().IsHeaderFile)
  1214. Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
  1215. << DiagD;
  1216. } else {
  1217. if (DiagD->getDescribedVarTemplate())
  1218. Diag(DiagD->getLocation(), diag::warn_unused_template)
  1219. << /*variable*/ 1 << DiagD;
  1220. else
  1221. Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD;
  1222. }
  1223. }
  1224. }
  1225. emitAndClearUnusedLocalTypedefWarnings();
  1226. }
  1227. if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
  1228. // FIXME: Load additional unused private field candidates from the external
  1229. // source.
  1230. RecordCompleteMap RecordsComplete;
  1231. RecordCompleteMap MNCComplete;
  1232. for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
  1233. E = UnusedPrivateFields.end(); I != E; ++I) {
  1234. const NamedDecl *D = *I;
  1235. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
  1236. if (RD && !RD->isUnion() &&
  1237. IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
  1238. Diag(D->getLocation(), diag::warn_unused_private_field)
  1239. << D->getDeclName();
  1240. }
  1241. }
  1242. }
  1243. if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
  1244. if (ExternalSource)
  1245. ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
  1246. for (const auto &DeletedFieldInfo : DeleteExprs) {
  1247. for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
  1248. AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
  1249. DeleteExprLoc.second);
  1250. }
  1251. }
  1252. }
  1253. // Check we've noticed that we're no longer parsing the initializer for every
  1254. // variable. If we miss cases, then at best we have a performance issue and
  1255. // at worst a rejects-valid bug.
  1256. assert(ParsingInitForAutoVars.empty() &&
  1257. "Didn't unmark var as having its initializer parsed");
  1258. if (!PP.isIncrementalProcessingEnabled())
  1259. TUScope = nullptr;
  1260. }
  1261. //===----------------------------------------------------------------------===//
  1262. // Helper functions.
  1263. //===----------------------------------------------------------------------===//
  1264. DeclContext *Sema::getFunctionLevelDeclContext(bool AllowLambda) {
  1265. DeclContext *DC = CurContext;
  1266. while (true) {
  1267. if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
  1268. isa<RequiresExprBodyDecl>(DC)) {
  1269. DC = DC->getParent();
  1270. } else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&
  1271. cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
  1272. cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
  1273. DC = DC->getParent()->getParent();
  1274. } else break;
  1275. }
  1276. return DC;
  1277. }
  1278. /// getCurFunctionDecl - If inside of a function body, this returns a pointer
  1279. /// to the function decl for the function being parsed. If we're currently
  1280. /// in a 'block', this returns the containing context.
  1281. FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) {
  1282. DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
  1283. return dyn_cast<FunctionDecl>(DC);
  1284. }
  1285. ObjCMethodDecl *Sema::getCurMethodDecl() {
  1286. DeclContext *DC = getFunctionLevelDeclContext();
  1287. while (isa<RecordDecl>(DC))
  1288. DC = DC->getParent();
  1289. return dyn_cast<ObjCMethodDecl>(DC);
  1290. }
  1291. NamedDecl *Sema::getCurFunctionOrMethodDecl() {
  1292. DeclContext *DC = getFunctionLevelDeclContext();
  1293. if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
  1294. return cast<NamedDecl>(DC);
  1295. return nullptr;
  1296. }
  1297. LangAS Sema::getDefaultCXXMethodAddrSpace() const {
  1298. if (getLangOpts().OpenCL)
  1299. return getASTContext().getDefaultOpenCLPointeeAddrSpace();
  1300. return LangAS::Default;
  1301. }
  1302. void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
  1303. // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
  1304. // and yet we also use the current diag ID on the DiagnosticsEngine. This has
  1305. // been made more painfully obvious by the refactor that introduced this
  1306. // function, but it is possible that the incoming argument can be
  1307. // eliminated. If it truly cannot be (for example, there is some reentrancy
  1308. // issue I am not seeing yet), then there should at least be a clarifying
  1309. // comment somewhere.
  1310. if (std::optional<TemplateDeductionInfo *> Info = isSFINAEContext()) {
  1311. switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
  1312. Diags.getCurrentDiagID())) {
  1313. case DiagnosticIDs::SFINAE_Report:
  1314. // We'll report the diagnostic below.
  1315. break;
  1316. case DiagnosticIDs::SFINAE_SubstitutionFailure:
  1317. // Count this failure so that we know that template argument deduction
  1318. // has failed.
  1319. ++NumSFINAEErrors;
  1320. // Make a copy of this suppressed diagnostic and store it with the
  1321. // template-deduction information.
  1322. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  1323. Diagnostic DiagInfo(&Diags);
  1324. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  1325. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1326. }
  1327. Diags.setLastDiagnosticIgnored(true);
  1328. Diags.Clear();
  1329. return;
  1330. case DiagnosticIDs::SFINAE_AccessControl: {
  1331. // Per C++ Core Issue 1170, access control is part of SFINAE.
  1332. // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
  1333. // make access control a part of SFINAE for the purposes of checking
  1334. // type traits.
  1335. if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
  1336. break;
  1337. SourceLocation Loc = Diags.getCurrentDiagLoc();
  1338. // Suppress this diagnostic.
  1339. ++NumSFINAEErrors;
  1340. // Make a copy of this suppressed diagnostic and store it with the
  1341. // template-deduction information.
  1342. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  1343. Diagnostic DiagInfo(&Diags);
  1344. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  1345. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1346. }
  1347. Diags.setLastDiagnosticIgnored(true);
  1348. Diags.Clear();
  1349. // Now the diagnostic state is clear, produce a C++98 compatibility
  1350. // warning.
  1351. Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
  1352. // The last diagnostic which Sema produced was ignored. Suppress any
  1353. // notes attached to it.
  1354. Diags.setLastDiagnosticIgnored(true);
  1355. return;
  1356. }
  1357. case DiagnosticIDs::SFINAE_Suppress:
  1358. // Make a copy of this suppressed diagnostic and store it with the
  1359. // template-deduction information;
  1360. if (*Info) {
  1361. Diagnostic DiagInfo(&Diags);
  1362. (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
  1363. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1364. }
  1365. // Suppress this diagnostic.
  1366. Diags.setLastDiagnosticIgnored(true);
  1367. Diags.Clear();
  1368. return;
  1369. }
  1370. }
  1371. // Copy the diagnostic printing policy over the ASTContext printing policy.
  1372. // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
  1373. Context.setPrintingPolicy(getPrintingPolicy());
  1374. // Emit the diagnostic.
  1375. if (!Diags.EmitCurrentDiagnostic())
  1376. return;
  1377. // If this is not a note, and we're in a template instantiation
  1378. // that is different from the last template instantiation where
  1379. // we emitted an error, print a template instantiation
  1380. // backtrace.
  1381. if (!DiagnosticIDs::isBuiltinNote(DiagID))
  1382. PrintContextStack();
  1383. }
  1384. Sema::SemaDiagnosticBuilder
  1385. Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
  1386. return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
  1387. }
  1388. bool Sema::hasUncompilableErrorOccurred() const {
  1389. if (getDiagnostics().hasUncompilableErrorOccurred())
  1390. return true;
  1391. auto *FD = dyn_cast<FunctionDecl>(CurContext);
  1392. if (!FD)
  1393. return false;
  1394. auto Loc = DeviceDeferredDiags.find(FD);
  1395. if (Loc == DeviceDeferredDiags.end())
  1396. return false;
  1397. for (auto PDAt : Loc->second) {
  1398. if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
  1399. return true;
  1400. }
  1401. return false;
  1402. }
  1403. // Print notes showing how we can reach FD starting from an a priori
  1404. // known-callable function.
  1405. static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
  1406. auto FnIt = S.DeviceKnownEmittedFns.find(FD);
  1407. while (FnIt != S.DeviceKnownEmittedFns.end()) {
  1408. // Respect error limit.
  1409. if (S.Diags.hasFatalErrorOccurred())
  1410. return;
  1411. DiagnosticBuilder Builder(
  1412. S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
  1413. Builder << FnIt->second.FD;
  1414. FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
  1415. }
  1416. }
  1417. namespace {
  1418. /// Helper class that emits deferred diagnostic messages if an entity directly
  1419. /// or indirectly using the function that causes the deferred diagnostic
  1420. /// messages is known to be emitted.
  1421. ///
  1422. /// During parsing of AST, certain diagnostic messages are recorded as deferred
  1423. /// diagnostics since it is unknown whether the functions containing such
  1424. /// diagnostics will be emitted. A list of potentially emitted functions and
  1425. /// variables that may potentially trigger emission of functions are also
  1426. /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
  1427. /// by each function to emit deferred diagnostics.
  1428. ///
  1429. /// During the visit, certain OpenMP directives or initializer of variables
  1430. /// with certain OpenMP attributes will cause subsequent visiting of any
  1431. /// functions enter a state which is called OpenMP device context in this
  1432. /// implementation. The state is exited when the directive or initializer is
  1433. /// exited. This state can change the emission states of subsequent uses
  1434. /// of functions.
  1435. ///
  1436. /// Conceptually the functions or variables to be visited form a use graph
  1437. /// where the parent node uses the child node. At any point of the visit,
  1438. /// the tree nodes traversed from the tree root to the current node form a use
  1439. /// stack. The emission state of the current node depends on two factors:
  1440. /// 1. the emission state of the root node
  1441. /// 2. whether the current node is in OpenMP device context
  1442. /// If the function is decided to be emitted, its contained deferred diagnostics
  1443. /// are emitted, together with the information about the use stack.
  1444. ///
  1445. class DeferredDiagnosticsEmitter
  1446. : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
  1447. public:
  1448. typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
  1449. // Whether the function is already in the current use-path.
  1450. llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
  1451. // The current use-path.
  1452. llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
  1453. // Whether the visiting of the function has been done. Done[0] is for the
  1454. // case not in OpenMP device context. Done[1] is for the case in OpenMP
  1455. // device context. We need two sets because diagnostics emission may be
  1456. // different depending on whether it is in OpenMP device context.
  1457. llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
  1458. // Emission state of the root node of the current use graph.
  1459. bool ShouldEmitRootNode;
  1460. // Current OpenMP device context level. It is initialized to 0 and each
  1461. // entering of device context increases it by 1 and each exit decreases
  1462. // it by 1. Non-zero value indicates it is currently in device context.
  1463. unsigned InOMPDeviceContext;
  1464. DeferredDiagnosticsEmitter(Sema &S)
  1465. : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
  1466. bool shouldVisitDiscardedStmt() const { return false; }
  1467. void VisitOMPTargetDirective(OMPTargetDirective *Node) {
  1468. ++InOMPDeviceContext;
  1469. Inherited::VisitOMPTargetDirective(Node);
  1470. --InOMPDeviceContext;
  1471. }
  1472. void visitUsedDecl(SourceLocation Loc, Decl *D) {
  1473. if (isa<VarDecl>(D))
  1474. return;
  1475. if (auto *FD = dyn_cast<FunctionDecl>(D))
  1476. checkFunc(Loc, FD);
  1477. else
  1478. Inherited::visitUsedDecl(Loc, D);
  1479. }
  1480. void checkVar(VarDecl *VD) {
  1481. assert(VD->isFileVarDecl() &&
  1482. "Should only check file-scope variables");
  1483. if (auto *Init = VD->getInit()) {
  1484. auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
  1485. bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
  1486. *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
  1487. if (IsDev)
  1488. ++InOMPDeviceContext;
  1489. this->Visit(Init);
  1490. if (IsDev)
  1491. --InOMPDeviceContext;
  1492. }
  1493. }
  1494. void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
  1495. auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
  1496. FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
  1497. if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
  1498. S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
  1499. return;
  1500. // Finalize analysis of OpenMP-specific constructs.
  1501. if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
  1502. (ShouldEmitRootNode || InOMPDeviceContext))
  1503. S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
  1504. if (Caller)
  1505. S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
  1506. // Always emit deferred diagnostics for the direct users. This does not
  1507. // lead to explosion of diagnostics since each user is visited at most
  1508. // twice.
  1509. if (ShouldEmitRootNode || InOMPDeviceContext)
  1510. emitDeferredDiags(FD, Caller);
  1511. // Do not revisit a function if the function body has been completely
  1512. // visited before.
  1513. if (!Done.insert(FD).second)
  1514. return;
  1515. InUsePath.insert(FD);
  1516. UsePath.push_back(FD);
  1517. if (auto *S = FD->getBody()) {
  1518. this->Visit(S);
  1519. }
  1520. UsePath.pop_back();
  1521. InUsePath.erase(FD);
  1522. }
  1523. void checkRecordedDecl(Decl *D) {
  1524. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1525. ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
  1526. Sema::FunctionEmissionStatus::Emitted;
  1527. checkFunc(SourceLocation(), FD);
  1528. } else
  1529. checkVar(cast<VarDecl>(D));
  1530. }
  1531. // Emit any deferred diagnostics for FD
  1532. void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
  1533. auto It = S.DeviceDeferredDiags.find(FD);
  1534. if (It == S.DeviceDeferredDiags.end())
  1535. return;
  1536. bool HasWarningOrError = false;
  1537. bool FirstDiag = true;
  1538. for (PartialDiagnosticAt &PDAt : It->second) {
  1539. // Respect error limit.
  1540. if (S.Diags.hasFatalErrorOccurred())
  1541. return;
  1542. const SourceLocation &Loc = PDAt.first;
  1543. const PartialDiagnostic &PD = PDAt.second;
  1544. HasWarningOrError |=
  1545. S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
  1546. DiagnosticsEngine::Warning;
  1547. {
  1548. DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
  1549. PD.Emit(Builder);
  1550. }
  1551. // Emit the note on the first diagnostic in case too many diagnostics
  1552. // cause the note not emitted.
  1553. if (FirstDiag && HasWarningOrError && ShowCallStack) {
  1554. emitCallStackNotes(S, FD);
  1555. FirstDiag = false;
  1556. }
  1557. }
  1558. }
  1559. };
  1560. } // namespace
  1561. void Sema::emitDeferredDiags() {
  1562. if (ExternalSource)
  1563. ExternalSource->ReadDeclsToCheckForDeferredDiags(
  1564. DeclsToCheckForDeferredDiags);
  1565. if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
  1566. DeclsToCheckForDeferredDiags.empty())
  1567. return;
  1568. DeferredDiagnosticsEmitter DDE(*this);
  1569. for (auto *D : DeclsToCheckForDeferredDiags)
  1570. DDE.checkRecordedDecl(D);
  1571. }
  1572. // In CUDA, there are some constructs which may appear in semantically-valid
  1573. // code, but trigger errors if we ever generate code for the function in which
  1574. // they appear. Essentially every construct you're not allowed to use on the
  1575. // device falls into this category, because you are allowed to use these
  1576. // constructs in a __host__ __device__ function, but only if that function is
  1577. // never codegen'ed on the device.
  1578. //
  1579. // To handle semantic checking for these constructs, we keep track of the set of
  1580. // functions we know will be emitted, either because we could tell a priori that
  1581. // they would be emitted, or because they were transitively called by a
  1582. // known-emitted function.
  1583. //
  1584. // We also keep a partial call graph of which not-known-emitted functions call
  1585. // which other not-known-emitted functions.
  1586. //
  1587. // When we see something which is illegal if the current function is emitted
  1588. // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
  1589. // CheckCUDACall), we first check if the current function is known-emitted. If
  1590. // so, we immediately output the diagnostic.
  1591. //
  1592. // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
  1593. // until we discover that the function is known-emitted, at which point we take
  1594. // it out of this map and emit the diagnostic.
  1595. Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
  1596. unsigned DiagID,
  1597. FunctionDecl *Fn, Sema &S)
  1598. : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
  1599. ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
  1600. switch (K) {
  1601. case K_Nop:
  1602. break;
  1603. case K_Immediate:
  1604. case K_ImmediateWithCallStack:
  1605. ImmediateDiag.emplace(
  1606. ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
  1607. break;
  1608. case K_Deferred:
  1609. assert(Fn && "Must have a function to attach the deferred diag to.");
  1610. auto &Diags = S.DeviceDeferredDiags[Fn];
  1611. PartialDiagId.emplace(Diags.size());
  1612. Diags.emplace_back(Loc, S.PDiag(DiagID));
  1613. break;
  1614. }
  1615. }
  1616. Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
  1617. : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
  1618. ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
  1619. PartialDiagId(D.PartialDiagId) {
  1620. // Clean the previous diagnostics.
  1621. D.ShowCallStack = false;
  1622. D.ImmediateDiag.reset();
  1623. D.PartialDiagId.reset();
  1624. }
  1625. Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
  1626. if (ImmediateDiag) {
  1627. // Emit our diagnostic and, if it was a warning or error, output a callstack
  1628. // if Fn isn't a priori known-emitted.
  1629. bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
  1630. DiagID, Loc) >= DiagnosticsEngine::Warning;
  1631. ImmediateDiag.reset(); // Emit the immediate diag.
  1632. if (IsWarningOrError && ShowCallStack)
  1633. emitCallStackNotes(S, Fn);
  1634. } else {
  1635. assert((!PartialDiagId || ShowCallStack) &&
  1636. "Must always show call stack for deferred diags.");
  1637. }
  1638. }
  1639. Sema::SemaDiagnosticBuilder
  1640. Sema::targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD) {
  1641. FD = FD ? FD : getCurFunctionDecl();
  1642. if (LangOpts.OpenMP)
  1643. return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID, FD)
  1644. : diagIfOpenMPHostCode(Loc, DiagID, FD);
  1645. if (getLangOpts().CUDA)
  1646. return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
  1647. : CUDADiagIfHostCode(Loc, DiagID);
  1648. if (getLangOpts().SYCLIsDevice)
  1649. return SYCLDiagIfDeviceCode(Loc, DiagID);
  1650. return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
  1651. FD, *this);
  1652. }
  1653. Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID,
  1654. bool DeferHint) {
  1655. bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
  1656. bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag &&
  1657. DiagnosticIDs::isDeferrable(DiagID) &&
  1658. (DeferHint || DeferDiags || !IsError);
  1659. auto SetIsLastErrorImmediate = [&](bool Flag) {
  1660. if (IsError)
  1661. IsLastErrorImmediate = Flag;
  1662. };
  1663. if (!ShouldDefer) {
  1664. SetIsLastErrorImmediate(true);
  1665. return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc,
  1666. DiagID, getCurFunctionDecl(), *this);
  1667. }
  1668. SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice
  1669. ? CUDADiagIfDeviceCode(Loc, DiagID)
  1670. : CUDADiagIfHostCode(Loc, DiagID);
  1671. SetIsLastErrorImmediate(DB.isImmediate());
  1672. return DB;
  1673. }
  1674. void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
  1675. if (isUnevaluatedContext() || Ty.isNull())
  1676. return;
  1677. // The original idea behind checkTypeSupport function is that unused
  1678. // declarations can be replaced with an array of bytes of the same size during
  1679. // codegen, such replacement doesn't seem to be possible for types without
  1680. // constant byte size like zero length arrays. So, do a deep check for SYCL.
  1681. if (D && LangOpts.SYCLIsDevice) {
  1682. llvm::DenseSet<QualType> Visited;
  1683. deepTypeCheckForSYCLDevice(Loc, Visited, D);
  1684. }
  1685. Decl *C = cast<Decl>(getCurLexicalContext());
  1686. // Memcpy operations for structs containing a member with unsupported type
  1687. // are ok, though.
  1688. if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
  1689. if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
  1690. MD->isTrivial())
  1691. return;
  1692. if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
  1693. if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
  1694. return;
  1695. }
  1696. // Try to associate errors with the lexical context, if that is a function, or
  1697. // the value declaration otherwise.
  1698. FunctionDecl *FD = isa<FunctionDecl>(C) ? cast<FunctionDecl>(C)
  1699. : dyn_cast_or_null<FunctionDecl>(D);
  1700. auto CheckDeviceType = [&](QualType Ty) {
  1701. if (Ty->isDependentType())
  1702. return;
  1703. if (Ty->isBitIntType()) {
  1704. if (!Context.getTargetInfo().hasBitIntType()) {
  1705. PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
  1706. if (D)
  1707. PD << D;
  1708. else
  1709. PD << "expression";
  1710. targetDiag(Loc, PD, FD)
  1711. << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
  1712. << Ty << Context.getTargetInfo().getTriple().str();
  1713. }
  1714. return;
  1715. }
  1716. // Check if we are dealing with two 'long double' but with different
  1717. // semantics.
  1718. bool LongDoubleMismatched = false;
  1719. if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {
  1720. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
  1721. if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
  1722. !Context.getTargetInfo().hasFloat128Type()) ||
  1723. (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
  1724. !Context.getTargetInfo().hasIbm128Type()))
  1725. LongDoubleMismatched = true;
  1726. }
  1727. if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
  1728. (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
  1729. (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) ||
  1730. (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
  1731. !Context.getTargetInfo().hasInt128Type()) ||
  1732. LongDoubleMismatched) {
  1733. PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
  1734. if (D)
  1735. PD << D;
  1736. else
  1737. PD << "expression";
  1738. if (targetDiag(Loc, PD, FD)
  1739. << true /*show bit size*/
  1740. << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
  1741. << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
  1742. if (D)
  1743. D->setInvalidDecl();
  1744. }
  1745. if (D)
  1746. targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
  1747. }
  1748. };
  1749. auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
  1750. if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) ||
  1751. LangOpts.CUDAIsDevice)
  1752. CheckDeviceType(Ty);
  1753. QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();
  1754. const TargetInfo &TI = Context.getTargetInfo();
  1755. if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
  1756. PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
  1757. if (D)
  1758. PD << D;
  1759. else
  1760. PD << "expression";
  1761. if (Diag(Loc, PD, FD)
  1762. << false /*show bit size*/ << 0 << Ty << false /*return*/
  1763. << Context.getTargetInfo().getTriple().str()) {
  1764. if (D)
  1765. D->setInvalidDecl();
  1766. }
  1767. if (D)
  1768. targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
  1769. }
  1770. bool IsDouble = UnqualTy == Context.DoubleTy;
  1771. bool IsFloat = UnqualTy == Context.FloatTy;
  1772. if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
  1773. PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
  1774. if (D)
  1775. PD << D;
  1776. else
  1777. PD << "expression";
  1778. if (Diag(Loc, PD, FD)
  1779. << false /*show bit size*/ << 0 << Ty << true /*return*/
  1780. << Context.getTargetInfo().getTriple().str()) {
  1781. if (D)
  1782. D->setInvalidDecl();
  1783. }
  1784. if (D)
  1785. targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
  1786. }
  1787. // Don't allow SVE types in functions without a SVE target.
  1788. if (Ty->isSVESizelessBuiltinType() && FD && FD->hasBody()) {
  1789. llvm::StringMap<bool> CallerFeatureMap;
  1790. Context.getFunctionFeatureMap(CallerFeatureMap, FD);
  1791. if (!Builtin::evaluateRequiredTargetFeatures(
  1792. "sve", CallerFeatureMap))
  1793. Diag(D->getLocation(), diag::err_sve_vector_in_non_sve_target) << Ty;
  1794. }
  1795. };
  1796. CheckType(Ty);
  1797. if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
  1798. for (const auto &ParamTy : FPTy->param_types())
  1799. CheckType(ParamTy);
  1800. CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
  1801. }
  1802. if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
  1803. CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
  1804. }
  1805. /// Looks through the macro-expansion chain for the given
  1806. /// location, looking for a macro expansion with the given name.
  1807. /// If one is found, returns true and sets the location to that
  1808. /// expansion loc.
  1809. bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
  1810. SourceLocation loc = locref;
  1811. if (!loc.isMacroID()) return false;
  1812. // There's no good way right now to look at the intermediate
  1813. // expansions, so just jump to the expansion location.
  1814. loc = getSourceManager().getExpansionLoc(loc);
  1815. // If that's written with the name, stop here.
  1816. SmallString<16> buffer;
  1817. if (getPreprocessor().getSpelling(loc, buffer) == name) {
  1818. locref = loc;
  1819. return true;
  1820. }
  1821. return false;
  1822. }
  1823. /// Determines the active Scope associated with the given declaration
  1824. /// context.
  1825. ///
  1826. /// This routine maps a declaration context to the active Scope object that
  1827. /// represents that declaration context in the parser. It is typically used
  1828. /// from "scope-less" code (e.g., template instantiation, lazy creation of
  1829. /// declarations) that injects a name for name-lookup purposes and, therefore,
  1830. /// must update the Scope.
  1831. ///
  1832. /// \returns The scope corresponding to the given declaraion context, or NULL
  1833. /// if no such scope is open.
  1834. Scope *Sema::getScopeForContext(DeclContext *Ctx) {
  1835. if (!Ctx)
  1836. return nullptr;
  1837. Ctx = Ctx->getPrimaryContext();
  1838. for (Scope *S = getCurScope(); S; S = S->getParent()) {
  1839. // Ignore scopes that cannot have declarations. This is important for
  1840. // out-of-line definitions of static class members.
  1841. if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
  1842. if (DeclContext *Entity = S->getEntity())
  1843. if (Ctx == Entity->getPrimaryContext())
  1844. return S;
  1845. }
  1846. return nullptr;
  1847. }
  1848. /// Enter a new function scope
  1849. void Sema::PushFunctionScope() {
  1850. if (FunctionScopes.empty() && CachedFunctionScope) {
  1851. // Use CachedFunctionScope to avoid allocating memory when possible.
  1852. CachedFunctionScope->Clear();
  1853. FunctionScopes.push_back(CachedFunctionScope.release());
  1854. } else {
  1855. FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
  1856. }
  1857. if (LangOpts.OpenMP)
  1858. pushOpenMPFunctionRegion();
  1859. }
  1860. void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
  1861. FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
  1862. BlockScope, Block));
  1863. }
  1864. LambdaScopeInfo *Sema::PushLambdaScope() {
  1865. LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
  1866. FunctionScopes.push_back(LSI);
  1867. return LSI;
  1868. }
  1869. void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
  1870. if (LambdaScopeInfo *const LSI = getCurLambda()) {
  1871. LSI->AutoTemplateParameterDepth = Depth;
  1872. return;
  1873. }
  1874. llvm_unreachable(
  1875. "Remove assertion if intentionally called in a non-lambda context.");
  1876. }
  1877. // Check that the type of the VarDecl has an accessible copy constructor and
  1878. // resolve its destructor's exception specification.
  1879. // This also performs initialization of block variables when they are moved
  1880. // to the heap. It uses the same rules as applicable for implicit moves
  1881. // according to the C++ standard in effect ([class.copy.elision]p3).
  1882. static void checkEscapingByref(VarDecl *VD, Sema &S) {
  1883. QualType T = VD->getType();
  1884. EnterExpressionEvaluationContext scope(
  1885. S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  1886. SourceLocation Loc = VD->getLocation();
  1887. Expr *VarRef =
  1888. new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
  1889. ExprResult Result;
  1890. auto IE = InitializedEntity::InitializeBlock(Loc, T);
  1891. if (S.getLangOpts().CPlusPlus2b) {
  1892. auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
  1893. VK_XValue, FPOptionsOverride());
  1894. Result = S.PerformCopyInitialization(IE, SourceLocation(), E);
  1895. } else {
  1896. Result = S.PerformMoveOrCopyInitialization(
  1897. IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible},
  1898. VarRef);
  1899. }
  1900. if (!Result.isInvalid()) {
  1901. Result = S.MaybeCreateExprWithCleanups(Result);
  1902. Expr *Init = Result.getAs<Expr>();
  1903. S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
  1904. }
  1905. // The destructor's exception specification is needed when IRGen generates
  1906. // block copy/destroy functions. Resolve it here.
  1907. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  1908. if (CXXDestructorDecl *DD = RD->getDestructor()) {
  1909. auto *FPT = DD->getType()->getAs<FunctionProtoType>();
  1910. S.ResolveExceptionSpec(Loc, FPT);
  1911. }
  1912. }
  1913. static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
  1914. // Set the EscapingByref flag of __block variables captured by
  1915. // escaping blocks.
  1916. for (const BlockDecl *BD : FSI.Blocks) {
  1917. for (const BlockDecl::Capture &BC : BD->captures()) {
  1918. VarDecl *VD = BC.getVariable();
  1919. if (VD->hasAttr<BlocksAttr>()) {
  1920. // Nothing to do if this is a __block variable captured by a
  1921. // non-escaping block.
  1922. if (BD->doesNotEscape())
  1923. continue;
  1924. VD->setEscapingByref();
  1925. }
  1926. // Check whether the captured variable is or contains an object of
  1927. // non-trivial C union type.
  1928. QualType CapType = BC.getVariable()->getType();
  1929. if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
  1930. CapType.hasNonTrivialToPrimitiveCopyCUnion())
  1931. S.checkNonTrivialCUnion(BC.getVariable()->getType(),
  1932. BD->getCaretLocation(),
  1933. Sema::NTCUC_BlockCapture,
  1934. Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
  1935. }
  1936. }
  1937. for (VarDecl *VD : FSI.ByrefBlockVars) {
  1938. // __block variables might require us to capture a copy-initializer.
  1939. if (!VD->isEscapingByref())
  1940. continue;
  1941. // It's currently invalid to ever have a __block variable with an
  1942. // array type; should we diagnose that here?
  1943. // Regardless, we don't want to ignore array nesting when
  1944. // constructing this copy.
  1945. if (VD->getType()->isStructureOrClassType())
  1946. checkEscapingByref(VD, S);
  1947. }
  1948. }
  1949. /// Pop a function (or block or lambda or captured region) scope from the stack.
  1950. ///
  1951. /// \param WP The warning policy to use for CFG-based warnings, or null if such
  1952. /// warnings should not be produced.
  1953. /// \param D The declaration corresponding to this function scope, if producing
  1954. /// CFG-based warnings.
  1955. /// \param BlockType The type of the block expression, if D is a BlockDecl.
  1956. Sema::PoppedFunctionScopePtr
  1957. Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
  1958. const Decl *D, QualType BlockType) {
  1959. assert(!FunctionScopes.empty() && "mismatched push/pop!");
  1960. markEscapingByrefs(*FunctionScopes.back(), *this);
  1961. PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
  1962. PoppedFunctionScopeDeleter(this));
  1963. if (LangOpts.OpenMP)
  1964. popOpenMPFunctionRegion(Scope.get());
  1965. // Issue any analysis-based warnings.
  1966. if (WP && D)
  1967. AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
  1968. else
  1969. for (const auto &PUD : Scope->PossiblyUnreachableDiags)
  1970. Diag(PUD.Loc, PUD.PD);
  1971. return Scope;
  1972. }
  1973. void Sema::PoppedFunctionScopeDeleter::
  1974. operator()(sema::FunctionScopeInfo *Scope) const {
  1975. // Stash the function scope for later reuse if it's for a normal function.
  1976. if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
  1977. Self->CachedFunctionScope.reset(Scope);
  1978. else
  1979. delete Scope;
  1980. }
  1981. void Sema::PushCompoundScope(bool IsStmtExpr) {
  1982. getCurFunction()->CompoundScopes.push_back(
  1983. CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
  1984. }
  1985. void Sema::PopCompoundScope() {
  1986. FunctionScopeInfo *CurFunction = getCurFunction();
  1987. assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
  1988. CurFunction->CompoundScopes.pop_back();
  1989. }
  1990. /// Determine whether any errors occurred within this function/method/
  1991. /// block.
  1992. bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
  1993. return getCurFunction()->hasUnrecoverableErrorOccurred();
  1994. }
  1995. void Sema::setFunctionHasBranchIntoScope() {
  1996. if (!FunctionScopes.empty())
  1997. FunctionScopes.back()->setHasBranchIntoScope();
  1998. }
  1999. void Sema::setFunctionHasBranchProtectedScope() {
  2000. if (!FunctionScopes.empty())
  2001. FunctionScopes.back()->setHasBranchProtectedScope();
  2002. }
  2003. void Sema::setFunctionHasIndirectGoto() {
  2004. if (!FunctionScopes.empty())
  2005. FunctionScopes.back()->setHasIndirectGoto();
  2006. }
  2007. void Sema::setFunctionHasMustTail() {
  2008. if (!FunctionScopes.empty())
  2009. FunctionScopes.back()->setHasMustTail();
  2010. }
  2011. BlockScopeInfo *Sema::getCurBlock() {
  2012. if (FunctionScopes.empty())
  2013. return nullptr;
  2014. auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
  2015. if (CurBSI && CurBSI->TheDecl &&
  2016. !CurBSI->TheDecl->Encloses(CurContext)) {
  2017. // We have switched contexts due to template instantiation.
  2018. assert(!CodeSynthesisContexts.empty());
  2019. return nullptr;
  2020. }
  2021. return CurBSI;
  2022. }
  2023. FunctionScopeInfo *Sema::getEnclosingFunction() const {
  2024. if (FunctionScopes.empty())
  2025. return nullptr;
  2026. for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
  2027. if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
  2028. continue;
  2029. return FunctionScopes[e];
  2030. }
  2031. return nullptr;
  2032. }
  2033. LambdaScopeInfo *Sema::getEnclosingLambda() const {
  2034. for (auto *Scope : llvm::reverse(FunctionScopes)) {
  2035. if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
  2036. if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext)) {
  2037. // We have switched contexts due to template instantiation.
  2038. // FIXME: We should swap out the FunctionScopes during code synthesis
  2039. // so that we don't need to check for this.
  2040. assert(!CodeSynthesisContexts.empty());
  2041. return nullptr;
  2042. }
  2043. return LSI;
  2044. }
  2045. }
  2046. return nullptr;
  2047. }
  2048. LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
  2049. if (FunctionScopes.empty())
  2050. return nullptr;
  2051. auto I = FunctionScopes.rbegin();
  2052. if (IgnoreNonLambdaCapturingScope) {
  2053. auto E = FunctionScopes.rend();
  2054. while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
  2055. ++I;
  2056. if (I == E)
  2057. return nullptr;
  2058. }
  2059. auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
  2060. if (CurLSI && CurLSI->Lambda &&
  2061. !CurLSI->Lambda->Encloses(CurContext)) {
  2062. // We have switched contexts due to template instantiation.
  2063. assert(!CodeSynthesisContexts.empty());
  2064. return nullptr;
  2065. }
  2066. return CurLSI;
  2067. }
  2068. // We have a generic lambda if we parsed auto parameters, or we have
  2069. // an associated template parameter list.
  2070. LambdaScopeInfo *Sema::getCurGenericLambda() {
  2071. if (LambdaScopeInfo *LSI = getCurLambda()) {
  2072. return (LSI->TemplateParams.size() ||
  2073. LSI->GLTemplateParameterList) ? LSI : nullptr;
  2074. }
  2075. return nullptr;
  2076. }
  2077. void Sema::ActOnComment(SourceRange Comment) {
  2078. if (!LangOpts.RetainCommentsFromSystemHeaders &&
  2079. SourceMgr.isInSystemHeader(Comment.getBegin()))
  2080. return;
  2081. RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
  2082. if (RC.isAlmostTrailingComment()) {
  2083. SourceRange MagicMarkerRange(Comment.getBegin(),
  2084. Comment.getBegin().getLocWithOffset(3));
  2085. StringRef MagicMarkerText;
  2086. switch (RC.getKind()) {
  2087. case RawComment::RCK_OrdinaryBCPL:
  2088. MagicMarkerText = "///<";
  2089. break;
  2090. case RawComment::RCK_OrdinaryC:
  2091. MagicMarkerText = "/**<";
  2092. break;
  2093. default:
  2094. llvm_unreachable("if this is an almost Doxygen comment, "
  2095. "it should be ordinary");
  2096. }
  2097. Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
  2098. FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
  2099. }
  2100. Context.addComment(RC);
  2101. }
  2102. // Pin this vtable to this file.
  2103. ExternalSemaSource::~ExternalSemaSource() {}
  2104. char ExternalSemaSource::ID;
  2105. void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
  2106. void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
  2107. void ExternalSemaSource::ReadKnownNamespaces(
  2108. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  2109. }
  2110. void ExternalSemaSource::ReadUndefinedButUsed(
  2111. llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
  2112. void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
  2113. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
  2114. /// Figure out if an expression could be turned into a call.
  2115. ///
  2116. /// Use this when trying to recover from an error where the programmer may have
  2117. /// written just the name of a function instead of actually calling it.
  2118. ///
  2119. /// \param E - The expression to examine.
  2120. /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
  2121. /// with no arguments, this parameter is set to the type returned by such a
  2122. /// call; otherwise, it is set to an empty QualType.
  2123. /// \param OverloadSet - If the expression is an overloaded function
  2124. /// name, this parameter is populated with the decls of the various overloads.
  2125. bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
  2126. UnresolvedSetImpl &OverloadSet) {
  2127. ZeroArgCallReturnTy = QualType();
  2128. OverloadSet.clear();
  2129. const OverloadExpr *Overloads = nullptr;
  2130. bool IsMemExpr = false;
  2131. if (E.getType() == Context.OverloadTy) {
  2132. OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
  2133. // Ignore overloads that are pointer-to-member constants.
  2134. if (FR.HasFormOfMemberPointer)
  2135. return false;
  2136. Overloads = FR.Expression;
  2137. } else if (E.getType() == Context.BoundMemberTy) {
  2138. Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
  2139. IsMemExpr = true;
  2140. }
  2141. bool Ambiguous = false;
  2142. bool IsMV = false;
  2143. if (Overloads) {
  2144. for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
  2145. DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
  2146. OverloadSet.addDecl(*it);
  2147. // Check whether the function is a non-template, non-member which takes no
  2148. // arguments.
  2149. if (IsMemExpr)
  2150. continue;
  2151. if (const FunctionDecl *OverloadDecl
  2152. = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
  2153. if (OverloadDecl->getMinRequiredArguments() == 0) {
  2154. if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
  2155. (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
  2156. OverloadDecl->isCPUSpecificMultiVersion()))) {
  2157. ZeroArgCallReturnTy = QualType();
  2158. Ambiguous = true;
  2159. } else {
  2160. ZeroArgCallReturnTy = OverloadDecl->getReturnType();
  2161. IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
  2162. OverloadDecl->isCPUSpecificMultiVersion();
  2163. }
  2164. }
  2165. }
  2166. }
  2167. // If it's not a member, use better machinery to try to resolve the call
  2168. if (!IsMemExpr)
  2169. return !ZeroArgCallReturnTy.isNull();
  2170. }
  2171. // Attempt to call the member with no arguments - this will correctly handle
  2172. // member templates with defaults/deduction of template arguments, overloads
  2173. // with default arguments, etc.
  2174. if (IsMemExpr && !E.isTypeDependent()) {
  2175. Sema::TentativeAnalysisScope Trap(*this);
  2176. ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
  2177. std::nullopt, SourceLocation());
  2178. if (R.isUsable()) {
  2179. ZeroArgCallReturnTy = R.get()->getType();
  2180. return true;
  2181. }
  2182. return false;
  2183. }
  2184. if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
  2185. if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
  2186. if (Fun->getMinRequiredArguments() == 0)
  2187. ZeroArgCallReturnTy = Fun->getReturnType();
  2188. return true;
  2189. }
  2190. }
  2191. // We don't have an expression that's convenient to get a FunctionDecl from,
  2192. // but we can at least check if the type is "function of 0 arguments".
  2193. QualType ExprTy = E.getType();
  2194. const FunctionType *FunTy = nullptr;
  2195. QualType PointeeTy = ExprTy->getPointeeType();
  2196. if (!PointeeTy.isNull())
  2197. FunTy = PointeeTy->getAs<FunctionType>();
  2198. if (!FunTy)
  2199. FunTy = ExprTy->getAs<FunctionType>();
  2200. if (const FunctionProtoType *FPT =
  2201. dyn_cast_or_null<FunctionProtoType>(FunTy)) {
  2202. if (FPT->getNumParams() == 0)
  2203. ZeroArgCallReturnTy = FunTy->getReturnType();
  2204. return true;
  2205. }
  2206. return false;
  2207. }
  2208. /// Give notes for a set of overloads.
  2209. ///
  2210. /// A companion to tryExprAsCall. In cases when the name that the programmer
  2211. /// wrote was an overloaded function, we may be able to make some guesses about
  2212. /// plausible overloads based on their return types; such guesses can be handed
  2213. /// off to this method to be emitted as notes.
  2214. ///
  2215. /// \param Overloads - The overloads to note.
  2216. /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
  2217. /// -fshow-overloads=best, this is the location to attach to the note about too
  2218. /// many candidates. Typically this will be the location of the original
  2219. /// ill-formed expression.
  2220. static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
  2221. const SourceLocation FinalNoteLoc) {
  2222. unsigned ShownOverloads = 0;
  2223. unsigned SuppressedOverloads = 0;
  2224. for (UnresolvedSetImpl::iterator It = Overloads.begin(),
  2225. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  2226. if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
  2227. ++SuppressedOverloads;
  2228. continue;
  2229. }
  2230. NamedDecl *Fn = (*It)->getUnderlyingDecl();
  2231. // Don't print overloads for non-default multiversioned functions.
  2232. if (const auto *FD = Fn->getAsFunction()) {
  2233. if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
  2234. !FD->getAttr<TargetAttr>()->isDefaultVersion())
  2235. continue;
  2236. if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&
  2237. !FD->getAttr<TargetVersionAttr>()->isDefaultVersion())
  2238. continue;
  2239. }
  2240. S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
  2241. ++ShownOverloads;
  2242. }
  2243. S.Diags.overloadCandidatesShown(ShownOverloads);
  2244. if (SuppressedOverloads)
  2245. S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
  2246. << SuppressedOverloads;
  2247. }
  2248. static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
  2249. const UnresolvedSetImpl &Overloads,
  2250. bool (*IsPlausibleResult)(QualType)) {
  2251. if (!IsPlausibleResult)
  2252. return noteOverloads(S, Overloads, Loc);
  2253. UnresolvedSet<2> PlausibleOverloads;
  2254. for (OverloadExpr::decls_iterator It = Overloads.begin(),
  2255. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  2256. const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
  2257. QualType OverloadResultTy = OverloadDecl->getReturnType();
  2258. if (IsPlausibleResult(OverloadResultTy))
  2259. PlausibleOverloads.addDecl(It.getDecl());
  2260. }
  2261. noteOverloads(S, PlausibleOverloads, Loc);
  2262. }
  2263. /// Determine whether the given expression can be called by just
  2264. /// putting parentheses after it. Notably, expressions with unary
  2265. /// operators can't be because the unary operator will start parsing
  2266. /// outside the call.
  2267. static bool IsCallableWithAppend(Expr *E) {
  2268. E = E->IgnoreImplicit();
  2269. return (!isa<CStyleCastExpr>(E) &&
  2270. !isa<UnaryOperator>(E) &&
  2271. !isa<BinaryOperator>(E) &&
  2272. !isa<CXXOperatorCallExpr>(E));
  2273. }
  2274. static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
  2275. if (const auto *UO = dyn_cast<UnaryOperator>(E))
  2276. E = UO->getSubExpr();
  2277. if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  2278. if (ULE->getNumDecls() == 0)
  2279. return false;
  2280. const NamedDecl *ND = *ULE->decls_begin();
  2281. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  2282. return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
  2283. }
  2284. return false;
  2285. }
  2286. bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
  2287. bool ForceComplain,
  2288. bool (*IsPlausibleResult)(QualType)) {
  2289. SourceLocation Loc = E.get()->getExprLoc();
  2290. SourceRange Range = E.get()->getSourceRange();
  2291. UnresolvedSet<4> Overloads;
  2292. // If this is a SFINAE context, don't try anything that might trigger ADL
  2293. // prematurely.
  2294. if (!isSFINAEContext()) {
  2295. QualType ZeroArgCallTy;
  2296. if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
  2297. !ZeroArgCallTy.isNull() &&
  2298. (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
  2299. // At this point, we know E is potentially callable with 0
  2300. // arguments and that it returns something of a reasonable type,
  2301. // so we can emit a fixit and carry on pretending that E was
  2302. // actually a CallExpr.
  2303. SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
  2304. bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
  2305. Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
  2306. << (IsCallableWithAppend(E.get())
  2307. ? FixItHint::CreateInsertion(ParenInsertionLoc,
  2308. "()")
  2309. : FixItHint());
  2310. if (!IsMV)
  2311. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  2312. // FIXME: Try this before emitting the fixit, and suppress diagnostics
  2313. // while doing so.
  2314. E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), std::nullopt,
  2315. Range.getEnd().getLocWithOffset(1));
  2316. return true;
  2317. }
  2318. }
  2319. if (!ForceComplain) return false;
  2320. bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
  2321. Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
  2322. if (!IsMV)
  2323. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  2324. E = ExprError();
  2325. return true;
  2326. }
  2327. IdentifierInfo *Sema::getSuperIdentifier() const {
  2328. if (!Ident_super)
  2329. Ident_super = &Context.Idents.get("super");
  2330. return Ident_super;
  2331. }
  2332. IdentifierInfo *Sema::getFloat128Identifier() const {
  2333. if (!Ident___float128)
  2334. Ident___float128 = &Context.Idents.get("__float128");
  2335. return Ident___float128;
  2336. }
  2337. void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
  2338. CapturedRegionKind K,
  2339. unsigned OpenMPCaptureLevel) {
  2340. auto *CSI = new CapturedRegionScopeInfo(
  2341. getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
  2342. (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
  2343. OpenMPCaptureLevel);
  2344. CSI->ReturnType = Context.VoidTy;
  2345. FunctionScopes.push_back(CSI);
  2346. }
  2347. CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
  2348. if (FunctionScopes.empty())
  2349. return nullptr;
  2350. return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
  2351. }
  2352. const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
  2353. Sema::getMismatchingDeleteExpressions() const {
  2354. return DeleteExprs;
  2355. }
  2356. Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S)
  2357. : S(S), OldFPFeaturesState(S.CurFPFeatures),
  2358. OldOverrides(S.FpPragmaStack.CurrentValue),
  2359. OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
  2360. OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
  2361. Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {
  2362. S.CurFPFeatures = OldFPFeaturesState;
  2363. S.FpPragmaStack.CurrentValue = OldOverrides;
  2364. S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
  2365. }
  2366. bool Sema::isDeclaratorFunctionLike(Declarator &D) {
  2367. assert(D.getCXXScopeSpec().isSet() &&
  2368. "can only be called for qualified names");
  2369. auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
  2370. LookupOrdinaryName, forRedeclarationInCurContext());
  2371. DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(),
  2372. !D.getDeclSpec().isFriendSpecified());
  2373. if (!DC)
  2374. return false;
  2375. LookupQualifiedName(LR, DC);
  2376. bool Result = std::all_of(LR.begin(), LR.end(), [](Decl *Dcl) {
  2377. if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
  2378. ND = ND->getUnderlyingDecl();
  2379. return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
  2380. isa<UsingDecl>(ND);
  2381. }
  2382. return false;
  2383. });
  2384. return Result;
  2385. }