Sema.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  1. //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the actions class which performs semantic analysis and
  11. // builds an AST out of a parse stream.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTDiagnostic.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclFriend.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/Basic/DiagnosticOptions.h"
  23. #include "clang/Basic/PartialDiagnostic.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/Lex/HeaderSearch.h"
  26. #include "clang/Lex/Preprocessor.h"
  27. #include "clang/Sema/CXXFieldCollector.h"
  28. #include "clang/Sema/DelayedDiagnostic.h"
  29. #include "clang/Sema/ExternalSemaSource.h"
  30. #include "clang/Sema/Initialization.h"
  31. #include "clang/Sema/MultiplexExternalSemaSource.h"
  32. #include "clang/Sema/ObjCMethodList.h"
  33. #include "clang/Sema/PrettyDeclStackTrace.h"
  34. #include "clang/Sema/Scope.h"
  35. #include "clang/Sema/ScopeInfo.h"
  36. #include "clang/Sema/SemaConsumer.h"
  37. #include "clang/Sema/SemaInternal.h"
  38. #include "clang/Sema/TemplateDeduction.h"
  39. #include "llvm/ADT/DenseMap.h"
  40. #include "llvm/ADT/SmallSet.h"
  41. using namespace clang;
  42. using namespace sema;
  43. SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
  44. return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
  45. }
  46. ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
  47. PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
  48. const Preprocessor &PP) {
  49. PrintingPolicy Policy = Context.getPrintingPolicy();
  50. // Our printing policy is copied over the ASTContext printing policy whenever
  51. // a diagnostic is emitted, so recompute it.
  52. Policy.Bool = Context.getLangOpts().Bool;
  53. if (!Policy.Bool) {
  54. if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
  55. Policy.Bool = BoolMacro->isObjectLike() &&
  56. BoolMacro->getNumTokens() == 1 &&
  57. BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
  58. }
  59. }
  60. return Policy;
  61. }
  62. void Sema::ActOnTranslationUnitScope(Scope *S) {
  63. TUScope = S;
  64. PushDeclContext(S, Context.getTranslationUnitDecl());
  65. }
  66. namespace clang {
  67. namespace sema {
  68. class SemaPPCallbacks : public PPCallbacks {
  69. Sema *S = nullptr;
  70. llvm::SmallVector<SourceLocation, 8> IncludeStack;
  71. public:
  72. void set(Sema &S) { this->S = &S; }
  73. void reset() { S = nullptr; }
  74. virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  75. SrcMgr::CharacteristicKind FileType,
  76. FileID PrevFID) override {
  77. if (!S)
  78. return;
  79. switch (Reason) {
  80. case EnterFile: {
  81. SourceManager &SM = S->getSourceManager();
  82. SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
  83. if (IncludeLoc.isValid()) {
  84. IncludeStack.push_back(IncludeLoc);
  85. S->DiagnoseNonDefaultPragmaPack(
  86. Sema::PragmaPackDiagnoseKind::NonDefaultStateAtInclude, IncludeLoc);
  87. }
  88. break;
  89. }
  90. case ExitFile:
  91. if (!IncludeStack.empty())
  92. S->DiagnoseNonDefaultPragmaPack(
  93. Sema::PragmaPackDiagnoseKind::ChangedStateAtExit,
  94. IncludeStack.pop_back_val());
  95. break;
  96. default:
  97. break;
  98. }
  99. }
  100. };
  101. } // end namespace sema
  102. } // end namespace clang
  103. Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
  104. TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
  105. : ExternalSource(nullptr), isMultiplexExternalSource(false),
  106. FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
  107. Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
  108. SourceMgr(PP.getSourceManager()), CollectStats(false),
  109. CodeCompleter(CodeCompleter), CurContext(nullptr),
  110. OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
  111. MSPointerToMemberRepresentationMethod(
  112. LangOpts.getMSPointerToMemberRepresentationMethod()),
  113. VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), PackStack(0),
  114. DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
  115. CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
  116. PragmaAttributeCurrentTargetDecl(nullptr),
  117. IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
  118. LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
  119. StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
  120. CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr), NSNumberDecl(nullptr),
  121. NSValueDecl(nullptr), NSStringDecl(nullptr),
  122. StringWithUTF8StringMethod(nullptr),
  123. ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
  124. ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
  125. DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
  126. TUKind(TUKind), NumSFINAEErrors(0), AccessCheckingSFINAE(false),
  127. InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
  128. ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
  129. DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
  130. ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
  131. CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
  132. TUScope = nullptr;
  133. LoadedExternalKnownNamespaces = false;
  134. for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
  135. NSNumberLiteralMethods[I] = nullptr;
  136. if (getLangOpts().ObjC1)
  137. NSAPIObj.reset(new NSAPI(Context));
  138. if (getLangOpts().CPlusPlus)
  139. FieldCollector.reset(new CXXFieldCollector());
  140. // Tell diagnostics how to render things from the AST library.
  141. Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
  142. ExprEvalContexts.emplace_back(
  143. ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
  144. nullptr, false);
  145. FunctionScopes.push_back(new FunctionScopeInfo(Diags));
  146. // Initilization of data sharing attributes stack for OpenMP
  147. InitDataSharingAttributesStack();
  148. std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
  149. llvm::make_unique<sema::SemaPPCallbacks>();
  150. SemaPPCallbackHandler = Callbacks.get();
  151. PP.addPPCallbacks(std::move(Callbacks));
  152. SemaPPCallbackHandler->set(*this);
  153. }
  154. void Sema::addImplicitTypedef(StringRef Name, QualType T) {
  155. DeclarationName DN = &Context.Idents.get(Name);
  156. if (IdResolver.begin(DN) == IdResolver.end())
  157. PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
  158. }
  159. void Sema::Initialize() {
  160. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  161. SC->InitializeSema(*this);
  162. // Tell the external Sema source about this Sema object.
  163. if (ExternalSemaSource *ExternalSema
  164. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  165. ExternalSema->InitializeSema(*this);
  166. // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
  167. // will not be able to merge any duplicate __va_list_tag decls correctly.
  168. VAListTagName = PP.getIdentifierInfo("__va_list_tag");
  169. if (!TUScope)
  170. return;
  171. // Initialize predefined 128-bit integer types, if needed.
  172. if (Context.getTargetInfo().hasInt128Type()) {
  173. // If either of the 128-bit integer types are unavailable to name lookup,
  174. // define them now.
  175. DeclarationName Int128 = &Context.Idents.get("__int128_t");
  176. if (IdResolver.begin(Int128) == IdResolver.end())
  177. PushOnScopeChains(Context.getInt128Decl(), TUScope);
  178. DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
  179. if (IdResolver.begin(UInt128) == IdResolver.end())
  180. PushOnScopeChains(Context.getUInt128Decl(), TUScope);
  181. }
  182. // Initialize predefined Objective-C types:
  183. if (getLangOpts().ObjC1) {
  184. // If 'SEL' does not yet refer to any declarations, make it refer to the
  185. // predefined 'SEL'.
  186. DeclarationName SEL = &Context.Idents.get("SEL");
  187. if (IdResolver.begin(SEL) == IdResolver.end())
  188. PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
  189. // If 'id' does not yet refer to any declarations, make it refer to the
  190. // predefined 'id'.
  191. DeclarationName Id = &Context.Idents.get("id");
  192. if (IdResolver.begin(Id) == IdResolver.end())
  193. PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
  194. // Create the built-in typedef for 'Class'.
  195. DeclarationName Class = &Context.Idents.get("Class");
  196. if (IdResolver.begin(Class) == IdResolver.end())
  197. PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
  198. // Create the built-in forward declaratino for 'Protocol'.
  199. DeclarationName Protocol = &Context.Idents.get("Protocol");
  200. if (IdResolver.begin(Protocol) == IdResolver.end())
  201. PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
  202. }
  203. // Create the internal type for the *StringMakeConstantString builtins.
  204. DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
  205. if (IdResolver.begin(ConstantString) == IdResolver.end())
  206. PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
  207. // Initialize Microsoft "predefined C++ types".
  208. if (getLangOpts().MSVCCompat) {
  209. if (getLangOpts().CPlusPlus &&
  210. IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
  211. PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
  212. TUScope);
  213. addImplicitTypedef("size_t", Context.getSizeType());
  214. }
  215. // Initialize predefined OpenCL types and supported extensions and (optional)
  216. // core features.
  217. if (getLangOpts().OpenCL) {
  218. getOpenCLOptions().addSupport(Context.getTargetInfo().getSupportedOpenCLOpts());
  219. getOpenCLOptions().enableSupportedCore(getLangOpts().OpenCLVersion);
  220. addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
  221. addImplicitTypedef("event_t", Context.OCLEventTy);
  222. if (getLangOpts().OpenCLVersion >= 200) {
  223. addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
  224. addImplicitTypedef("queue_t", Context.OCLQueueTy);
  225. addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
  226. addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
  227. addImplicitTypedef("atomic_uint",
  228. Context.getAtomicType(Context.UnsignedIntTy));
  229. auto AtomicLongT = Context.getAtomicType(Context.LongTy);
  230. addImplicitTypedef("atomic_long", AtomicLongT);
  231. auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
  232. addImplicitTypedef("atomic_ulong", AtomicULongT);
  233. addImplicitTypedef("atomic_float",
  234. Context.getAtomicType(Context.FloatTy));
  235. auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
  236. addImplicitTypedef("atomic_double", AtomicDoubleT);
  237. // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
  238. // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
  239. addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
  240. auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
  241. addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
  242. auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
  243. addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
  244. auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
  245. addImplicitTypedef("atomic_size_t", AtomicSizeT);
  246. auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
  247. addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
  248. // OpenCL v2.0 s6.13.11.6:
  249. // - The atomic_long and atomic_ulong types are supported if the
  250. // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
  251. // extensions are supported.
  252. // - The atomic_double type is only supported if double precision
  253. // is supported and the cl_khr_int64_base_atomics and
  254. // cl_khr_int64_extended_atomics extensions are supported.
  255. // - If the device address space is 64-bits, the data types
  256. // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
  257. // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
  258. // cl_khr_int64_extended_atomics extensions are supported.
  259. std::vector<QualType> Atomic64BitTypes;
  260. Atomic64BitTypes.push_back(AtomicLongT);
  261. Atomic64BitTypes.push_back(AtomicULongT);
  262. Atomic64BitTypes.push_back(AtomicDoubleT);
  263. if (Context.getTypeSize(AtomicSizeT) == 64) {
  264. Atomic64BitTypes.push_back(AtomicSizeT);
  265. Atomic64BitTypes.push_back(AtomicIntPtrT);
  266. Atomic64BitTypes.push_back(AtomicUIntPtrT);
  267. Atomic64BitTypes.push_back(AtomicPtrDiffT);
  268. }
  269. for (auto &I : Atomic64BitTypes)
  270. setOpenCLExtensionForType(I,
  271. "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
  272. setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
  273. }
  274. setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
  275. #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
  276. setOpenCLExtensionForType(Context.Id, Ext);
  277. #include "clang/Basic/OpenCLImageTypes.def"
  278. };
  279. if (Context.getTargetInfo().hasBuiltinMSVaList()) {
  280. DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
  281. if (IdResolver.begin(MSVaList) == IdResolver.end())
  282. PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
  283. }
  284. DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
  285. if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
  286. PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
  287. }
  288. Sema::~Sema() {
  289. if (VisContext) FreeVisContext();
  290. // Kill all the active scopes.
  291. for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
  292. delete FunctionScopes[I];
  293. if (FunctionScopes.size() == 1)
  294. delete FunctionScopes[0];
  295. // Tell the SemaConsumer to forget about us; we're going out of scope.
  296. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  297. SC->ForgetSema();
  298. // Detach from the external Sema source.
  299. if (ExternalSemaSource *ExternalSema
  300. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  301. ExternalSema->ForgetSema();
  302. // If Sema's ExternalSource is the multiplexer - we own it.
  303. if (isMultiplexExternalSource)
  304. delete ExternalSource;
  305. threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
  306. // Destroys data sharing attributes stack for OpenMP
  307. DestroyDataSharingAttributesStack();
  308. // Detach from the PP callback handler which outlives Sema since it's owned
  309. // by the preprocessor.
  310. SemaPPCallbackHandler->reset();
  311. assert(DelayedTypos.empty() && "Uncorrected typos!");
  312. }
  313. /// makeUnavailableInSystemHeader - There is an error in the current
  314. /// context. If we're still in a system header, and we can plausibly
  315. /// make the relevant declaration unavailable instead of erroring, do
  316. /// so and return true.
  317. bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
  318. UnavailableAttr::ImplicitReason reason) {
  319. // If we're not in a function, it's an error.
  320. FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
  321. if (!fn) return false;
  322. // If we're in template instantiation, it's an error.
  323. if (inTemplateInstantiation())
  324. return false;
  325. // If that function's not in a system header, it's an error.
  326. if (!Context.getSourceManager().isInSystemHeader(loc))
  327. return false;
  328. // If the function is already unavailable, it's not an error.
  329. if (fn->hasAttr<UnavailableAttr>()) return true;
  330. fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
  331. return true;
  332. }
  333. ASTMutationListener *Sema::getASTMutationListener() const {
  334. return getASTConsumer().GetASTMutationListener();
  335. }
  336. ///\brief Registers an external source. If an external source already exists,
  337. /// creates a multiplex external source and appends to it.
  338. ///
  339. ///\param[in] E - A non-null external sema source.
  340. ///
  341. void Sema::addExternalSource(ExternalSemaSource *E) {
  342. assert(E && "Cannot use with NULL ptr");
  343. if (!ExternalSource) {
  344. ExternalSource = E;
  345. return;
  346. }
  347. if (isMultiplexExternalSource)
  348. static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
  349. else {
  350. ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
  351. isMultiplexExternalSource = true;
  352. }
  353. }
  354. /// \brief Print out statistics about the semantic analysis.
  355. void Sema::PrintStats() const {
  356. llvm::errs() << "\n*** Semantic Analysis Stats:\n";
  357. llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
  358. BumpAlloc.PrintStats();
  359. AnalysisWarnings.PrintStats();
  360. }
  361. void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
  362. QualType SrcType,
  363. SourceLocation Loc) {
  364. Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
  365. if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
  366. return;
  367. Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
  368. if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
  369. return;
  370. Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
  371. }
  372. void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
  373. if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
  374. E->getLocStart()))
  375. return;
  376. // nullptr only exists from C++11 on, so don't warn on its absence earlier.
  377. if (!getLangOpts().CPlusPlus11)
  378. return;
  379. if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
  380. return;
  381. if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
  382. return;
  383. // If it is a macro from system header, and if the macro name is not "NULL",
  384. // do not warn.
  385. SourceLocation MaybeMacroLoc = E->getLocStart();
  386. if (Diags.getSuppressSystemWarnings() &&
  387. SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
  388. !findMacroSpelling(MaybeMacroLoc, "NULL"))
  389. return;
  390. Diag(E->getLocStart(), diag::warn_zero_as_null_pointer_constant)
  391. << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
  392. }
  393. /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
  394. /// If there is already an implicit cast, merge into the existing one.
  395. /// The result is of the given category.
  396. ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
  397. CastKind Kind, ExprValueKind VK,
  398. const CXXCastPath *BasePath,
  399. CheckedConversionKind CCK) {
  400. #ifndef NDEBUG
  401. if (VK == VK_RValue && !E->isRValue()) {
  402. switch (Kind) {
  403. default:
  404. llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
  405. "kind");
  406. case CK_LValueToRValue:
  407. case CK_ArrayToPointerDecay:
  408. case CK_FunctionToPointerDecay:
  409. case CK_ToVoid:
  410. break;
  411. }
  412. }
  413. assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
  414. #endif
  415. diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getLocStart());
  416. diagnoseZeroToNullptrConversion(Kind, E);
  417. QualType ExprTy = Context.getCanonicalType(E->getType());
  418. QualType TypeTy = Context.getCanonicalType(Ty);
  419. if (ExprTy == TypeTy)
  420. return E;
  421. // C++1z [conv.array]: The temporary materialization conversion is applied.
  422. // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
  423. if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
  424. E->getValueKind() == VK_RValue) {
  425. // The temporary is an lvalue in C++98 and an xvalue otherwise.
  426. ExprResult Materialized = CreateMaterializeTemporaryExpr(
  427. E->getType(), E, !getLangOpts().CPlusPlus11);
  428. if (Materialized.isInvalid())
  429. return ExprError();
  430. E = Materialized.get();
  431. }
  432. if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
  433. if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
  434. ImpCast->setType(Ty);
  435. ImpCast->setValueKind(VK);
  436. return E;
  437. }
  438. }
  439. return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
  440. }
  441. /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
  442. /// to the conversion from scalar type ScalarTy to the Boolean type.
  443. CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
  444. switch (ScalarTy->getScalarTypeKind()) {
  445. case Type::STK_Bool: return CK_NoOp;
  446. case Type::STK_CPointer: return CK_PointerToBoolean;
  447. case Type::STK_BlockPointer: return CK_PointerToBoolean;
  448. case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
  449. case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
  450. case Type::STK_Integral: return CK_IntegralToBoolean;
  451. case Type::STK_Floating: return CK_FloatingToBoolean;
  452. case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
  453. case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
  454. }
  455. llvm_unreachable("unknown scalar type kind");
  456. }
  457. /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
  458. static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
  459. if (D->getMostRecentDecl()->isUsed())
  460. return true;
  461. if (D->isExternallyVisible())
  462. return true;
  463. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  464. // If this is a function template and none of its specializations is used,
  465. // we should warn.
  466. if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
  467. for (const auto *Spec : Template->specializations())
  468. if (ShouldRemoveFromUnused(SemaRef, Spec))
  469. return true;
  470. // UnusedFileScopedDecls stores the first declaration.
  471. // The declaration may have become definition so check again.
  472. const FunctionDecl *DeclToCheck;
  473. if (FD->hasBody(DeclToCheck))
  474. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  475. // Later redecls may add new information resulting in not having to warn,
  476. // so check again.
  477. DeclToCheck = FD->getMostRecentDecl();
  478. if (DeclToCheck != FD)
  479. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  480. }
  481. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  482. // If a variable usable in constant expressions is referenced,
  483. // don't warn if it isn't used: if the value of a variable is required
  484. // for the computation of a constant expression, it doesn't make sense to
  485. // warn even if the variable isn't odr-used. (isReferenced doesn't
  486. // precisely reflect that, but it's a decent approximation.)
  487. if (VD->isReferenced() &&
  488. VD->isUsableInConstantExpressions(SemaRef->Context))
  489. return true;
  490. if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
  491. // If this is a variable template and none of its specializations is used,
  492. // we should warn.
  493. for (const auto *Spec : Template->specializations())
  494. if (ShouldRemoveFromUnused(SemaRef, Spec))
  495. return true;
  496. // UnusedFileScopedDecls stores the first declaration.
  497. // The declaration may have become definition so check again.
  498. const VarDecl *DeclToCheck = VD->getDefinition();
  499. if (DeclToCheck)
  500. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  501. // Later redecls may add new information resulting in not having to warn,
  502. // so check again.
  503. DeclToCheck = VD->getMostRecentDecl();
  504. if (DeclToCheck != VD)
  505. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  506. }
  507. return false;
  508. }
  509. static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
  510. if (auto *FD = dyn_cast<FunctionDecl>(ND))
  511. return FD->isExternC();
  512. return cast<VarDecl>(ND)->isExternC();
  513. }
  514. /// Determine whether ND is an external-linkage function or variable whose
  515. /// type has no linkage.
  516. bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
  517. // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
  518. // because we also want to catch the case where its type has VisibleNoLinkage,
  519. // which does not affect the linkage of VD.
  520. return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
  521. !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
  522. !isFunctionOrVarDeclExternC(VD);
  523. }
  524. /// Obtains a sorted list of functions and variables that are undefined but
  525. /// ODR-used.
  526. void Sema::getUndefinedButUsed(
  527. SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
  528. for (const auto &UndefinedUse : UndefinedButUsed) {
  529. NamedDecl *ND = UndefinedUse.first;
  530. // Ignore attributes that have become invalid.
  531. if (ND->isInvalidDecl()) continue;
  532. // __attribute__((weakref)) is basically a definition.
  533. if (ND->hasAttr<WeakRefAttr>()) continue;
  534. if (isa<CXXDeductionGuideDecl>(ND))
  535. continue;
  536. if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
  537. // An exported function will always be emitted when defined, so even if
  538. // the function is inline, it doesn't have to be emitted in this TU. An
  539. // imported function implies that it has been exported somewhere else.
  540. continue;
  541. }
  542. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  543. if (FD->isDefined())
  544. continue;
  545. if (FD->isExternallyVisible() &&
  546. !isExternalWithNoLinkageType(FD) &&
  547. !FD->getMostRecentDecl()->isInlined())
  548. continue;
  549. } else {
  550. auto *VD = cast<VarDecl>(ND);
  551. if (VD->hasDefinition() != VarDecl::DeclarationOnly)
  552. continue;
  553. if (VD->isExternallyVisible() &&
  554. !isExternalWithNoLinkageType(VD) &&
  555. !VD->getMostRecentDecl()->isInline())
  556. continue;
  557. }
  558. Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
  559. }
  560. }
  561. /// checkUndefinedButUsed - Check for undefined objects with internal linkage
  562. /// or that are inline.
  563. static void checkUndefinedButUsed(Sema &S) {
  564. if (S.UndefinedButUsed.empty()) return;
  565. // Collect all the still-undefined entities with internal linkage.
  566. SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
  567. S.getUndefinedButUsed(Undefined);
  568. if (Undefined.empty()) return;
  569. for (auto Undef : Undefined) {
  570. ValueDecl *VD = cast<ValueDecl>(Undef.first);
  571. SourceLocation UseLoc = Undef.second;
  572. if (S.isExternalWithNoLinkageType(VD)) {
  573. // C++ [basic.link]p8:
  574. // A type without linkage shall not be used as the type of a variable
  575. // or function with external linkage unless
  576. // -- the entity has C language linkage
  577. // -- the entity is not odr-used or is defined in the same TU
  578. //
  579. // As an extension, accept this in cases where the type is externally
  580. // visible, since the function or variable actually can be defined in
  581. // another translation unit in that case.
  582. S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
  583. ? diag::ext_undefined_internal_type
  584. : diag::err_undefined_internal_type)
  585. << isa<VarDecl>(VD) << VD;
  586. } else if (!VD->isExternallyVisible()) {
  587. // FIXME: We can promote this to an error. The function or variable can't
  588. // be defined anywhere else, so the program must necessarily violate the
  589. // one definition rule.
  590. S.Diag(VD->getLocation(), diag::warn_undefined_internal)
  591. << isa<VarDecl>(VD) << VD;
  592. } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
  593. (void)FD;
  594. assert(FD->getMostRecentDecl()->isInlined() &&
  595. "used object requires definition but isn't inline or internal?");
  596. // FIXME: This is ill-formed; we should reject.
  597. S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
  598. } else {
  599. assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
  600. "used var requires definition but isn't inline or internal?");
  601. S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
  602. }
  603. if (UseLoc.isValid())
  604. S.Diag(UseLoc, diag::note_used_here);
  605. }
  606. S.UndefinedButUsed.clear();
  607. }
  608. void Sema::LoadExternalWeakUndeclaredIdentifiers() {
  609. if (!ExternalSource)
  610. return;
  611. SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
  612. ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
  613. for (auto &WeakID : WeakIDs)
  614. WeakUndeclaredIdentifiers.insert(WeakID);
  615. }
  616. typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
  617. /// \brief Returns true, if all methods and nested classes of the given
  618. /// CXXRecordDecl are defined in this translation unit.
  619. ///
  620. /// Should only be called from ActOnEndOfTranslationUnit so that all
  621. /// definitions are actually read.
  622. static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
  623. RecordCompleteMap &MNCComplete) {
  624. RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
  625. if (Cache != MNCComplete.end())
  626. return Cache->second;
  627. if (!RD->isCompleteDefinition())
  628. return false;
  629. bool Complete = true;
  630. for (DeclContext::decl_iterator I = RD->decls_begin(),
  631. E = RD->decls_end();
  632. I != E && Complete; ++I) {
  633. if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
  634. Complete = M->isDefined() || M->isDefaulted() ||
  635. (M->isPure() && !isa<CXXDestructorDecl>(M));
  636. else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
  637. // If the template function is marked as late template parsed at this
  638. // point, it has not been instantiated and therefore we have not
  639. // performed semantic analysis on it yet, so we cannot know if the type
  640. // can be considered complete.
  641. Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
  642. F->getTemplatedDecl()->isDefined();
  643. else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
  644. if (R->isInjectedClassName())
  645. continue;
  646. if (R->hasDefinition())
  647. Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
  648. MNCComplete);
  649. else
  650. Complete = false;
  651. }
  652. }
  653. MNCComplete[RD] = Complete;
  654. return Complete;
  655. }
  656. /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
  657. /// translation unit, i.e. all methods are defined or pure virtual and all
  658. /// friends, friend functions and nested classes are fully defined in this
  659. /// translation unit.
  660. ///
  661. /// Should only be called from ActOnEndOfTranslationUnit so that all
  662. /// definitions are actually read.
  663. static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
  664. RecordCompleteMap &RecordsComplete,
  665. RecordCompleteMap &MNCComplete) {
  666. RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
  667. if (Cache != RecordsComplete.end())
  668. return Cache->second;
  669. bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
  670. for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
  671. E = RD->friend_end();
  672. I != E && Complete; ++I) {
  673. // Check if friend classes and methods are complete.
  674. if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
  675. // Friend classes are available as the TypeSourceInfo of the FriendDecl.
  676. if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
  677. Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
  678. else
  679. Complete = false;
  680. } else {
  681. // Friend functions are available through the NamedDecl of FriendDecl.
  682. if (const FunctionDecl *FD =
  683. dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
  684. Complete = FD->isDefined();
  685. else
  686. // This is a template friend, give up.
  687. Complete = false;
  688. }
  689. }
  690. RecordsComplete[RD] = Complete;
  691. return Complete;
  692. }
  693. void Sema::emitAndClearUnusedLocalTypedefWarnings() {
  694. if (ExternalSource)
  695. ExternalSource->ReadUnusedLocalTypedefNameCandidates(
  696. UnusedLocalTypedefNameCandidates);
  697. for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
  698. if (TD->isReferenced())
  699. continue;
  700. Diag(TD->getLocation(), diag::warn_unused_local_typedef)
  701. << isa<TypeAliasDecl>(TD) << TD->getDeclName();
  702. }
  703. UnusedLocalTypedefNameCandidates.clear();
  704. }
  705. /// This is called before the very first declaration in the translation unit
  706. /// is parsed. Note that the ASTContext may have already injected some
  707. /// declarations.
  708. void Sema::ActOnStartOfTranslationUnit() {
  709. if (getLangOpts().ModulesTS) {
  710. SourceLocation StartOfTU =
  711. SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
  712. // We start in the global module; all those declarations are implicitly
  713. // module-private (though they do not have module linkage).
  714. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  715. auto *GlobalModule = Map.createGlobalModuleForInterfaceUnit(StartOfTU);
  716. assert(GlobalModule && "module creation should not fail");
  717. // Enter the scope of the global module.
  718. ModuleScopes.push_back({});
  719. ModuleScopes.back().Module = GlobalModule;
  720. VisibleModules.setVisible(GlobalModule, StartOfTU);
  721. // All declarations created from now on are owned by the global module.
  722. auto *TU = Context.getTranslationUnitDecl();
  723. TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
  724. TU->setLocalOwningModule(GlobalModule);
  725. }
  726. }
  727. /// ActOnEndOfTranslationUnit - This is called at the very end of the
  728. /// translation unit when EOF is reached and all but the top-level scope is
  729. /// popped.
  730. void Sema::ActOnEndOfTranslationUnit() {
  731. assert(DelayedDiagnostics.getCurrentPool() == nullptr
  732. && "reached end of translation unit with a pool attached?");
  733. // If code completion is enabled, don't perform any end-of-translation-unit
  734. // work.
  735. if (PP.isCodeCompletionEnabled())
  736. return;
  737. // Complete translation units and modules define vtables and perform implicit
  738. // instantiations. PCH files do not.
  739. if (TUKind != TU_Prefix) {
  740. DiagnoseUseOfUnimplementedSelectors();
  741. // If DefinedUsedVTables ends up marking any virtual member functions it
  742. // might lead to more pending template instantiations, which we then need
  743. // to instantiate.
  744. DefineUsedVTables();
  745. // C++: Perform implicit template instantiations.
  746. //
  747. // FIXME: When we perform these implicit instantiations, we do not
  748. // carefully keep track of the point of instantiation (C++ [temp.point]).
  749. // This means that name lookup that occurs within the template
  750. // instantiation will always happen at the end of the translation unit,
  751. // so it will find some names that are not required to be found. This is
  752. // valid, but we could do better by diagnosing if an instantiation uses a
  753. // name that was not visible at its first point of instantiation.
  754. if (ExternalSource) {
  755. // Load pending instantiations from the external source.
  756. SmallVector<PendingImplicitInstantiation, 4> Pending;
  757. ExternalSource->ReadPendingInstantiations(Pending);
  758. for (auto PII : Pending)
  759. if (auto Func = dyn_cast<FunctionDecl>(PII.first))
  760. Func->setInstantiationIsPending(true);
  761. PendingInstantiations.insert(PendingInstantiations.begin(),
  762. Pending.begin(), Pending.end());
  763. }
  764. PerformPendingInstantiations();
  765. if (LateTemplateParserCleanup)
  766. LateTemplateParserCleanup(OpaqueParser);
  767. CheckDelayedMemberExceptionSpecs();
  768. }
  769. DiagnoseUnterminatedPragmaPack();
  770. DiagnoseUnterminatedPragmaAttribute();
  771. // All delayed member exception specs should be checked or we end up accepting
  772. // incompatible declarations.
  773. // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
  774. // write out the lists to the AST file (if any).
  775. assert(DelayedDefaultedMemberExceptionSpecs.empty());
  776. assert(DelayedExceptionSpecChecks.empty());
  777. // All dllexport classes should have been processed already.
  778. assert(DelayedDllExportClasses.empty());
  779. // Remove file scoped decls that turned out to be used.
  780. UnusedFileScopedDecls.erase(
  781. std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
  782. UnusedFileScopedDecls.end(),
  783. [this](const DeclaratorDecl *DD) {
  784. return ShouldRemoveFromUnused(this, DD);
  785. }),
  786. UnusedFileScopedDecls.end());
  787. if (TUKind == TU_Prefix) {
  788. // Translation unit prefixes don't need any of the checking below.
  789. if (!PP.isIncrementalProcessingEnabled())
  790. TUScope = nullptr;
  791. return;
  792. }
  793. // Check for #pragma weak identifiers that were never declared
  794. LoadExternalWeakUndeclaredIdentifiers();
  795. for (auto WeakID : WeakUndeclaredIdentifiers) {
  796. if (WeakID.second.getUsed())
  797. continue;
  798. Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
  799. LookupOrdinaryName);
  800. if (PrevDecl != nullptr &&
  801. !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
  802. Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
  803. << "'weak'" << ExpectedVariableOrFunction;
  804. else
  805. Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
  806. << WeakID.first;
  807. }
  808. if (LangOpts.CPlusPlus11 &&
  809. !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
  810. CheckDelegatingCtorCycles();
  811. if (!Diags.hasErrorOccurred()) {
  812. if (ExternalSource)
  813. ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
  814. checkUndefinedButUsed(*this);
  815. }
  816. if (TUKind == TU_Module) {
  817. // If we are building a module interface unit, we need to have seen the
  818. // module declaration by now.
  819. if (getLangOpts().getCompilingModule() ==
  820. LangOptions::CMK_ModuleInterface &&
  821. ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit) {
  822. // FIXME: Make a better guess as to where to put the module declaration.
  823. Diag(getSourceManager().getLocForStartOfFile(
  824. getSourceManager().getMainFileID()),
  825. diag::err_module_declaration_missing);
  826. }
  827. // If we are building a module, resolve all of the exported declarations
  828. // now.
  829. if (Module *CurrentModule = PP.getCurrentModule()) {
  830. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  831. SmallVector<Module *, 2> Stack;
  832. Stack.push_back(CurrentModule);
  833. while (!Stack.empty()) {
  834. Module *Mod = Stack.pop_back_val();
  835. // Resolve the exported declarations and conflicts.
  836. // FIXME: Actually complain, once we figure out how to teach the
  837. // diagnostic client to deal with complaints in the module map at this
  838. // point.
  839. ModMap.resolveExports(Mod, /*Complain=*/false);
  840. ModMap.resolveUses(Mod, /*Complain=*/false);
  841. ModMap.resolveConflicts(Mod, /*Complain=*/false);
  842. // Queue the submodules, so their exports will also be resolved.
  843. Stack.append(Mod->submodule_begin(), Mod->submodule_end());
  844. }
  845. }
  846. // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
  847. // modules when they are built, not every time they are used.
  848. emitAndClearUnusedLocalTypedefWarnings();
  849. // Modules don't need any of the checking below.
  850. if (!PP.isIncrementalProcessingEnabled())
  851. TUScope = nullptr;
  852. return;
  853. }
  854. // C99 6.9.2p2:
  855. // A declaration of an identifier for an object that has file
  856. // scope without an initializer, and without a storage-class
  857. // specifier or with the storage-class specifier static,
  858. // constitutes a tentative definition. If a translation unit
  859. // contains one or more tentative definitions for an identifier,
  860. // and the translation unit contains no external definition for
  861. // that identifier, then the behavior is exactly as if the
  862. // translation unit contains a file scope declaration of that
  863. // identifier, with the composite type as of the end of the
  864. // translation unit, with an initializer equal to 0.
  865. llvm::SmallSet<VarDecl *, 32> Seen;
  866. for (TentativeDefinitionsType::iterator
  867. T = TentativeDefinitions.begin(ExternalSource),
  868. TEnd = TentativeDefinitions.end();
  869. T != TEnd; ++T)
  870. {
  871. VarDecl *VD = (*T)->getActingDefinition();
  872. // If the tentative definition was completed, getActingDefinition() returns
  873. // null. If we've already seen this variable before, insert()'s second
  874. // return value is false.
  875. if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
  876. continue;
  877. if (const IncompleteArrayType *ArrayT
  878. = Context.getAsIncompleteArrayType(VD->getType())) {
  879. // Set the length of the array to 1 (C99 6.9.2p5).
  880. Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
  881. llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
  882. QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
  883. One, ArrayType::Normal, 0);
  884. VD->setType(T);
  885. } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
  886. diag::err_tentative_def_incomplete_type))
  887. VD->setInvalidDecl();
  888. // No initialization is performed for a tentative definition.
  889. CheckCompleteVariableDeclaration(VD);
  890. // Notify the consumer that we've completed a tentative definition.
  891. if (!VD->isInvalidDecl())
  892. Consumer.CompleteTentativeDefinition(VD);
  893. }
  894. // If there were errors, disable 'unused' warnings since they will mostly be
  895. // noise.
  896. if (!Diags.hasErrorOccurred()) {
  897. // Output warning for unused file scoped decls.
  898. for (UnusedFileScopedDeclsType::iterator
  899. I = UnusedFileScopedDecls.begin(ExternalSource),
  900. E = UnusedFileScopedDecls.end(); I != E; ++I) {
  901. if (ShouldRemoveFromUnused(this, *I))
  902. continue;
  903. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  904. const FunctionDecl *DiagD;
  905. if (!FD->hasBody(DiagD))
  906. DiagD = FD;
  907. if (DiagD->isDeleted())
  908. continue; // Deleted functions are supposed to be unused.
  909. if (DiagD->isReferenced()) {
  910. if (isa<CXXMethodDecl>(DiagD))
  911. Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
  912. << DiagD->getDeclName();
  913. else {
  914. if (FD->getStorageClass() == SC_Static &&
  915. !FD->isInlineSpecified() &&
  916. !SourceMgr.isInMainFile(
  917. SourceMgr.getExpansionLoc(FD->getLocation())))
  918. Diag(DiagD->getLocation(),
  919. diag::warn_unneeded_static_internal_decl)
  920. << DiagD->getDeclName();
  921. else
  922. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  923. << /*function*/0 << DiagD->getDeclName();
  924. }
  925. } else {
  926. if (FD->getDescribedFunctionTemplate())
  927. Diag(DiagD->getLocation(), diag::warn_unused_template)
  928. << /*function*/0 << DiagD->getDeclName();
  929. else
  930. Diag(DiagD->getLocation(),
  931. isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
  932. : diag::warn_unused_function)
  933. << DiagD->getDeclName();
  934. }
  935. } else {
  936. const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
  937. if (!DiagD)
  938. DiagD = cast<VarDecl>(*I);
  939. if (DiagD->isReferenced()) {
  940. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  941. << /*variable*/1 << DiagD->getDeclName();
  942. } else if (DiagD->getType().isConstQualified()) {
  943. const SourceManager &SM = SourceMgr;
  944. if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
  945. !PP.getLangOpts().IsHeaderFile)
  946. Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
  947. << DiagD->getDeclName();
  948. } else {
  949. if (DiagD->getDescribedVarTemplate())
  950. Diag(DiagD->getLocation(), diag::warn_unused_template)
  951. << /*variable*/1 << DiagD->getDeclName();
  952. else
  953. Diag(DiagD->getLocation(), diag::warn_unused_variable)
  954. << DiagD->getDeclName();
  955. }
  956. }
  957. }
  958. emitAndClearUnusedLocalTypedefWarnings();
  959. }
  960. if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
  961. RecordCompleteMap RecordsComplete;
  962. RecordCompleteMap MNCComplete;
  963. for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
  964. E = UnusedPrivateFields.end(); I != E; ++I) {
  965. const NamedDecl *D = *I;
  966. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
  967. if (RD && !RD->isUnion() &&
  968. IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
  969. Diag(D->getLocation(), diag::warn_unused_private_field)
  970. << D->getDeclName();
  971. }
  972. }
  973. }
  974. if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
  975. if (ExternalSource)
  976. ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
  977. for (const auto &DeletedFieldInfo : DeleteExprs) {
  978. for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
  979. AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
  980. DeleteExprLoc.second);
  981. }
  982. }
  983. }
  984. // Check we've noticed that we're no longer parsing the initializer for every
  985. // variable. If we miss cases, then at best we have a performance issue and
  986. // at worst a rejects-valid bug.
  987. assert(ParsingInitForAutoVars.empty() &&
  988. "Didn't unmark var as having its initializer parsed");
  989. if (!PP.isIncrementalProcessingEnabled())
  990. TUScope = nullptr;
  991. }
  992. //===----------------------------------------------------------------------===//
  993. // Helper functions.
  994. //===----------------------------------------------------------------------===//
  995. DeclContext *Sema::getFunctionLevelDeclContext() {
  996. DeclContext *DC = CurContext;
  997. while (true) {
  998. if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
  999. DC = DC->getParent();
  1000. } else if (isa<CXXMethodDecl>(DC) &&
  1001. cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
  1002. cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
  1003. DC = DC->getParent()->getParent();
  1004. }
  1005. else break;
  1006. }
  1007. return DC;
  1008. }
  1009. /// getCurFunctionDecl - If inside of a function body, this returns a pointer
  1010. /// to the function decl for the function being parsed. If we're currently
  1011. /// in a 'block', this returns the containing context.
  1012. FunctionDecl *Sema::getCurFunctionDecl() {
  1013. DeclContext *DC = getFunctionLevelDeclContext();
  1014. return dyn_cast<FunctionDecl>(DC);
  1015. }
  1016. ObjCMethodDecl *Sema::getCurMethodDecl() {
  1017. DeclContext *DC = getFunctionLevelDeclContext();
  1018. while (isa<RecordDecl>(DC))
  1019. DC = DC->getParent();
  1020. return dyn_cast<ObjCMethodDecl>(DC);
  1021. }
  1022. NamedDecl *Sema::getCurFunctionOrMethodDecl() {
  1023. DeclContext *DC = getFunctionLevelDeclContext();
  1024. if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
  1025. return cast<NamedDecl>(DC);
  1026. return nullptr;
  1027. }
  1028. void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
  1029. // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
  1030. // and yet we also use the current diag ID on the DiagnosticsEngine. This has
  1031. // been made more painfully obvious by the refactor that introduced this
  1032. // function, but it is possible that the incoming argument can be
  1033. // eliminated. If it truly cannot be (for example, there is some reentrancy
  1034. // issue I am not seeing yet), then there should at least be a clarifying
  1035. // comment somewhere.
  1036. if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
  1037. switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
  1038. Diags.getCurrentDiagID())) {
  1039. case DiagnosticIDs::SFINAE_Report:
  1040. // We'll report the diagnostic below.
  1041. break;
  1042. case DiagnosticIDs::SFINAE_SubstitutionFailure:
  1043. // Count this failure so that we know that template argument deduction
  1044. // has failed.
  1045. ++NumSFINAEErrors;
  1046. // Make a copy of this suppressed diagnostic and store it with the
  1047. // template-deduction information.
  1048. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  1049. Diagnostic DiagInfo(&Diags);
  1050. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  1051. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1052. }
  1053. Diags.setLastDiagnosticIgnored();
  1054. Diags.Clear();
  1055. return;
  1056. case DiagnosticIDs::SFINAE_AccessControl: {
  1057. // Per C++ Core Issue 1170, access control is part of SFINAE.
  1058. // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
  1059. // make access control a part of SFINAE for the purposes of checking
  1060. // type traits.
  1061. if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
  1062. break;
  1063. SourceLocation Loc = Diags.getCurrentDiagLoc();
  1064. // Suppress this diagnostic.
  1065. ++NumSFINAEErrors;
  1066. // Make a copy of this suppressed diagnostic and store it with the
  1067. // template-deduction information.
  1068. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  1069. Diagnostic DiagInfo(&Diags);
  1070. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  1071. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1072. }
  1073. Diags.setLastDiagnosticIgnored();
  1074. Diags.Clear();
  1075. // Now the diagnostic state is clear, produce a C++98 compatibility
  1076. // warning.
  1077. Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
  1078. // The last diagnostic which Sema produced was ignored. Suppress any
  1079. // notes attached to it.
  1080. Diags.setLastDiagnosticIgnored();
  1081. return;
  1082. }
  1083. case DiagnosticIDs::SFINAE_Suppress:
  1084. // Make a copy of this suppressed diagnostic and store it with the
  1085. // template-deduction information;
  1086. if (*Info) {
  1087. Diagnostic DiagInfo(&Diags);
  1088. (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
  1089. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1090. }
  1091. // Suppress this diagnostic.
  1092. Diags.setLastDiagnosticIgnored();
  1093. Diags.Clear();
  1094. return;
  1095. }
  1096. }
  1097. // Set up the context's printing policy based on our current state.
  1098. Context.setPrintingPolicy(getPrintingPolicy());
  1099. // Emit the diagnostic.
  1100. if (!Diags.EmitCurrentDiagnostic())
  1101. return;
  1102. // If this is not a note, and we're in a template instantiation
  1103. // that is different from the last template instantiation where
  1104. // we emitted an error, print a template instantiation
  1105. // backtrace.
  1106. if (!DiagnosticIDs::isBuiltinNote(DiagID))
  1107. PrintContextStack();
  1108. }
  1109. Sema::SemaDiagnosticBuilder
  1110. Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
  1111. SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
  1112. PD.Emit(Builder);
  1113. return Builder;
  1114. }
  1115. /// \brief Looks through the macro-expansion chain for the given
  1116. /// location, looking for a macro expansion with the given name.
  1117. /// If one is found, returns true and sets the location to that
  1118. /// expansion loc.
  1119. bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
  1120. SourceLocation loc = locref;
  1121. if (!loc.isMacroID()) return false;
  1122. // There's no good way right now to look at the intermediate
  1123. // expansions, so just jump to the expansion location.
  1124. loc = getSourceManager().getExpansionLoc(loc);
  1125. // If that's written with the name, stop here.
  1126. SmallVector<char, 16> buffer;
  1127. if (getPreprocessor().getSpelling(loc, buffer) == name) {
  1128. locref = loc;
  1129. return true;
  1130. }
  1131. return false;
  1132. }
  1133. /// \brief Determines the active Scope associated with the given declaration
  1134. /// context.
  1135. ///
  1136. /// This routine maps a declaration context to the active Scope object that
  1137. /// represents that declaration context in the parser. It is typically used
  1138. /// from "scope-less" code (e.g., template instantiation, lazy creation of
  1139. /// declarations) that injects a name for name-lookup purposes and, therefore,
  1140. /// must update the Scope.
  1141. ///
  1142. /// \returns The scope corresponding to the given declaraion context, or NULL
  1143. /// if no such scope is open.
  1144. Scope *Sema::getScopeForContext(DeclContext *Ctx) {
  1145. if (!Ctx)
  1146. return nullptr;
  1147. Ctx = Ctx->getPrimaryContext();
  1148. for (Scope *S = getCurScope(); S; S = S->getParent()) {
  1149. // Ignore scopes that cannot have declarations. This is important for
  1150. // out-of-line definitions of static class members.
  1151. if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
  1152. if (DeclContext *Entity = S->getEntity())
  1153. if (Ctx == Entity->getPrimaryContext())
  1154. return S;
  1155. }
  1156. return nullptr;
  1157. }
  1158. /// \brief Enter a new function scope
  1159. void Sema::PushFunctionScope() {
  1160. if (FunctionScopes.size() == 1) {
  1161. // Use the "top" function scope rather than having to allocate
  1162. // memory for a new scope.
  1163. FunctionScopes.back()->Clear();
  1164. FunctionScopes.push_back(FunctionScopes.back());
  1165. if (LangOpts.OpenMP)
  1166. pushOpenMPFunctionRegion();
  1167. return;
  1168. }
  1169. FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
  1170. if (LangOpts.OpenMP)
  1171. pushOpenMPFunctionRegion();
  1172. }
  1173. void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
  1174. FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
  1175. BlockScope, Block));
  1176. }
  1177. LambdaScopeInfo *Sema::PushLambdaScope() {
  1178. LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
  1179. FunctionScopes.push_back(LSI);
  1180. return LSI;
  1181. }
  1182. void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
  1183. if (LambdaScopeInfo *const LSI = getCurLambda()) {
  1184. LSI->AutoTemplateParameterDepth = Depth;
  1185. return;
  1186. }
  1187. llvm_unreachable(
  1188. "Remove assertion if intentionally called in a non-lambda context.");
  1189. }
  1190. void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
  1191. const Decl *D, const BlockExpr *blkExpr) {
  1192. FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
  1193. assert(!FunctionScopes.empty() && "mismatched push/pop!");
  1194. if (LangOpts.OpenMP)
  1195. popOpenMPFunctionRegion(Scope);
  1196. // Issue any analysis-based warnings.
  1197. if (WP && D)
  1198. AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
  1199. else
  1200. for (const auto &PUD : Scope->PossiblyUnreachableDiags)
  1201. Diag(PUD.Loc, PUD.PD);
  1202. if (FunctionScopes.back() != Scope)
  1203. delete Scope;
  1204. }
  1205. void Sema::PushCompoundScope() {
  1206. getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
  1207. }
  1208. void Sema::PopCompoundScope() {
  1209. FunctionScopeInfo *CurFunction = getCurFunction();
  1210. assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
  1211. CurFunction->CompoundScopes.pop_back();
  1212. }
  1213. /// \brief Determine whether any errors occurred within this function/method/
  1214. /// block.
  1215. bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
  1216. return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
  1217. }
  1218. BlockScopeInfo *Sema::getCurBlock() {
  1219. if (FunctionScopes.empty())
  1220. return nullptr;
  1221. auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
  1222. if (CurBSI && CurBSI->TheDecl &&
  1223. !CurBSI->TheDecl->Encloses(CurContext)) {
  1224. // We have switched contexts due to template instantiation.
  1225. assert(!CodeSynthesisContexts.empty());
  1226. return nullptr;
  1227. }
  1228. return CurBSI;
  1229. }
  1230. LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
  1231. if (FunctionScopes.empty())
  1232. return nullptr;
  1233. auto I = FunctionScopes.rbegin();
  1234. if (IgnoreNonLambdaCapturingScope) {
  1235. auto E = FunctionScopes.rend();
  1236. while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
  1237. ++I;
  1238. if (I == E)
  1239. return nullptr;
  1240. }
  1241. auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
  1242. if (CurLSI && CurLSI->Lambda &&
  1243. !CurLSI->Lambda->Encloses(CurContext)) {
  1244. // We have switched contexts due to template instantiation.
  1245. assert(!CodeSynthesisContexts.empty());
  1246. return nullptr;
  1247. }
  1248. return CurLSI;
  1249. }
  1250. // We have a generic lambda if we parsed auto parameters, or we have
  1251. // an associated template parameter list.
  1252. LambdaScopeInfo *Sema::getCurGenericLambda() {
  1253. if (LambdaScopeInfo *LSI = getCurLambda()) {
  1254. return (LSI->AutoTemplateParams.size() ||
  1255. LSI->GLTemplateParameterList) ? LSI : nullptr;
  1256. }
  1257. return nullptr;
  1258. }
  1259. void Sema::ActOnComment(SourceRange Comment) {
  1260. if (!LangOpts.RetainCommentsFromSystemHeaders &&
  1261. SourceMgr.isInSystemHeader(Comment.getBegin()))
  1262. return;
  1263. RawComment RC(SourceMgr, Comment, false,
  1264. LangOpts.CommentOpts.ParseAllComments);
  1265. if (RC.isAlmostTrailingComment()) {
  1266. SourceRange MagicMarkerRange(Comment.getBegin(),
  1267. Comment.getBegin().getLocWithOffset(3));
  1268. StringRef MagicMarkerText;
  1269. switch (RC.getKind()) {
  1270. case RawComment::RCK_OrdinaryBCPL:
  1271. MagicMarkerText = "///<";
  1272. break;
  1273. case RawComment::RCK_OrdinaryC:
  1274. MagicMarkerText = "/**<";
  1275. break;
  1276. default:
  1277. llvm_unreachable("if this is an almost Doxygen comment, "
  1278. "it should be ordinary");
  1279. }
  1280. Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
  1281. FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
  1282. }
  1283. Context.addComment(RC);
  1284. }
  1285. // Pin this vtable to this file.
  1286. ExternalSemaSource::~ExternalSemaSource() {}
  1287. void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
  1288. void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
  1289. void ExternalSemaSource::ReadKnownNamespaces(
  1290. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  1291. }
  1292. void ExternalSemaSource::ReadUndefinedButUsed(
  1293. llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
  1294. void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
  1295. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
  1296. void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
  1297. SourceLocation Loc = this->Loc;
  1298. if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
  1299. if (Loc.isValid()) {
  1300. Loc.print(OS, S.getSourceManager());
  1301. OS << ": ";
  1302. }
  1303. OS << Message;
  1304. if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
  1305. OS << " '";
  1306. ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true);
  1307. OS << "'";
  1308. }
  1309. OS << '\n';
  1310. }
  1311. /// \brief Figure out if an expression could be turned into a call.
  1312. ///
  1313. /// Use this when trying to recover from an error where the programmer may have
  1314. /// written just the name of a function instead of actually calling it.
  1315. ///
  1316. /// \param E - The expression to examine.
  1317. /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
  1318. /// with no arguments, this parameter is set to the type returned by such a
  1319. /// call; otherwise, it is set to an empty QualType.
  1320. /// \param OverloadSet - If the expression is an overloaded function
  1321. /// name, this parameter is populated with the decls of the various overloads.
  1322. bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
  1323. UnresolvedSetImpl &OverloadSet) {
  1324. ZeroArgCallReturnTy = QualType();
  1325. OverloadSet.clear();
  1326. const OverloadExpr *Overloads = nullptr;
  1327. bool IsMemExpr = false;
  1328. if (E.getType() == Context.OverloadTy) {
  1329. OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
  1330. // Ignore overloads that are pointer-to-member constants.
  1331. if (FR.HasFormOfMemberPointer)
  1332. return false;
  1333. Overloads = FR.Expression;
  1334. } else if (E.getType() == Context.BoundMemberTy) {
  1335. Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
  1336. IsMemExpr = true;
  1337. }
  1338. bool Ambiguous = false;
  1339. if (Overloads) {
  1340. for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
  1341. DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
  1342. OverloadSet.addDecl(*it);
  1343. // Check whether the function is a non-template, non-member which takes no
  1344. // arguments.
  1345. if (IsMemExpr)
  1346. continue;
  1347. if (const FunctionDecl *OverloadDecl
  1348. = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
  1349. if (OverloadDecl->getMinRequiredArguments() == 0) {
  1350. if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
  1351. ZeroArgCallReturnTy = QualType();
  1352. Ambiguous = true;
  1353. } else
  1354. ZeroArgCallReturnTy = OverloadDecl->getReturnType();
  1355. }
  1356. }
  1357. }
  1358. // If it's not a member, use better machinery to try to resolve the call
  1359. if (!IsMemExpr)
  1360. return !ZeroArgCallReturnTy.isNull();
  1361. }
  1362. // Attempt to call the member with no arguments - this will correctly handle
  1363. // member templates with defaults/deduction of template arguments, overloads
  1364. // with default arguments, etc.
  1365. if (IsMemExpr && !E.isTypeDependent()) {
  1366. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  1367. getDiagnostics().setSuppressAllDiagnostics(true);
  1368. ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
  1369. None, SourceLocation());
  1370. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  1371. if (R.isUsable()) {
  1372. ZeroArgCallReturnTy = R.get()->getType();
  1373. return true;
  1374. }
  1375. return false;
  1376. }
  1377. if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
  1378. if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
  1379. if (Fun->getMinRequiredArguments() == 0)
  1380. ZeroArgCallReturnTy = Fun->getReturnType();
  1381. return true;
  1382. }
  1383. }
  1384. // We don't have an expression that's convenient to get a FunctionDecl from,
  1385. // but we can at least check if the type is "function of 0 arguments".
  1386. QualType ExprTy = E.getType();
  1387. const FunctionType *FunTy = nullptr;
  1388. QualType PointeeTy = ExprTy->getPointeeType();
  1389. if (!PointeeTy.isNull())
  1390. FunTy = PointeeTy->getAs<FunctionType>();
  1391. if (!FunTy)
  1392. FunTy = ExprTy->getAs<FunctionType>();
  1393. if (const FunctionProtoType *FPT =
  1394. dyn_cast_or_null<FunctionProtoType>(FunTy)) {
  1395. if (FPT->getNumParams() == 0)
  1396. ZeroArgCallReturnTy = FunTy->getReturnType();
  1397. return true;
  1398. }
  1399. return false;
  1400. }
  1401. /// \brief Give notes for a set of overloads.
  1402. ///
  1403. /// A companion to tryExprAsCall. In cases when the name that the programmer
  1404. /// wrote was an overloaded function, we may be able to make some guesses about
  1405. /// plausible overloads based on their return types; such guesses can be handed
  1406. /// off to this method to be emitted as notes.
  1407. ///
  1408. /// \param Overloads - The overloads to note.
  1409. /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
  1410. /// -fshow-overloads=best, this is the location to attach to the note about too
  1411. /// many candidates. Typically this will be the location of the original
  1412. /// ill-formed expression.
  1413. static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
  1414. const SourceLocation FinalNoteLoc) {
  1415. int ShownOverloads = 0;
  1416. int SuppressedOverloads = 0;
  1417. for (UnresolvedSetImpl::iterator It = Overloads.begin(),
  1418. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  1419. // FIXME: Magic number for max shown overloads stolen from
  1420. // OverloadCandidateSet::NoteCandidates.
  1421. if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
  1422. ++SuppressedOverloads;
  1423. continue;
  1424. }
  1425. NamedDecl *Fn = (*It)->getUnderlyingDecl();
  1426. S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
  1427. ++ShownOverloads;
  1428. }
  1429. if (SuppressedOverloads)
  1430. S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
  1431. << SuppressedOverloads;
  1432. }
  1433. static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
  1434. const UnresolvedSetImpl &Overloads,
  1435. bool (*IsPlausibleResult)(QualType)) {
  1436. if (!IsPlausibleResult)
  1437. return noteOverloads(S, Overloads, Loc);
  1438. UnresolvedSet<2> PlausibleOverloads;
  1439. for (OverloadExpr::decls_iterator It = Overloads.begin(),
  1440. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  1441. const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
  1442. QualType OverloadResultTy = OverloadDecl->getReturnType();
  1443. if (IsPlausibleResult(OverloadResultTy))
  1444. PlausibleOverloads.addDecl(It.getDecl());
  1445. }
  1446. noteOverloads(S, PlausibleOverloads, Loc);
  1447. }
  1448. /// Determine whether the given expression can be called by just
  1449. /// putting parentheses after it. Notably, expressions with unary
  1450. /// operators can't be because the unary operator will start parsing
  1451. /// outside the call.
  1452. static bool IsCallableWithAppend(Expr *E) {
  1453. E = E->IgnoreImplicit();
  1454. return (!isa<CStyleCastExpr>(E) &&
  1455. !isa<UnaryOperator>(E) &&
  1456. !isa<BinaryOperator>(E) &&
  1457. !isa<CXXOperatorCallExpr>(E));
  1458. }
  1459. bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
  1460. bool ForceComplain,
  1461. bool (*IsPlausibleResult)(QualType)) {
  1462. SourceLocation Loc = E.get()->getExprLoc();
  1463. SourceRange Range = E.get()->getSourceRange();
  1464. QualType ZeroArgCallTy;
  1465. UnresolvedSet<4> Overloads;
  1466. if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
  1467. !ZeroArgCallTy.isNull() &&
  1468. (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
  1469. // At this point, we know E is potentially callable with 0
  1470. // arguments and that it returns something of a reasonable type,
  1471. // so we can emit a fixit and carry on pretending that E was
  1472. // actually a CallExpr.
  1473. SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
  1474. Diag(Loc, PD)
  1475. << /*zero-arg*/ 1 << Range
  1476. << (IsCallableWithAppend(E.get())
  1477. ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
  1478. : FixItHint());
  1479. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  1480. // FIXME: Try this before emitting the fixit, and suppress diagnostics
  1481. // while doing so.
  1482. E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
  1483. Range.getEnd().getLocWithOffset(1));
  1484. return true;
  1485. }
  1486. if (!ForceComplain) return false;
  1487. Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
  1488. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  1489. E = ExprError();
  1490. return true;
  1491. }
  1492. IdentifierInfo *Sema::getSuperIdentifier() const {
  1493. if (!Ident_super)
  1494. Ident_super = &Context.Idents.get("super");
  1495. return Ident_super;
  1496. }
  1497. IdentifierInfo *Sema::getFloat128Identifier() const {
  1498. if (!Ident___float128)
  1499. Ident___float128 = &Context.Idents.get("__float128");
  1500. return Ident___float128;
  1501. }
  1502. void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
  1503. CapturedRegionKind K) {
  1504. CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
  1505. getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
  1506. (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0);
  1507. CSI->ReturnType = Context.VoidTy;
  1508. FunctionScopes.push_back(CSI);
  1509. }
  1510. CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
  1511. if (FunctionScopes.empty())
  1512. return nullptr;
  1513. return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
  1514. }
  1515. const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
  1516. Sema::getMismatchingDeleteExpressions() const {
  1517. return DeleteExprs;
  1518. }
  1519. void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
  1520. if (ExtStr.empty())
  1521. return;
  1522. llvm::SmallVector<StringRef, 1> Exts;
  1523. ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
  1524. auto CanT = T.getCanonicalType().getTypePtr();
  1525. for (auto &I : Exts)
  1526. OpenCLTypeExtMap[CanT].insert(I.str());
  1527. }
  1528. void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
  1529. llvm::SmallVector<StringRef, 1> Exts;
  1530. ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
  1531. if (Exts.empty())
  1532. return;
  1533. for (auto &I : Exts)
  1534. OpenCLDeclExtMap[FD].insert(I.str());
  1535. }
  1536. void Sema::setCurrentOpenCLExtensionForType(QualType T) {
  1537. if (CurrOpenCLExtension.empty())
  1538. return;
  1539. setOpenCLExtensionForType(T, CurrOpenCLExtension);
  1540. }
  1541. void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
  1542. if (CurrOpenCLExtension.empty())
  1543. return;
  1544. setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
  1545. }
  1546. bool Sema::isOpenCLDisabledDecl(Decl *FD) {
  1547. auto Loc = OpenCLDeclExtMap.find(FD);
  1548. if (Loc == OpenCLDeclExtMap.end())
  1549. return false;
  1550. for (auto &I : Loc->second) {
  1551. if (!getOpenCLOptions().isEnabled(I))
  1552. return true;
  1553. }
  1554. return false;
  1555. }
  1556. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
  1557. bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
  1558. DiagInfoT DiagInfo, MapT &Map,
  1559. unsigned Selector,
  1560. SourceRange SrcRange) {
  1561. auto Loc = Map.find(D);
  1562. if (Loc == Map.end())
  1563. return false;
  1564. bool Disabled = false;
  1565. for (auto &I : Loc->second) {
  1566. if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
  1567. Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
  1568. << I << SrcRange;
  1569. Disabled = true;
  1570. }
  1571. }
  1572. return Disabled;
  1573. }
  1574. bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
  1575. // Check extensions for declared types.
  1576. Decl *Decl = nullptr;
  1577. if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
  1578. Decl = TypedefT->getDecl();
  1579. if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
  1580. Decl = TagT->getDecl();
  1581. auto Loc = DS.getTypeSpecTypeLoc();
  1582. if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
  1583. return true;
  1584. // Check extensions for builtin types.
  1585. return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
  1586. QT, OpenCLTypeExtMap);
  1587. }
  1588. bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) {
  1589. IdentifierInfo *FnName = D.getIdentifier();
  1590. return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), FnName,
  1591. OpenCLDeclExtMap, 1, D.getSourceRange());
  1592. }