Sema.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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/Sema/SemaInternal.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTDiagnostic.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/StmtCXX.h"
  23. #include "clang/Basic/DiagnosticOptions.h"
  24. #include "clang/Basic/FileManager.h"
  25. #include "clang/Basic/PartialDiagnostic.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/Lex/HeaderSearch.h"
  28. #include "clang/Lex/Preprocessor.h"
  29. #include "clang/Sema/CXXFieldCollector.h"
  30. #include "clang/Sema/DelayedDiagnostic.h"
  31. #include "clang/Sema/ExternalSemaSource.h"
  32. #include "clang/Sema/MultiplexExternalSemaSource.h"
  33. #include "clang/Sema/ObjCMethodList.h"
  34. #include "clang/Sema/PrettyDeclStackTrace.h"
  35. #include "clang/Sema/Scope.h"
  36. #include "clang/Sema/ScopeInfo.h"
  37. #include "clang/Sema/SemaConsumer.h"
  38. #include "clang/Sema/TemplateDeduction.h"
  39. #include "llvm/ADT/APFloat.h"
  40. #include "llvm/ADT/DenseMap.h"
  41. #include "llvm/ADT/SmallSet.h"
  42. #include "llvm/Support/CrashRecoveryContext.h"
  43. using namespace clang;
  44. using namespace sema;
  45. SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
  46. return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
  47. }
  48. ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
  49. PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
  50. const Preprocessor &PP) {
  51. PrintingPolicy Policy = Context.getPrintingPolicy();
  52. Policy.Bool = Context.getLangOpts().Bool;
  53. if (!Policy.Bool) {
  54. if (const MacroInfo *
  55. BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) {
  56. Policy.Bool = BoolMacro->isObjectLike() &&
  57. BoolMacro->getNumTokens() == 1 &&
  58. BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
  59. }
  60. }
  61. return Policy;
  62. }
  63. void Sema::ActOnTranslationUnitScope(Scope *S) {
  64. TUScope = S;
  65. PushDeclContext(S, Context.getTranslationUnitDecl());
  66. }
  67. Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
  68. TranslationUnitKind TUKind,
  69. CodeCompleteConsumer *CodeCompleter)
  70. : ExternalSource(nullptr),
  71. isMultiplexExternalSource(false), FPFeatures(pp.getLangOpts()),
  72. LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
  73. Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
  74. CollectStats(false), CodeCompleter(CodeCompleter),
  75. CurContext(nullptr), OriginalLexicalContext(nullptr),
  76. PackContext(nullptr), MSStructPragmaOn(false),
  77. MSPointerToMemberRepresentationMethod(
  78. LangOpts.getMSPointerToMemberRepresentationMethod()),
  79. VtorDispModeStack(1, MSVtorDispAttr::Mode(LangOpts.VtorDispMode)),
  80. DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
  81. CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
  82. IsBuildingRecoveryCallExpr(false),
  83. ExprNeedsCleanups(false), LateTemplateParser(nullptr),
  84. LateTemplateParserCleanup(nullptr),
  85. OpaqueParser(nullptr), IdResolver(pp), StdInitializerList(nullptr),
  86. CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr),
  87. NSNumberDecl(nullptr), NSValueDecl(nullptr),
  88. NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
  89. ValueWithBytesObjCTypeMethod(nullptr),
  90. NSArrayDecl(nullptr), ArrayWithObjectsMethod(nullptr),
  91. NSDictionaryDecl(nullptr), DictionaryWithObjectsMethod(nullptr),
  92. MSAsmLabelNameCounter(0),
  93. GlobalNewDeleteDeclared(false),
  94. TUKind(TUKind),
  95. NumSFINAEErrors(0),
  96. CachedFakeTopLevelModule(nullptr),
  97. AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
  98. NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
  99. CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
  100. TyposCorrected(0), AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),
  101. VarDataSharingAttributesStack(nullptr), CurScope(nullptr),
  102. Ident_super(nullptr), Ident___float128(nullptr)
  103. {
  104. TUScope = nullptr;
  105. LoadedExternalKnownNamespaces = false;
  106. #if 0 // HLSL Change Starts
  107. for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
  108. NSNumberLiteralMethods[I] = nullptr;
  109. if (getLangOpts().ObjC1)
  110. NSAPIObj.reset(new NSAPI(Context));
  111. #endif // HLSL Change Ends
  112. if (getLangOpts().CPlusPlus)
  113. FieldCollector.reset(new CXXFieldCollector());
  114. // Tell diagnostics how to render things from the AST library.
  115. PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
  116. &Context);
  117. ExprEvalContexts.emplace_back(PotentiallyEvaluated, 0, false, nullptr, false);
  118. FunctionScopes.push_back(new FunctionScopeInfo(Diags));
  119. // Initilization of data sharing attributes stack for OpenMP
  120. // InitDataSharingAttributesStack(); // HLSL Change - no support for OpenMP
  121. }
  122. void Sema::addImplicitTypedef(StringRef Name, QualType T) {
  123. DeclarationName DN = &Context.Idents.get(Name);
  124. if (IdResolver.begin(DN) == IdResolver.end())
  125. PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
  126. }
  127. void Sema::Initialize() {
  128. // Tell the AST consumer about this Sema object.
  129. Consumer.Initialize(Context);
  130. // FIXME: Isn't this redundant with the initialization above?
  131. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  132. SC->InitializeSema(*this);
  133. // Tell the external Sema source about this Sema object.
  134. if (ExternalSemaSource *ExternalSema
  135. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  136. ExternalSema->InitializeSema(*this);
  137. // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
  138. // will not be able to merge any duplicate __va_list_tag decls correctly.
  139. VAListTagName = PP.getIdentifierInfo("__va_list_tag");
  140. // Initialize predefined 128-bit integer types, if needed.
  141. if (Context.getTargetInfo().hasInt128Type()) {
  142. // If either of the 128-bit integer types are unavailable to name lookup,
  143. // define them now.
  144. DeclarationName Int128 = &Context.Idents.get("__int128_t");
  145. if (IdResolver.begin(Int128) == IdResolver.end())
  146. PushOnScopeChains(Context.getInt128Decl(), TUScope);
  147. DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
  148. if (IdResolver.begin(UInt128) == IdResolver.end())
  149. PushOnScopeChains(Context.getUInt128Decl(), TUScope);
  150. }
  151. // Initialize predefined Objective-C types:
  152. if (PP.getLangOpts().ObjC1) {
  153. // If 'SEL' does not yet refer to any declarations, make it refer to the
  154. // predefined 'SEL'.
  155. DeclarationName SEL = &Context.Idents.get("SEL");
  156. if (IdResolver.begin(SEL) == IdResolver.end())
  157. PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
  158. // If 'id' does not yet refer to any declarations, make it refer to the
  159. // predefined 'id'.
  160. DeclarationName Id = &Context.Idents.get("id");
  161. if (IdResolver.begin(Id) == IdResolver.end())
  162. PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
  163. // Create the built-in typedef for 'Class'.
  164. DeclarationName Class = &Context.Idents.get("Class");
  165. if (IdResolver.begin(Class) == IdResolver.end())
  166. PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
  167. // Create the built-in forward declaratino for 'Protocol'.
  168. DeclarationName Protocol = &Context.Idents.get("Protocol");
  169. if (IdResolver.begin(Protocol) == IdResolver.end())
  170. PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
  171. }
  172. // Initialize Microsoft "predefined C++ types".
  173. if (PP.getLangOpts().MSVCCompat) {
  174. if (PP.getLangOpts().CPlusPlus &&
  175. IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
  176. PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
  177. TUScope);
  178. addImplicitTypedef("size_t", Context.getSizeType());
  179. }
  180. // Initialize predefined OpenCL types.
  181. if (PP.getLangOpts().OpenCL) {
  182. addImplicitTypedef("image1d_t", Context.OCLImage1dTy);
  183. addImplicitTypedef("image1d_array_t", Context.OCLImage1dArrayTy);
  184. addImplicitTypedef("image1d_buffer_t", Context.OCLImage1dBufferTy);
  185. addImplicitTypedef("image2d_t", Context.OCLImage2dTy);
  186. addImplicitTypedef("image2d_array_t", Context.OCLImage2dArrayTy);
  187. addImplicitTypedef("image3d_t", Context.OCLImage3dTy);
  188. addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
  189. addImplicitTypedef("event_t", Context.OCLEventTy);
  190. if (getLangOpts().OpenCLVersion >= 200) {
  191. addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
  192. addImplicitTypedef("atomic_uint",
  193. Context.getAtomicType(Context.UnsignedIntTy));
  194. addImplicitTypedef("atomic_long", Context.getAtomicType(Context.LongTy));
  195. addImplicitTypedef("atomic_ulong",
  196. Context.getAtomicType(Context.UnsignedLongTy));
  197. addImplicitTypedef("atomic_float",
  198. Context.getAtomicType(Context.FloatTy));
  199. addImplicitTypedef("atomic_double",
  200. Context.getAtomicType(Context.DoubleTy));
  201. // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
  202. // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
  203. addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
  204. addImplicitTypedef("atomic_intptr_t",
  205. Context.getAtomicType(Context.getIntPtrType()));
  206. addImplicitTypedef("atomic_uintptr_t",
  207. Context.getAtomicType(Context.getUIntPtrType()));
  208. addImplicitTypedef("atomic_size_t",
  209. Context.getAtomicType(Context.getSizeType()));
  210. addImplicitTypedef("atomic_ptrdiff_t",
  211. Context.getAtomicType(Context.getPointerDiffType()));
  212. }
  213. }
  214. DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
  215. if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
  216. PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
  217. }
  218. Sema::~Sema() {
  219. llvm::DeleteContainerSeconds(LateParsedTemplateMap);
  220. if (PackContext) FreePackedContext();
  221. if (VisContext) FreeVisContext();
  222. // Kill all the active scopes.
  223. for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
  224. delete FunctionScopes[I];
  225. if (FunctionScopes.size() == 1)
  226. delete FunctionScopes[0];
  227. // Tell the SemaConsumer to forget about us; we're going out of scope.
  228. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  229. SC->ForgetSema();
  230. // Detach from the external Sema source.
  231. if (ExternalSemaSource *ExternalSema
  232. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  233. ExternalSema->ForgetSema();
  234. // If Sema's ExternalSource is the multiplexer - we own it.
  235. if (isMultiplexExternalSource)
  236. delete ExternalSource;
  237. threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
  238. // Destroys data sharing attributes stack for OpenMP
  239. // DestroyDataSharingAttributesStack(); // HLSL Change - no support for OpenMP
  240. assert(DelayedTypos.empty() && "Uncorrected typos!");
  241. }
  242. /// makeUnavailableInSystemHeader - There is an error in the current
  243. /// context. If we're still in a system header, and we can plausibly
  244. /// make the relevant declaration unavailable instead of erroring, do
  245. /// so and return true.
  246. bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
  247. StringRef msg) {
  248. // If we're not in a function, it's an error.
  249. FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
  250. if (!fn) return false;
  251. // If we're in template instantiation, it's an error.
  252. if (!ActiveTemplateInstantiations.empty())
  253. return false;
  254. // If that function's not in a system header, it's an error.
  255. if (!Context.getSourceManager().isInSystemHeader(loc))
  256. return false;
  257. // If the function is already unavailable, it's not an error.
  258. if (fn->hasAttr<UnavailableAttr>()) return true;
  259. fn->addAttr(UnavailableAttr::CreateImplicit(Context, msg, loc));
  260. return true;
  261. }
  262. ASTMutationListener *Sema::getASTMutationListener() const {
  263. return getASTConsumer().GetASTMutationListener();
  264. }
  265. ///\brief Registers an external source. If an external source already exists,
  266. /// creates a multiplex external source and appends to it.
  267. ///
  268. ///\param[in] E - A non-null external sema source.
  269. ///
  270. void Sema::addExternalSource(ExternalSemaSource *E) {
  271. assert(E && "Cannot use with NULL ptr");
  272. if (!ExternalSource) {
  273. ExternalSource = E;
  274. return;
  275. }
  276. if (isMultiplexExternalSource)
  277. static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
  278. else {
  279. ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
  280. isMultiplexExternalSource = true;
  281. }
  282. }
  283. /// \brief Print out statistics about the semantic analysis.
  284. void Sema::PrintStats() const {
  285. llvm::errs() << "\n*** Semantic Analysis Stats:\n";
  286. llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
  287. BumpAlloc.PrintStats();
  288. AnalysisWarnings.PrintStats();
  289. }
  290. /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
  291. /// If there is already an implicit cast, merge into the existing one.
  292. /// The result is of the given category.
  293. ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
  294. CastKind Kind, ExprValueKind VK,
  295. const CXXCastPath *BasePath,
  296. CheckedConversionKind CCK) {
  297. #ifndef NDEBUG
  298. if (VK == VK_RValue && !E->isRValue()) {
  299. switch (Kind) {
  300. default:
  301. llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
  302. "kind");
  303. case CK_LValueToRValue:
  304. case CK_ArrayToPointerDecay:
  305. case CK_FunctionToPointerDecay:
  306. case CK_ToVoid:
  307. break;
  308. }
  309. }
  310. assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
  311. #endif
  312. if (VK == VK_LValue) {
  313. if (Kind == CastKind::CK_HLSLVectorTruncationCast ||
  314. Kind == CastKind::CK_HLSLMatrixTruncationCast) {
  315. Diag(E->getLocStart(), diag::err_hlsl_unsupported_lvalue_cast_op);
  316. }
  317. }
  318. // Check whether we're implicitly casting from a nullable type to a nonnull
  319. // type.
  320. if (auto exprNullability = E->getType()->getNullability(Context)) {
  321. if (*exprNullability == NullabilityKind::Nullable) {
  322. if (auto typeNullability = Ty->getNullability(Context)) {
  323. if (*typeNullability == NullabilityKind::NonNull) {
  324. Diag(E->getLocStart(), diag::warn_nullability_lost)
  325. << E->getType() << Ty;
  326. }
  327. }
  328. }
  329. }
  330. QualType ExprTy = Context.getCanonicalType(E->getType());
  331. QualType TypeTy = Context.getCanonicalType(Ty);
  332. if (ExprTy == TypeTy)
  333. return E;
  334. if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
  335. if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
  336. ImpCast->setType(Ty);
  337. ImpCast->setValueKind(VK);
  338. return E;
  339. }
  340. }
  341. return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
  342. }
  343. /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
  344. /// to the conversion from scalar type ScalarTy to the Boolean type.
  345. CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
  346. switch (ScalarTy->getScalarTypeKind()) {
  347. case Type::STK_Bool: return CK_NoOp;
  348. case Type::STK_CPointer: return CK_PointerToBoolean;
  349. case Type::STK_BlockPointer: return CK_PointerToBoolean;
  350. case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
  351. case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
  352. case Type::STK_Integral: return CK_IntegralToBoolean;
  353. case Type::STK_Floating: return CK_FloatingToBoolean;
  354. case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
  355. case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
  356. }
  357. return CK_Invalid;
  358. }
  359. /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
  360. static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
  361. if (D->getMostRecentDecl()->isUsed())
  362. return true;
  363. if (D->isExternallyVisible())
  364. return true;
  365. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  366. // UnusedFileScopedDecls stores the first declaration.
  367. // The declaration may have become definition so check again.
  368. const FunctionDecl *DeclToCheck;
  369. if (FD->hasBody(DeclToCheck))
  370. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  371. // Later redecls may add new information resulting in not having to warn,
  372. // so check again.
  373. DeclToCheck = FD->getMostRecentDecl();
  374. if (DeclToCheck != FD)
  375. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  376. }
  377. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  378. // If a variable usable in constant expressions is referenced,
  379. // don't warn if it isn't used: if the value of a variable is required
  380. // for the computation of a constant expression, it doesn't make sense to
  381. // warn even if the variable isn't odr-used. (isReferenced doesn't
  382. // precisely reflect that, but it's a decent approximation.)
  383. if (VD->isReferenced() &&
  384. VD->isUsableInConstantExpressions(SemaRef->Context))
  385. return true;
  386. // UnusedFileScopedDecls stores the first declaration.
  387. // The declaration may have become definition so check again.
  388. const VarDecl *DeclToCheck = VD->getDefinition();
  389. if (DeclToCheck)
  390. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  391. // Later redecls may add new information resulting in not having to warn,
  392. // so check again.
  393. DeclToCheck = VD->getMostRecentDecl();
  394. if (DeclToCheck != VD)
  395. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  396. }
  397. return false;
  398. }
  399. /// Obtains a sorted list of functions that are undefined but ODR-used.
  400. void Sema::getUndefinedButUsed(
  401. SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
  402. for (llvm::DenseMap<NamedDecl *, SourceLocation>::iterator
  403. I = UndefinedButUsed.begin(), E = UndefinedButUsed.end();
  404. I != E; ++I) {
  405. NamedDecl *ND = I->first;
  406. // Ignore attributes that have become invalid.
  407. if (ND->isInvalidDecl()) continue;
  408. // __attribute__((weakref)) is basically a definition.
  409. if (ND->hasAttr<WeakRefAttr>()) continue;
  410. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  411. if (FD->isDefined())
  412. continue;
  413. if (FD->isExternallyVisible() &&
  414. !FD->getMostRecentDecl()->isInlined())
  415. continue;
  416. } else {
  417. if (cast<VarDecl>(ND)->hasDefinition() != VarDecl::DeclarationOnly)
  418. continue;
  419. if (ND->isExternallyVisible())
  420. continue;
  421. }
  422. Undefined.push_back(std::make_pair(ND, I->second));
  423. }
  424. // Sort (in order of use site) so that we're not dependent on the iteration
  425. // order through an llvm::DenseMap.
  426. SourceManager &SM = Context.getSourceManager();
  427. std::sort(Undefined.begin(), Undefined.end(),
  428. [&SM](const std::pair<NamedDecl *, SourceLocation> &l,
  429. const std::pair<NamedDecl *, SourceLocation> &r) {
  430. if (l.second.isValid() && !r.second.isValid())
  431. return true;
  432. if (!l.second.isValid() && r.second.isValid())
  433. return false;
  434. if (l.second != r.second)
  435. return SM.isBeforeInTranslationUnit(l.second, r.second);
  436. return SM.isBeforeInTranslationUnit(l.first->getLocation(),
  437. r.first->getLocation());
  438. });
  439. }
  440. /// checkUndefinedButUsed - Check for undefined objects with internal linkage
  441. /// or that are inline.
  442. static void checkUndefinedButUsed(Sema &S) {
  443. if (S.UndefinedButUsed.empty()) return;
  444. // Collect all the still-undefined entities with internal linkage.
  445. SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
  446. S.getUndefinedButUsed(Undefined);
  447. if (Undefined.empty()) return;
  448. for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
  449. I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
  450. NamedDecl *ND = I->first;
  451. if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
  452. // An exported function will always be emitted when defined, so even if
  453. // the function is inline, it doesn't have to be emitted in this TU. An
  454. // imported function implies that it has been exported somewhere else.
  455. continue;
  456. }
  457. if (!ND->isExternallyVisible()) {
  458. S.Diag(ND->getLocation(), diag::warn_undefined_internal)
  459. << isa<VarDecl>(ND) << ND;
  460. } else {
  461. assert(cast<FunctionDecl>(ND)->getMostRecentDecl()->isInlined() &&
  462. "used object requires definition but isn't inline or internal?");
  463. S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
  464. }
  465. if (I->second.isValid())
  466. S.Diag(I->second, diag::note_used_here);
  467. }
  468. }
  469. void Sema::LoadExternalWeakUndeclaredIdentifiers() {
  470. if (!ExternalSource)
  471. return;
  472. SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
  473. ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
  474. for (auto &WeakID : WeakIDs)
  475. WeakUndeclaredIdentifiers.insert(WeakID);
  476. }
  477. typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
  478. /// \brief Returns true, if all methods and nested classes of the given
  479. /// CXXRecordDecl are defined in this translation unit.
  480. ///
  481. /// Should only be called from ActOnEndOfTranslationUnit so that all
  482. /// definitions are actually read.
  483. static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
  484. RecordCompleteMap &MNCComplete) {
  485. RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
  486. if (Cache != MNCComplete.end())
  487. return Cache->second;
  488. if (!RD->isCompleteDefinition())
  489. return false;
  490. bool Complete = true;
  491. for (DeclContext::decl_iterator I = RD->decls_begin(),
  492. E = RD->decls_end();
  493. I != E && Complete; ++I) {
  494. if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
  495. Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
  496. else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
  497. // If the template function is marked as late template parsed at this
  498. // point, it has not been instantiated and therefore we have not
  499. // performed semantic analysis on it yet, so we cannot know if the type
  500. // can be considered complete.
  501. Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
  502. F->getTemplatedDecl()->isDefined();
  503. else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
  504. if (R->isInjectedClassName())
  505. continue;
  506. if (R->hasDefinition())
  507. Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
  508. MNCComplete);
  509. else
  510. Complete = false;
  511. }
  512. }
  513. MNCComplete[RD] = Complete;
  514. return Complete;
  515. }
  516. /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
  517. /// translation unit, i.e. all methods are defined or pure virtual and all
  518. /// friends, friend functions and nested classes are fully defined in this
  519. /// translation unit.
  520. ///
  521. /// Should only be called from ActOnEndOfTranslationUnit so that all
  522. /// definitions are actually read.
  523. static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
  524. RecordCompleteMap &RecordsComplete,
  525. RecordCompleteMap &MNCComplete) {
  526. RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
  527. if (Cache != RecordsComplete.end())
  528. return Cache->second;
  529. bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
  530. for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
  531. E = RD->friend_end();
  532. I != E && Complete; ++I) {
  533. // Check if friend classes and methods are complete.
  534. if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
  535. // Friend classes are available as the TypeSourceInfo of the FriendDecl.
  536. if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
  537. Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
  538. else
  539. Complete = false;
  540. } else {
  541. // Friend functions are available through the NamedDecl of FriendDecl.
  542. if (const FunctionDecl *FD =
  543. dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
  544. Complete = FD->isDefined();
  545. else
  546. // This is a template friend, give up.
  547. Complete = false;
  548. }
  549. }
  550. RecordsComplete[RD] = Complete;
  551. return Complete;
  552. }
  553. void Sema::emitAndClearUnusedLocalTypedefWarnings() {
  554. if (ExternalSource)
  555. ExternalSource->ReadUnusedLocalTypedefNameCandidates(
  556. UnusedLocalTypedefNameCandidates);
  557. for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
  558. if (TD->isReferenced())
  559. continue;
  560. Diag(TD->getLocation(), diag::warn_unused_local_typedef)
  561. << isa<TypeAliasDecl>(TD) << TD->getDeclName();
  562. }
  563. UnusedLocalTypedefNameCandidates.clear();
  564. }
  565. /// ActOnEndOfTranslationUnit - This is called at the very end of the
  566. /// translation unit when EOF is reached and all but the top-level scope is
  567. /// popped.
  568. void Sema::ActOnEndOfTranslationUnit() {
  569. assert(DelayedDiagnostics.getCurrentPool() == nullptr
  570. && "reached end of translation unit with a pool attached?");
  571. // If code completion is enabled, don't perform any end-of-translation-unit
  572. // work.
  573. if (PP.isCodeCompletionEnabled())
  574. return;
  575. // Complete translation units and modules define vtables and perform implicit
  576. // instantiations. PCH files do not.
  577. if (TUKind != TU_Prefix) {
  578. DiagnoseUseOfUnimplementedSelectors();
  579. // If DefinedUsedVTables ends up marking any virtual member functions it
  580. // might lead to more pending template instantiations, which we then need
  581. // to instantiate.
  582. DefineUsedVTables();
  583. // C++: Perform implicit template instantiations.
  584. //
  585. // FIXME: When we perform these implicit instantiations, we do not
  586. // carefully keep track of the point of instantiation (C++ [temp.point]).
  587. // This means that name lookup that occurs within the template
  588. // instantiation will always happen at the end of the translation unit,
  589. // so it will find some names that are not required to be found. This is
  590. // valid, but we could do better by diagnosing if an instantiation uses a
  591. // name that was not visible at its first point of instantiation.
  592. if (ExternalSource) {
  593. // Load pending instantiations from the external source.
  594. SmallVector<PendingImplicitInstantiation, 4> Pending;
  595. ExternalSource->ReadPendingInstantiations(Pending);
  596. PendingInstantiations.insert(PendingInstantiations.begin(),
  597. Pending.begin(), Pending.end());
  598. }
  599. PerformPendingInstantiations();
  600. if (LateTemplateParserCleanup)
  601. LateTemplateParserCleanup(OpaqueParser);
  602. CheckDelayedMemberExceptionSpecs();
  603. }
  604. // All delayed member exception specs should be checked or we end up accepting
  605. // incompatible declarations.
  606. // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
  607. // write out the lists to the AST file (if any).
  608. assert(DelayedDefaultedMemberExceptionSpecs.empty());
  609. assert(DelayedExceptionSpecChecks.empty());
  610. // Remove file scoped decls that turned out to be used.
  611. UnusedFileScopedDecls.erase(
  612. std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
  613. UnusedFileScopedDecls.end(),
  614. std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), this)),
  615. UnusedFileScopedDecls.end());
  616. if (TUKind == TU_Prefix) {
  617. // Translation unit prefixes don't need any of the checking below.
  618. TUScope = nullptr;
  619. return;
  620. }
  621. // Check for #pragma weak identifiers that were never declared
  622. LoadExternalWeakUndeclaredIdentifiers();
  623. for (auto WeakID : WeakUndeclaredIdentifiers) {
  624. if (WeakID.second.getUsed())
  625. continue;
  626. Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
  627. << WeakID.first;
  628. }
  629. if (LangOpts.CPlusPlus11 &&
  630. !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
  631. CheckDelegatingCtorCycles();
  632. if (TUKind == TU_Module) {
  633. // If we are building a module, resolve all of the exported declarations
  634. // now.
  635. if (Module *CurrentModule = PP.getCurrentModule()) {
  636. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  637. SmallVector<Module *, 2> Stack;
  638. Stack.push_back(CurrentModule);
  639. while (!Stack.empty()) {
  640. Module *Mod = Stack.pop_back_val();
  641. // Resolve the exported declarations and conflicts.
  642. // FIXME: Actually complain, once we figure out how to teach the
  643. // diagnostic client to deal with complaints in the module map at this
  644. // point.
  645. ModMap.resolveExports(Mod, /*Complain=*/false);
  646. ModMap.resolveUses(Mod, /*Complain=*/false);
  647. ModMap.resolveConflicts(Mod, /*Complain=*/false);
  648. // Queue the submodules, so their exports will also be resolved.
  649. Stack.append(Mod->submodule_begin(), Mod->submodule_end());
  650. }
  651. }
  652. // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
  653. // modules when they are built, not every time they are used.
  654. emitAndClearUnusedLocalTypedefWarnings();
  655. // Modules don't need any of the checking below.
  656. TUScope = nullptr;
  657. return;
  658. }
  659. // C99 6.9.2p2:
  660. // A declaration of an identifier for an object that has file
  661. // scope without an initializer, and without a storage-class
  662. // specifier or with the storage-class specifier static,
  663. // constitutes a tentative definition. If a translation unit
  664. // contains one or more tentative definitions for an identifier,
  665. // and the translation unit contains no external definition for
  666. // that identifier, then the behavior is exactly as if the
  667. // translation unit contains a file scope declaration of that
  668. // identifier, with the composite type as of the end of the
  669. // translation unit, with an initializer equal to 0.
  670. llvm::SmallSet<VarDecl *, 32> Seen;
  671. for (TentativeDefinitionsType::iterator
  672. T = TentativeDefinitions.begin(ExternalSource),
  673. TEnd = TentativeDefinitions.end();
  674. T != TEnd; ++T)
  675. {
  676. VarDecl *VD = (*T)->getActingDefinition();
  677. // If the tentative definition was completed, getActingDefinition() returns
  678. // null. If we've already seen this variable before, insert()'s second
  679. // return value is false.
  680. if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
  681. continue;
  682. if (const IncompleteArrayType *ArrayT
  683. = Context.getAsIncompleteArrayType(VD->getType())) {
  684. // Set the length of the array to 1 (C99 6.9.2p5).
  685. Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
  686. llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
  687. QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
  688. One, ArrayType::Normal, 0);
  689. VD->setType(T);
  690. } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
  691. diag::err_tentative_def_incomplete_type))
  692. VD->setInvalidDecl();
  693. CheckCompleteVariableDeclaration(VD);
  694. // Notify the consumer that we've completed a tentative definition.
  695. if (!VD->isInvalidDecl())
  696. Consumer.CompleteTentativeDefinition(VD);
  697. }
  698. // If there were errors, disable 'unused' warnings since they will mostly be
  699. // noise.
  700. if (!Diags.hasErrorOccurred()) {
  701. // Output warning for unused file scoped decls.
  702. for (UnusedFileScopedDeclsType::iterator
  703. I = UnusedFileScopedDecls.begin(ExternalSource),
  704. E = UnusedFileScopedDecls.end(); I != E; ++I) {
  705. if (ShouldRemoveFromUnused(this, *I))
  706. continue;
  707. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  708. const FunctionDecl *DiagD;
  709. if (!FD->hasBody(DiagD))
  710. DiagD = FD;
  711. if (DiagD->isDeleted())
  712. continue; // Deleted functions are supposed to be unused.
  713. if (DiagD->isReferenced()) {
  714. if (isa<CXXMethodDecl>(DiagD))
  715. Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
  716. << DiagD->getDeclName();
  717. else {
  718. if (FD->getStorageClass() == SC_Static &&
  719. !FD->isInlineSpecified() &&
  720. !SourceMgr.isInMainFile(
  721. SourceMgr.getExpansionLoc(FD->getLocation())))
  722. Diag(DiagD->getLocation(),
  723. diag::warn_unneeded_static_internal_decl)
  724. << DiagD->getDeclName();
  725. else
  726. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  727. << /*function*/0 << DiagD->getDeclName();
  728. }
  729. } else {
  730. Diag(DiagD->getLocation(),
  731. isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
  732. : diag::warn_unused_function)
  733. << DiagD->getDeclName();
  734. }
  735. } else {
  736. const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
  737. if (!DiagD)
  738. DiagD = cast<VarDecl>(*I);
  739. if (DiagD->isReferenced()) {
  740. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  741. << /*variable*/1 << DiagD->getDeclName();
  742. } else if (DiagD->getType().isConstQualified()) {
  743. Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
  744. << DiagD->getDeclName();
  745. } else {
  746. Diag(DiagD->getLocation(), diag::warn_unused_variable)
  747. << DiagD->getDeclName();
  748. }
  749. }
  750. }
  751. if (ExternalSource)
  752. ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
  753. checkUndefinedButUsed(*this);
  754. emitAndClearUnusedLocalTypedefWarnings();
  755. }
  756. if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
  757. RecordCompleteMap RecordsComplete;
  758. RecordCompleteMap MNCComplete;
  759. for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
  760. E = UnusedPrivateFields.end(); I != E; ++I) {
  761. const NamedDecl *D = *I;
  762. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
  763. if (RD && !RD->isUnion() &&
  764. IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
  765. Diag(D->getLocation(), diag::warn_unused_private_field)
  766. << D->getDeclName();
  767. }
  768. }
  769. }
  770. if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
  771. if (ExternalSource)
  772. ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
  773. for (const auto &DeletedFieldInfo : DeleteExprs) {
  774. for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
  775. AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
  776. DeleteExprLoc.second);
  777. }
  778. }
  779. }
  780. // Check we've noticed that we're no longer parsing the initializer for every
  781. // variable. If we miss cases, then at best we have a performance issue and
  782. // at worst a rejects-valid bug.
  783. assert(ParsingInitForAutoVars.empty() &&
  784. "Didn't unmark var as having its initializer parsed");
  785. TUScope = nullptr;
  786. }
  787. //===----------------------------------------------------------------------===//
  788. // Helper functions.
  789. //===----------------------------------------------------------------------===//
  790. DeclContext *Sema::getFunctionLevelDeclContext() {
  791. DeclContext *DC = CurContext;
  792. while (true) {
  793. if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
  794. DC = DC->getParent();
  795. } else if (isa<CXXMethodDecl>(DC) &&
  796. cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
  797. cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
  798. DC = DC->getParent()->getParent();
  799. }
  800. else break;
  801. }
  802. return DC;
  803. }
  804. /// getCurFunctionDecl - If inside of a function body, this returns a pointer
  805. /// to the function decl for the function being parsed. If we're currently
  806. /// in a 'block', this returns the containing context.
  807. FunctionDecl *Sema::getCurFunctionDecl() {
  808. DeclContext *DC = getFunctionLevelDeclContext();
  809. return dyn_cast<FunctionDecl>(DC);
  810. }
  811. ObjCMethodDecl *Sema::getCurMethodDecl() {
  812. DeclContext *DC = getFunctionLevelDeclContext();
  813. while (isa<RecordDecl>(DC))
  814. DC = DC->getParent();
  815. return dyn_cast<ObjCMethodDecl>(DC);
  816. }
  817. NamedDecl *Sema::getCurFunctionOrMethodDecl() {
  818. DeclContext *DC = getFunctionLevelDeclContext();
  819. if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
  820. return cast<NamedDecl>(DC);
  821. return nullptr;
  822. }
  823. void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
  824. // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
  825. // and yet we also use the current diag ID on the DiagnosticsEngine. This has
  826. // been made more painfully obvious by the refactor that introduced this
  827. // function, but it is possible that the incoming argument can be
  828. // eliminnated. If it truly cannot be (for example, there is some reentrancy
  829. // issue I am not seeing yet), then there should at least be a clarifying
  830. // comment somewhere.
  831. if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
  832. switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
  833. Diags.getCurrentDiagID())) {
  834. case DiagnosticIDs::SFINAE_Report:
  835. // We'll report the diagnostic below.
  836. break;
  837. case DiagnosticIDs::SFINAE_SubstitutionFailure:
  838. // Count this failure so that we know that template argument deduction
  839. // has failed.
  840. ++NumSFINAEErrors;
  841. // Make a copy of this suppressed diagnostic and store it with the
  842. // template-deduction information.
  843. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  844. Diagnostic DiagInfo(&Diags);
  845. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  846. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  847. }
  848. Diags.setLastDiagnosticIgnored();
  849. Diags.Clear();
  850. return;
  851. case DiagnosticIDs::SFINAE_AccessControl: {
  852. // Per C++ Core Issue 1170, access control is part of SFINAE.
  853. // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
  854. // make access control a part of SFINAE for the purposes of checking
  855. // type traits.
  856. if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
  857. break;
  858. SourceLocation Loc = Diags.getCurrentDiagLoc();
  859. // Suppress this diagnostic.
  860. ++NumSFINAEErrors;
  861. // Make a copy of this suppressed diagnostic and store it with the
  862. // template-deduction information.
  863. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  864. Diagnostic DiagInfo(&Diags);
  865. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  866. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  867. }
  868. Diags.setLastDiagnosticIgnored();
  869. Diags.Clear();
  870. // Now the diagnostic state is clear, produce a C++98 compatibility
  871. // warning.
  872. Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
  873. // The last diagnostic which Sema produced was ignored. Suppress any
  874. // notes attached to it.
  875. Diags.setLastDiagnosticIgnored();
  876. return;
  877. }
  878. case DiagnosticIDs::SFINAE_Suppress:
  879. // Make a copy of this suppressed diagnostic and store it with the
  880. // template-deduction information;
  881. if (*Info) {
  882. Diagnostic DiagInfo(&Diags);
  883. (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
  884. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  885. }
  886. // Suppress this diagnostic.
  887. Diags.setLastDiagnosticIgnored();
  888. Diags.Clear();
  889. return;
  890. }
  891. }
  892. // Set up the context's printing policy based on our current state.
  893. Context.setPrintingPolicy(getPrintingPolicy());
  894. // Emit the diagnostic.
  895. if (!Diags.EmitCurrentDiagnostic())
  896. return;
  897. // If this is not a note, and we're in a template instantiation
  898. // that is different from the last template instantiation where
  899. // we emitted an error, print a template instantiation
  900. // backtrace.
  901. if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
  902. !ActiveTemplateInstantiations.empty() &&
  903. ActiveTemplateInstantiations.back()
  904. != LastTemplateInstantiationErrorContext) {
  905. PrintInstantiationStack();
  906. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiations.back();
  907. }
  908. }
  909. Sema::SemaDiagnosticBuilder
  910. Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
  911. SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
  912. PD.Emit(Builder);
  913. return Builder;
  914. }
  915. /// \brief Looks through the macro-expansion chain for the given
  916. /// location, looking for a macro expansion with the given name.
  917. /// If one is found, returns true and sets the location to that
  918. /// expansion loc.
  919. bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
  920. SourceLocation loc = locref;
  921. if (!loc.isMacroID()) return false;
  922. // There's no good way right now to look at the intermediate
  923. // expansions, so just jump to the expansion location.
  924. loc = getSourceManager().getExpansionLoc(loc);
  925. // If that's written with the name, stop here.
  926. SmallVector<char, 16> buffer;
  927. if (getPreprocessor().getSpelling(loc, buffer) == name) {
  928. locref = loc;
  929. return true;
  930. }
  931. return false;
  932. }
  933. /// \brief Determines the active Scope associated with the given declaration
  934. /// context.
  935. ///
  936. /// This routine maps a declaration context to the active Scope object that
  937. /// represents that declaration context in the parser. It is typically used
  938. /// from "scope-less" code (e.g., template instantiation, lazy creation of
  939. /// declarations) that injects a name for name-lookup purposes and, therefore,
  940. /// must update the Scope.
  941. ///
  942. /// \returns The scope corresponding to the given declaraion context, or NULL
  943. /// if no such scope is open.
  944. Scope *Sema::getScopeForContext(DeclContext *Ctx) {
  945. if (!Ctx)
  946. return nullptr;
  947. Ctx = Ctx->getPrimaryContext();
  948. for (Scope *S = getCurScope(); S; S = S->getParent()) {
  949. // Ignore scopes that cannot have declarations. This is important for
  950. // out-of-line definitions of static class members.
  951. if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
  952. if (DeclContext *Entity = S->getEntity())
  953. if (Ctx == Entity->getPrimaryContext())
  954. return S;
  955. }
  956. return nullptr;
  957. }
  958. /// \brief Enter a new function scope
  959. void Sema::PushFunctionScope() {
  960. if (FunctionScopes.size() == 1) {
  961. // Use the "top" function scope rather than having to allocate
  962. // memory for a new scope.
  963. FunctionScopes.back()->Clear();
  964. FunctionScopes.push_back(FunctionScopes.back());
  965. return;
  966. }
  967. FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
  968. }
  969. void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
  970. FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
  971. BlockScope, Block));
  972. }
  973. LambdaScopeInfo *Sema::PushLambdaScope() {
  974. LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
  975. FunctionScopes.push_back(LSI);
  976. return LSI;
  977. }
  978. void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
  979. if (LambdaScopeInfo *const LSI = getCurLambda()) {
  980. LSI->AutoTemplateParameterDepth = Depth;
  981. return;
  982. }
  983. llvm_unreachable(
  984. "Remove assertion if intentionally called in a non-lambda context.");
  985. }
  986. void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
  987. const Decl *D, const BlockExpr *blkExpr) {
  988. FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
  989. assert(!FunctionScopes.empty() && "mismatched push/pop!");
  990. // Issue any analysis-based warnings.
  991. if (WP && D)
  992. AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
  993. else
  994. for (const auto &PUD : Scope->PossiblyUnreachableDiags)
  995. Diag(PUD.Loc, PUD.PD);
  996. if (FunctionScopes.back() != Scope)
  997. delete Scope;
  998. }
  999. void Sema::PushCompoundScope() {
  1000. getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
  1001. }
  1002. void Sema::PopCompoundScope() {
  1003. FunctionScopeInfo *CurFunction = getCurFunction();
  1004. assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
  1005. CurFunction->CompoundScopes.pop_back();
  1006. }
  1007. /// \brief Determine whether any errors occurred within this function/method/
  1008. /// block.
  1009. bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
  1010. return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
  1011. }
  1012. BlockScopeInfo *Sema::getCurBlock() {
  1013. if (FunctionScopes.empty())
  1014. return nullptr;
  1015. auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
  1016. if (CurBSI && CurBSI->TheDecl &&
  1017. !CurBSI->TheDecl->Encloses(CurContext)) {
  1018. // We have switched contexts due to template instantiation.
  1019. assert(!ActiveTemplateInstantiations.empty());
  1020. return nullptr;
  1021. }
  1022. return CurBSI;
  1023. }
  1024. LambdaScopeInfo *Sema::getCurLambda() {
  1025. if (FunctionScopes.empty())
  1026. return nullptr;
  1027. auto CurLSI = dyn_cast<LambdaScopeInfo>(FunctionScopes.back());
  1028. if (CurLSI && CurLSI->Lambda &&
  1029. !CurLSI->Lambda->Encloses(CurContext)) {
  1030. // We have switched contexts due to template instantiation.
  1031. assert(!ActiveTemplateInstantiations.empty());
  1032. return nullptr;
  1033. }
  1034. return CurLSI;
  1035. }
  1036. // We have a generic lambda if we parsed auto parameters, or we have
  1037. // an associated template parameter list.
  1038. LambdaScopeInfo *Sema::getCurGenericLambda() {
  1039. if (LambdaScopeInfo *LSI = getCurLambda()) {
  1040. return (LSI->AutoTemplateParams.size() ||
  1041. LSI->GLTemplateParameterList) ? LSI : nullptr;
  1042. }
  1043. return nullptr;
  1044. }
  1045. void Sema::ActOnComment(SourceRange Comment) {
  1046. if (!LangOpts.RetainCommentsFromSystemHeaders &&
  1047. SourceMgr.isInSystemHeader(Comment.getBegin()))
  1048. return;
  1049. RawComment RC(SourceMgr, Comment, false,
  1050. LangOpts.CommentOpts.ParseAllComments);
  1051. if (RC.isAlmostTrailingComment()) {
  1052. SourceRange MagicMarkerRange(Comment.getBegin(),
  1053. Comment.getBegin().getLocWithOffset(3));
  1054. StringRef MagicMarkerText;
  1055. switch (RC.getKind()) {
  1056. case RawComment::RCK_OrdinaryBCPL:
  1057. MagicMarkerText = "///<";
  1058. break;
  1059. case RawComment::RCK_OrdinaryC:
  1060. MagicMarkerText = "/**<";
  1061. break;
  1062. default:
  1063. llvm_unreachable("if this is an almost Doxygen comment, "
  1064. "it should be ordinary");
  1065. }
  1066. Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
  1067. FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
  1068. }
  1069. Context.addComment(RC);
  1070. }
  1071. // Pin this vtable to this file.
  1072. ExternalSemaSource::~ExternalSemaSource() {}
  1073. void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
  1074. void ExternalSemaSource::ReadKnownNamespaces(
  1075. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  1076. }
  1077. void ExternalSemaSource::ReadUndefinedButUsed(
  1078. llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) {
  1079. }
  1080. void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
  1081. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
  1082. void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
  1083. SourceLocation Loc = this->Loc;
  1084. if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
  1085. if (Loc.isValid()) {
  1086. Loc.print(OS, S.getSourceManager());
  1087. OS << ": ";
  1088. }
  1089. OS << Message;
  1090. if (TheDecl && isa<NamedDecl>(TheDecl)) {
  1091. std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
  1092. if (!Name.empty())
  1093. OS << " '" << Name << '\'';
  1094. }
  1095. OS << '\n';
  1096. }
  1097. /// \brief Figure out if an expression could be turned into a call.
  1098. ///
  1099. /// Use this when trying to recover from an error where the programmer may have
  1100. /// written just the name of a function instead of actually calling it.
  1101. ///
  1102. /// \param E - The expression to examine.
  1103. /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
  1104. /// with no arguments, this parameter is set to the type returned by such a
  1105. /// call; otherwise, it is set to an empty QualType.
  1106. /// \param OverloadSet - If the expression is an overloaded function
  1107. /// name, this parameter is populated with the decls of the various overloads.
  1108. bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
  1109. UnresolvedSetImpl &OverloadSet) {
  1110. ZeroArgCallReturnTy = QualType();
  1111. OverloadSet.clear();
  1112. const OverloadExpr *Overloads = nullptr;
  1113. bool IsMemExpr = false;
  1114. if (E.getType() == Context.OverloadTy) {
  1115. OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
  1116. // Ignore overloads that are pointer-to-member constants.
  1117. if (FR.HasFormOfMemberPointer)
  1118. return false;
  1119. Overloads = FR.Expression;
  1120. } else if (E.getType() == Context.BoundMemberTy) {
  1121. Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
  1122. IsMemExpr = true;
  1123. }
  1124. bool Ambiguous = false;
  1125. if (Overloads) {
  1126. for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
  1127. DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
  1128. OverloadSet.addDecl(*it);
  1129. // Check whether the function is a non-template, non-member which takes no
  1130. // arguments.
  1131. if (IsMemExpr)
  1132. continue;
  1133. if (const FunctionDecl *OverloadDecl
  1134. = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
  1135. if (OverloadDecl->getMinRequiredArguments() == 0) {
  1136. if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
  1137. ZeroArgCallReturnTy = QualType();
  1138. Ambiguous = true;
  1139. } else
  1140. ZeroArgCallReturnTy = OverloadDecl->getReturnType();
  1141. }
  1142. }
  1143. }
  1144. // If it's not a member, use better machinery to try to resolve the call
  1145. if (!IsMemExpr)
  1146. return !ZeroArgCallReturnTy.isNull();
  1147. }
  1148. // Attempt to call the member with no arguments - this will correctly handle
  1149. // member templates with defaults/deduction of template arguments, overloads
  1150. // with default arguments, etc.
  1151. if (IsMemExpr && !E.isTypeDependent()) {
  1152. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  1153. getDiagnostics().setSuppressAllDiagnostics(true);
  1154. ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
  1155. None, SourceLocation());
  1156. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  1157. if (R.isUsable()) {
  1158. ZeroArgCallReturnTy = R.get()->getType();
  1159. return true;
  1160. }
  1161. return false;
  1162. }
  1163. if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
  1164. if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
  1165. if (Fun->getMinRequiredArguments() == 0)
  1166. ZeroArgCallReturnTy = Fun->getReturnType();
  1167. return true;
  1168. }
  1169. }
  1170. // We don't have an expression that's convenient to get a FunctionDecl from,
  1171. // but we can at least check if the type is "function of 0 arguments".
  1172. QualType ExprTy = E.getType();
  1173. const FunctionType *FunTy = nullptr;
  1174. QualType PointeeTy = ExprTy->getPointeeType();
  1175. if (!PointeeTy.isNull())
  1176. FunTy = PointeeTy->getAs<FunctionType>();
  1177. if (!FunTy)
  1178. FunTy = ExprTy->getAs<FunctionType>();
  1179. if (const FunctionProtoType *FPT =
  1180. dyn_cast_or_null<FunctionProtoType>(FunTy)) {
  1181. if (FPT->getNumParams() == 0)
  1182. ZeroArgCallReturnTy = FunTy->getReturnType();
  1183. return true;
  1184. }
  1185. return false;
  1186. }
  1187. /// \brief Give notes for a set of overloads.
  1188. ///
  1189. /// A companion to tryExprAsCall. In cases when the name that the programmer
  1190. /// wrote was an overloaded function, we may be able to make some guesses about
  1191. /// plausible overloads based on their return types; such guesses can be handed
  1192. /// off to this method to be emitted as notes.
  1193. ///
  1194. /// \param Overloads - The overloads to note.
  1195. /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
  1196. /// -fshow-overloads=best, this is the location to attach to the note about too
  1197. /// many candidates. Typically this will be the location of the original
  1198. /// ill-formed expression.
  1199. static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
  1200. const SourceLocation FinalNoteLoc) {
  1201. int ShownOverloads = 0;
  1202. int SuppressedOverloads = 0;
  1203. for (UnresolvedSetImpl::iterator It = Overloads.begin(),
  1204. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  1205. // FIXME: Magic number for max shown overloads stolen from
  1206. // OverloadCandidateSet::NoteCandidates.
  1207. if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
  1208. ++SuppressedOverloads;
  1209. continue;
  1210. }
  1211. NamedDecl *Fn = (*It)->getUnderlyingDecl();
  1212. if (!Fn->getLocation().isValid()) continue; // HLSL Change: skip built-in locations
  1213. S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
  1214. ++ShownOverloads;
  1215. }
  1216. if (SuppressedOverloads)
  1217. S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
  1218. << SuppressedOverloads;
  1219. }
  1220. static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
  1221. const UnresolvedSetImpl &Overloads,
  1222. bool (*IsPlausibleResult)(QualType)) {
  1223. if (!IsPlausibleResult)
  1224. return noteOverloads(S, Overloads, Loc);
  1225. UnresolvedSet<2> PlausibleOverloads;
  1226. for (OverloadExpr::decls_iterator It = Overloads.begin(),
  1227. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  1228. const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
  1229. QualType OverloadResultTy = OverloadDecl->getReturnType();
  1230. if (IsPlausibleResult(OverloadResultTy))
  1231. PlausibleOverloads.addDecl(It.getDecl());
  1232. }
  1233. noteOverloads(S, PlausibleOverloads, Loc);
  1234. }
  1235. /// Determine whether the given expression can be called by just
  1236. /// putting parentheses after it. Notably, expressions with unary
  1237. /// operators can't be because the unary operator will start parsing
  1238. /// outside the call.
  1239. static bool IsCallableWithAppend(Expr *E) {
  1240. E = E->IgnoreImplicit();
  1241. return (!isa<CStyleCastExpr>(E) &&
  1242. !isa<UnaryOperator>(E) &&
  1243. !isa<BinaryOperator>(E) &&
  1244. !isa<CXXOperatorCallExpr>(E));
  1245. }
  1246. bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
  1247. bool ForceComplain,
  1248. bool (*IsPlausibleResult)(QualType)) {
  1249. SourceLocation Loc = E.get()->getExprLoc();
  1250. SourceRange Range = E.get()->getSourceRange();
  1251. QualType ZeroArgCallTy;
  1252. UnresolvedSet<4> Overloads;
  1253. if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
  1254. !ZeroArgCallTy.isNull() &&
  1255. (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
  1256. // At this point, we know E is potentially callable with 0
  1257. // arguments and that it returns something of a reasonable type,
  1258. // so we can emit a fixit and carry on pretending that E was
  1259. // actually a CallExpr.
  1260. SourceLocation ParenInsertionLoc = PP.getLocForEndOfToken(Range.getEnd());
  1261. Diag(Loc, PD)
  1262. << /*zero-arg*/ 1 << Range
  1263. << (IsCallableWithAppend(E.get())
  1264. ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
  1265. : FixItHint());
  1266. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  1267. // FIXME: Try this before emitting the fixit, and suppress diagnostics
  1268. // while doing so.
  1269. E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
  1270. Range.getEnd().getLocWithOffset(1));
  1271. return true;
  1272. }
  1273. if (!ForceComplain) return false;
  1274. Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
  1275. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  1276. E = ExprError();
  1277. return true;
  1278. }
  1279. IdentifierInfo *Sema::getSuperIdentifier() const {
  1280. if (!Ident_super)
  1281. Ident_super = &Context.Idents.get("super");
  1282. return Ident_super;
  1283. }
  1284. IdentifierInfo *Sema::getFloat128Identifier() const {
  1285. if (!Ident___float128)
  1286. Ident___float128 = &Context.Idents.get("__float128");
  1287. return Ident___float128;
  1288. }
  1289. void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
  1290. CapturedRegionKind K) {
  1291. CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
  1292. getDiagnostics(), S, CD, RD, CD->getContextParam(), K);
  1293. CSI->ReturnType = Context.VoidTy;
  1294. FunctionScopes.push_back(CSI);
  1295. }
  1296. CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
  1297. if (FunctionScopes.empty())
  1298. return nullptr;
  1299. return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
  1300. }
  1301. const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
  1302. Sema::getMismatchingDeleteExpressions() const {
  1303. return DeleteExprs;
  1304. }