Bug Summary

File:tools/clang/lib/Sema/SemaDeclAttr.cpp
Warning:line 4119, column 53
Potential leak of memory pointed to by field 'DiagStorage'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclAttr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325118/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-14-150435-17243-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp

/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp

1//===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
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 decl-related attribute processing.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/Mangle.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/Basic/CharInfo.h"
26#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/DelayedDiagnostic.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/SemaInternal.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/Support/MathExtras.h"
38
39using namespace clang;
40using namespace sema;
41
42namespace AttributeLangSupport {
43 enum LANG {
44 C,
45 Cpp,
46 ObjC
47 };
48} // end namespace AttributeLangSupport
49
50//===----------------------------------------------------------------------===//
51// Helper functions
52//===----------------------------------------------------------------------===//
53
54/// isFunctionOrMethod - Return true if the given decl has function
55/// type (function or function-typed variable) or an Objective-C
56/// method.
57static bool isFunctionOrMethod(const Decl *D) {
58 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
59}
60
61/// \brief Return true if the given decl has function type (function or
62/// function-typed variable) or an Objective-C method or a block.
63static bool isFunctionOrMethodOrBlock(const Decl *D) {
64 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
65}
66
67/// Return true if the given decl has a declarator that should have
68/// been processed by Sema::GetTypeForDeclarator.
69static bool hasDeclarator(const Decl *D) {
70 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
71 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
72 isa<ObjCPropertyDecl>(D);
73}
74
75/// hasFunctionProto - Return true if the given decl has a argument
76/// information. This decl should have already passed
77/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
78static bool hasFunctionProto(const Decl *D) {
79 if (const FunctionType *FnTy = D->getFunctionType())
80 return isa<FunctionProtoType>(FnTy);
81 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
82}
83
84/// getFunctionOrMethodNumParams - Return number of function or method
85/// parameters. It is an error to call this on a K&R function (use
86/// hasFunctionProto first).
87static unsigned getFunctionOrMethodNumParams(const Decl *D) {
88 if (const FunctionType *FnTy = D->getFunctionType())
89 return cast<FunctionProtoType>(FnTy)->getNumParams();
90 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
91 return BD->getNumParams();
92 return cast<ObjCMethodDecl>(D)->param_size();
93}
94
95static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
96 if (const FunctionType *FnTy = D->getFunctionType())
97 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
98 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
99 return BD->getParamDecl(Idx)->getType();
100
101 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
102}
103
104static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
105 if (const auto *FD = dyn_cast<FunctionDecl>(D))
106 return FD->getParamDecl(Idx)->getSourceRange();
107 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
108 return MD->parameters()[Idx]->getSourceRange();
109 if (const auto *BD = dyn_cast<BlockDecl>(D))
110 return BD->getParamDecl(Idx)->getSourceRange();
111 return SourceRange();
112}
113
114static QualType getFunctionOrMethodResultType(const Decl *D) {
115 if (const FunctionType *FnTy = D->getFunctionType())
116 return cast<FunctionType>(FnTy)->getReturnType();
117 return cast<ObjCMethodDecl>(D)->getReturnType();
118}
119
120static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
121 if (const auto *FD = dyn_cast<FunctionDecl>(D))
122 return FD->getReturnTypeSourceRange();
123 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
124 return MD->getReturnTypeSourceRange();
125 return SourceRange();
126}
127
128static bool isFunctionOrMethodVariadic(const Decl *D) {
129 if (const FunctionType *FnTy = D->getFunctionType()) {
130 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
131 return proto->isVariadic();
132 }
133 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
134 return BD->isVariadic();
135
136 return cast<ObjCMethodDecl>(D)->isVariadic();
137}
138
139static bool isInstanceMethod(const Decl *D) {
140 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
141 return MethodDecl->isInstance();
142 return false;
143}
144
145static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
146 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
147 if (!PT)
148 return false;
149
150 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
151 if (!Cls)
152 return false;
153
154 IdentifierInfo* ClsName = Cls->getIdentifier();
155
156 // FIXME: Should we walk the chain of classes?
157 return ClsName == &Ctx.Idents.get("NSString") ||
158 ClsName == &Ctx.Idents.get("NSMutableString");
159}
160
161static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
162 const PointerType *PT = T->getAs<PointerType>();
163 if (!PT)
164 return false;
165
166 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
167 if (!RT)
168 return false;
169
170 const RecordDecl *RD = RT->getDecl();
171 if (RD->getTagKind() != TTK_Struct)
172 return false;
173
174 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
175}
176
177static unsigned getNumAttributeArgs(const AttributeList &Attr) {
178 // FIXME: Include the type in the argument list.
179 return Attr.getNumArgs() + Attr.hasParsedType();
180}
181
182template <typename Compare>
183static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
184 unsigned Num, unsigned Diag,
185 Compare Comp) {
186 if (Comp(getNumAttributeArgs(Attr), Num)) {
187 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
188 return false;
189 }
190
191 return true;
192}
193
194/// \brief Check if the attribute has exactly as many args as Num. May
195/// output an error.
196static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
197 unsigned Num) {
198 return checkAttributeNumArgsImpl(S, Attr, Num,
199 diag::err_attribute_wrong_number_arguments,
200 std::not_equal_to<unsigned>());
201}
202
203/// \brief Check if the attribute has at least as many args as Num. May
204/// output an error.
205static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
206 unsigned Num) {
207 return checkAttributeNumArgsImpl(S, Attr, Num,
208 diag::err_attribute_too_few_arguments,
209 std::less<unsigned>());
210}
211
212/// \brief Check if the attribute has at most as many args as Num. May
213/// output an error.
214static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
215 unsigned Num) {
216 return checkAttributeNumArgsImpl(S, Attr, Num,
217 diag::err_attribute_too_many_arguments,
218 std::greater<unsigned>());
219}
220
221/// \brief A helper function to provide Attribute Location for the Attr types
222/// AND the AttributeList.
223template <typename AttrInfo>
224static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
225 SourceLocation>::type
226getAttrLoc(const AttrInfo &Attr) {
227 return Attr.getLocation();
228}
229static SourceLocation getAttrLoc(const clang::AttributeList &Attr) {
230 return Attr.getLoc();
231}
232
233/// \brief A helper function to provide Attribute Name for the Attr types
234/// AND the AttributeList.
235template <typename AttrInfo>
236static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
237 const AttrInfo *>::type
238getAttrName(const AttrInfo &Attr) {
239 return &Attr;
240}
241static const IdentifierInfo *getAttrName(const clang::AttributeList &Attr) {
242 return Attr.getName();
243}
244
245/// \brief If Expr is a valid integer constant, get the value of the integer
246/// expression and return success or failure. May output an error.
247template<typename AttrInfo>
248static bool checkUInt32Argument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
249 uint32_t &Val, unsigned Idx = UINT_MAX(2147483647 *2U +1U)) {
250 llvm::APSInt I(32);
251 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
252 !Expr->isIntegerConstantExpr(I, S.Context)) {
253 if (Idx != UINT_MAX(2147483647 *2U +1U))
254 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
255 << getAttrName(Attr) << Idx << AANT_ArgumentIntegerConstant
256 << Expr->getSourceRange();
257 else
258 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_type)
259 << getAttrName(Attr) << AANT_ArgumentIntegerConstant
260 << Expr->getSourceRange();
261 return false;
262 }
263
264 if (!I.isIntN(32)) {
265 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
266 << I.toString(10, false) << 32 << /* Unsigned */ 1;
267 return false;
268 }
269
270 Val = (uint32_t)I.getZExtValue();
271 return true;
272}
273
274/// \brief Wrapper around checkUInt32Argument, with an extra check to be sure
275/// that the result will fit into a regular (signed) int. All args have the same
276/// purpose as they do in checkUInt32Argument.
277template<typename AttrInfo>
278static bool checkPositiveIntArgument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
279 int &Val, unsigned Idx = UINT_MAX(2147483647 *2U +1U)) {
280 uint32_t UVal;
281 if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx))
282 return false;
283
284 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
285 llvm::APSInt I(32); // for toString
286 I = UVal;
287 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
288 << I.toString(10, false) << 32 << /* Unsigned */ 0;
289 return false;
290 }
291
292 Val = UVal;
293 return true;
294}
295
296/// \brief Diagnose mutually exclusive attributes when present on a given
297/// declaration. Returns true if diagnosed.
298template <typename AttrTy>
299static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
300 IdentifierInfo *Ident) {
301 if (AttrTy *A = D->getAttr<AttrTy>()) {
302 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
303 << A;
304 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
305 return true;
306 }
307 return false;
308}
309
310/// \brief Check if IdxExpr is a valid parameter index for a function or
311/// instance method D. May output an error.
312///
313/// \returns true if IdxExpr is a valid index.
314template <typename AttrInfo>
315static bool checkFunctionOrMethodParameterIndex(
316 Sema &S, const Decl *D, const AttrInfo &Attr, unsigned AttrArgNum,
317 const Expr *IdxExpr, uint64_t &Idx, bool AllowImplicitThis = false) {
318 assert(isFunctionOrMethodOrBlock(D))(static_cast <bool> (isFunctionOrMethodOrBlock(D)) ? void
(0) : __assert_fail ("isFunctionOrMethodOrBlock(D)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 318, __extension__ __PRETTY_FUNCTION__))
;
319
320 // In C++ the implicit 'this' function parameter also counts.
321 // Parameters are counted from one.
322 bool HP = hasFunctionProto(D);
323 bool HasImplicitThisParam = isInstanceMethod(D);
324 bool IV = HP && isFunctionOrMethodVariadic(D);
325 unsigned NumParams =
326 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
327
328 llvm::APSInt IdxInt;
329 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
330 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
331 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
332 << getAttrName(Attr) << AttrArgNum << AANT_ArgumentIntegerConstant
333 << IdxExpr->getSourceRange();
334 return false;
335 }
336
337 Idx = IdxInt.getLimitedValue();
338 if (Idx < 1 || (!IV && Idx > NumParams)) {
339 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_out_of_bounds)
340 << getAttrName(Attr) << AttrArgNum << IdxExpr->getSourceRange();
341 return false;
342 }
343 Idx--; // Convert to zero-based.
344 if (HasImplicitThisParam && !AllowImplicitThis) {
345 if (Idx == 0) {
346 S.Diag(getAttrLoc(Attr),
347 diag::err_attribute_invalid_implicit_this_argument)
348 << getAttrName(Attr) << IdxExpr->getSourceRange();
349 return false;
350 }
351 --Idx;
352 }
353
354 return true;
355}
356
357/// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
358/// If not emit an error and return false. If the argument is an identifier it
359/// will emit an error with a fixit hint and treat it as if it was a string
360/// literal.
361bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
362 unsigned ArgNum, StringRef &Str,
363 SourceLocation *ArgLocation) {
364 // Look for identifiers. If we have one emit a hint to fix it to a literal.
365 if (Attr.isArgIdent(ArgNum)) {
366 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
367 Diag(Loc->Loc, diag::err_attribute_argument_type)
368 << Attr.getName() << AANT_ArgumentString
369 << FixItHint::CreateInsertion(Loc->Loc, "\"")
370 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
371 Str = Loc->Ident->getName();
372 if (ArgLocation)
373 *ArgLocation = Loc->Loc;
374 return true;
375 }
376
377 // Now check for an actual string literal.
378 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
379 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
380 if (ArgLocation)
381 *ArgLocation = ArgExpr->getLocStart();
382
383 if (!Literal || !Literal->isAscii()) {
384 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
385 << Attr.getName() << AANT_ArgumentString;
386 return false;
387 }
388
389 Str = Literal->getString();
390 return true;
391}
392
393/// \brief Applies the given attribute to the Decl without performing any
394/// additional semantic checking.
395template <typename AttrType>
396static void handleSimpleAttribute(Sema &S, Decl *D,
397 const AttributeList &Attr) {
398 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
399 Attr.getAttributeSpellingListIndex()));
400}
401
402template <typename AttrType>
403static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
404 const AttributeList &Attr) {
405 handleSimpleAttribute<AttrType>(S, D, Attr);
406}
407
408/// \brief Applies the given attribute to the Decl so long as the Decl doesn't
409/// already have one of the given incompatible attributes.
410template <typename AttrType, typename IncompatibleAttrType,
411 typename... IncompatibleAttrTypes>
412static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
413 const AttributeList &Attr) {
414 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
415 Attr.getName()))
416 return;
417 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
418 Attr);
419}
420
421/// \brief Check if the passed-in expression is of type int or bool.
422static bool isIntOrBool(Expr *Exp) {
423 QualType QT = Exp->getType();
424 return QT->isBooleanType() || QT->isIntegerType();
425}
426
427
428// Check to see if the type is a smart pointer of some kind. We assume
429// it's a smart pointer if it defines both operator-> and operator*.
430static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
431 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
432 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
433 if (Res1.empty())
434 return false;
435
436 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
437 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
438 if (Res2.empty())
439 return false;
440
441 return true;
442}
443
444/// \brief Check if passed in Decl is a pointer type.
445/// Note that this function may produce an error message.
446/// \return true if the Decl is a pointer type; false otherwise
447static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
448 const AttributeList &Attr) {
449 const ValueDecl *vd = cast<ValueDecl>(D);
450 QualType QT = vd->getType();
451 if (QT->isAnyPointerType())
452 return true;
453
454 if (const RecordType *RT = QT->getAs<RecordType>()) {
455 // If it's an incomplete type, it could be a smart pointer; skip it.
456 // (We don't want to force template instantiation if we can avoid it,
457 // since that would alter the order in which templates are instantiated.)
458 if (RT->isIncompleteType())
459 return true;
460
461 if (threadSafetyCheckIsSmartPointer(S, RT))
462 return true;
463 }
464
465 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
466 << Attr.getName() << QT;
467 return false;
468}
469
470/// \brief Checks that the passed in QualType either is of RecordType or points
471/// to RecordType. Returns the relevant RecordType, null if it does not exit.
472static const RecordType *getRecordType(QualType QT) {
473 if (const RecordType *RT = QT->getAs<RecordType>())
474 return RT;
475
476 // Now check if we point to record type.
477 if (const PointerType *PT = QT->getAs<PointerType>())
478 return PT->getPointeeType()->getAs<RecordType>();
479
480 return nullptr;
481}
482
483static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
484 const RecordType *RT = getRecordType(Ty);
485
486 if (!RT)
487 return false;
488
489 // Don't check for the capability if the class hasn't been defined yet.
490 if (RT->isIncompleteType())
491 return true;
492
493 // Allow smart pointers to be used as capability objects.
494 // FIXME -- Check the type that the smart pointer points to.
495 if (threadSafetyCheckIsSmartPointer(S, RT))
496 return true;
497
498 // Check if the record itself has a capability.
499 RecordDecl *RD = RT->getDecl();
500 if (RD->hasAttr<CapabilityAttr>())
501 return true;
502
503 // Else check if any base classes have a capability.
504 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
505 CXXBasePaths BPaths(false, false);
506 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
507 const auto *Type = BS->getType()->getAs<RecordType>();
508 return Type->getDecl()->hasAttr<CapabilityAttr>();
509 }, BPaths))
510 return true;
511 }
512 return false;
513}
514
515static bool checkTypedefTypeForCapability(QualType Ty) {
516 const auto *TD = Ty->getAs<TypedefType>();
517 if (!TD)
518 return false;
519
520 TypedefNameDecl *TN = TD->getDecl();
521 if (!TN)
522 return false;
523
524 return TN->hasAttr<CapabilityAttr>();
525}
526
527static bool typeHasCapability(Sema &S, QualType Ty) {
528 if (checkTypedefTypeForCapability(Ty))
529 return true;
530
531 if (checkRecordTypeForCapability(S, Ty))
532 return true;
533
534 return false;
535}
536
537static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
538 // Capability expressions are simple expressions involving the boolean logic
539 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
540 // a DeclRefExpr is found, its type should be checked to determine whether it
541 // is a capability or not.
542
543 if (const auto *E = dyn_cast<CastExpr>(Ex))
544 return isCapabilityExpr(S, E->getSubExpr());
545 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
546 return isCapabilityExpr(S, E->getSubExpr());
547 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
548 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
549 E->getOpcode() == UO_Deref)
550 return isCapabilityExpr(S, E->getSubExpr());
551 return false;
552 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
553 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
554 return isCapabilityExpr(S, E->getLHS()) &&
555 isCapabilityExpr(S, E->getRHS());
556 return false;
557 }
558
559 return typeHasCapability(S, Ex->getType());
560}
561
562/// \brief Checks that all attribute arguments, starting from Sidx, resolve to
563/// a capability object.
564/// \param Sidx The attribute argument index to start checking with.
565/// \param ParamIdxOk Whether an argument can be indexing into a function
566/// parameter list.
567static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
568 const AttributeList &Attr,
569 SmallVectorImpl<Expr *> &Args,
570 int Sidx = 0,
571 bool ParamIdxOk = false) {
572 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
573 Expr *ArgExp = Attr.getArgAsExpr(Idx);
574
575 if (ArgExp->isTypeDependent()) {
576 // FIXME -- need to check this again on template instantiation
577 Args.push_back(ArgExp);
578 continue;
579 }
580
581 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
582 if (StrLit->getLength() == 0 ||
583 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
584 // Pass empty strings to the analyzer without warnings.
585 // Treat "*" as the universal lock.
586 Args.push_back(ArgExp);
587 continue;
588 }
589
590 // We allow constant strings to be used as a placeholder for expressions
591 // that are not valid C++ syntax, but warn that they are ignored.
592 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
593 Attr.getName();
594 Args.push_back(ArgExp);
595 continue;
596 }
597
598 QualType ArgTy = ArgExp->getType();
599
600 // A pointer to member expression of the form &MyClass::mu is treated
601 // specially -- we need to look at the type of the member.
602 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
603 if (UOp->getOpcode() == UO_AddrOf)
604 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
605 if (DRE->getDecl()->isCXXInstanceMember())
606 ArgTy = DRE->getDecl()->getType();
607
608 // First see if we can just cast to record type, or pointer to record type.
609 const RecordType *RT = getRecordType(ArgTy);
610
611 // Now check if we index into a record type function param.
612 if(!RT && ParamIdxOk) {
613 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
614 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
615 if(FD && IL) {
616 unsigned int NumParams = FD->getNumParams();
617 llvm::APInt ArgValue = IL->getValue();
618 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
619 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
620 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
621 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
622 << Attr.getName() << Idx + 1 << NumParams;
623 continue;
624 }
625 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
626 }
627 }
628
629 // If the type does not have a capability, see if the components of the
630 // expression have capabilities. This allows for writing C code where the
631 // capability may be on the type, and the expression is a capability
632 // boolean logic expression. Eg) requires_capability(A || B && !C)
633 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
634 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
635 << Attr.getName() << ArgTy;
636
637 Args.push_back(ArgExp);
638 }
639}
640
641//===----------------------------------------------------------------------===//
642// Attribute Implementations
643//===----------------------------------------------------------------------===//
644
645static void handlePtGuardedVarAttr(Sema &S, Decl *D,
646 const AttributeList &Attr) {
647 if (!threadSafetyCheckIsPointer(S, D, Attr))
648 return;
649
650 D->addAttr(::new (S.Context)
651 PtGuardedVarAttr(Attr.getRange(), S.Context,
652 Attr.getAttributeSpellingListIndex()));
653}
654
655static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
656 const AttributeList &Attr,
657 Expr* &Arg) {
658 SmallVector<Expr*, 1> Args;
659 // check that all arguments are lockable objects
660 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
661 unsigned Size = Args.size();
662 if (Size != 1)
663 return false;
664
665 Arg = Args[0];
666
667 return true;
668}
669
670static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
671 Expr *Arg = nullptr;
672 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
673 return;
674
675 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
676 Attr.getAttributeSpellingListIndex()));
677}
678
679static void handlePtGuardedByAttr(Sema &S, Decl *D,
680 const AttributeList &Attr) {
681 Expr *Arg = nullptr;
682 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
683 return;
684
685 if (!threadSafetyCheckIsPointer(S, D, Attr))
686 return;
687
688 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
689 S.Context, Arg,
690 Attr.getAttributeSpellingListIndex()));
691}
692
693static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
694 const AttributeList &Attr,
695 SmallVectorImpl<Expr *> &Args) {
696 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
697 return false;
698
699 // Check that this attribute only applies to lockable types.
700 QualType QT = cast<ValueDecl>(D)->getType();
701 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
702 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
703 << Attr.getName();
704 return false;
705 }
706
707 // Check that all arguments are lockable objects.
708 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
709 if (Args.empty())
710 return false;
711
712 return true;
713}
714
715static void handleAcquiredAfterAttr(Sema &S, Decl *D,
716 const AttributeList &Attr) {
717 SmallVector<Expr*, 1> Args;
718 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
719 return;
720
721 Expr **StartArg = &Args[0];
722 D->addAttr(::new (S.Context)
723 AcquiredAfterAttr(Attr.getRange(), S.Context,
724 StartArg, Args.size(),
725 Attr.getAttributeSpellingListIndex()));
726}
727
728static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
729 const AttributeList &Attr) {
730 SmallVector<Expr*, 1> Args;
731 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
732 return;
733
734 Expr **StartArg = &Args[0];
735 D->addAttr(::new (S.Context)
736 AcquiredBeforeAttr(Attr.getRange(), S.Context,
737 StartArg, Args.size(),
738 Attr.getAttributeSpellingListIndex()));
739}
740
741static bool checkLockFunAttrCommon(Sema &S, Decl *D,
742 const AttributeList &Attr,
743 SmallVectorImpl<Expr *> &Args) {
744 // zero or more arguments ok
745 // check that all arguments are lockable objects
746 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
747
748 return true;
749}
750
751static void handleAssertSharedLockAttr(Sema &S, Decl *D,
752 const AttributeList &Attr) {
753 SmallVector<Expr*, 1> Args;
754 if (!checkLockFunAttrCommon(S, D, Attr, Args))
755 return;
756
757 unsigned Size = Args.size();
758 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
759 D->addAttr(::new (S.Context)
760 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
761 Attr.getAttributeSpellingListIndex()));
762}
763
764static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
765 const AttributeList &Attr) {
766 SmallVector<Expr*, 1> Args;
767 if (!checkLockFunAttrCommon(S, D, Attr, Args))
768 return;
769
770 unsigned Size = Args.size();
771 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
772 D->addAttr(::new (S.Context)
773 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
774 StartArg, Size,
775 Attr.getAttributeSpellingListIndex()));
776}
777
778/// \brief Checks to be sure that the given parameter number is in bounds, and is
779/// an integral type. Will emit appropriate diagnostics if this returns
780/// false.
781///
782/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
783/// to actually retrieve the argument, so it's base-0.
784template <typename AttrInfo>
785static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
786 const AttrInfo &Attr, Expr *AttrArg,
787 unsigned FuncParamNo, unsigned AttrArgNo,
788 bool AllowDependentType = false) {
789 uint64_t Idx;
790 if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo, AttrArg,
791 Idx))
792 return false;
793
794 const ParmVarDecl *Param = FD->getParamDecl(Idx);
795 if (AllowDependentType && Param->getType()->isDependentType())
796 return true;
797 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
798 SourceLocation SrcLoc = AttrArg->getLocStart();
799 S.Diag(SrcLoc, diag::err_attribute_integers_only)
800 << getAttrName(Attr) << Param->getSourceRange();
801 return false;
802 }
803 return true;
804}
805
806/// \brief Checks to be sure that the given parameter number is in bounds, and is
807/// an integral type. Will emit appropriate diagnostics if this returns false.
808///
809/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
810/// to actually retrieve the argument, so it's base-0.
811static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
812 const AttributeList &Attr,
813 unsigned FuncParamNo, unsigned AttrArgNo,
814 bool AllowDependentType = false) {
815 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument")(static_cast <bool> (Attr.isArgExpr(AttrArgNo) &&
"Expected expression argument") ? void (0) : __assert_fail (
"Attr.isArgExpr(AttrArgNo) && \"Expected expression argument\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 815, __extension__ __PRETTY_FUNCTION__))
;
816 return checkParamIsIntegerType(S, FD, Attr, Attr.getArgAsExpr(AttrArgNo),
817 FuncParamNo, AttrArgNo, AllowDependentType);
818}
819
820static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
821 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
822 !checkAttributeAtMostNumArgs(S, Attr, 2))
823 return;
824
825 const auto *FD = cast<FunctionDecl>(D);
826 if (!FD->getReturnType()->isPointerType()) {
827 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
828 << Attr.getName();
829 return;
830 }
831
832 const Expr *SizeExpr = Attr.getArgAsExpr(0);
833 int SizeArgNo;
834 // Parameter indices are 1-indexed, hence Index=1
835 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1))
836 return;
837
838 if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0))
839 return;
840
841 // Args are 1-indexed, so 0 implies that the arg was not present
842 int NumberArgNo = 0;
843 if (Attr.getNumArgs() == 2) {
844 const Expr *NumberExpr = Attr.getArgAsExpr(1);
845 // Parameter indices are 1-based, hence Index=2
846 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo,
847 /*Index=*/2))
848 return;
849
850 if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1))
851 return;
852 }
853
854 D->addAttr(::new (S.Context) AllocSizeAttr(
855 Attr.getRange(), S.Context, SizeArgNo, NumberArgNo,
856 Attr.getAttributeSpellingListIndex()));
857}
858
859static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
860 const AttributeList &Attr,
861 SmallVectorImpl<Expr *> &Args) {
862 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
863 return false;
864
865 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
866 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
867 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
868 return false;
869 }
870
871 // check that all arguments are lockable objects
872 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
873
874 return true;
875}
876
877static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
878 const AttributeList &Attr) {
879 SmallVector<Expr*, 2> Args;
880 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
881 return;
882
883 D->addAttr(::new (S.Context)
884 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
885 Attr.getArgAsExpr(0),
886 Args.data(), Args.size(),
887 Attr.getAttributeSpellingListIndex()));
888}
889
890static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
891 const AttributeList &Attr) {
892 SmallVector<Expr*, 2> Args;
893 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
894 return;
895
896 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
897 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
898 Args.size(), Attr.getAttributeSpellingListIndex()));
899}
900
901static void handleLockReturnedAttr(Sema &S, Decl *D,
902 const AttributeList &Attr) {
903 // check that the argument is lockable object
904 SmallVector<Expr*, 1> Args;
905 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
906 unsigned Size = Args.size();
907 if (Size == 0)
908 return;
909
910 D->addAttr(::new (S.Context)
911 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
912 Attr.getAttributeSpellingListIndex()));
913}
914
915static void handleLocksExcludedAttr(Sema &S, Decl *D,
916 const AttributeList &Attr) {
917 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
918 return;
919
920 // check that all arguments are lockable objects
921 SmallVector<Expr*, 1> Args;
922 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
923 unsigned Size = Args.size();
924 if (Size == 0)
925 return;
926 Expr **StartArg = &Args[0];
927
928 D->addAttr(::new (S.Context)
929 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
930 Attr.getAttributeSpellingListIndex()));
931}
932
933static bool checkFunctionConditionAttr(Sema &S, Decl *D,
934 const AttributeList &Attr,
935 Expr *&Cond, StringRef &Msg) {
936 Cond = Attr.getArgAsExpr(0);
937 if (!Cond->isTypeDependent()) {
938 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
939 if (Converted.isInvalid())
940 return false;
941 Cond = Converted.get();
942 }
943
944 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
945 return false;
946
947 if (Msg.empty())
948 Msg = "<no message provided>";
949
950 SmallVector<PartialDiagnosticAt, 8> Diags;
951 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
952 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
953 Diags)) {
954 S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr)
955 << Attr.getName();
956 for (const PartialDiagnosticAt &PDiag : Diags)
957 S.Diag(PDiag.first, PDiag.second);
958 return false;
959 }
960 return true;
961}
962
963static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
964 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
965
966 Expr *Cond;
967 StringRef Msg;
968 if (checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
969 D->addAttr(::new (S.Context)
970 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
971 Attr.getAttributeSpellingListIndex()));
972}
973
974namespace {
975/// Determines if a given Expr references any of the given function's
976/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
977class ArgumentDependenceChecker
978 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
979#ifndef NDEBUG
980 const CXXRecordDecl *ClassType;
981#endif
982 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
983 bool Result;
984
985public:
986 ArgumentDependenceChecker(const FunctionDecl *FD) {
987#ifndef NDEBUG
988 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
989 ClassType = MD->getParent();
990 else
991 ClassType = nullptr;
992#endif
993 Parms.insert(FD->param_begin(), FD->param_end());
994 }
995
996 bool referencesArgs(Expr *E) {
997 Result = false;
998 TraverseStmt(E);
999 return Result;
1000 }
1001
1002 bool VisitCXXThisExpr(CXXThisExpr *E) {
1003 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&(static_cast <bool> (E->getType()->getPointeeCXXRecordDecl
() == ClassType && "`this` doesn't refer to the enclosing class?"
) ? void (0) : __assert_fail ("E->getType()->getPointeeCXXRecordDecl() == ClassType && \"`this` doesn't refer to the enclosing class?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 1004, __extension__ __PRETTY_FUNCTION__))
1004 "`this` doesn't refer to the enclosing class?")(static_cast <bool> (E->getType()->getPointeeCXXRecordDecl
() == ClassType && "`this` doesn't refer to the enclosing class?"
) ? void (0) : __assert_fail ("E->getType()->getPointeeCXXRecordDecl() == ClassType && \"`this` doesn't refer to the enclosing class?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 1004, __extension__ __PRETTY_FUNCTION__))
;
1005 Result = true;
1006 return false;
1007 }
1008
1009 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1010 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1011 if (Parms.count(PVD)) {
1012 Result = true;
1013 return false;
1014 }
1015 return true;
1016 }
1017};
1018}
1019
1020static void handleDiagnoseIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1021 S.Diag(Attr.getLoc(), diag::ext_clang_diagnose_if);
1022
1023 Expr *Cond;
1024 StringRef Msg;
1025 if (!checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
1026 return;
1027
1028 StringRef DiagTypeStr;
1029 if (!S.checkStringLiteralArgumentAttr(Attr, 2, DiagTypeStr))
1030 return;
1031
1032 DiagnoseIfAttr::DiagnosticType DiagType;
1033 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1034 S.Diag(Attr.getArgAsExpr(2)->getLocStart(),
1035 diag::err_diagnose_if_invalid_diagnostic_type);
1036 return;
1037 }
1038
1039 bool ArgDependent = false;
1040 if (const auto *FD = dyn_cast<FunctionDecl>(D))
1041 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1042 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1043 Attr.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D),
1044 Attr.getAttributeSpellingListIndex()));
1045}
1046
1047static void handlePassObjectSizeAttr(Sema &S, Decl *D,
1048 const AttributeList &Attr) {
1049 if (D->hasAttr<PassObjectSizeAttr>()) {
1050 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
1051 << Attr.getName();
1052 return;
1053 }
1054
1055 Expr *E = Attr.getArgAsExpr(0);
1056 uint32_t Type;
1057 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
1058 return;
1059
1060 // pass_object_size's argument is passed in as the second argument of
1061 // __builtin_object_size. So, it has the same constraints as that second
1062 // argument; namely, it must be in the range [0, 3].
1063 if (Type > 3) {
1064 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
1065 << Attr.getName() << 0 << 3 << E->getSourceRange();
1066 return;
1067 }
1068
1069 // pass_object_size is only supported on constant pointer parameters; as a
1070 // kindness to users, we allow the parameter to be non-const for declarations.
1071 // At this point, we have no clue if `D` belongs to a function declaration or
1072 // definition, so we defer the constness check until later.
1073 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1074 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
1075 << Attr.getName() << 1;
1076 return;
1077 }
1078
1079 D->addAttr(::new (S.Context)
1080 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
1081 Attr.getAttributeSpellingListIndex()));
1082}
1083
1084static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1085 ConsumableAttr::ConsumedState DefaultState;
1086
1087 if (Attr.isArgIdent(0)) {
1088 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1089 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1090 DefaultState)) {
1091 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1092 << Attr.getName() << IL->Ident;
1093 return;
1094 }
1095 } else {
1096 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1097 << Attr.getName() << AANT_ArgumentIdentifier;
1098 return;
1099 }
1100
1101 D->addAttr(::new (S.Context)
1102 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
1103 Attr.getAttributeSpellingListIndex()));
1104}
1105
1106static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1107 const AttributeList &Attr) {
1108 ASTContext &CurrContext = S.getASTContext();
1109 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1110
1111 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1112 if (!RD->hasAttr<ConsumableAttr>()) {
1113 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1114 RD->getNameAsString();
1115
1116 return false;
1117 }
1118 }
1119
1120 return true;
1121}
1122
1123static void handleCallableWhenAttr(Sema &S, Decl *D,
1124 const AttributeList &Attr) {
1125 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1126 return;
1127
1128 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1129 return;
1130
1131 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1132 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1133 CallableWhenAttr::ConsumedState CallableState;
1134
1135 StringRef StateString;
1136 SourceLocation Loc;
1137 if (Attr.isArgIdent(ArgIndex)) {
1138 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
1139 StateString = Ident->Ident->getName();
1140 Loc = Ident->Loc;
1141 } else {
1142 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1143 return;
1144 }
1145
1146 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1147 CallableState)) {
1148 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1149 << Attr.getName() << StateString;
1150 return;
1151 }
1152
1153 States.push_back(CallableState);
1154 }
1155
1156 D->addAttr(::new (S.Context)
1157 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1158 States.size(), Attr.getAttributeSpellingListIndex()));
1159}
1160
1161static void handleParamTypestateAttr(Sema &S, Decl *D,
1162 const AttributeList &Attr) {
1163 ParamTypestateAttr::ConsumedState ParamState;
1164
1165 if (Attr.isArgIdent(0)) {
1166 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1167 StringRef StateString = Ident->Ident->getName();
1168
1169 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1170 ParamState)) {
1171 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1172 << Attr.getName() << StateString;
1173 return;
1174 }
1175 } else {
1176 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1177 Attr.getName() << AANT_ArgumentIdentifier;
1178 return;
1179 }
1180
1181 // FIXME: This check is currently being done in the analysis. It can be
1182 // enabled here only after the parser propagates attributes at
1183 // template specialization definition, not declaration.
1184 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1185 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1186 //
1187 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1188 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1189 // ReturnType.getAsString();
1190 // return;
1191 //}
1192
1193 D->addAttr(::new (S.Context)
1194 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
1195 Attr.getAttributeSpellingListIndex()));
1196}
1197
1198static void handleReturnTypestateAttr(Sema &S, Decl *D,
1199 const AttributeList &Attr) {
1200 ReturnTypestateAttr::ConsumedState ReturnState;
1201
1202 if (Attr.isArgIdent(0)) {
1203 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1204 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1205 ReturnState)) {
1206 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1207 << Attr.getName() << IL->Ident;
1208 return;
1209 }
1210 } else {
1211 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1212 Attr.getName() << AANT_ArgumentIdentifier;
1213 return;
1214 }
1215
1216 // FIXME: This check is currently being done in the analysis. It can be
1217 // enabled here only after the parser propagates attributes at
1218 // template specialization definition, not declaration.
1219 //QualType ReturnType;
1220 //
1221 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1222 // ReturnType = Param->getType();
1223 //
1224 //} else if (const CXXConstructorDecl *Constructor =
1225 // dyn_cast<CXXConstructorDecl>(D)) {
1226 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1227 //
1228 //} else {
1229 //
1230 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1231 //}
1232 //
1233 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1234 //
1235 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1236 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1237 // ReturnType.getAsString();
1238 // return;
1239 //}
1240
1241 D->addAttr(::new (S.Context)
1242 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1243 Attr.getAttributeSpellingListIndex()));
1244}
1245
1246static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1247 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1248 return;
1249
1250 SetTypestateAttr::ConsumedState NewState;
1251 if (Attr.isArgIdent(0)) {
1252 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1253 StringRef Param = Ident->Ident->getName();
1254 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1255 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1256 << Attr.getName() << Param;
1257 return;
1258 }
1259 } else {
1260 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1261 Attr.getName() << AANT_ArgumentIdentifier;
1262 return;
1263 }
1264
1265 D->addAttr(::new (S.Context)
1266 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1267 Attr.getAttributeSpellingListIndex()));
1268}
1269
1270static void handleTestTypestateAttr(Sema &S, Decl *D,
1271 const AttributeList &Attr) {
1272 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1273 return;
1274
1275 TestTypestateAttr::ConsumedState TestState;
1276 if (Attr.isArgIdent(0)) {
1277 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1278 StringRef Param = Ident->Ident->getName();
1279 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1280 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1281 << Attr.getName() << Param;
1282 return;
1283 }
1284 } else {
1285 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1286 Attr.getName() << AANT_ArgumentIdentifier;
1287 return;
1288 }
1289
1290 D->addAttr(::new (S.Context)
1291 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1292 Attr.getAttributeSpellingListIndex()));
1293}
1294
1295static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1296 const AttributeList &Attr) {
1297 // Remember this typedef decl, we will need it later for diagnostics.
1298 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1299}
1300
1301static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1302 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1303 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1304 Attr.getAttributeSpellingListIndex()));
1305 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1306 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1307 !FD->getType()->isIncompleteType() &&
1308 FD->isBitField() &&
1309 S.Context.getTypeAlign(FD->getType()) <= 8);
1310
1311 if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1312 if (BitfieldByteAligned)
1313 // The PS4 target needs to maintain ABI backwards compatibility.
1314 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1315 << Attr.getName() << FD->getType();
1316 else
1317 FD->addAttr(::new (S.Context) PackedAttr(
1318 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1319 } else {
1320 // Report warning about changed offset in the newer compiler versions.
1321 if (BitfieldByteAligned)
1322 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1323
1324 FD->addAttr(::new (S.Context) PackedAttr(
1325 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1326 }
1327
1328 } else
1329 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1330}
1331
1332static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1333 // The IBOutlet/IBOutletCollection attributes only apply to instance
1334 // variables or properties of Objective-C classes. The outlet must also
1335 // have an object reference type.
1336 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1337 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1338 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1339 << Attr.getName() << VD->getType() << 0;
1340 return false;
1341 }
1342 }
1343 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1344 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1345 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1346 << Attr.getName() << PD->getType() << 1;
1347 return false;
1348 }
1349 }
1350 else {
1351 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1352 return false;
1353 }
1354
1355 return true;
1356}
1357
1358static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1359 if (!checkIBOutletCommon(S, D, Attr))
1360 return;
1361
1362 D->addAttr(::new (S.Context)
1363 IBOutletAttr(Attr.getRange(), S.Context,
1364 Attr.getAttributeSpellingListIndex()));
1365}
1366
1367static void handleIBOutletCollection(Sema &S, Decl *D,
1368 const AttributeList &Attr) {
1369
1370 // The iboutletcollection attribute can have zero or one arguments.
1371 if (Attr.getNumArgs() > 1) {
1372 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1373 << Attr.getName() << 1;
1374 return;
1375 }
1376
1377 if (!checkIBOutletCommon(S, D, Attr))
1378 return;
1379
1380 ParsedType PT;
1381
1382 if (Attr.hasParsedType())
1383 PT = Attr.getTypeArg();
1384 else {
1385 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1386 S.getScopeForContext(D->getDeclContext()->getParent()));
1387 if (!PT) {
1388 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1389 return;
1390 }
1391 }
1392
1393 TypeSourceInfo *QTLoc = nullptr;
1394 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1395 if (!QTLoc)
1396 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1397
1398 // Diagnose use of non-object type in iboutletcollection attribute.
1399 // FIXME. Gnu attribute extension ignores use of builtin types in
1400 // attributes. So, __attribute__((iboutletcollection(char))) will be
1401 // treated as __attribute__((iboutletcollection())).
1402 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1403 S.Diag(Attr.getLoc(),
1404 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1405 : diag::err_iboutletcollection_type) << QT;
1406 return;
1407 }
1408
1409 D->addAttr(::new (S.Context)
1410 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1411 Attr.getAttributeSpellingListIndex()));
1412}
1413
1414bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1415 if (RefOkay) {
1416 if (T->isReferenceType())
1417 return true;
1418 } else {
1419 T = T.getNonReferenceType();
1420 }
1421
1422 // The nonnull attribute, and other similar attributes, can be applied to a
1423 // transparent union that contains a pointer type.
1424 if (const RecordType *UT = T->getAsUnionType()) {
1425 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1426 RecordDecl *UD = UT->getDecl();
1427 for (const auto *I : UD->fields()) {
1428 QualType QT = I->getType();
1429 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1430 return true;
1431 }
1432 }
1433 }
1434
1435 return T->isAnyPointerType() || T->isBlockPointerType();
1436}
1437
1438static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1439 SourceRange AttrParmRange,
1440 SourceRange TypeRange,
1441 bool isReturnValue = false) {
1442 if (!S.isValidPointerAttrType(T)) {
1443 if (isReturnValue)
1444 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1445 << Attr.getName() << AttrParmRange << TypeRange;
1446 else
1447 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1448 << Attr.getName() << AttrParmRange << TypeRange << 0;
1449 return false;
1450 }
1451 return true;
1452}
1453
1454static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1455 SmallVector<unsigned, 8> NonNullArgs;
1456 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1457 Expr *Ex = Attr.getArgAsExpr(I);
1458 uint64_t Idx;
1459 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1460 return;
1461
1462 // Is the function argument a pointer type?
1463 if (Idx < getFunctionOrMethodNumParams(D) &&
1464 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1465 Ex->getSourceRange(),
1466 getFunctionOrMethodParamRange(D, Idx)))
1467 continue;
1468
1469 NonNullArgs.push_back(Idx);
1470 }
1471
1472 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1473 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1474 // check if the attribute came from a macro expansion or a template
1475 // instantiation.
1476 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1477 !S.inTemplateInstantiation()) {
1478 bool AnyPointers = isFunctionOrMethodVariadic(D);
1479 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1480 I != E && !AnyPointers; ++I) {
1481 QualType T = getFunctionOrMethodParamType(D, I);
1482 if (T->isDependentType() || S.isValidPointerAttrType(T))
1483 AnyPointers = true;
1484 }
1485
1486 if (!AnyPointers)
1487 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1488 }
1489
1490 unsigned *Start = NonNullArgs.data();
1491 unsigned Size = NonNullArgs.size();
1492 llvm::array_pod_sort(Start, Start + Size);
1493 D->addAttr(::new (S.Context)
1494 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1495 Attr.getAttributeSpellingListIndex()));
1496}
1497
1498static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1499 const AttributeList &Attr) {
1500 if (Attr.getNumArgs() > 0) {
1501 if (D->getFunctionType()) {
1502 handleNonNullAttr(S, D, Attr);
1503 } else {
1504 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1505 << D->getSourceRange();
1506 }
1507 return;
1508 }
1509
1510 // Is the argument a pointer type?
1511 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1512 D->getSourceRange()))
1513 return;
1514
1515 D->addAttr(::new (S.Context)
1516 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1517 Attr.getAttributeSpellingListIndex()));
1518}
1519
1520static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1521 const AttributeList &Attr) {
1522 QualType ResultType = getFunctionOrMethodResultType(D);
1523 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1524 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1525 /* isReturnValue */ true))
1526 return;
1527
1528 D->addAttr(::new (S.Context)
1529 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1530 Attr.getAttributeSpellingListIndex()));
1531}
1532
1533static void handleNoEscapeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1534 if (D->isInvalidDecl())
1535 return;
1536
1537 // noescape only applies to pointer types.
1538 QualType T = cast<ParmVarDecl>(D)->getType();
1539 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1540 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1541 << Attr.getName() << Attr.getRange() << 0;
1542 return;
1543 }
1544
1545 D->addAttr(::new (S.Context) NoEscapeAttr(
1546 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1547}
1548
1549static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1550 const AttributeList &Attr) {
1551 Expr *E = Attr.getArgAsExpr(0),
1552 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1553 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1554 Attr.getAttributeSpellingListIndex());
1555}
1556
1557static void handleAllocAlignAttr(Sema &S, Decl *D,
1558 const AttributeList &Attr) {
1559 S.AddAllocAlignAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
1560 Attr.getAttributeSpellingListIndex());
1561}
1562
1563void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1564 Expr *OE, unsigned SpellingListIndex) {
1565 QualType ResultType = getFunctionOrMethodResultType(D);
1566 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1567
1568 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1569 SourceLocation AttrLoc = AttrRange.getBegin();
1570
1571 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1572 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1573 << &TmpAttr << AttrRange << SR;
1574 return;
1575 }
1576
1577 if (!E->isValueDependent()) {
1578 llvm::APSInt I(64);
1579 if (!E->isIntegerConstantExpr(I, Context)) {
1580 if (OE)
1581 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1582 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1583 << E->getSourceRange();
1584 else
1585 Diag(AttrLoc, diag::err_attribute_argument_type)
1586 << &TmpAttr << AANT_ArgumentIntegerConstant
1587 << E->getSourceRange();
1588 return;
1589 }
1590
1591 if (!I.isPowerOf2()) {
1592 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1593 << E->getSourceRange();
1594 return;
1595 }
1596 }
1597
1598 if (OE) {
1599 if (!OE->isValueDependent()) {
1600 llvm::APSInt I(64);
1601 if (!OE->isIntegerConstantExpr(I, Context)) {
1602 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1603 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1604 << OE->getSourceRange();
1605 return;
1606 }
1607 }
1608 }
1609
1610 D->addAttr(::new (Context)
1611 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1612}
1613
1614void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1615 unsigned SpellingListIndex) {
1616 QualType ResultType = getFunctionOrMethodResultType(D);
1617
1618 AllocAlignAttr TmpAttr(AttrRange, Context, 0, SpellingListIndex);
1619 SourceLocation AttrLoc = AttrRange.getBegin();
1620
1621 if (!ResultType->isDependentType() &&
1622 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1623 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1624 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1625 return;
1626 }
1627
1628 uint64_t IndexVal;
1629 const auto *FuncDecl = cast<FunctionDecl>(D);
1630 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1631 /*AttrArgNo=*/1, ParamExpr,
1632 IndexVal))
1633 return;
1634
1635 QualType Ty = getFunctionOrMethodParamType(D, IndexVal);
1636 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1637 Diag(ParamExpr->getLocStart(), diag::err_attribute_integers_only)
1638 << &TmpAttr << FuncDecl->getParamDecl(IndexVal)->getSourceRange();
1639 return;
1640 }
1641
1642 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
1643 // because that has corrected for the implicit this parameter, and is zero-
1644 // based. The attribute expects what the user wrote explicitly.
1645 llvm::APSInt Val;
1646 ParamExpr->EvaluateAsInt(Val, Context);
1647
1648 D->addAttr(::new (Context) AllocAlignAttr(
1649 AttrRange, Context, Val.getZExtValue(), SpellingListIndex));
1650}
1651
1652/// Normalize the attribute, __foo__ becomes foo.
1653/// Returns true if normalization was applied.
1654static bool normalizeName(StringRef &AttrName) {
1655 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1656 AttrName.endswith("__")) {
1657 AttrName = AttrName.drop_front(2).drop_back(2);
1658 return true;
1659 }
1660 return false;
1661}
1662
1663static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1664 // This attribute must be applied to a function declaration. The first
1665 // argument to the attribute must be an identifier, the name of the resource,
1666 // for example: malloc. The following arguments must be argument indexes, the
1667 // arguments must be of integer type for Returns, otherwise of pointer type.
1668 // The difference between Holds and Takes is that a pointer may still be used
1669 // after being held. free() should be __attribute((ownership_takes)), whereas
1670 // a list append function may well be __attribute((ownership_holds)).
1671
1672 if (!AL.isArgIdent(0)) {
1673 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1674 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1675 return;
1676 }
1677
1678 // Figure out our Kind.
1679 OwnershipAttr::OwnershipKind K =
1680 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1681 AL.getAttributeSpellingListIndex()).getOwnKind();
1682
1683 // Check arguments.
1684 switch (K) {
1685 case OwnershipAttr::Takes:
1686 case OwnershipAttr::Holds:
1687 if (AL.getNumArgs() < 2) {
1688 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1689 << AL.getName() << 2;
1690 return;
1691 }
1692 break;
1693 case OwnershipAttr::Returns:
1694 if (AL.getNumArgs() > 2) {
1695 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1696 << AL.getName() << 1;
1697 return;
1698 }
1699 break;
1700 }
1701
1702 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1703
1704 StringRef ModuleName = Module->getName();
1705 if (normalizeName(ModuleName)) {
1706 Module = &S.PP.getIdentifierTable().get(ModuleName);
1707 }
1708
1709 SmallVector<unsigned, 8> OwnershipArgs;
1710 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1711 Expr *Ex = AL.getArgAsExpr(i);
1712 uint64_t Idx;
1713 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1714 return;
1715
1716 // Is the function argument a pointer type?
1717 QualType T = getFunctionOrMethodParamType(D, Idx);
1718 int Err = -1; // No error
1719 switch (K) {
1720 case OwnershipAttr::Takes:
1721 case OwnershipAttr::Holds:
1722 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1723 Err = 0;
1724 break;
1725 case OwnershipAttr::Returns:
1726 if (!T->isIntegerType())
1727 Err = 1;
1728 break;
1729 }
1730 if (-1 != Err) {
1731 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1732 << Ex->getSourceRange();
1733 return;
1734 }
1735
1736 // Check we don't have a conflict with another ownership attribute.
1737 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1738 // Cannot have two ownership attributes of different kinds for the same
1739 // index.
1740 if (I->getOwnKind() != K && I->args_end() !=
1741 std::find(I->args_begin(), I->args_end(), Idx)) {
1742 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1743 << AL.getName() << I;
1744 return;
1745 } else if (K == OwnershipAttr::Returns &&
1746 I->getOwnKind() == OwnershipAttr::Returns) {
1747 // A returns attribute conflicts with any other returns attribute using
1748 // a different index. Note, diagnostic reporting is 1-based, but stored
1749 // argument indexes are 0-based.
1750 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1751 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1752 << *(I->args_begin()) + 1;
1753 if (I->args_size())
1754 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1755 << (unsigned)Idx + 1 << Ex->getSourceRange();
1756 return;
1757 }
1758 }
1759 }
1760 OwnershipArgs.push_back(Idx);
1761 }
1762
1763 unsigned* start = OwnershipArgs.data();
1764 unsigned size = OwnershipArgs.size();
1765 llvm::array_pod_sort(start, start + size);
1766
1767 D->addAttr(::new (S.Context)
1768 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1769 AL.getAttributeSpellingListIndex()));
1770}
1771
1772static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1773 // Check the attribute arguments.
1774 if (Attr.getNumArgs() > 1) {
1775 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1776 << Attr.getName() << 1;
1777 return;
1778 }
1779
1780 NamedDecl *nd = cast<NamedDecl>(D);
1781
1782 // gcc rejects
1783 // class c {
1784 // static int a __attribute__((weakref ("v2")));
1785 // static int b() __attribute__((weakref ("f3")));
1786 // };
1787 // and ignores the attributes of
1788 // void f(void) {
1789 // static int a __attribute__((weakref ("v2")));
1790 // }
1791 // we reject them
1792 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1793 if (!Ctx->isFileContext()) {
1794 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1795 << nd;
1796 return;
1797 }
1798
1799 // The GCC manual says
1800 //
1801 // At present, a declaration to which `weakref' is attached can only
1802 // be `static'.
1803 //
1804 // It also says
1805 //
1806 // Without a TARGET,
1807 // given as an argument to `weakref' or to `alias', `weakref' is
1808 // equivalent to `weak'.
1809 //
1810 // gcc 4.4.1 will accept
1811 // int a7 __attribute__((weakref));
1812 // as
1813 // int a7 __attribute__((weak));
1814 // This looks like a bug in gcc. We reject that for now. We should revisit
1815 // it if this behaviour is actually used.
1816
1817 // GCC rejects
1818 // static ((alias ("y"), weakref)).
1819 // Should we? How to check that weakref is before or after alias?
1820
1821 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1822 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1823 // StringRef parameter it was given anyway.
1824 StringRef Str;
1825 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1826 // GCC will accept anything as the argument of weakref. Should we
1827 // check for an existing decl?
1828 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1829 Attr.getAttributeSpellingListIndex()));
1830
1831 D->addAttr(::new (S.Context)
1832 WeakRefAttr(Attr.getRange(), S.Context,
1833 Attr.getAttributeSpellingListIndex()));
1834}
1835
1836static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1837 StringRef Str;
1838 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1839 return;
1840
1841 // Aliases should be on declarations, not definitions.
1842 const auto *FD = cast<FunctionDecl>(D);
1843 if (FD->isThisDeclarationADefinition()) {
1844 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1845 return;
1846 }
1847
1848 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1849 Attr.getAttributeSpellingListIndex()));
1850}
1851
1852static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1853 StringRef Str;
1854 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1855 return;
1856
1857 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1858 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1859 return;
1860 }
1861 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1862 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1863 }
1864
1865 // Aliases should be on declarations, not definitions.
1866 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1867 if (FD->isThisDeclarationADefinition()) {
1868 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
1869 return;
1870 }
1871 } else {
1872 const auto *VD = cast<VarDecl>(D);
1873 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1874 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
1875 return;
1876 }
1877 }
1878
1879 // FIXME: check if target symbol exists in current file
1880
1881 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1882 Attr.getAttributeSpellingListIndex()));
1883}
1884
1885static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1886 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
1887 return;
1888
1889 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1890 Attr.getAttributeSpellingListIndex()));
1891}
1892
1893static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1894 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
1895 return;
1896
1897 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1898 Attr.getAttributeSpellingListIndex()));
1899}
1900
1901static void handleTLSModelAttr(Sema &S, Decl *D,
1902 const AttributeList &Attr) {
1903 StringRef Model;
1904 SourceLocation LiteralLoc;
1905 // Check that it is a string.
1906 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1907 return;
1908
1909 // Check that the value.
1910 if (Model != "global-dynamic" && Model != "local-dynamic"
1911 && Model != "initial-exec" && Model != "local-exec") {
1912 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1913 return;
1914 }
1915
1916 D->addAttr(::new (S.Context)
1917 TLSModelAttr(Attr.getRange(), S.Context, Model,
1918 Attr.getAttributeSpellingListIndex()));
1919}
1920
1921static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1922 QualType ResultType = getFunctionOrMethodResultType(D);
1923 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1924 D->addAttr(::new (S.Context) RestrictAttr(
1925 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1926 return;
1927 }
1928
1929 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1930 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1931}
1932
1933static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1934 if (S.LangOpts.CPlusPlus) {
1935 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1936 << Attr.getName() << AttributeLangSupport::Cpp;
1937 return;
1938 }
1939
1940 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1941 Attr.getAttributeSpellingListIndex()))
1942 D->addAttr(CA);
1943}
1944
1945static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1946 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1947 Attr.getName()))
1948 return;
1949
1950 if (Attr.isDeclspecAttribute()) {
1951 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1952 const auto &Arch = Triple.getArch();
1953 if (Arch != llvm::Triple::x86 &&
1954 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1955 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_on_arch)
1956 << Attr.getName() << Triple.getArchName();
1957 return;
1958 }
1959 }
1960
1961 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1962 Attr.getAttributeSpellingListIndex()));
1963}
1964
1965static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &Attrs) {
1966 if (hasDeclarator(D)) return;
1967
1968 if (S.CheckNoReturnAttr(Attrs))
1969 return;
1970
1971 if (!isa<ObjCMethodDecl>(D)) {
1972 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
1973 << Attrs.getName() << ExpectedFunctionOrMethod;
1974 return;
1975 }
1976
1977 D->addAttr(::new (S.Context) NoReturnAttr(
1978 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
1979}
1980
1981static void handleNoCallerSavedRegsAttr(Sema &S, Decl *D,
1982 const AttributeList &Attr) {
1983 if (S.CheckNoCallerSavedRegsAttr(Attr))
1984 return;
1985
1986 D->addAttr(::new (S.Context) AnyX86NoCallerSavedRegistersAttr(
1987 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1988}
1989
1990bool Sema::CheckNoReturnAttr(const AttributeList &Attrs) {
1991 if (!checkAttributeNumArgs(*this, Attrs, 0)) {
1992 Attrs.setInvalid();
1993 return true;
1994 }
1995
1996 return false;
1997}
1998
1999bool Sema::CheckNoCallerSavedRegsAttr(const AttributeList &Attr) {
2000 // Check whether the attribute is valid on the current target.
2001 if (!Attr.existsInTarget(Context.getTargetInfo())) {
2002 Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored) << Attr.getName();
2003 Attr.setInvalid();
2004 return true;
2005 }
2006
2007 if (!checkAttributeNumArgs(*this, Attr, 0)) {
2008 Attr.setInvalid();
2009 return true;
2010 }
2011
2012 return false;
2013}
2014
2015static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
2016 const AttributeList &Attr) {
2017
2018 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2019 // because 'analyzer_noreturn' does not impact the type.
2020 if (!isFunctionOrMethodOrBlock(D)) {
2021 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2022 if (!VD || (!VD->getType()->isBlockPointerType() &&
2023 !VD->getType()->isFunctionPointerType())) {
2024 S.Diag(Attr.getLoc(),
2025 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
2026 : diag::warn_attribute_wrong_decl_type)
2027 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2028 return;
2029 }
2030 }
2031
2032 D->addAttr(::new (S.Context)
2033 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
2034 Attr.getAttributeSpellingListIndex()));
2035}
2036
2037// PS3 PPU-specific.
2038static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2039/*
2040 Returning a Vector Class in Registers
2041
2042 According to the PPU ABI specifications, a class with a single member of
2043 vector type is returned in memory when used as the return value of a function.
2044 This results in inefficient code when implementing vector classes. To return
2045 the value in a single vector register, add the vecreturn attribute to the
2046 class definition. This attribute is also applicable to struct types.
2047
2048 Example:
2049
2050 struct Vector
2051 {
2052 __vector float xyzw;
2053 } __attribute__((vecreturn));
2054
2055 Vector Add(Vector lhs, Vector rhs)
2056 {
2057 Vector result;
2058 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2059 return result; // This will be returned in a register
2060 }
2061*/
2062 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2063 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
2064 return;
2065 }
2066
2067 RecordDecl *record = cast<RecordDecl>(D);
2068 int count = 0;
2069
2070 if (!isa<CXXRecordDecl>(record)) {
2071 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2072 return;
2073 }
2074
2075 if (!cast<CXXRecordDecl>(record)->isPOD()) {
2076 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2077 return;
2078 }
2079
2080 for (const auto *I : record->fields()) {
2081 if ((count == 1) || !I->getType()->isVectorType()) {
2082 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2083 return;
2084 }
2085 count++;
2086 }
2087
2088 D->addAttr(::new (S.Context)
2089 VecReturnAttr(Attr.getRange(), S.Context,
2090 Attr.getAttributeSpellingListIndex()));
2091}
2092
2093static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2094 const AttributeList &Attr) {
2095 if (isa<ParmVarDecl>(D)) {
2096 // [[carries_dependency]] can only be applied to a parameter if it is a
2097 // parameter of a function declaration or lambda.
2098 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2099 S.Diag(Attr.getLoc(),
2100 diag::err_carries_dependency_param_not_function_decl);
2101 return;
2102 }
2103 }
2104
2105 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2106 Attr.getRange(), S.Context,
2107 Attr.getAttributeSpellingListIndex()));
2108}
2109
2110static void handleNotTailCalledAttr(Sema &S, Decl *D,
2111 const AttributeList &Attr) {
2112 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
2113 Attr.getName()))
2114 return;
2115
2116 D->addAttr(::new (S.Context) NotTailCalledAttr(
2117 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2118}
2119
2120static void handleDisableTailCallsAttr(Sema &S, Decl *D,
2121 const AttributeList &Attr) {
2122 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
2123 Attr.getName()))
2124 return;
2125
2126 D->addAttr(::new (S.Context) DisableTailCallsAttr(
2127 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2128}
2129
2130static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2131 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2132 if (VD->hasLocalStorage()) {
2133 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2134 return;
2135 }
2136 } else if (!isFunctionOrMethod(D)) {
2137 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2138 << Attr.getName() << ExpectedVariableOrFunction;
2139 return;
2140 }
2141
2142 D->addAttr(::new (S.Context)
2143 UsedAttr(Attr.getRange(), S.Context,
2144 Attr.getAttributeSpellingListIndex()));
2145}
2146
2147static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2148 bool IsCXX17Attr = Attr.isCXX11Attribute() && !Attr.getScopeName();
2149
2150 if (IsCXX17Attr && isa<VarDecl>(D)) {
2151 // The C++17 spelling of this attribute cannot be applied to a static data
2152 // member per [dcl.attr.unused]p2.
2153 if (cast<VarDecl>(D)->isStaticDataMember()) {
2154 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2155 << Attr.getName() << ExpectedForMaybeUnused;
2156 return;
2157 }
2158 }
2159
2160 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2161 // about using it as an extension.
2162 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2163 S.Diag(Attr.getLoc(), diag::ext_cxx17_attr) << Attr.getName();
2164
2165 D->addAttr(::new (S.Context) UnusedAttr(
2166 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2167}
2168
2169static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2170 uint32_t priority = ConstructorAttr::DefaultPriority;
2171 if (Attr.getNumArgs() &&
2172 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2173 return;
2174
2175 D->addAttr(::new (S.Context)
2176 ConstructorAttr(Attr.getRange(), S.Context, priority,
2177 Attr.getAttributeSpellingListIndex()));
2178}
2179
2180static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2181 uint32_t priority = DestructorAttr::DefaultPriority;
2182 if (Attr.getNumArgs() &&
2183 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2184 return;
2185
2186 D->addAttr(::new (S.Context)
2187 DestructorAttr(Attr.getRange(), S.Context, priority,
2188 Attr.getAttributeSpellingListIndex()));
2189}
2190
2191template <typename AttrTy>
2192static void handleAttrWithMessage(Sema &S, Decl *D,
2193 const AttributeList &Attr) {
2194 // Handle the case where the attribute has a text message.
2195 StringRef Str;
2196 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2197 return;
2198
2199 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2200 Attr.getAttributeSpellingListIndex()));
2201}
2202
2203static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2204 const AttributeList &Attr) {
2205 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2206 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2207 << Attr.getName() << Attr.getRange();
2208 return;
2209 }
2210
2211 D->addAttr(::new (S.Context)
2212 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
2213 Attr.getAttributeSpellingListIndex()));
2214}
2215
2216static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2217 IdentifierInfo *Platform,
2218 VersionTuple Introduced,
2219 VersionTuple Deprecated,
2220 VersionTuple Obsoleted) {
2221 StringRef PlatformName
2222 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2223 if (PlatformName.empty())
2224 PlatformName = Platform->getName();
2225
2226 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2227 // of these steps are needed).
2228 if (!Introduced.empty() && !Deprecated.empty() &&
2229 !(Introduced <= Deprecated)) {
2230 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2231 << 1 << PlatformName << Deprecated.getAsString()
2232 << 0 << Introduced.getAsString();
2233 return true;
2234 }
2235
2236 if (!Introduced.empty() && !Obsoleted.empty() &&
2237 !(Introduced <= Obsoleted)) {
2238 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2239 << 2 << PlatformName << Obsoleted.getAsString()
2240 << 0 << Introduced.getAsString();
2241 return true;
2242 }
2243
2244 if (!Deprecated.empty() && !Obsoleted.empty() &&
2245 !(Deprecated <= Obsoleted)) {
2246 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2247 << 2 << PlatformName << Obsoleted.getAsString()
2248 << 1 << Deprecated.getAsString();
2249 return true;
2250 }
2251
2252 return false;
2253}
2254
2255/// \brief Check whether the two versions match.
2256///
2257/// If either version tuple is empty, then they are assumed to match. If
2258/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2259static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2260 bool BeforeIsOkay) {
2261 if (X.empty() || Y.empty())
2262 return true;
2263
2264 if (X == Y)
2265 return true;
2266
2267 if (BeforeIsOkay && X < Y)
2268 return true;
2269
2270 return false;
2271}
2272
2273AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2274 IdentifierInfo *Platform,
2275 bool Implicit,
2276 VersionTuple Introduced,
2277 VersionTuple Deprecated,
2278 VersionTuple Obsoleted,
2279 bool IsUnavailable,
2280 StringRef Message,
2281 bool IsStrict,
2282 StringRef Replacement,
2283 AvailabilityMergeKind AMK,
2284 unsigned AttrSpellingListIndex) {
2285 VersionTuple MergedIntroduced = Introduced;
2286 VersionTuple MergedDeprecated = Deprecated;
2287 VersionTuple MergedObsoleted = Obsoleted;
2288 bool FoundAny = false;
2289 bool OverrideOrImpl = false;
2290 switch (AMK) {
2291 case AMK_None:
2292 case AMK_Redeclaration:
2293 OverrideOrImpl = false;
2294 break;
2295
2296 case AMK_Override:
2297 case AMK_ProtocolImplementation:
2298 OverrideOrImpl = true;
2299 break;
2300 }
2301
2302 if (D->hasAttrs()) {
2303 AttrVec &Attrs = D->getAttrs();
2304 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2305 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2306 if (!OldAA) {
2307 ++i;
2308 continue;
2309 }
2310
2311 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2312 if (OldPlatform != Platform) {
2313 ++i;
2314 continue;
2315 }
2316
2317 // If there is an existing availability attribute for this platform that
2318 // is explicit and the new one is implicit use the explicit one and
2319 // discard the new implicit attribute.
2320 if (!OldAA->isImplicit() && Implicit) {
2321 return nullptr;
2322 }
2323
2324 // If there is an existing attribute for this platform that is implicit
2325 // and the new attribute is explicit then erase the old one and
2326 // continue processing the attributes.
2327 if (!Implicit && OldAA->isImplicit()) {
2328 Attrs.erase(Attrs.begin() + i);
2329 --e;
2330 continue;
2331 }
2332
2333 FoundAny = true;
2334 VersionTuple OldIntroduced = OldAA->getIntroduced();
2335 VersionTuple OldDeprecated = OldAA->getDeprecated();
2336 VersionTuple OldObsoleted = OldAA->getObsoleted();
2337 bool OldIsUnavailable = OldAA->getUnavailable();
2338
2339 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2340 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2341 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2342 !(OldIsUnavailable == IsUnavailable ||
2343 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2344 if (OverrideOrImpl) {
2345 int Which = -1;
2346 VersionTuple FirstVersion;
2347 VersionTuple SecondVersion;
2348 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2349 Which = 0;
2350 FirstVersion = OldIntroduced;
2351 SecondVersion = Introduced;
2352 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2353 Which = 1;
2354 FirstVersion = Deprecated;
2355 SecondVersion = OldDeprecated;
2356 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2357 Which = 2;
2358 FirstVersion = Obsoleted;
2359 SecondVersion = OldObsoleted;
2360 }
2361
2362 if (Which == -1) {
2363 Diag(OldAA->getLocation(),
2364 diag::warn_mismatched_availability_override_unavail)
2365 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2366 << (AMK == AMK_Override);
2367 } else {
2368 Diag(OldAA->getLocation(),
2369 diag::warn_mismatched_availability_override)
2370 << Which
2371 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2372 << FirstVersion.getAsString() << SecondVersion.getAsString()
2373 << (AMK == AMK_Override);
2374 }
2375 if (AMK == AMK_Override)
2376 Diag(Range.getBegin(), diag::note_overridden_method);
2377 else
2378 Diag(Range.getBegin(), diag::note_protocol_method);
2379 } else {
2380 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2381 Diag(Range.getBegin(), diag::note_previous_attribute);
2382 }
2383
2384 Attrs.erase(Attrs.begin() + i);
2385 --e;
2386 continue;
2387 }
2388
2389 VersionTuple MergedIntroduced2 = MergedIntroduced;
2390 VersionTuple MergedDeprecated2 = MergedDeprecated;
2391 VersionTuple MergedObsoleted2 = MergedObsoleted;
2392
2393 if (MergedIntroduced2.empty())
2394 MergedIntroduced2 = OldIntroduced;
2395 if (MergedDeprecated2.empty())
2396 MergedDeprecated2 = OldDeprecated;
2397 if (MergedObsoleted2.empty())
2398 MergedObsoleted2 = OldObsoleted;
2399
2400 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2401 MergedIntroduced2, MergedDeprecated2,
2402 MergedObsoleted2)) {
2403 Attrs.erase(Attrs.begin() + i);
2404 --e;
2405 continue;
2406 }
2407
2408 MergedIntroduced = MergedIntroduced2;
2409 MergedDeprecated = MergedDeprecated2;
2410 MergedObsoleted = MergedObsoleted2;
2411 ++i;
2412 }
2413 }
2414
2415 if (FoundAny &&
2416 MergedIntroduced == Introduced &&
2417 MergedDeprecated == Deprecated &&
2418 MergedObsoleted == Obsoleted)
2419 return nullptr;
2420
2421 // Only create a new attribute if !OverrideOrImpl, but we want to do
2422 // the checking.
2423 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2424 MergedDeprecated, MergedObsoleted) &&
2425 !OverrideOrImpl) {
2426 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2427 Introduced, Deprecated,
2428 Obsoleted, IsUnavailable, Message,
2429 IsStrict, Replacement,
2430 AttrSpellingListIndex);
2431 Avail->setImplicit(Implicit);
2432 return Avail;
2433 }
2434 return nullptr;
2435}
2436
2437static void handleAvailabilityAttr(Sema &S, Decl *D,
2438 const AttributeList &Attr) {
2439 if (!checkAttributeNumArgs(S, Attr, 1))
2440 return;
2441 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2442 unsigned Index = Attr.getAttributeSpellingListIndex();
2443
2444 IdentifierInfo *II = Platform->Ident;
2445 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2446 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2447 << Platform->Ident;
2448
2449 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2450 if (!ND) // We warned about this already, so just return.
2451 return;
2452
2453 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2454 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2455 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2456 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2457 bool IsStrict = Attr.getStrictLoc().isValid();
2458 StringRef Str;
2459 if (const StringLiteral *SE =
2460 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2461 Str = SE->getString();
2462 StringRef Replacement;
2463 if (const StringLiteral *SE =
2464 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2465 Replacement = SE->getString();
2466
2467 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2468 false/*Implicit*/,
2469 Introduced.Version,
2470 Deprecated.Version,
2471 Obsoleted.Version,
2472 IsUnavailable, Str,
2473 IsStrict, Replacement,
2474 Sema::AMK_None,
2475 Index);
2476 if (NewAttr)
2477 D->addAttr(NewAttr);
2478
2479 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2480 // matches before the start of the watchOS platform.
2481 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2482 IdentifierInfo *NewII = nullptr;
2483 if (II->getName() == "ios")
2484 NewII = &S.Context.Idents.get("watchos");
2485 else if (II->getName() == "ios_app_extension")
2486 NewII = &S.Context.Idents.get("watchos_app_extension");
2487
2488 if (NewII) {
2489 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2490 if (Version.empty())
2491 return Version;
2492 auto Major = Version.getMajor();
2493 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2494 if (NewMajor >= 2) {
2495 if (Version.getMinor().hasValue()) {
2496 if (Version.getSubminor().hasValue())
2497 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2498 Version.getSubminor().getValue());
2499 else
2500 return VersionTuple(NewMajor, Version.getMinor().getValue());
2501 }
2502 }
2503
2504 return VersionTuple(2, 0);
2505 };
2506
2507 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2508 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2509 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2510
2511 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2512 Attr.getRange(),
2513 NewII,
2514 true/*Implicit*/,
2515 NewIntroduced,
2516 NewDeprecated,
2517 NewObsoleted,
2518 IsUnavailable, Str,
2519 IsStrict,
2520 Replacement,
2521 Sema::AMK_None,
2522 Index);
2523 if (NewAttr)
2524 D->addAttr(NewAttr);
2525 }
2526 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2527 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2528 // matches before the start of the tvOS platform.
2529 IdentifierInfo *NewII = nullptr;
2530 if (II->getName() == "ios")
2531 NewII = &S.Context.Idents.get("tvos");
2532 else if (II->getName() == "ios_app_extension")
2533 NewII = &S.Context.Idents.get("tvos_app_extension");
2534
2535 if (NewII) {
2536 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2537 Attr.getRange(),
2538 NewII,
2539 true/*Implicit*/,
2540 Introduced.Version,
2541 Deprecated.Version,
2542 Obsoleted.Version,
2543 IsUnavailable, Str,
2544 IsStrict,
2545 Replacement,
2546 Sema::AMK_None,
2547 Index);
2548 if (NewAttr)
2549 D->addAttr(NewAttr);
2550 }
2551 }
2552}
2553
2554static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2555 const AttributeList &Attr) {
2556 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2557 return;
2558 assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&(static_cast <bool> (checkAttributeAtMostNumArgs(S, Attr
, 3) && "Invalid number of arguments in an external_source_symbol attribute"
) ? void (0) : __assert_fail ("checkAttributeAtMostNumArgs(S, Attr, 3) && \"Invalid number of arguments in an external_source_symbol attribute\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 2559, __extension__ __PRETTY_FUNCTION__))
2559 "Invalid number of arguments in an external_source_symbol attribute")(static_cast <bool> (checkAttributeAtMostNumArgs(S, Attr
, 3) && "Invalid number of arguments in an external_source_symbol attribute"
) ? void (0) : __assert_fail ("checkAttributeAtMostNumArgs(S, Attr, 3) && \"Invalid number of arguments in an external_source_symbol attribute\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 2559, __extension__ __PRETTY_FUNCTION__))
;
2560
2561 StringRef Language;
2562 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0)))
2563 Language = SE->getString();
2564 StringRef DefinedIn;
2565 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1)))
2566 DefinedIn = SE->getString();
2567 bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr;
2568
2569 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2570 Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2571 Attr.getAttributeSpellingListIndex()));
2572}
2573
2574template <class T>
2575static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2576 typename T::VisibilityType value,
2577 unsigned attrSpellingListIndex) {
2578 T *existingAttr = D->getAttr<T>();
2579 if (existingAttr) {
2580 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2581 if (existingValue == value)
2582 return nullptr;
2583 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2584 S.Diag(range.getBegin(), diag::note_previous_attribute);
2585 D->dropAttr<T>();
2586 }
2587 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2588}
2589
2590VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2591 VisibilityAttr::VisibilityType Vis,
2592 unsigned AttrSpellingListIndex) {
2593 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2594 AttrSpellingListIndex);
2595}
2596
2597TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2598 TypeVisibilityAttr::VisibilityType Vis,
2599 unsigned AttrSpellingListIndex) {
2600 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2601 AttrSpellingListIndex);
2602}
2603
2604static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2605 bool isTypeVisibility) {
2606 // Visibility attributes don't mean anything on a typedef.
2607 if (isa<TypedefNameDecl>(D)) {
2608 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2609 << Attr.getName();
2610 return;
2611 }
2612
2613 // 'type_visibility' can only go on a type or namespace.
2614 if (isTypeVisibility &&
2615 !(isa<TagDecl>(D) ||
2616 isa<ObjCInterfaceDecl>(D) ||
2617 isa<NamespaceDecl>(D))) {
2618 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2619 << Attr.getName() << ExpectedTypeOrNamespace;
2620 return;
2621 }
2622
2623 // Check that the argument is a string literal.
2624 StringRef TypeStr;
2625 SourceLocation LiteralLoc;
2626 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2627 return;
2628
2629 VisibilityAttr::VisibilityType type;
2630 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2631 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2632 << Attr.getName() << TypeStr;
2633 return;
2634 }
2635
2636 // Complain about attempts to use protected visibility on targets
2637 // (like Darwin) that don't support it.
2638 if (type == VisibilityAttr::Protected &&
2639 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2640 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2641 type = VisibilityAttr::Default;
2642 }
2643
2644 unsigned Index = Attr.getAttributeSpellingListIndex();
2645 clang::Attr *newAttr;
2646 if (isTypeVisibility) {
2647 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2648 (TypeVisibilityAttr::VisibilityType) type,
2649 Index);
2650 } else {
2651 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2652 }
2653 if (newAttr)
2654 D->addAttr(newAttr);
2655}
2656
2657static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2658 const AttributeList &Attr) {
2659 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2660 if (!Attr.isArgIdent(0)) {
2661 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2662 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2663 return;
2664 }
2665
2666 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2667 ObjCMethodFamilyAttr::FamilyKind F;
2668 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2669 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2670 << IL->Ident;
2671 return;
2672 }
2673
2674 if (F == ObjCMethodFamilyAttr::OMF_init &&
2675 !method->getReturnType()->isObjCObjectPointerType()) {
2676 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2677 << method->getReturnType();
2678 // Ignore the attribute.
2679 return;
2680 }
2681
2682 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2683 S.Context, F,
2684 Attr.getAttributeSpellingListIndex()));
2685}
2686
2687static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2688 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2689 QualType T = TD->getUnderlyingType();
2690 if (!T->isCARCBridgableType()) {
2691 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2692 return;
2693 }
2694 }
2695 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2696 QualType T = PD->getType();
2697 if (!T->isCARCBridgableType()) {
2698 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2699 return;
2700 }
2701 }
2702 else {
2703 // It is okay to include this attribute on properties, e.g.:
2704 //
2705 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2706 //
2707 // In this case it follows tradition and suppresses an error in the above
2708 // case.
2709 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2710 }
2711 D->addAttr(::new (S.Context)
2712 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2713 Attr.getAttributeSpellingListIndex()));
2714}
2715
2716static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2717 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2718 QualType T = TD->getUnderlyingType();
2719 if (!T->isObjCObjectPointerType()) {
2720 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2721 return;
2722 }
2723 } else {
2724 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2725 return;
2726 }
2727 D->addAttr(::new (S.Context)
2728 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2729 Attr.getAttributeSpellingListIndex()));
2730}
2731
2732static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2733 if (!Attr.isArgIdent(0)) {
2734 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2735 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2736 return;
2737 }
2738
2739 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2740 BlocksAttr::BlockType type;
2741 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2742 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2743 << Attr.getName() << II;
2744 return;
2745 }
2746
2747 D->addAttr(::new (S.Context)
2748 BlocksAttr(Attr.getRange(), S.Context, type,
2749 Attr.getAttributeSpellingListIndex()));
2750}
2751
2752static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2753 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2754 if (Attr.getNumArgs() > 0) {
2755 Expr *E = Attr.getArgAsExpr(0);
2756 llvm::APSInt Idx(32);
2757 if (E->isTypeDependent() || E->isValueDependent() ||
2758 !E->isIntegerConstantExpr(Idx, S.Context)) {
2759 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2760 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2761 << E->getSourceRange();
2762 return;
2763 }
2764
2765 if (Idx.isSigned() && Idx.isNegative()) {
2766 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2767 << E->getSourceRange();
2768 return;
2769 }
2770
2771 sentinel = Idx.getZExtValue();
2772 }
2773
2774 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2775 if (Attr.getNumArgs() > 1) {
2776 Expr *E = Attr.getArgAsExpr(1);
2777 llvm::APSInt Idx(32);
2778 if (E->isTypeDependent() || E->isValueDependent() ||
2779 !E->isIntegerConstantExpr(Idx, S.Context)) {
2780 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2781 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2782 << E->getSourceRange();
2783 return;
2784 }
2785 nullPos = Idx.getZExtValue();
2786
2787 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2788 // FIXME: This error message could be improved, it would be nice
2789 // to say what the bounds actually are.
2790 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2791 << E->getSourceRange();
2792 return;
2793 }
2794 }
2795
2796 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2797 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2798 if (isa<FunctionNoProtoType>(FT)) {
2799 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2800 return;
2801 }
2802
2803 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2804 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2805 return;
2806 }
2807 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2808 if (!MD->isVariadic()) {
2809 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2810 return;
2811 }
2812 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2813 if (!BD->isVariadic()) {
2814 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2815 return;
2816 }
2817 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2818 QualType Ty = V->getType();
2819 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2820 const FunctionType *FT = Ty->isFunctionPointerType()
2821 ? D->getFunctionType()
2822 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2823 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2824 int m = Ty->isFunctionPointerType() ? 0 : 1;
2825 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2826 return;
2827 }
2828 } else {
2829 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2830 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2831 return;
2832 }
2833 } else {
2834 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2835 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2836 return;
2837 }
2838 D->addAttr(::new (S.Context)
2839 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2840 Attr.getAttributeSpellingListIndex()));
2841}
2842
2843static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2844 if (D->getFunctionType() &&
2845 D->getFunctionType()->getReturnType()->isVoidType()) {
2846 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2847 << Attr.getName() << 0;
2848 return;
2849 }
2850 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2851 if (MD->getReturnType()->isVoidType()) {
2852 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2853 << Attr.getName() << 1;
2854 return;
2855 }
2856
2857 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2858 // about using it as an extension.
2859 if (!S.getLangOpts().CPlusPlus17 && Attr.isCXX11Attribute() &&
2860 !Attr.getScopeName())
2861 S.Diag(Attr.getLoc(), diag::ext_cxx17_attr) << Attr.getName();
2862
2863 D->addAttr(::new (S.Context)
2864 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2865 Attr.getAttributeSpellingListIndex()));
2866}
2867
2868static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2869 // weak_import only applies to variable & function declarations.
2870 bool isDef = false;
2871 if (!D->canBeWeakImported(isDef)) {
2872 if (isDef)
2873 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2874 << "weak_import";
2875 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2876 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2877 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2878 // Nothing to warn about here.
2879 } else
2880 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2881 << Attr.getName() << ExpectedVariableOrFunction;
2882
2883 return;
2884 }
2885
2886 D->addAttr(::new (S.Context)
2887 WeakImportAttr(Attr.getRange(), S.Context,
2888 Attr.getAttributeSpellingListIndex()));
2889}
2890
2891// Handles reqd_work_group_size and work_group_size_hint.
2892template <typename WorkGroupAttr>
2893static void handleWorkGroupSize(Sema &S, Decl *D,
2894 const AttributeList &Attr) {
2895 uint32_t WGSize[3];
2896 for (unsigned i = 0; i < 3; ++i) {
2897 const Expr *E = Attr.getArgAsExpr(i);
2898 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2899 return;
2900 if (WGSize[i] == 0) {
2901 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2902 << Attr.getName() << E->getSourceRange();
2903 return;
2904 }
2905 }
2906
2907 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2908 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2909 Existing->getYDim() == WGSize[1] &&
2910 Existing->getZDim() == WGSize[2]))
2911 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2912
2913 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2914 WGSize[0], WGSize[1], WGSize[2],
2915 Attr.getAttributeSpellingListIndex()));
2916}
2917
2918// Handles intel_reqd_sub_group_size.
2919static void handleSubGroupSize(Sema &S, Decl *D, const AttributeList &Attr) {
2920 uint32_t SGSize;
2921 const Expr *E = Attr.getArgAsExpr(0);
2922 if (!checkUInt32Argument(S, Attr, E, SGSize))
2923 return;
2924 if (SGSize == 0) {
2925 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2926 << Attr.getName() << E->getSourceRange();
2927 return;
2928 }
2929
2930 OpenCLIntelReqdSubGroupSizeAttr *Existing =
2931 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2932 if (Existing && Existing->getSubGroupSize() != SGSize)
2933 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2934
2935 D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2936 Attr.getRange(), S.Context, SGSize,
2937 Attr.getAttributeSpellingListIndex()));
2938}
2939
2940static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2941 if (!Attr.hasParsedType()) {
2942 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2943 << Attr.getName() << 1;
2944 return;
2945 }
2946
2947 TypeSourceInfo *ParmTSI = nullptr;
2948 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2949 assert(ParmTSI && "no type source info for attribute argument")(static_cast <bool> (ParmTSI && "no type source info for attribute argument"
) ? void (0) : __assert_fail ("ParmTSI && \"no type source info for attribute argument\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 2949, __extension__ __PRETTY_FUNCTION__))
;
2950
2951 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2952 (ParmType->isBooleanType() ||
2953 !ParmType->isIntegralType(S.getASTContext()))) {
2954 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2955 << ParmType;
2956 return;
2957 }
2958
2959 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2960 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2961 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2962 return;
2963 }
2964 }
2965
2966 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2967 ParmTSI,
2968 Attr.getAttributeSpellingListIndex()));
2969}
2970
2971SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2972 StringRef Name,
2973 unsigned AttrSpellingListIndex) {
2974 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2975 if (ExistingAttr->getName() == Name)
2976 return nullptr;
2977 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2978 Diag(Range.getBegin(), diag::note_previous_attribute);
2979 return nullptr;
2980 }
2981 return ::new (Context) SectionAttr(Range, Context, Name,
2982 AttrSpellingListIndex);
2983}
2984
2985bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2986 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2987 if (!Error.empty()) {
2988 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2989 return false;
2990 }
2991 return true;
2992}
2993
2994static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2995 // Make sure that there is a string literal as the sections's single
2996 // argument.
2997 StringRef Str;
2998 SourceLocation LiteralLoc;
2999 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
3000 return;
3001
3002 if (!S.checkSectionName(LiteralLoc, Str))
3003 return;
3004
3005 // If the target wants to validate the section specifier, make it happen.
3006 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
3007 if (!Error.empty()) {
3008 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3009 << Error;
3010 return;
3011 }
3012
3013 unsigned Index = Attr.getAttributeSpellingListIndex();
3014 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
3015 if (NewAttr)
3016 D->addAttr(NewAttr);
3017}
3018
3019// Check for things we'd like to warn about. Multiversioning issues are
3020// handled later in the process, once we know how many exist.
3021bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3022 enum FirstParam { Unsupported, Duplicate };
3023 enum SecondParam { None, Architecture };
3024 for (auto Str : {"tune=", "fpmath="})
3025 if (AttrStr.find(Str) != StringRef::npos)
3026 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3027 << Unsupported << None << Str;
3028
3029 TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3030
3031 if (!ParsedAttrs.Architecture.empty() &&
3032 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3033 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3034 << Unsupported << Architecture << ParsedAttrs.Architecture;
3035
3036 if (ParsedAttrs.DuplicateArchitecture)
3037 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3038 << Duplicate << None << "arch=";
3039
3040 for (const auto &Feature : ParsedAttrs.Features) {
3041 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3042 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3043 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3044 << Unsupported << None << CurFeature;
3045 }
3046
3047 return true;
3048}
3049
3050static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3051 StringRef Str;
3052 SourceLocation LiteralLoc;
3053 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc) ||
3054 !S.checkTargetAttr(LiteralLoc, Str))
3055 return;
3056 unsigned Index = Attr.getAttributeSpellingListIndex();
3057 TargetAttr *NewAttr =
3058 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
3059 D->addAttr(NewAttr);
3060}
3061
3062static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3063 Expr *E = Attr.getArgAsExpr(0);
3064 SourceLocation Loc = E->getExprLoc();
3065 FunctionDecl *FD = nullptr;
3066 DeclarationNameInfo NI;
3067
3068 // gcc only allows for simple identifiers. Since we support more than gcc, we
3069 // will warn the user.
3070 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3071 if (DRE->hasQualifier())
3072 S.Diag(Loc, diag::warn_cleanup_ext);
3073 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3074 NI = DRE->getNameInfo();
3075 if (!FD) {
3076 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3077 << NI.getName();
3078 return;
3079 }
3080 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3081 if (ULE->hasExplicitTemplateArgs())
3082 S.Diag(Loc, diag::warn_cleanup_ext);
3083 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3084 NI = ULE->getNameInfo();
3085 if (!FD) {
3086 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3087 << NI.getName();
3088 if (ULE->getType() == S.Context.OverloadTy)
3089 S.NoteAllOverloadCandidates(ULE);
3090 return;
3091 }
3092 } else {
3093 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3094 return;
3095 }
3096
3097 if (FD->getNumParams() != 1) {
3098 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3099 << NI.getName();
3100 return;
3101 }
3102
3103 // We're currently more strict than GCC about what function types we accept.
3104 // If this ever proves to be a problem it should be easy to fix.
3105 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3106 QualType ParamTy = FD->getParamDecl(0)->getType();
3107 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3108 ParamTy, Ty) != Sema::Compatible) {
3109 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3110 << NI.getName() << ParamTy << Ty;
3111 return;
3112 }
3113
3114 D->addAttr(::new (S.Context)
3115 CleanupAttr(Attr.getRange(), S.Context, FD,
3116 Attr.getAttributeSpellingListIndex()));
3117}
3118
3119static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3120 const AttributeList &Attr) {
3121 if (!Attr.isArgIdent(0)) {
3122 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3123 << Attr.getName() << 0 << AANT_ArgumentIdentifier;
3124 return;
3125 }
3126
3127 EnumExtensibilityAttr::Kind ExtensibilityKind;
3128 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3129 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3130 ExtensibilityKind)) {
3131 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3132 << Attr.getName() << II;
3133 return;
3134 }
3135
3136 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3137 Attr.getRange(), S.Context, ExtensibilityKind,
3138 Attr.getAttributeSpellingListIndex()));
3139}
3140
3141/// Handle __attribute__((format_arg((idx)))) attribute based on
3142/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3143static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3144 Expr *IdxExpr = Attr.getArgAsExpr(0);
3145 uint64_t Idx;
3146 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
3147 return;
3148
3149 // Make sure the format string is really a string.
3150 QualType Ty = getFunctionOrMethodParamType(D, Idx);
3151
3152 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3153 if (NotNSStringTy &&
3154 !isCFStringType(Ty, S.Context) &&
3155 (!Ty->isPointerType() ||
3156 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3157 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3158 << "a string type" << IdxExpr->getSourceRange()
3159 << getFunctionOrMethodParamRange(D, 0);
3160 return;
3161 }
3162 Ty = getFunctionOrMethodResultType(D);
3163 if (!isNSStringType(Ty, S.Context) &&
3164 !isCFStringType(Ty, S.Context) &&
3165 (!Ty->isPointerType() ||
3166 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3167 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
3168 << (NotNSStringTy ? "string type" : "NSString")
3169 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3170 return;
3171 }
3172
3173 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
3174 // because that has corrected for the implicit this parameter, and is zero-
3175 // based. The attribute expects what the user wrote explicitly.
3176 llvm::APSInt Val;
3177 IdxExpr->EvaluateAsInt(Val, S.Context);
3178
3179 D->addAttr(::new (S.Context)
3180 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
3181 Attr.getAttributeSpellingListIndex()));
3182}
3183
3184enum FormatAttrKind {
3185 CFStringFormat,
3186 NSStringFormat,
3187 StrftimeFormat,
3188 SupportedFormat,
3189 IgnoredFormat,
3190 InvalidFormat
3191};
3192
3193/// getFormatAttrKind - Map from format attribute names to supported format
3194/// types.
3195static FormatAttrKind getFormatAttrKind(StringRef Format) {
3196 return llvm::StringSwitch<FormatAttrKind>(Format)
3197 // Check for formats that get handled specially.
3198 .Case("NSString", NSStringFormat)
3199 .Case("CFString", CFStringFormat)
3200 .Case("strftime", StrftimeFormat)
3201
3202 // Otherwise, check for supported formats.
3203 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3204 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3205 .Case("kprintf", SupportedFormat) // OpenBSD.
3206 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3207 .Case("os_trace", SupportedFormat)
3208 .Case("os_log", SupportedFormat)
3209
3210 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3211 .Default(InvalidFormat);
3212}
3213
3214/// Handle __attribute__((init_priority(priority))) attributes based on
3215/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3216static void handleInitPriorityAttr(Sema &S, Decl *D,
3217 const AttributeList &Attr) {
3218 if (!S.getLangOpts().CPlusPlus) {
3219 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3220 return;
3221 }
3222
3223 if (S.getCurFunctionOrMethodDecl()) {
3224 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3225 Attr.setInvalid();
3226 return;
3227 }
3228 QualType T = cast<VarDecl>(D)->getType();
3229 if (S.Context.getAsArrayType(T))
3230 T = S.Context.getBaseElementType(T);
3231 if (!T->getAs<RecordType>()) {
3232 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3233 Attr.setInvalid();
3234 return;
3235 }
3236
3237 Expr *E = Attr.getArgAsExpr(0);
3238 uint32_t prioritynum;
3239 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
3240 Attr.setInvalid();
3241 return;
3242 }
3243
3244 if (prioritynum < 101 || prioritynum > 65535) {
3245 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
3246 << E->getSourceRange() << Attr.getName() << 101 << 65535;
3247 Attr.setInvalid();
3248 return;
3249 }
3250 D->addAttr(::new (S.Context)
3251 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3252 Attr.getAttributeSpellingListIndex()));
3253}
3254
3255FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3256 IdentifierInfo *Format, int FormatIdx,
3257 int FirstArg,
3258 unsigned AttrSpellingListIndex) {
3259 // Check whether we already have an equivalent format attribute.
3260 for (auto *F : D->specific_attrs<FormatAttr>()) {
3261 if (F->getType() == Format &&
3262 F->getFormatIdx() == FormatIdx &&
3263 F->getFirstArg() == FirstArg) {
3264 // If we don't have a valid location for this attribute, adopt the
3265 // location.
3266 if (F->getLocation().isInvalid())
3267 F->setRange(Range);
3268 return nullptr;
3269 }
3270 }
3271
3272 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3273 FirstArg, AttrSpellingListIndex);
3274}
3275
3276/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3277/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3278static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3279 if (!Attr.isArgIdent(0)) {
3280 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3281 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3282 return;
3283 }
3284
3285 // In C++ the implicit 'this' function parameter also counts, and they are
3286 // counted from one.
3287 bool HasImplicitThisParam = isInstanceMethod(D);
3288 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3289
3290 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3291 StringRef Format = II->getName();
3292
3293 if (normalizeName(Format)) {
3294 // If we've modified the string name, we need a new identifier for it.
3295 II = &S.Context.Idents.get(Format);
3296 }
3297
3298 // Check for supported formats.
3299 FormatAttrKind Kind = getFormatAttrKind(Format);
3300
3301 if (Kind == IgnoredFormat)
3302 return;
3303
3304 if (Kind == InvalidFormat) {
3305 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3306 << Attr.getName() << II->getName();
3307 return;
3308 }
3309
3310 // checks for the 2nd argument
3311 Expr *IdxExpr = Attr.getArgAsExpr(1);
3312 uint32_t Idx;
3313 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
3314 return;
3315
3316 if (Idx < 1 || Idx > NumArgs) {
3317 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3318 << Attr.getName() << 2 << IdxExpr->getSourceRange();
3319 return;
3320 }
3321
3322 // FIXME: Do we need to bounds check?
3323 unsigned ArgIdx = Idx - 1;
3324
3325 if (HasImplicitThisParam) {
3326 if (ArgIdx == 0) {
3327 S.Diag(Attr.getLoc(),
3328 diag::err_format_attribute_implicit_this_format_string)
3329 << IdxExpr->getSourceRange();
3330 return;
3331 }
3332 ArgIdx--;
3333 }
3334
3335 // make sure the format string is really a string
3336 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3337
3338 if (Kind == CFStringFormat) {
3339 if (!isCFStringType(Ty, S.Context)) {
3340 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3341 << "a CFString" << IdxExpr->getSourceRange()
3342 << getFunctionOrMethodParamRange(D, ArgIdx);
3343 return;
3344 }
3345 } else if (Kind == NSStringFormat) {
3346 // FIXME: do we need to check if the type is NSString*? What are the
3347 // semantics?
3348 if (!isNSStringType(Ty, S.Context)) {
3349 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3350 << "an NSString" << IdxExpr->getSourceRange()
3351 << getFunctionOrMethodParamRange(D, ArgIdx);
3352 return;
3353 }
3354 } else if (!Ty->isPointerType() ||
3355 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3356 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3357 << "a string type" << IdxExpr->getSourceRange()
3358 << getFunctionOrMethodParamRange(D, ArgIdx);
3359 return;
3360 }
3361
3362 // check the 3rd argument
3363 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
3364 uint32_t FirstArg;
3365 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
3366 return;
3367
3368 // check if the function is variadic if the 3rd argument non-zero
3369 if (FirstArg != 0) {
3370 if (isFunctionOrMethodVariadic(D)) {
3371 ++NumArgs; // +1 for ...
3372 } else {
3373 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3374 return;
3375 }
3376 }
3377
3378 // strftime requires FirstArg to be 0 because it doesn't read from any
3379 // variable the input is just the current time + the format string.
3380 if (Kind == StrftimeFormat) {
3381 if (FirstArg != 0) {
3382 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3383 << FirstArgExpr->getSourceRange();
3384 return;
3385 }
3386 // if 0 it disables parameter checking (to use with e.g. va_list)
3387 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3388 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3389 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
3390 return;
3391 }
3392
3393 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3394 Idx, FirstArg,
3395 Attr.getAttributeSpellingListIndex());
3396 if (NewAttr)
3397 D->addAttr(NewAttr);
3398}
3399
3400static void handleTransparentUnionAttr(Sema &S, Decl *D,
3401 const AttributeList &Attr) {
3402 // Try to find the underlying union declaration.
3403 RecordDecl *RD = nullptr;
3404 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3405 if (TD && TD->getUnderlyingType()->isUnionType())
3406 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3407 else
3408 RD = dyn_cast<RecordDecl>(D);
3409
3410 if (!RD || !RD->isUnion()) {
3411 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3412 << Attr.getName() << ExpectedUnion;
3413 return;
3414 }
3415
3416 if (!RD->isCompleteDefinition()) {
3417 if (!RD->isBeingDefined())
3418 S.Diag(Attr.getLoc(),
3419 diag::warn_transparent_union_attribute_not_definition);
3420 return;
3421 }
3422
3423 RecordDecl::field_iterator Field = RD->field_begin(),
3424 FieldEnd = RD->field_end();
3425 if (Field == FieldEnd) {
3426 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3427 return;
3428 }
3429
3430 FieldDecl *FirstField = *Field;
3431 QualType FirstType = FirstField->getType();
3432 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3433 S.Diag(FirstField->getLocation(),
3434 diag::warn_transparent_union_attribute_floating)
3435 << FirstType->isVectorType() << FirstType;
3436 return;
3437 }
3438
3439 if (FirstType->isIncompleteType())
3440 return;
3441 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3442 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3443 for (; Field != FieldEnd; ++Field) {
3444 QualType FieldType = Field->getType();
3445 if (FieldType->isIncompleteType())
3446 return;
3447 // FIXME: this isn't fully correct; we also need to test whether the
3448 // members of the union would all have the same calling convention as the
3449 // first member of the union. Checking just the size and alignment isn't
3450 // sufficient (consider structs passed on the stack instead of in registers
3451 // as an example).
3452 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3453 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3454 // Warn if we drop the attribute.
3455 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3456 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3457 : S.Context.getTypeAlign(FieldType);
3458 S.Diag(Field->getLocation(),
3459 diag::warn_transparent_union_attribute_field_size_align)
3460 << isSize << Field->getDeclName() << FieldBits;
3461 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3462 S.Diag(FirstField->getLocation(),
3463 diag::note_transparent_union_first_field_size_align)
3464 << isSize << FirstBits;
3465 return;
3466 }
3467 }
3468
3469 RD->addAttr(::new (S.Context)
3470 TransparentUnionAttr(Attr.getRange(), S.Context,
3471 Attr.getAttributeSpellingListIndex()));
3472}
3473
3474static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3475 // Make sure that there is a string literal as the annotation's single
3476 // argument.
3477 StringRef Str;
3478 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3479 return;
3480
3481 // Don't duplicate annotations that are already set.
3482 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3483 if (I->getAnnotation() == Str)
3484 return;
3485 }
3486
3487 D->addAttr(::new (S.Context)
3488 AnnotateAttr(Attr.getRange(), S.Context, Str,
3489 Attr.getAttributeSpellingListIndex()));
3490}
3491
3492static void handleAlignValueAttr(Sema &S, Decl *D,
3493 const AttributeList &Attr) {
3494 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3495 Attr.getAttributeSpellingListIndex());
3496}
3497
3498void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3499 unsigned SpellingListIndex) {
3500 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3501 SourceLocation AttrLoc = AttrRange.getBegin();
3502
3503 QualType T;
3504 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3505 T = TD->getUnderlyingType();
3506 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3507 T = VD->getType();
3508 else
3509 llvm_unreachable("Unknown decl type for align_value")::llvm::llvm_unreachable_internal("Unknown decl type for align_value"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3509)
;
3510
3511 if (!T->isDependentType() && !T->isAnyPointerType() &&
3512 !T->isReferenceType() && !T->isMemberPointerType()) {
3513 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3514 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3515 return;
3516 }
3517
3518 if (!E->isValueDependent()) {
3519 llvm::APSInt Alignment;
3520 ExprResult ICE
3521 = VerifyIntegerConstantExpression(E, &Alignment,
3522 diag::err_align_value_attribute_argument_not_int,
3523 /*AllowFold*/ false);
3524 if (ICE.isInvalid())
3525 return;
3526
3527 if (!Alignment.isPowerOf2()) {
3528 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3529 << E->getSourceRange();
3530 return;
3531 }
3532
3533 D->addAttr(::new (Context)
3534 AlignValueAttr(AttrRange, Context, ICE.get(),
3535 SpellingListIndex));
3536 return;
3537 }
3538
3539 // Save dependent expressions in the AST to be instantiated.
3540 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3541}
3542
3543static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3544 // check the attribute arguments.
3545 if (Attr.getNumArgs() > 1) {
3546 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3547 << Attr.getName() << 1;
3548 return;
3549 }
3550
3551 if (Attr.getNumArgs() == 0) {
3552 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3553 true, nullptr, Attr.getAttributeSpellingListIndex()));
3554 return;
3555 }
3556
3557 Expr *E = Attr.getArgAsExpr(0);
3558 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3559 S.Diag(Attr.getEllipsisLoc(),
3560 diag::err_pack_expansion_without_parameter_packs);
3561 return;
3562 }
3563
3564 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3565 return;
3566
3567 if (E->isValueDependent()) {
3568 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3569 if (!TND->getUnderlyingType()->isDependentType()) {
3570 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3571 << E->getSourceRange();
3572 return;
3573 }
3574 }
3575 }
3576
3577 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3578 Attr.isPackExpansion());
3579}
3580
3581void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3582 unsigned SpellingListIndex, bool IsPackExpansion) {
3583 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3584 SourceLocation AttrLoc = AttrRange.getBegin();
3585
3586 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3587 if (TmpAttr.isAlignas()) {
3588 // C++11 [dcl.align]p1:
3589 // An alignment-specifier may be applied to a variable or to a class
3590 // data member, but it shall not be applied to a bit-field, a function
3591 // parameter, the formal parameter of a catch clause, or a variable
3592 // declared with the register storage class specifier. An
3593 // alignment-specifier may also be applied to the declaration of a class
3594 // or enumeration type.
3595 // C11 6.7.5/2:
3596 // An alignment attribute shall not be specified in a declaration of
3597 // a typedef, or a bit-field, or a function, or a parameter, or an
3598 // object declared with the register storage-class specifier.
3599 int DiagKind = -1;
3600 if (isa<ParmVarDecl>(D)) {
3601 DiagKind = 0;
3602 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3603 if (VD->getStorageClass() == SC_Register)
3604 DiagKind = 1;
3605 if (VD->isExceptionVariable())
3606 DiagKind = 2;
3607 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3608 if (FD->isBitField())
3609 DiagKind = 3;
3610 } else if (!isa<TagDecl>(D)) {
3611 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3612 << (TmpAttr.isC11() ? ExpectedVariableOrField
3613 : ExpectedVariableFieldOrTag);
3614 return;
3615 }
3616 if (DiagKind != -1) {
3617 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3618 << &TmpAttr << DiagKind;
3619 return;
3620 }
3621 }
3622
3623 if (E->isTypeDependent() || E->isValueDependent()) {
3624 // Save dependent expressions in the AST to be instantiated.
3625 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3626 AA->setPackExpansion(IsPackExpansion);
3627 D->addAttr(AA);
3628 return;
3629 }
3630
3631 // FIXME: Cache the number on the Attr object?
3632 llvm::APSInt Alignment;
3633 ExprResult ICE
3634 = VerifyIntegerConstantExpression(E, &Alignment,
3635 diag::err_aligned_attribute_argument_not_int,
3636 /*AllowFold*/ false);
3637 if (ICE.isInvalid())
3638 return;
3639
3640 uint64_t AlignVal = Alignment.getZExtValue();
3641
3642 // C++11 [dcl.align]p2:
3643 // -- if the constant expression evaluates to zero, the alignment
3644 // specifier shall have no effect
3645 // C11 6.7.5p6:
3646 // An alignment specification of zero has no effect.
3647 if (!(TmpAttr.isAlignas() && !Alignment)) {
3648 if (!llvm::isPowerOf2_64(AlignVal)) {
3649 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3650 << E->getSourceRange();
3651 return;
3652 }
3653 }
3654
3655 // Alignment calculations can wrap around if it's greater than 2**28.
3656 unsigned MaxValidAlignment =
3657 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3658 : 268435456;
3659 if (AlignVal > MaxValidAlignment) {
3660 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3661 << E->getSourceRange();
3662 return;
3663 }
3664
3665 if (Context.getTargetInfo().isTLSSupported()) {
3666 unsigned MaxTLSAlign =
3667 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3668 .getQuantity();
3669 auto *VD = dyn_cast<VarDecl>(D);
3670 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3671 VD->getTLSKind() != VarDecl::TLS_None) {
3672 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3673 << (unsigned)AlignVal << VD << MaxTLSAlign;
3674 return;
3675 }
3676 }
3677
3678 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3679 ICE.get(), SpellingListIndex);
3680 AA->setPackExpansion(IsPackExpansion);
3681 D->addAttr(AA);
3682}
3683
3684void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3685 unsigned SpellingListIndex, bool IsPackExpansion) {
3686 // FIXME: Cache the number on the Attr object if non-dependent?
3687 // FIXME: Perform checking of type validity
3688 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3689 SpellingListIndex);
3690 AA->setPackExpansion(IsPackExpansion);
3691 D->addAttr(AA);
3692}
3693
3694void Sema::CheckAlignasUnderalignment(Decl *D) {
3695 assert(D->hasAttrs() && "no attributes on decl")(static_cast <bool> (D->hasAttrs() && "no attributes on decl"
) ? void (0) : __assert_fail ("D->hasAttrs() && \"no attributes on decl\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3695, __extension__ __PRETTY_FUNCTION__))
;
3696
3697 QualType UnderlyingTy, DiagTy;
3698 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3699 UnderlyingTy = DiagTy = VD->getType();
3700 } else {
3701 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3702 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3703 UnderlyingTy = ED->getIntegerType();
3704 }
3705 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3706 return;
3707
3708 // C++11 [dcl.align]p5, C11 6.7.5/4:
3709 // The combined effect of all alignment attributes in a declaration shall
3710 // not specify an alignment that is less strict than the alignment that
3711 // would otherwise be required for the entity being declared.
3712 AlignedAttr *AlignasAttr = nullptr;
3713 unsigned Align = 0;
3714 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3715 if (I->isAlignmentDependent())
3716 return;
3717 if (I->isAlignas())
3718 AlignasAttr = I;
3719 Align = std::max(Align, I->getAlignment(Context));
3720 }
3721
3722 if (AlignasAttr && Align) {
3723 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3724 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3725 if (NaturalAlign > RequestedAlign)
3726 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3727 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3728 }
3729}
3730
3731bool Sema::checkMSInheritanceAttrOnDefinition(
3732 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3733 MSInheritanceAttr::Spelling SemanticSpelling) {
3734 assert(RD->hasDefinition() && "RD has no definition!")(static_cast <bool> (RD->hasDefinition() && "RD has no definition!"
) ? void (0) : __assert_fail ("RD->hasDefinition() && \"RD has no definition!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3734, __extension__ __PRETTY_FUNCTION__))
;
3735
3736 // We may not have seen base specifiers or any virtual methods yet. We will
3737 // have to wait until the record is defined to catch any mismatches.
3738 if (!RD->getDefinition()->isCompleteDefinition())
3739 return false;
3740
3741 // The unspecified model never matches what a definition could need.
3742 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3743 return false;
3744
3745 if (BestCase) {
3746 if (RD->calculateInheritanceModel() == SemanticSpelling)
3747 return false;
3748 } else {
3749 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3750 return false;
3751 }
3752
3753 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3754 << 0 /*definition*/;
3755 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3756 << RD->getNameAsString();
3757 return true;
3758}
3759
3760/// parseModeAttrArg - Parses attribute mode string and returns parsed type
3761/// attribute.
3762static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3763 bool &IntegerMode, bool &ComplexMode) {
3764 IntegerMode = true;
3765 ComplexMode = false;
3766 switch (Str.size()) {
3767 case 2:
3768 switch (Str[0]) {
3769 case 'Q':
3770 DestWidth = 8;
3771 break;
3772 case 'H':
3773 DestWidth = 16;
3774 break;
3775 case 'S':
3776 DestWidth = 32;
3777 break;
3778 case 'D':
3779 DestWidth = 64;
3780 break;
3781 case 'X':
3782 DestWidth = 96;
3783 break;
3784 case 'T':
3785 DestWidth = 128;
3786 break;
3787 }
3788 if (Str[1] == 'F') {
3789 IntegerMode = false;
3790 } else if (Str[1] == 'C') {
3791 IntegerMode = false;
3792 ComplexMode = true;
3793 } else if (Str[1] != 'I') {
3794 DestWidth = 0;
3795 }
3796 break;
3797 case 4:
3798 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3799 // pointer on PIC16 and other embedded platforms.
3800 if (Str == "word")
3801 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3802 else if (Str == "byte")
3803 DestWidth = S.Context.getTargetInfo().getCharWidth();
3804 break;
3805 case 7:
3806 if (Str == "pointer")
3807 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3808 break;
3809 case 11:
3810 if (Str == "unwind_word")
3811 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3812 break;
3813 }
3814}
3815
3816/// handleModeAttr - This attribute modifies the width of a decl with primitive
3817/// type.
3818///
3819/// Despite what would be logical, the mode attribute is a decl attribute, not a
3820/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3821/// HImode, not an intermediate pointer.
3822static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3823 // This attribute isn't documented, but glibc uses it. It changes
3824 // the width of an int or unsigned int to the specified size.
3825 if (!Attr.isArgIdent(0)) {
3826 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3827 << AANT_ArgumentIdentifier;
3828 return;
3829 }
3830
3831 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3832
3833 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3834}
3835
3836void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3837 unsigned SpellingListIndex, bool InInstantiation) {
3838 StringRef Str = Name->getName();
3839 normalizeName(Str);
3840 SourceLocation AttrLoc = AttrRange.getBegin();
3841
3842 unsigned DestWidth = 0;
3843 bool IntegerMode = true;
3844 bool ComplexMode = false;
3845 llvm::APInt VectorSize(64, 0);
3846 if (Str.size() >= 4 && Str[0] == 'V') {
3847 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3848 size_t StrSize = Str.size();
3849 size_t VectorStringLength = 0;
3850 while ((VectorStringLength + 1) < StrSize &&
3851 isdigit(Str[VectorStringLength + 1]))
3852 ++VectorStringLength;
3853 if (VectorStringLength &&
3854 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3855 VectorSize.isPowerOf2()) {
3856 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3857 IntegerMode, ComplexMode);
3858 // Avoid duplicate warning from template instantiation.
3859 if (!InInstantiation)
3860 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3861 } else {
3862 VectorSize = 0;
3863 }
3864 }
3865
3866 if (!VectorSize)
3867 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3868
3869 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3870 // and friends, at least with glibc.
3871 // FIXME: Make sure floating-point mappings are accurate
3872 // FIXME: Support XF and TF types
3873 if (!DestWidth) {
3874 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3875 return;
3876 }
3877
3878 QualType OldTy;
3879 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3880 OldTy = TD->getUnderlyingType();
3881 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3882 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3883 // Try to get type from enum declaration, default to int.
3884 OldTy = ED->getIntegerType();
3885 if (OldTy.isNull())
3886 OldTy = Context.IntTy;
3887 } else
3888 OldTy = cast<ValueDecl>(D)->getType();
3889
3890 if (OldTy->isDependentType()) {
3891 D->addAttr(::new (Context)
3892 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3893 return;
3894 }
3895
3896 // Base type can also be a vector type (see PR17453).
3897 // Distinguish between base type and base element type.
3898 QualType OldElemTy = OldTy;
3899 if (const VectorType *VT = OldTy->getAs<VectorType>())
3900 OldElemTy = VT->getElementType();
3901
3902 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3903 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3904 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3905 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3906 VectorSize.getBoolValue()) {
3907 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3908 return;
3909 }
3910 bool IntegralOrAnyEnumType =
3911 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3912
3913 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3914 !IntegralOrAnyEnumType)
3915 Diag(AttrLoc, diag::err_mode_not_primitive);
3916 else if (IntegerMode) {
3917 if (!IntegralOrAnyEnumType)
3918 Diag(AttrLoc, diag::err_mode_wrong_type);
3919 } else if (ComplexMode) {
3920 if (!OldElemTy->isComplexType())
3921 Diag(AttrLoc, diag::err_mode_wrong_type);
3922 } else {
3923 if (!OldElemTy->isFloatingType())
3924 Diag(AttrLoc, diag::err_mode_wrong_type);
3925 }
3926
3927 QualType NewElemTy;
3928
3929 if (IntegerMode)
3930 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3931 OldElemTy->isSignedIntegerType());
3932 else
3933 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
3934
3935 if (NewElemTy.isNull()) {
3936 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3937 return;
3938 }
3939
3940 if (ComplexMode) {
3941 NewElemTy = Context.getComplexType(NewElemTy);
3942 }
3943
3944 QualType NewTy = NewElemTy;
3945 if (VectorSize.getBoolValue()) {
3946 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3947 VectorType::GenericVector);
3948 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3949 // Complex machine mode does not support base vector types.
3950 if (ComplexMode) {
3951 Diag(AttrLoc, diag::err_complex_mode_vector_type);
3952 return;
3953 }
3954 unsigned NumElements = Context.getTypeSize(OldElemTy) *
3955 OldVT->getNumElements() /
3956 Context.getTypeSize(NewElemTy);
3957 NewTy =
3958 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3959 }
3960
3961 if (NewTy.isNull()) {
3962 Diag(AttrLoc, diag::err_mode_wrong_type);
3963 return;
3964 }
3965
3966 // Install the new type.
3967 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3968 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3969 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3970 ED->setIntegerType(NewTy);
3971 else
3972 cast<ValueDecl>(D)->setType(NewTy);
3973
3974 D->addAttr(::new (Context)
3975 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3976}
3977
3978static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3979 D->addAttr(::new (S.Context)
3980 NoDebugAttr(Attr.getRange(), S.Context,
3981 Attr.getAttributeSpellingListIndex()));
3982}
3983
3984AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3985 IdentifierInfo *Ident,
3986 unsigned AttrSpellingListIndex) {
3987 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3988 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3989 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3990 return nullptr;
3991 }
3992
3993 if (D->hasAttr<AlwaysInlineAttr>())
3994 return nullptr;
3995
3996 return ::new (Context) AlwaysInlineAttr(Range, Context,
3997 AttrSpellingListIndex);
3998}
3999
4000CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
4001 IdentifierInfo *Ident,
4002 unsigned AttrSpellingListIndex) {
4003 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
4004 return nullptr;
4005
4006 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
4007}
4008
4009InternalLinkageAttr *
4010Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
4011 IdentifierInfo *Ident,
4012 unsigned AttrSpellingListIndex) {
4013 if (auto VD = dyn_cast<VarDecl>(D)) {
4014 // Attribute applies to Var but not any subclass of it (like ParmVar,
4015 // ImplicitParm or VarTemplateSpecialization).
4016 if (VD->getKind() != Decl::Var) {
4017 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
4018 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4019 : ExpectedVariableOrFunction);
4020 return nullptr;
4021 }
4022 // Attribute does not apply to non-static local variables.
4023 if (VD->hasLocalStorage()) {
4024 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4025 return nullptr;
4026 }
4027 }
4028
4029 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
4030 return nullptr;
4031
4032 return ::new (Context)
4033 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
4034}
4035
4036MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
4037 unsigned AttrSpellingListIndex) {
4038 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4039 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
4040 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4041 return nullptr;
4042 }
4043
4044 if (D->hasAttr<MinSizeAttr>())
4045 return nullptr;
4046
4047 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
4048}
4049
4050OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
4051 unsigned AttrSpellingListIndex) {
4052 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4053 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4054 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4055 D->dropAttr<AlwaysInlineAttr>();
4056 }
4057 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4058 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4059 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4060 D->dropAttr<MinSizeAttr>();
4061 }
4062
4063 if (D->hasAttr<OptimizeNoneAttr>())
4064 return nullptr;
4065
4066 return ::new (Context) OptimizeNoneAttr(Range, Context,
4067 AttrSpellingListIndex);
4068}
4069
4070static void handleAlwaysInlineAttr(Sema &S, Decl *D,
4071 const AttributeList &Attr) {
4072 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
4073 Attr.getName()))
4074 return;
4075
4076 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4077 D, Attr.getRange(), Attr.getName(),
4078 Attr.getAttributeSpellingListIndex()))
4079 D->addAttr(Inline);
4080}
4081
4082static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4083 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4084 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4085 D->addAttr(MinSize);
4086}
4087
4088static void handleOptimizeNoneAttr(Sema &S, Decl *D,
4089 const AttributeList &Attr) {
4090 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4091 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4092 D->addAttr(Optnone);
4093}
4094
4095static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4096 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
4097 Attr.getName()))
4098 return;
4099 auto *VD = cast<VarDecl>(D);
4100 if (!VD->hasGlobalStorage()) {
4101 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
4102 return;
4103 }
4104 D->addAttr(::new (S.Context) CUDAConstantAttr(
4105 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4106}
4107
4108static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4109 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
1
Taking false branch
4110 Attr.getName()))
4111 return;
4112 auto *VD = cast<VarDecl>(D);
4113 // extern __shared__ is only allowed on arrays with no length (e.g.
4114 // "int x[]").
4115 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
2
Taking false branch
4116 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
4117 return;
4118 }
4119 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
3
Assuming the condition is true
22
Potential leak of memory pointed to by field 'DiagStorage'
4120 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
4
Calling 'operator<<'
21
Returned allocated memory
4121 << S.CurrentCUDATarget())
4122 return;
4123 D->addAttr(::new (S.Context) CUDASharedAttr(
4124 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4125}
4126
4127static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4128 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
4129 Attr.getName()) ||
4130 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
4131 Attr.getName())) {
4132 return;
4133 }
4134 FunctionDecl *FD = cast<FunctionDecl>(D);
4135 if (!FD->getReturnType()->isVoidType()) {
4136 SourceRange RTRange = FD->getReturnTypeSourceRange();
4137 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4138 << FD->getType()
4139 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4140 : FixItHint());
4141 return;
4142 }
4143 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4144 if (Method->isInstance()) {
4145 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
4146 << Method;
4147 return;
4148 }
4149 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
4150 }
4151 // Only warn for "inline" when compiling for host, to cut down on noise.
4152 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4153 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
4154
4155 D->addAttr(::new (S.Context)
4156 CUDAGlobalAttr(Attr.getRange(), S.Context,
4157 Attr.getAttributeSpellingListIndex()));
4158}
4159
4160static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4161 FunctionDecl *Fn = cast<FunctionDecl>(D);
4162 if (!Fn->isInlineSpecified()) {
4163 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4164 return;
4165 }
4166
4167 D->addAttr(::new (S.Context)
4168 GNUInlineAttr(Attr.getRange(), S.Context,
4169 Attr.getAttributeSpellingListIndex()));
4170}
4171
4172static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4173 if (hasDeclarator(D)) return;
4174
4175 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
4176 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4177 CallingConv CC;
4178 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
4179 return;
4180
4181 if (!isa<ObjCMethodDecl>(D)) {
4182 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4183 << Attr.getName() << ExpectedFunctionOrMethod;
4184 return;
4185 }
4186
4187 switch (Attr.getKind()) {
4188 case AttributeList::AT_FastCall:
4189 D->addAttr(::new (S.Context)
4190 FastCallAttr(Attr.getRange(), S.Context,
4191 Attr.getAttributeSpellingListIndex()));
4192 return;
4193 case AttributeList::AT_StdCall:
4194 D->addAttr(::new (S.Context)
4195 StdCallAttr(Attr.getRange(), S.Context,
4196 Attr.getAttributeSpellingListIndex()));
4197 return;
4198 case AttributeList::AT_ThisCall:
4199 D->addAttr(::new (S.Context)
4200 ThisCallAttr(Attr.getRange(), S.Context,
4201 Attr.getAttributeSpellingListIndex()));
4202 return;
4203 case AttributeList::AT_CDecl:
4204 D->addAttr(::new (S.Context)
4205 CDeclAttr(Attr.getRange(), S.Context,
4206 Attr.getAttributeSpellingListIndex()));
4207 return;
4208 case AttributeList::AT_Pascal:
4209 D->addAttr(::new (S.Context)
4210 PascalAttr(Attr.getRange(), S.Context,
4211 Attr.getAttributeSpellingListIndex()));
4212 return;
4213 case AttributeList::AT_SwiftCall:
4214 D->addAttr(::new (S.Context)
4215 SwiftCallAttr(Attr.getRange(), S.Context,
4216 Attr.getAttributeSpellingListIndex()));
4217 return;
4218 case AttributeList::AT_VectorCall:
4219 D->addAttr(::new (S.Context)
4220 VectorCallAttr(Attr.getRange(), S.Context,
4221 Attr.getAttributeSpellingListIndex()));
4222 return;
4223 case AttributeList::AT_MSABI:
4224 D->addAttr(::new (S.Context)
4225 MSABIAttr(Attr.getRange(), S.Context,
4226 Attr.getAttributeSpellingListIndex()));
4227 return;
4228 case AttributeList::AT_SysVABI:
4229 D->addAttr(::new (S.Context)
4230 SysVABIAttr(Attr.getRange(), S.Context,
4231 Attr.getAttributeSpellingListIndex()));
4232 return;
4233 case AttributeList::AT_RegCall:
4234 D->addAttr(::new (S.Context) RegCallAttr(
4235 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4236 return;
4237 case AttributeList::AT_Pcs: {
4238 PcsAttr::PCSType PCS;
4239 switch (CC) {
4240 case CC_AAPCS:
4241 PCS = PcsAttr::AAPCS;
4242 break;
4243 case CC_AAPCS_VFP:
4244 PCS = PcsAttr::AAPCS_VFP;
4245 break;
4246 default:
4247 llvm_unreachable("unexpected calling convention in pcs attribute")::llvm::llvm_unreachable_internal("unexpected calling convention in pcs attribute"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4247)
;
4248 }
4249
4250 D->addAttr(::new (S.Context)
4251 PcsAttr(Attr.getRange(), S.Context, PCS,
4252 Attr.getAttributeSpellingListIndex()));
4253 return;
4254 }
4255 case AttributeList::AT_IntelOclBicc:
4256 D->addAttr(::new (S.Context)
4257 IntelOclBiccAttr(Attr.getRange(), S.Context,
4258 Attr.getAttributeSpellingListIndex()));
4259 return;
4260 case AttributeList::AT_PreserveMost:
4261 D->addAttr(::new (S.Context) PreserveMostAttr(
4262 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4263 return;
4264 case AttributeList::AT_PreserveAll:
4265 D->addAttr(::new (S.Context) PreserveAllAttr(
4266 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4267 return;
4268 default:
4269 llvm_unreachable("unexpected attribute kind")::llvm::llvm_unreachable_internal("unexpected attribute kind"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4269)
;
4270 }
4271}
4272
4273static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4274 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4275 return;
4276
4277 std::vector<StringRef> DiagnosticIdentifiers;
4278 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4279 StringRef RuleName;
4280
4281 if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr))
4282 return;
4283
4284 // FIXME: Warn if the rule name is unknown. This is tricky because only
4285 // clang-tidy knows about available rules.
4286 DiagnosticIdentifiers.push_back(RuleName);
4287 }
4288 D->addAttr(::new (S.Context) SuppressAttr(
4289 Attr.getRange(), S.Context, DiagnosticIdentifiers.data(),
4290 DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex()));
4291}
4292
4293bool Sema::CheckCallingConvAttr(const AttributeList &Attrs, CallingConv &CC,
4294 const FunctionDecl *FD) {
4295 if (Attrs.isInvalid())
4296 return true;
4297
4298 if (Attrs.hasProcessingCache()) {
4299 CC = (CallingConv) Attrs.getProcessingCache();
4300 return false;
4301 }
4302
4303 unsigned ReqArgs = Attrs.getKind() == AttributeList::AT_Pcs ? 1 : 0;
4304 if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4305 Attrs.setInvalid();
4306 return true;
4307 }
4308
4309 // TODO: diagnose uses of these conventions on the wrong target.
4310 switch (Attrs.getKind()) {
4311 case AttributeList::AT_CDecl: CC = CC_C; break;
4312 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4313 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4314 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4315 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
4316 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
4317 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
4318 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
4319 case AttributeList::AT_MSABI:
4320 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4321 CC_Win64;
4322 break;
4323 case AttributeList::AT_SysVABI:
4324 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4325 CC_C;
4326 break;
4327 case AttributeList::AT_Pcs: {
4328 StringRef StrRef;
4329 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4330 Attrs.setInvalid();
4331 return true;
4332 }
4333 if (StrRef == "aapcs") {
4334 CC = CC_AAPCS;
4335 break;
4336 } else if (StrRef == "aapcs-vfp") {
4337 CC = CC_AAPCS_VFP;
4338 break;
4339 }
4340
4341 Attrs.setInvalid();
4342 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4343 return true;
4344 }
4345 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
4346 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4347 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
4348 default: llvm_unreachable("unexpected attribute kind")::llvm::llvm_unreachable_internal("unexpected attribute kind"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4348)
;
4349 }
4350
4351 const TargetInfo &TI = Context.getTargetInfo();
4352 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4353 if (A != TargetInfo::CCCR_OK) {
4354 if (A == TargetInfo::CCCR_Warning)
4355 Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs.getName();
4356
4357 // This convention is not valid for the target. Use the default function or
4358 // method calling convention.
4359 bool IsCXXMethod = false, IsVariadic = false;
4360 if (FD) {
4361 IsCXXMethod = FD->isCXXInstanceMember();
4362 IsVariadic = FD->isVariadic();
4363 }
4364 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4365 }
4366
4367 Attrs.setProcessingCache((unsigned) CC);
4368 return false;
4369}
4370
4371/// Pointer-like types in the default address space.
4372static bool isValidSwiftContextType(QualType type) {
4373 if (!type->hasPointerRepresentation())
4374 return type->isDependentType();
4375 return type->getPointeeType().getAddressSpace() == LangAS::Default;
4376}
4377
4378/// Pointers and references in the default address space.
4379static bool isValidSwiftIndirectResultType(QualType type) {
4380 if (auto ptrType = type->getAs<PointerType>()) {
4381 type = ptrType->getPointeeType();
4382 } else if (auto refType = type->getAs<ReferenceType>()) {
4383 type = refType->getPointeeType();
4384 } else {
4385 return type->isDependentType();
4386 }
4387 return type.getAddressSpace() == LangAS::Default;
4388}
4389
4390/// Pointers and references to pointers in the default address space.
4391static bool isValidSwiftErrorResultType(QualType type) {
4392 if (auto ptrType = type->getAs<PointerType>()) {
4393 type = ptrType->getPointeeType();
4394 } else if (auto refType = type->getAs<ReferenceType>()) {
4395 type = refType->getPointeeType();
4396 } else {
4397 return type->isDependentType();
4398 }
4399 if (!type.getQualifiers().empty())
4400 return false;
4401 return isValidSwiftContextType(type);
4402}
4403
4404static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &Attrs,
4405 ParameterABI Abi) {
4406 S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
4407 Attrs.getAttributeSpellingListIndex());
4408}
4409
4410void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4411 unsigned spellingIndex) {
4412
4413 QualType type = cast<ParmVarDecl>(D)->getType();
4414
4415 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4416 if (existingAttr->getABI() != abi) {
4417 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4418 << getParameterABISpelling(abi) << existingAttr;
4419 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4420 return;
4421 }
4422 }
4423
4424 switch (abi) {
4425 case ParameterABI::Ordinary:
4426 llvm_unreachable("explicit attribute for ordinary parameter ABI?")::llvm::llvm_unreachable_internal("explicit attribute for ordinary parameter ABI?"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4426)
;
4427
4428 case ParameterABI::SwiftContext:
4429 if (!isValidSwiftContextType(type)) {
4430 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4431 << getParameterABISpelling(abi)
4432 << /*pointer to pointer */ 0 << type;
4433 }
4434 D->addAttr(::new (Context)
4435 SwiftContextAttr(range, Context, spellingIndex));
4436 return;
4437
4438 case ParameterABI::SwiftErrorResult:
4439 if (!isValidSwiftErrorResultType(type)) {
4440 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4441 << getParameterABISpelling(abi)
4442 << /*pointer to pointer */ 1 << type;
4443 }
4444 D->addAttr(::new (Context)
4445 SwiftErrorResultAttr(range, Context, spellingIndex));
4446 return;
4447
4448 case ParameterABI::SwiftIndirectResult:
4449 if (!isValidSwiftIndirectResultType(type)) {
4450 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4451 << getParameterABISpelling(abi)
4452 << /*pointer*/ 0 << type;
4453 }
4454 D->addAttr(::new (Context)
4455 SwiftIndirectResultAttr(range, Context, spellingIndex));
4456 return;
4457 }
4458 llvm_unreachable("bad parameter ABI attribute")::llvm::llvm_unreachable_internal("bad parameter ABI attribute"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4458)
;
4459}
4460
4461/// Checks a regparm attribute, returning true if it is ill-formed and
4462/// otherwise setting numParams to the appropriate value.
4463bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4464 if (Attr.isInvalid())
4465 return true;
4466
4467 if (!checkAttributeNumArgs(*this, Attr, 1)) {
4468 Attr.setInvalid();
4469 return true;
4470 }
4471
4472 uint32_t NP;
4473 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
4474 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
4475 Attr.setInvalid();
4476 return true;
4477 }
4478
4479 if (Context.getTargetInfo().getRegParmMax() == 0) {
4480 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
4481 << NumParamsExpr->getSourceRange();
4482 Attr.setInvalid();
4483 return true;
4484 }
4485
4486 numParams = NP;
4487 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4488 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
4489 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4490 Attr.setInvalid();
4491 return true;
4492 }
4493
4494 return false;
4495}
4496
4497// Checks whether an argument of launch_bounds attribute is
4498// acceptable, performs implicit conversion to Rvalue, and returns
4499// non-nullptr Expr result on success. Otherwise, it returns nullptr
4500// and may output an error.
4501static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4502 const CUDALaunchBoundsAttr &Attr,
4503 const unsigned Idx) {
4504 if (S.DiagnoseUnexpandedParameterPack(E))
4505 return nullptr;
4506
4507 // Accept template arguments for now as they depend on something else.
4508 // We'll get to check them when they eventually get instantiated.
4509 if (E->isValueDependent())
4510 return E;
4511
4512 llvm::APSInt I(64);
4513 if (!E->isIntegerConstantExpr(I, S.Context)) {
4514 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4515 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4516 return nullptr;
4517 }
4518 // Make sure we can fit it in 32 bits.
4519 if (!I.isIntN(32)) {
4520 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4521 << 32 << /* Unsigned */ 1;
4522 return nullptr;
4523 }
4524 if (I < 0)
4525 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4526 << &Attr << Idx << E->getSourceRange();
4527
4528 // We may need to perform implicit conversion of the argument.
4529 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4530 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4531 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4532 assert(!ValArg.isInvalid() &&(static_cast <bool> (!ValArg.isInvalid() && "Unexpected PerformCopyInitialization() failure."
) ? void (0) : __assert_fail ("!ValArg.isInvalid() && \"Unexpected PerformCopyInitialization() failure.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4533, __extension__ __PRETTY_FUNCTION__))
4533 "Unexpected PerformCopyInitialization() failure.")(static_cast <bool> (!ValArg.isInvalid() && "Unexpected PerformCopyInitialization() failure."
) ? void (0) : __assert_fail ("!ValArg.isInvalid() && \"Unexpected PerformCopyInitialization() failure.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4533, __extension__ __PRETTY_FUNCTION__))
;
4534
4535 return ValArg.getAs<Expr>();
4536}
4537
4538void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4539 Expr *MinBlocks, unsigned SpellingListIndex) {
4540 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4541 SpellingListIndex);
4542 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4543 if (MaxThreads == nullptr)
4544 return;
4545
4546 if (MinBlocks) {
4547 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4548 if (MinBlocks == nullptr)
4549 return;
4550 }
4551
4552 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4553 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4554}
4555
4556static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4557 const AttributeList &Attr) {
4558 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4559 !checkAttributeAtMostNumArgs(S, Attr, 2))
4560 return;
4561
4562 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4563 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4564 Attr.getAttributeSpellingListIndex());
4565}
4566
4567static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4568 const AttributeList &Attr) {
4569 if (!Attr.isArgIdent(0)) {
4570 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4571 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4572 return;
4573 }
4574
4575 if (!checkAttributeNumArgs(S, Attr, 3))
4576 return;
4577
4578 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
4579
4580 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4581 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4582 << Attr.getName() << ExpectedFunctionOrMethod;
4583 return;
4584 }
4585
4586 uint64_t ArgumentIdx;
4587 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4588 ArgumentIdx))
4589 return;
4590
4591 uint64_t TypeTagIdx;
4592 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4593 TypeTagIdx))
4594 return;
4595
4596 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
4597 if (IsPointer) {
4598 // Ensure that buffer has a pointer type.
4599 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
4600 if (!BufferTy->isPointerType()) {
4601 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4602 << Attr.getName() << 0;
4603 }
4604 }
4605
4606 D->addAttr(::new (S.Context)
4607 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4608 ArgumentIdx, TypeTagIdx, IsPointer,
4609 Attr.getAttributeSpellingListIndex()));
4610}
4611
4612static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4613 const AttributeList &Attr) {
4614 if (!Attr.isArgIdent(0)) {
4615 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4616 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4617 return;
4618 }
4619
4620 if (!checkAttributeNumArgs(S, Attr, 1))
4621 return;
4622
4623 if (!isa<VarDecl>(D)) {
4624 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4625 << Attr.getName() << ExpectedVariable;
4626 return;
4627 }
4628
4629 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4630 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4631 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4632 assert(MatchingCTypeLoc && "no type source info for attribute argument")(static_cast <bool> (MatchingCTypeLoc && "no type source info for attribute argument"
) ? void (0) : __assert_fail ("MatchingCTypeLoc && \"no type source info for attribute argument\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4632, __extension__ __PRETTY_FUNCTION__))
;
4633
4634 D->addAttr(::new (S.Context)
4635 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4636 MatchingCTypeLoc,
4637 Attr.getLayoutCompatible(),
4638 Attr.getMustBeNull(),
4639 Attr.getAttributeSpellingListIndex()));
4640}
4641
4642static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4643 const AttributeList &Attr) {
4644 uint64_t ArgCount;
4645
4646 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
4647 ArgCount,
4648 true /* AllowImplicitThis*/))
4649 return;
4650
4651 // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1.
4652 D->addAttr(::new (S.Context)
4653 XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4654 Attr.getAttributeSpellingListIndex()));
4655}
4656
4657//===----------------------------------------------------------------------===//
4658// Checker-specific attribute handlers.
4659//===----------------------------------------------------------------------===//
4660
4661static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
4662 return type->isDependentType() ||
4663 type->isObjCRetainableType();
4664}
4665
4666static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4667 return type->isDependentType() ||
4668 type->isObjCObjectPointerType() ||
4669 S.Context.isObjCNSObjectType(type);
4670}
4671
4672static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4673 return type->isDependentType() ||
4674 type->isPointerType() ||
4675 isValidSubjectOfNSAttribute(S, type);
4676}
4677
4678static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4679 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4680 Attr.getKind() == AttributeList::AT_NSConsumed,
4681 /*template instantiation*/ false);
4682}
4683
4684void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4685 unsigned spellingIndex, bool isNSConsumed,
4686 bool isTemplateInstantiation) {
4687 ParmVarDecl *param = cast<ParmVarDecl>(D);
4688 bool typeOK;
4689
4690 if (isNSConsumed) {
4691 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
4692 } else {
4693 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
4694 }
4695
4696 if (!typeOK) {
4697 // These attributes are normally just advisory, but in ARC, ns_consumed
4698 // is significant. Allow non-dependent code to contain inappropriate
4699 // attributes even in ARC, but require template instantiations to be
4700 // set up correctly.
4701 Diag(D->getLocStart(),
4702 (isTemplateInstantiation && isNSConsumed &&
4703 getLangOpts().ObjCAutoRefCount
4704 ? diag::err_ns_attribute_wrong_parameter_type
4705 : diag::warn_ns_attribute_wrong_parameter_type))
4706 << attrRange
4707 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4708 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
4709 return;
4710 }
4711
4712 if (isNSConsumed)
4713 param->addAttr(::new (Context)
4714 NSConsumedAttr(attrRange, Context, spellingIndex));
4715 else
4716 param->addAttr(::new (Context)
4717 CFConsumedAttr(attrRange, Context, spellingIndex));
4718}
4719
4720bool Sema::checkNSReturnsRetainedReturnType(SourceLocation loc,
4721 QualType type) {
4722 if (isValidSubjectOfNSReturnsRetainedAttribute(type))
4723 return false;
4724
4725 Diag(loc, diag::warn_ns_attribute_wrong_return_type)
4726 << "'ns_returns_retained'" << 0 << 0;
4727 return true;
4728}
4729
4730static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4731 const AttributeList &Attr) {
4732 QualType returnType;
4733
4734 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4735 returnType = MD->getReturnType();
4736 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4737 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4738 return; // ignore: was handled as a type attribute
4739 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4740 returnType = PD->getType();
4741 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4742 returnType = FD->getReturnType();
4743 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4744 returnType = Param->getType()->getPointeeType();
4745 if (returnType.isNull()) {
4746 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4747 << Attr.getName() << /*pointer-to-CF*/2
4748 << Attr.getRange();
4749 return;
4750 }
4751 } else if (Attr.isUsedAsTypeAttr()) {
4752 return;
4753 } else {
4754 AttributeDeclKind ExpectedDeclKind;
4755 switch (Attr.getKind()) {
4756 default: llvm_unreachable("invalid ownership attribute")::llvm::llvm_unreachable_internal("invalid ownership attribute"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4756)
;
4757 case AttributeList::AT_NSReturnsRetained:
4758 case AttributeList::AT_NSReturnsAutoreleased:
4759 case AttributeList::AT_NSReturnsNotRetained:
4760 ExpectedDeclKind = ExpectedFunctionOrMethod;
4761 break;
4762
4763 case AttributeList::AT_CFReturnsRetained:
4764 case AttributeList::AT_CFReturnsNotRetained:
4765 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4766 break;
4767 }
4768 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4769 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4770 return;
4771 }
4772
4773 bool typeOK;
4774 bool cf;
4775 switch (Attr.getKind()) {
4776 default: llvm_unreachable("invalid ownership attribute")::llvm::llvm_unreachable_internal("invalid ownership attribute"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4776)
;
4777 case AttributeList::AT_NSReturnsRetained:
4778 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4779 cf = false;
4780 break;
4781
4782 case AttributeList::AT_NSReturnsAutoreleased:
4783 case AttributeList::AT_NSReturnsNotRetained:
4784 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4785 cf = false;
4786 break;
4787
4788 case AttributeList::AT_CFReturnsRetained:
4789 case AttributeList::AT_CFReturnsNotRetained:
4790 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4791 cf = true;
4792 break;
4793 }
4794
4795 if (!typeOK) {
4796 if (Attr.isUsedAsTypeAttr())
4797 return;
4798
4799 if (isa<ParmVarDecl>(D)) {
4800 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4801 << Attr.getName() << /*pointer-to-CF*/2
4802 << Attr.getRange();
4803 } else {
4804 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4805 enum : unsigned {
4806 Function,
4807 Method,
4808 Property
4809 } SubjectKind = Function;
4810 if (isa<ObjCMethodDecl>(D))
4811 SubjectKind = Method;
4812 else if (isa<ObjCPropertyDecl>(D))
4813 SubjectKind = Property;
4814 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4815 << Attr.getName() << SubjectKind << cf
4816 << Attr.getRange();
4817 }
4818 return;
4819 }
4820
4821 switch (Attr.getKind()) {
4822 default:
4823 llvm_unreachable("invalid ownership attribute")::llvm::llvm_unreachable_internal("invalid ownership attribute"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4823)
;
4824 case AttributeList::AT_NSReturnsAutoreleased:
4825 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4826 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4827 return;
4828 case AttributeList::AT_CFReturnsNotRetained:
4829 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4830 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4831 return;
4832 case AttributeList::AT_NSReturnsNotRetained:
4833 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4834 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4835 return;
4836 case AttributeList::AT_CFReturnsRetained:
4837 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4838 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4839 return;
4840 case AttributeList::AT_NSReturnsRetained:
4841 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4842 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4843 return;
4844 };
4845}
4846
4847static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4848 const AttributeList &Attrs) {
4849 const int EP_ObjCMethod = 1;
4850 const int EP_ObjCProperty = 2;
4851
4852 SourceLocation loc = Attrs.getLoc();
4853 QualType resultType;
4854 if (isa<ObjCMethodDecl>(D))
4855 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4856 else
4857 resultType = cast<ObjCPropertyDecl>(D)->getType();
4858
4859 if (!resultType->isReferenceType() &&
4860 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4861 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4862 << SourceRange(loc)
4863 << Attrs.getName()
4864 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4865 << /*non-retainable pointer*/ 2;
4866
4867 // Drop the attribute.
4868 return;
4869 }
4870
4871 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4872 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
4873}
4874
4875static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4876 const AttributeList &Attrs) {
4877 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4878
4879 DeclContext *DC = method->getDeclContext();
4880 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4881 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4882 << Attrs.getName() << 0;
4883 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4884 return;
4885 }
4886 if (method->getMethodFamily() == OMF_dealloc) {
4887 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4888 << Attrs.getName() << 1;
4889 return;
4890 }
4891
4892 method->addAttr(::new (S.Context)
4893 ObjCRequiresSuperAttr(Attrs.getRange(), S.Context,
4894 Attrs.getAttributeSpellingListIndex()));
4895}
4896
4897static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4898 const AttributeList &Attr) {
4899 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4900 Attr.getName()))
4901 return;
4902
4903 D->addAttr(::new (S.Context)
4904 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4905 Attr.getAttributeSpellingListIndex()));
4906}
4907
4908static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4909 const AttributeList &Attr) {
4910 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4911 Attr.getName()))
4912 return;
4913
4914 D->addAttr(::new (S.Context)
4915 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4916 Attr.getAttributeSpellingListIndex()));
4917}
4918
4919static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4920 const AttributeList &Attr) {
4921 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4922
4923 if (!Parm) {
4924 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4925 return;
4926 }
4927
4928 // Typedefs only allow objc_bridge(id) and have some additional checking.
4929 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4930 if (!Parm->Ident->isStr("id")) {
4931 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4932 << Attr.getName();
4933 return;
4934 }
4935
4936 // Only allow 'cv void *'.
4937 QualType T = TD->getUnderlyingType();
4938 if (!T->isVoidPointerType()) {
4939 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4940 return;
4941 }
4942 }
4943
4944 D->addAttr(::new (S.Context)
4945 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4946 Attr.getAttributeSpellingListIndex()));
4947}
4948
4949static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4950 const AttributeList &Attr) {
4951 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4952
4953 if (!Parm) {
4954 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4955 return;
4956 }
4957
4958 D->addAttr(::new (S.Context)
4959 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4960 Attr.getAttributeSpellingListIndex()));
4961}
4962
4963static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4964 const AttributeList &Attr) {
4965 IdentifierInfo *RelatedClass =
4966 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4967 if (!RelatedClass) {
4968 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4969 return;
4970 }
4971 IdentifierInfo *ClassMethod =
4972 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4973 IdentifierInfo *InstanceMethod =
4974 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4975 D->addAttr(::new (S.Context)
4976 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4977 ClassMethod, InstanceMethod,
4978 Attr.getAttributeSpellingListIndex()));
4979}
4980
4981static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4982 const AttributeList &Attr) {
4983 ObjCInterfaceDecl *IFace;
4984 if (ObjCCategoryDecl *CatDecl =
4985 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4986 IFace = CatDecl->getClassInterface();
4987 else
4988 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4989
4990 if (!IFace)
4991 return;
4992
4993 IFace->setHasDesignatedInitializers();
4994 D->addAttr(::new (S.Context)
4995 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4996 Attr.getAttributeSpellingListIndex()));
4997}
4998
4999static void handleObjCRuntimeName(Sema &S, Decl *D,
5000 const AttributeList &Attr) {
5001 StringRef MetaDataName;
5002 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
5003 return;
5004 D->addAttr(::new (S.Context)
5005 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
5006 MetaDataName,
5007 Attr.getAttributeSpellingListIndex()));
5008}
5009
5010// When a user wants to use objc_boxable with a union or struct
5011// but they don't have access to the declaration (legacy/third-party code)
5012// then they can 'enable' this feature with a typedef:
5013// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5014static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
5015 bool notify = false;
5016
5017 RecordDecl *RD = dyn_cast<RecordDecl>(D);
5018 if (RD && RD->getDefinition()) {
5019 RD = RD->getDefinition();
5020 notify = true;
5021 }
5022
5023 if (RD) {
5024 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
5025 ObjCBoxableAttr(Attr.getRange(), S.Context,
5026 Attr.getAttributeSpellingListIndex());
5027 RD->addAttr(BoxableAttr);
5028 if (notify) {
5029 // we need to notify ASTReader/ASTWriter about
5030 // modification of existing declaration
5031 if (ASTMutationListener *L = S.getASTMutationListener())
5032 L->AddedAttributeToRecord(BoxableAttr, RD);
5033 }
5034 }
5035}
5036
5037static void handleObjCOwnershipAttr(Sema &S, Decl *D,
5038 const AttributeList &Attr) {
5039 if (hasDeclarator(D)) return;
5040
5041 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
5042 << Attr.getRange() << Attr.getName() << ExpectedVariable;
5043}
5044
5045static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5046 const AttributeList &Attr) {
5047 ValueDecl *vd = cast<ValueDecl>(D);
5048 QualType type = vd->getType();
5049
5050 if (!type->isDependentType() &&
5051 !type->isObjCLifetimeType()) {
5052 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5053 << type;
5054 return;
5055 }
5056
5057 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5058
5059 // If we have no lifetime yet, check the lifetime we're presumably
5060 // going to infer.
5061 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
5062 lifetime = type->getObjCARCImplicitLifetime();
5063
5064 switch (lifetime) {
5065 case Qualifiers::OCL_None:
5066 assert(type->isDependentType() &&(static_cast <bool> (type->isDependentType() &&
"didn't infer lifetime for non-dependent type?") ? void (0) :
__assert_fail ("type->isDependentType() && \"didn't infer lifetime for non-dependent type?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 5067, __extension__ __PRETTY_FUNCTION__))
5067 "didn't infer lifetime for non-dependent type?")(static_cast <bool> (type->isDependentType() &&
"didn't infer lifetime for non-dependent type?") ? void (0) :
__assert_fail ("type->isDependentType() && \"didn't infer lifetime for non-dependent type?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 5067, __extension__ __PRETTY_FUNCTION__))
;
5068 break;
5069
5070 case Qualifiers::OCL_Weak: // meaningful
5071 case Qualifiers::OCL_Strong: // meaningful
5072 break;
5073
5074 case Qualifiers::OCL_ExplicitNone:
5075 case Qualifiers::OCL_Autoreleasing:
5076 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5077 << (lifetime == Qualifiers::OCL_Autoreleasing);
5078 break;
5079 }
5080
5081 D->addAttr(::new (S.Context)
5082 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
5083 Attr.getAttributeSpellingListIndex()));
5084}
5085
5086//===----------------------------------------------------------------------===//
5087// Microsoft specific attribute handlers.
5088//===----------------------------------------------------------------------===//
5089
5090UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
5091 unsigned AttrSpellingListIndex, StringRef Uuid) {
5092 if (const auto *UA = D->getAttr<UuidAttr>()) {
5093 if (UA->getGuid().equals_lower(Uuid))
5094 return nullptr;
5095 Diag(UA->getLocation(), diag::err_mismatched_uuid);
5096 Diag(Range.getBegin(), diag::note_previous_uuid);
5097 D->dropAttr<UuidAttr>();
5098 }
5099
5100 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5101}
5102
5103static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5104 if (!S.LangOpts.CPlusPlus) {
5105 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5106 << Attr.getName() << AttributeLangSupport::C;
5107 return;
5108 }
5109
5110 StringRef StrRef;
5111 SourceLocation LiteralLoc;
5112 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
5113 return;
5114
5115 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5116 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5117 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5118 StrRef = StrRef.drop_front().drop_back();
5119
5120 // Validate GUID length.
5121 if (StrRef.size() != 36) {
5122 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5123 return;
5124 }
5125
5126 for (unsigned i = 0; i < 36; ++i) {
5127 if (i == 8 || i == 13 || i == 18 || i == 23) {
5128 if (StrRef[i] != '-') {
5129 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5130 return;
5131 }
5132 } else if (!isHexDigit(StrRef[i])) {
5133 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5134 return;
5135 }
5136 }
5137
5138 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5139 // the only thing in the [] list, the [] too), and add an insertion of
5140 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5141 // separating attributes nor of the [ and the ] are in the AST.
5142 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5143 // on cfe-dev.
5144 if (Attr.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5145 S.Diag(Attr.getLoc(), diag::warn_atl_uuid_deprecated);
5146
5147 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
5148 Attr.getAttributeSpellingListIndex(), StrRef);
5149 if (UA)
5150 D->addAttr(UA);
5151}
5152
5153static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5154 if (!S.LangOpts.CPlusPlus) {
5155 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5156 << Attr.getName() << AttributeLangSupport::C;
5157 return;
5158 }
5159 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5160 D, Attr.getRange(), /*BestCase=*/true,
5161 Attr.getAttributeSpellingListIndex(),
5162 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
5163 if (IA) {
5164 D->addAttr(IA);
5165 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5166 }
5167}
5168
5169static void handleDeclspecThreadAttr(Sema &S, Decl *D,
5170 const AttributeList &Attr) {
5171 VarDecl *VD = cast<VarDecl>(D);
5172 if (!S.Context.getTargetInfo().isTLSSupported()) {
5173 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
5174 return;
5175 }
5176 if (VD->getTSCSpec() != TSCS_unspecified) {
5177 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
5178 return;
5179 }
5180 if (VD->hasLocalStorage()) {
5181 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5182 return;
5183 }
5184 VD->addAttr(::new (S.Context) ThreadAttr(
5185 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5186}
5187
5188static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5189 SmallVector<StringRef, 4> Tags;
5190 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5191 StringRef Tag;
5192 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
5193 return;
5194 Tags.push_back(Tag);
5195 }
5196
5197 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5198 if (!NS->isInline()) {
5199 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5200 return;
5201 }
5202 if (NS->isAnonymousNamespace()) {
5203 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5204 return;
5205 }
5206 if (Attr.getNumArgs() == 0)
5207 Tags.push_back(NS->getName());
5208 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5209 return;
5210
5211 // Store tags sorted and without duplicates.
5212 std::sort(Tags.begin(), Tags.end());
5213 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5214
5215 D->addAttr(::new (S.Context)
5216 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
5217 Attr.getAttributeSpellingListIndex()));
5218}
5219
5220static void handleARMInterruptAttr(Sema &S, Decl *D,
5221 const AttributeList &Attr) {
5222 // Check the attribute arguments.
5223 if (Attr.getNumArgs() > 1) {
5224 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5225 << Attr.getName() << 1;
5226 return;
5227 }
5228
5229 StringRef Str;
5230 SourceLocation ArgLoc;
5231
5232 if (Attr.getNumArgs() == 0)
5233 Str = "";
5234 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5235 return;
5236
5237 ARMInterruptAttr::InterruptType Kind;
5238 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5239 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5240 << Attr.getName() << Str << ArgLoc;
5241 return;
5242 }
5243
5244 unsigned Index = Attr.getAttributeSpellingListIndex();
5245 D->addAttr(::new (S.Context)
5246 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
5247}
5248
5249static void handleMSP430InterruptAttr(Sema &S, Decl *D,
5250 const AttributeList &Attr) {
5251 if (!checkAttributeNumArgs(S, Attr, 1))
5252 return;
5253
5254 if (!Attr.isArgExpr(0)) {
5255 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
5256 << AANT_ArgumentIntegerConstant;
5257 return;
5258 }
5259
5260 // FIXME: Check for decl - it should be void ()(void).
5261
5262 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5263 llvm::APSInt NumParams(32);
5264 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5265 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5266 << Attr.getName() << AANT_ArgumentIntegerConstant
5267 << NumParamsExpr->getSourceRange();
5268 return;
5269 }
5270
5271 unsigned Num = NumParams.getLimitedValue(255);
5272 if ((Num & 1) || Num > 30) {
5273 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5274 << Attr.getName() << (int)NumParams.getSExtValue()
5275 << NumParamsExpr->getSourceRange();
5276 return;
5277 }
5278
5279 D->addAttr(::new (S.Context)
5280 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5281 Attr.getAttributeSpellingListIndex()));
5282 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5283}
5284
5285static void handleMipsInterruptAttr(Sema &S, Decl *D,
5286 const AttributeList &Attr) {
5287 // Only one optional argument permitted.
5288 if (Attr.getNumArgs() > 1) {
5289 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5290 << Attr.getName() << 1;
5291 return;
5292 }
5293
5294 StringRef Str;
5295 SourceLocation ArgLoc;
5296
5297 if (Attr.getNumArgs() == 0)
5298 Str = "";
5299 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5300 return;
5301
5302 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5303 // a) Must be a function.
5304 // b) Must have no parameters.
5305 // c) Must have the 'void' return type.
5306 // d) Cannot have the 'mips16' attribute, as that instruction set
5307 // lacks the 'eret' instruction.
5308 // e) The attribute itself must either have no argument or one of the
5309 // valid interrupt types, see [MipsInterruptDocs].
5310
5311 if (!isFunctionOrMethod(D)) {
5312 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5313 << "'interrupt'" << ExpectedFunctionOrMethod;
5314 return;
5315 }
5316
5317 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5318 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5319 << 0;
5320 return;
5321 }
5322
5323 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5324 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5325 << 1;
5326 return;
5327 }
5328
5329 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
5330 Attr.getName()))
5331 return;
5332
5333 MipsInterruptAttr::InterruptType Kind;
5334 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5335 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5336 << Attr.getName() << "'" + std::string(Str) + "'";
5337 return;
5338 }
5339
5340 D->addAttr(::new (S.Context) MipsInterruptAttr(
5341 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
5342}
5343
5344static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
5345 const AttributeList &Attr) {
5346 // Semantic checks for a function with the 'interrupt' attribute.
5347 // a) Must be a function.
5348 // b) Must have the 'void' return type.
5349 // c) Must take 1 or 2 arguments.
5350 // d) The 1st argument must be a pointer.
5351 // e) The 2nd argument (if any) must be an unsigned integer.
5352 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5353 CXXMethodDecl::isStaticOverloadedOperator(
5354 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5355 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5356 << Attr.getName() << ExpectedFunctionWithProtoType;
5357 return;
5358 }
5359 // Interrupt handler must have void return type.
5360 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5361 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5362 diag::err_anyx86_interrupt_attribute)
5363 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5364 ? 0
5365 : 1)
5366 << 0;
5367 return;
5368 }
5369 // Interrupt handler must have 1 or 2 parameters.
5370 unsigned NumParams = getFunctionOrMethodNumParams(D);
5371 if (NumParams < 1 || NumParams > 2) {
5372 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5373 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5374 ? 0
5375 : 1)
5376 << 1;
5377 return;
5378 }
5379 // The first argument must be a pointer.
5380 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5381 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5382 diag::err_anyx86_interrupt_attribute)
5383 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5384 ? 0
5385 : 1)
5386 << 2;
5387 return;
5388 }
5389 // The second argument, if present, must be an unsigned integer.
5390 unsigned TypeSize =
5391 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5392 ? 64
5393 : 32;
5394 if (NumParams == 2 &&
5395 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5396 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5397 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5398 diag::err_anyx86_interrupt_attribute)
5399 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5400 ? 0
5401 : 1)
5402 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5403 return;
5404 }
5405 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5406 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5407 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5408}
5409
5410static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5411 if (!isFunctionOrMethod(D)) {
5412 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5413 << "'interrupt'" << ExpectedFunction;
5414 return;
5415 }
5416
5417 if (!checkAttributeNumArgs(S, Attr, 0))
5418 return;
5419
5420 handleSimpleAttribute<AVRInterruptAttr>(S, D, Attr);
5421}
5422
5423static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5424 if (!isFunctionOrMethod(D)) {
5425 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5426 << "'signal'" << ExpectedFunction;
5427 return;
5428 }
5429
5430 if (!checkAttributeNumArgs(S, Attr, 0))
5431 return;
5432
5433 handleSimpleAttribute<AVRSignalAttr>(S, D, Attr);
5434}
5435
5436static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5437 // Dispatch the interrupt attribute based on the current target.
5438 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5439 case llvm::Triple::msp430:
5440 handleMSP430InterruptAttr(S, D, Attr);
5441 break;
5442 case llvm::Triple::mipsel:
5443 case llvm::Triple::mips:
5444 handleMipsInterruptAttr(S, D, Attr);
5445 break;
5446 case llvm::Triple::x86:
5447 case llvm::Triple::x86_64:
5448 handleAnyX86InterruptAttr(S, D, Attr);
5449 break;
5450 case llvm::Triple::avr:
5451 handleAVRInterruptAttr(S, D, Attr);
5452 break;
5453 default:
5454 handleARMInterruptAttr(S, D, Attr);
5455 break;
5456 }
5457}
5458
5459static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5460 const AttributeList &Attr) {
5461 uint32_t Min = 0;
5462 Expr *MinExpr = Attr.getArgAsExpr(0);
5463 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5464 return;
5465
5466 uint32_t Max = 0;
5467 Expr *MaxExpr = Attr.getArgAsExpr(1);
5468 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5469 return;
5470
5471 if (Min == 0 && Max != 0) {
5472 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5473 << Attr.getName() << 0;
5474 return;
5475 }
5476 if (Min > Max) {
5477 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5478 << Attr.getName() << 1;
5479 return;
5480 }
5481
5482 D->addAttr(::new (S.Context)
5483 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5484 Attr.getAttributeSpellingListIndex()));
5485}
5486
5487static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5488 const AttributeList &Attr) {
5489 uint32_t Min = 0;
5490 Expr *MinExpr = Attr.getArgAsExpr(0);
5491 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5492 return;
5493
5494 uint32_t Max = 0;
5495 if (Attr.getNumArgs() == 2) {
5496 Expr *MaxExpr = Attr.getArgAsExpr(1);
5497 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5498 return;
5499 }
5500
5501 if (Min == 0 && Max != 0) {
5502 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5503 << Attr.getName() << 0;
5504 return;
5505 }
5506 if (Max != 0 && Min > Max) {
5507 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5508 << Attr.getName() << 1;
5509 return;
5510 }
5511
5512 D->addAttr(::new (S.Context)
5513 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5514 Attr.getAttributeSpellingListIndex()));
5515}
5516
5517static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5518 const AttributeList &Attr) {
5519 uint32_t NumSGPR = 0;
5520 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5521 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
5522 return;
5523
5524 D->addAttr(::new (S.Context)
5525 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5526 Attr.getAttributeSpellingListIndex()));
5527}
5528
5529static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5530 const AttributeList &Attr) {
5531 uint32_t NumVGPR = 0;
5532 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5533 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5534 return;
5535
5536 D->addAttr(::new (S.Context)
5537 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
5538 Attr.getAttributeSpellingListIndex()));
5539}
5540
5541static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5542 const AttributeList& Attr) {
5543 // If we try to apply it to a function pointer, don't warn, but don't
5544 // do anything, either. It doesn't matter anyway, because there's nothing
5545 // special about calling a force_align_arg_pointer function.
5546 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5547 if (VD && VD->getType()->isFunctionPointerType())
5548 return;
5549 // Also don't warn on function pointer typedefs.
5550 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5551 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5552 TD->getUnderlyingType()->isFunctionType()))
5553 return;
5554 // Attribute can only be applied to function types.
5555 if (!isa<FunctionDecl>(D)) {
5556 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5557 << Attr.getName() << ExpectedFunction;
5558 return;
5559 }
5560
5561 D->addAttr(::new (S.Context)
5562 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5563 Attr.getAttributeSpellingListIndex()));
5564}
5565
5566static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5567 uint32_t Version;
5568 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5569 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5570 return;
5571
5572 // TODO: Investigate what happens with the next major version of MSVC.
5573 if (Version != LangOptions::MSVC2015) {
5574 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5575 << Attr.getName() << Version << VersionExpr->getSourceRange();
5576 return;
5577 }
5578
5579 D->addAttr(::new (S.Context)
5580 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5581 Attr.getAttributeSpellingListIndex()));
5582}
5583
5584DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5585 unsigned AttrSpellingListIndex) {
5586 if (D->hasAttr<DLLExportAttr>()) {
5587 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5588 return nullptr;
5589 }
5590
5591 if (D->hasAttr<DLLImportAttr>())
5592 return nullptr;
5593
5594 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5595}
5596
5597DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5598 unsigned AttrSpellingListIndex) {
5599 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5600 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5601 D->dropAttr<DLLImportAttr>();
5602 }
5603
5604 if (D->hasAttr<DLLExportAttr>())
5605 return nullptr;
5606
5607 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5608}
5609
5610static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
5611 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5612 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5613 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5614 << A.getName();
5615 return;
5616 }
5617
5618 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5619 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5620 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5621 // MinGW doesn't allow dllimport on inline functions.
5622 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5623 << A.getName();
5624 return;
5625 }
5626 }
5627
5628 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5629 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5630 MD->getParent()->isLambda()) {
5631 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5632 return;
5633 }
5634 }
5635
5636 unsigned Index = A.getAttributeSpellingListIndex();
5637 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5638 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5639 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5640 if (NewAttr)
5641 D->addAttr(NewAttr);
5642}
5643
5644MSInheritanceAttr *
5645Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5646 unsigned AttrSpellingListIndex,
5647 MSInheritanceAttr::Spelling SemanticSpelling) {
5648 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5649 if (IA->getSemanticSpelling() == SemanticSpelling)
5650 return nullptr;
5651 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5652 << 1 /*previous declaration*/;
5653 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5654 D->dropAttr<MSInheritanceAttr>();
5655 }
5656
5657 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5658 if (RD->hasDefinition()) {
5659 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5660 SemanticSpelling)) {
5661 return nullptr;
5662 }
5663 } else {
5664 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5665 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5666 << 1 /*partial specialization*/;
5667 return nullptr;
5668 }
5669 if (RD->getDescribedClassTemplate()) {
5670 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5671 << 0 /*primary template*/;
5672 return nullptr;
5673 }
5674 }
5675
5676 return ::new (Context)
5677 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5678}
5679
5680static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5681 // The capability attributes take a single string parameter for the name of
5682 // the capability they represent. The lockable attribute does not take any
5683 // parameters. However, semantically, both attributes represent the same
5684 // concept, and so they use the same semantic attribute. Eventually, the
5685 // lockable attribute will be removed.
5686 //
5687 // For backward compatibility, any capability which has no specified string
5688 // literal will be considered a "mutex."
5689 StringRef N("mutex");
5690 SourceLocation LiteralLoc;
5691 if (Attr.getKind() == AttributeList::AT_Capability &&
5692 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5693 return;
5694
5695 // Currently, there are only two names allowed for a capability: role and
5696 // mutex (case insensitive). Diagnose other capability names.
5697 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5698 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5699
5700 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5701 Attr.getAttributeSpellingListIndex()));
5702}
5703
5704static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5705 const AttributeList &Attr) {
5706 SmallVector<Expr*, 1> Args;
5707 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5708 return;
5709
5710 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5711 Args.data(), Args.size(),
5712 Attr.getAttributeSpellingListIndex()));
5713}
5714
5715static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5716 const AttributeList &Attr) {
5717 SmallVector<Expr*, 1> Args;
5718 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5719 return;
5720
5721 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5722 S.Context,
5723 Args.data(), Args.size(),
5724 Attr.getAttributeSpellingListIndex()));
5725}
5726
5727static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5728 const AttributeList &Attr) {
5729 SmallVector<Expr*, 2> Args;
5730 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5731 return;
5732
5733 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5734 S.Context,
5735 Attr.getArgAsExpr(0),
5736 Args.data(),
5737 Args.size(),
5738 Attr.getAttributeSpellingListIndex()));
5739}
5740
5741static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5742 const AttributeList &Attr) {
5743 // Check that all arguments are lockable objects.
5744 SmallVector<Expr *, 1> Args;
5745 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
5746
5747 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5748 Attr.getRange(), S.Context, Args.data(), Args.size(),
5749 Attr.getAttributeSpellingListIndex()));
5750}
5751
5752static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5753 const AttributeList &Attr) {
5754 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5755 return;
5756
5757 // check that all arguments are lockable objects
5758 SmallVector<Expr*, 1> Args;
5759 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
5760 if (Args.empty())
5761 return;
5762
5763 RequiresCapabilityAttr *RCA = ::new (S.Context)
5764 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5765 Args.size(), Attr.getAttributeSpellingListIndex());
5766
5767 D->addAttr(RCA);
5768}
5769
5770static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5771 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5772 if (NSD->isAnonymousNamespace()) {
5773 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5774 // Do not want to attach the attribute to the namespace because that will
5775 // cause confusing diagnostic reports for uses of declarations within the
5776 // namespace.
5777 return;
5778 }
5779 }
5780
5781 // Handle the cases where the attribute has a text message.
5782 StringRef Str, Replacement;
5783 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5784 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5785 return;
5786
5787 // Only support a single optional message for Declspec and CXX11.
5788 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5789 checkAttributeAtMostNumArgs(S, Attr, 1);
5790 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5791 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5792 return;
5793
5794 if (!S.getLangOpts().CPlusPlus14)
5795 if (Attr.isCXX11Attribute() &&
5796 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
5797 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
5798
5799 D->addAttr(::new (S.Context)
5800 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5801 Attr.getAttributeSpellingListIndex()));
5802}
5803
5804static bool isGlobalVar(const Decl *D) {
5805 if (const auto *S = dyn_cast<VarDecl>(D))
5806 return S->hasGlobalStorage();
5807 return false;
5808}
5809
5810static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5811 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5812 return;
5813
5814 std::vector<StringRef> Sanitizers;
5815
5816 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5817 StringRef SanitizerName;
5818 SourceLocation LiteralLoc;
5819
5820 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5821 return;
5822
5823 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5824 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5825 else if (isGlobalVar(D) && SanitizerName != "address")
5826 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5827 << Attr.getName() << ExpectedFunctionOrMethod;
5828 Sanitizers.push_back(SanitizerName);
5829 }
5830
5831 D->addAttr(::new (S.Context) NoSanitizeAttr(
5832 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5833 Attr.getAttributeSpellingListIndex()));
5834}
5835
5836static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5837 const AttributeList &Attr) {
5838 StringRef AttrName = Attr.getName()->getName();
5839 normalizeName(AttrName);
5840 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5841 .Case("no_address_safety_analysis", "address")
5842 .Case("no_sanitize_address", "address")
5843 .Case("no_sanitize_thread", "thread")
5844 .Case("no_sanitize_memory", "memory");
5845 if (isGlobalVar(D) && SanitizerName != "address")
5846 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5847 << Attr.getName() << ExpectedFunction;
5848 D->addAttr(::new (S.Context)
5849 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5850 Attr.getAttributeSpellingListIndex()));
5851}
5852
5853static void handleInternalLinkageAttr(Sema &S, Decl *D,
5854 const AttributeList &Attr) {
5855 if (InternalLinkageAttr *Internal =
5856 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5857 Attr.getAttributeSpellingListIndex()))
5858 D->addAttr(Internal);
5859}
5860
5861static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5862 if (S.LangOpts.OpenCLVersion != 200)
5863 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5864 << Attr.getName() << "2.0" << 0;
5865 else
5866 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5867 << Attr.getName() << "2.0";
5868}
5869
5870/// Handles semantic checking for features that are common to all attributes,
5871/// such as checking whether a parameter was properly specified, or the correct
5872/// number of arguments were passed, etc.
5873static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5874 const AttributeList &Attr) {
5875 // Several attributes carry different semantics than the parsing requires, so
5876 // those are opted out of the common argument checks.
5877 //
5878 // We also bail on unknown and ignored attributes because those are handled
5879 // as part of the target-specific handling logic.
5880 if (Attr.getKind() == AttributeList::UnknownAttribute)
5881 return false;
5882 // Check whether the attribute requires specific language extensions to be
5883 // enabled.
5884 if (!Attr.diagnoseLangOpts(S))
5885 return true;
5886 // Check whether the attribute appertains to the given subject.
5887 if (!Attr.diagnoseAppertainsTo(S, D))
5888 return true;
5889 if (Attr.hasCustomParsing())
5890 return false;
5891
5892 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5893 // If there are no optional arguments, then checking for the argument count
5894 // is trivial.
5895 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5896 return true;
5897 } else {
5898 // There are optional arguments, so checking is slightly more involved.
5899 if (Attr.getMinArgs() &&
5900 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5901 return true;
5902 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5903 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5904 return true;
5905 }
5906
5907 return false;
5908}
5909
5910static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5911 const AttributeList &Attr) {
5912 if (D->isInvalidDecl())
5913 return;
5914
5915 // Check if there is only one access qualifier.
5916 if (D->hasAttr<OpenCLAccessAttr>()) {
5917 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5918 << D->getSourceRange();
5919 D->setInvalidDecl(true);
5920 return;
5921 }
5922
5923 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5924 // image object can be read and written.
5925 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5926 // object. Using the read_write (or __read_write) qualifier with the pipe
5927 // qualifier is a compilation error.
5928 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5929 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5930 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5931 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5932 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5933 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5934 D->setInvalidDecl(true);
5935 return;
5936 }
5937 }
5938 }
5939
5940 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5941 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5942}
5943
5944//===----------------------------------------------------------------------===//
5945// Top Level Sema Entry Points
5946//===----------------------------------------------------------------------===//
5947
5948/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5949/// the attribute applies to decls. If the attribute is a type attribute, just
5950/// silently ignore it if a GNU attribute.
5951static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5952 const AttributeList &Attr,
5953 bool IncludeCXX11Attributes) {
5954 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
5955 return;
5956
5957 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5958 // instead.
5959 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5960 return;
5961
5962 // Unknown attributes are automatically warned on. Target-specific attributes
5963 // which do not apply to the current target architecture are treated as
5964 // though they were unknown attributes.
5965 if (Attr.getKind() == AttributeList::UnknownAttribute ||
5966 !Attr.existsInTarget(S.Context.getTargetInfo())) {
5967 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5968 ? diag::warn_unhandled_ms_attribute_ignored
5969 : diag::warn_unknown_attribute_ignored)
5970 << Attr.getName();
5971 return;
5972 }
5973
5974 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5975 return;
5976
5977 switch (Attr.getKind()) {
5978 default:
5979 if (!Attr.isStmtAttr()) {
5980 // Type attributes are handled elsewhere; silently move on.
5981 assert(Attr.isTypeAttr() && "Non-type attribute not handled")(static_cast <bool> (Attr.isTypeAttr() && "Non-type attribute not handled"
) ? void (0) : __assert_fail ("Attr.isTypeAttr() && \"Non-type attribute not handled\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 5981, __extension__ __PRETTY_FUNCTION__))
;
5982 break;
5983 }
5984 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5985 << Attr.getName() << D->getLocation();
5986 break;
5987 case AttributeList::AT_Interrupt:
5988 handleInterruptAttr(S, D, Attr);
5989 break;
5990 case AttributeList::AT_X86ForceAlignArgPointer:
5991 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5992 break;
5993 case AttributeList::AT_DLLExport:
5994 case AttributeList::AT_DLLImport:
5995 handleDLLAttr(S, D, Attr);
5996 break;
5997 case AttributeList::AT_Mips16:
5998 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
5999 MipsInterruptAttr>(S, D, Attr);
6000 break;
6001 case AttributeList::AT_NoMips16:
6002 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
6003 break;
6004 case AttributeList::AT_MicroMips:
6005 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, Attr);
6006 break;
6007 case AttributeList::AT_NoMicroMips:
6008 handleSimpleAttribute<NoMicroMipsAttr>(S, D, Attr);
6009 break;
6010 case AttributeList::AT_MipsLongCall:
6011 handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
6012 S, D, Attr);
6013 break;
6014 case AttributeList::AT_MipsShortCall:
6015 handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
6016 S, D, Attr);
6017 break;
6018 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
6019 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
6020 break;
6021 case AttributeList::AT_AMDGPUWavesPerEU:
6022 handleAMDGPUWavesPerEUAttr(S, D, Attr);
6023 break;
6024 case AttributeList::AT_AMDGPUNumSGPR:
6025 handleAMDGPUNumSGPRAttr(S, D, Attr);
6026 break;
6027 case AttributeList::AT_AMDGPUNumVGPR:
6028 handleAMDGPUNumVGPRAttr(S, D, Attr);
6029 break;
6030 case AttributeList::AT_AVRSignal:
6031 handleAVRSignalAttr(S, D, Attr);
6032 break;
6033 case AttributeList::AT_IBAction:
6034 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
6035 break;
6036 case AttributeList::AT_IBOutlet:
6037 handleIBOutlet(S, D, Attr);
6038 break;
6039 case AttributeList::AT_IBOutletCollection:
6040 handleIBOutletCollection(S, D, Attr);
6041 break;
6042 case AttributeList::AT_IFunc:
6043 handleIFuncAttr(S, D, Attr);
6044 break;
6045 case AttributeList::AT_Alias:
6046 handleAliasAttr(S, D, Attr);
6047 break;
6048 case AttributeList::AT_Aligned:
6049 handleAlignedAttr(S, D, Attr);
6050 break;
6051 case AttributeList::AT_AlignValue:
6052 handleAlignValueAttr(S, D, Attr);
6053 break;
6054 case AttributeList::AT_AllocSize:
6055 handleAllocSizeAttr(S, D, Attr);
6056 break;
6057 case AttributeList::AT_AlwaysInline:
6058 handleAlwaysInlineAttr(S, D, Attr);
6059 break;
6060 case AttributeList::AT_Artificial:
6061 handleSimpleAttribute<ArtificialAttr>(S, D, Attr);
6062 break;
6063 case AttributeList::AT_AnalyzerNoReturn:
6064 handleAnalyzerNoReturnAttr(S, D, Attr);
6065 break;
6066 case AttributeList::AT_TLSModel:
6067 handleTLSModelAttr(S, D, Attr);
6068 break;
6069 case AttributeList::AT_Annotate:
6070 handleAnnotateAttr(S, D, Attr);
6071 break;
6072 case AttributeList::AT_Availability:
6073 handleAvailabilityAttr(S, D, Attr);
6074 break;
6075 case AttributeList::AT_CarriesDependency:
6076 handleDependencyAttr(S, scope, D, Attr);
6077 break;
6078 case AttributeList::AT_Common:
6079 handleCommonAttr(S, D, Attr);
6080 break;
6081 case AttributeList::AT_CUDAConstant:
6082 handleConstantAttr(S, D, Attr);
6083 break;
6084 case AttributeList::AT_PassObjectSize:
6085 handlePassObjectSizeAttr(S, D, Attr);
6086 break;
6087 case AttributeList::AT_Constructor:
6088 handleConstructorAttr(S, D, Attr);
6089 break;
6090 case AttributeList::AT_CXX11NoReturn:
6091 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
6092 break;
6093 case AttributeList::AT_Deprecated:
6094 handleDeprecatedAttr(S, D, Attr);
6095 break;
6096 case AttributeList::AT_Destructor:
6097 handleDestructorAttr(S, D, Attr);
6098 break;
6099 case AttributeList::AT_EnableIf:
6100 handleEnableIfAttr(S, D, Attr);
6101 break;
6102 case AttributeList::AT_DiagnoseIf:
6103 handleDiagnoseIfAttr(S, D, Attr);
6104 break;
6105 case AttributeList::AT_ExtVectorType:
6106 handleExtVectorTypeAttr(S, scope, D, Attr);
6107 break;
6108 case AttributeList::AT_ExternalSourceSymbol:
6109 handleExternalSourceSymbolAttr(S, D, Attr);
6110 break;
6111 case AttributeList::AT_MinSize:
6112 handleMinSizeAttr(S, D, Attr);
6113 break;
6114 case AttributeList::AT_OptimizeNone:
6115 handleOptimizeNoneAttr(S, D, Attr);
6116 break;
6117 case AttributeList::AT_FlagEnum:
6118 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
6119 break;
6120 case AttributeList::AT_EnumExtensibility:
6121 handleEnumExtensibilityAttr(S, D, Attr);
6122 break;
6123 case AttributeList::AT_Flatten:
6124 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
6125 break;
6126 case AttributeList::AT_Format:
6127 handleFormatAttr(S, D, Attr);
6128 break;
6129 case AttributeList::AT_FormatArg:
6130 handleFormatArgAttr(S, D, Attr);
6131 break;
6132 case AttributeList::AT_CUDAGlobal:
6133 handleGlobalAttr(S, D, Attr);
6134 break;
6135 case AttributeList::AT_CUDADevice:
6136 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6137 Attr);
6138 break;
6139 case AttributeList::AT_CUDAHost:
6140 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
6141 Attr);
6142 break;
6143 case AttributeList::AT_GNUInline:
6144 handleGNUInlineAttr(S, D, Attr);
6145 break;
6146 case AttributeList::AT_CUDALaunchBounds:
6147 handleLaunchBoundsAttr(S, D, Attr);
6148 break;
6149 case AttributeList::AT_Restrict:
6150 handleRestrictAttr(S, D, Attr);
6151 break;
6152 case AttributeList::AT_MayAlias:
6153 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
6154 break;
6155 case AttributeList::AT_Mode:
6156 handleModeAttr(S, D, Attr);
6157 break;
6158 case AttributeList::AT_NoAlias:
6159 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
6160 break;
6161 case AttributeList::AT_NoCommon:
6162 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
6163 break;
6164 case AttributeList::AT_NoSplitStack:
6165 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
6166 break;
6167 case AttributeList::AT_NonNull:
6168 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
6169 handleNonNullAttrParameter(S, PVD, Attr);
6170 else
6171 handleNonNullAttr(S, D, Attr);
6172 break;
6173 case AttributeList::AT_ReturnsNonNull:
6174 handleReturnsNonNullAttr(S, D, Attr);
6175 break;
6176 case AttributeList::AT_NoEscape:
6177 handleNoEscapeAttr(S, D, Attr);
6178 break;
6179 case AttributeList::AT_AssumeAligned:
6180 handleAssumeAlignedAttr(S, D, Attr);
6181 break;
6182 case AttributeList::AT_AllocAlign:
6183 handleAllocAlignAttr(S, D, Attr);
6184 break;
6185 case AttributeList::AT_Overloadable:
6186 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
6187 break;
6188 case AttributeList::AT_Ownership:
6189 handleOwnershipAttr(S, D, Attr);
6190 break;
6191 case AttributeList::AT_Cold:
6192 handleColdAttr(S, D, Attr);
6193 break;
6194 case AttributeList::AT_Hot:
6195 handleHotAttr(S, D, Attr);
6196 break;
6197 case AttributeList::AT_Naked:
6198 handleNakedAttr(S, D, Attr);
6199 break;
6200 case AttributeList::AT_NoReturn:
6201 handleNoReturnAttr(S, D, Attr);
6202 break;
6203 case AttributeList::AT_NoThrow:
6204 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
6205 break;
6206 case AttributeList::AT_CUDAShared:
6207 handleSharedAttr(S, D, Attr);
6208 break;
6209 case AttributeList::AT_VecReturn:
6210 handleVecReturnAttr(S, D, Attr);
6211 break;
6212 case AttributeList::AT_ObjCOwnership:
6213 handleObjCOwnershipAttr(S, D, Attr);
6214 break;
6215 case AttributeList::AT_ObjCPreciseLifetime:
6216 handleObjCPreciseLifetimeAttr(S, D, Attr);
6217 break;
6218 case AttributeList::AT_ObjCReturnsInnerPointer:
6219 handleObjCReturnsInnerPointerAttr(S, D, Attr);
6220 break;
6221 case AttributeList::AT_ObjCRequiresSuper:
6222 handleObjCRequiresSuperAttr(S, D, Attr);
6223 break;
6224 case AttributeList::AT_ObjCBridge:
6225 handleObjCBridgeAttr(S, scope, D, Attr);
6226 break;
6227 case AttributeList::AT_ObjCBridgeMutable:
6228 handleObjCBridgeMutableAttr(S, scope, D, Attr);
6229 break;
6230 case AttributeList::AT_ObjCBridgeRelated:
6231 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
6232 break;
6233 case AttributeList::AT_ObjCDesignatedInitializer:
6234 handleObjCDesignatedInitializer(S, D, Attr);
6235 break;
6236 case AttributeList::AT_ObjCRuntimeName:
6237 handleObjCRuntimeName(S, D, Attr);
6238 break;
6239 case AttributeList::AT_ObjCRuntimeVisible:
6240 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
6241 break;
6242 case AttributeList::AT_ObjCBoxable:
6243 handleObjCBoxable(S, D, Attr);
6244 break;
6245 case AttributeList::AT_CFAuditedTransfer:
6246 handleCFAuditedTransferAttr(S, D, Attr);
6247 break;
6248 case AttributeList::AT_CFUnknownTransfer:
6249 handleCFUnknownTransferAttr(S, D, Attr);
6250 break;
6251 case AttributeList::AT_CFConsumed:
6252 case AttributeList::AT_NSConsumed:
6253 handleNSConsumedAttr(S, D, Attr);
6254 break;
6255 case AttributeList::AT_NSConsumesSelf:
6256 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
6257 break;
6258 case AttributeList::AT_NSReturnsAutoreleased:
6259 case AttributeList::AT_NSReturnsNotRetained:
6260 case AttributeList::AT_CFReturnsNotRetained:
6261 case AttributeList::AT_NSReturnsRetained:
6262 case AttributeList::AT_CFReturnsRetained:
6263 handleNSReturnsRetainedAttr(S, D, Attr);
6264 break;
6265 case AttributeList::AT_WorkGroupSizeHint:
6266 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
6267 break;
6268 case AttributeList::AT_ReqdWorkGroupSize:
6269 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
6270 break;
6271 case AttributeList::AT_OpenCLIntelReqdSubGroupSize:
6272 handleSubGroupSize(S, D, Attr);
6273 break;
6274 case AttributeList::AT_VecTypeHint:
6275 handleVecTypeHint(S, D, Attr);
6276 break;
6277 case AttributeList::AT_RequireConstantInit:
6278 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
6279 break;
6280 case AttributeList::AT_InitPriority:
6281 handleInitPriorityAttr(S, D, Attr);
6282 break;
6283 case AttributeList::AT_Packed:
6284 handlePackedAttr(S, D, Attr);
6285 break;
6286 case AttributeList::AT_Section:
6287 handleSectionAttr(S, D, Attr);
6288 break;
6289 case AttributeList::AT_Target:
6290 handleTargetAttr(S, D, Attr);
6291 break;
6292 case AttributeList::AT_Unavailable:
6293 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
6294 break;
6295 case AttributeList::AT_ArcWeakrefUnavailable:
6296 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
6297 break;
6298 case AttributeList::AT_ObjCRootClass:
6299 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
6300 break;
6301 case AttributeList::AT_ObjCSubclassingRestricted:
6302 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
6303 break;
6304 case AttributeList::AT_ObjCExplicitProtocolImpl:
6305 handleObjCSuppresProtocolAttr(S, D, Attr);
6306 break;
6307 case AttributeList::AT_ObjCRequiresPropertyDefs:
6308 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
6309 break;
6310 case AttributeList::AT_Unused:
6311 handleUnusedAttr(S, D, Attr);
6312 break;
6313 case AttributeList::AT_ReturnsTwice:
6314 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
6315 break;
6316 case AttributeList::AT_NotTailCalled:
6317 handleNotTailCalledAttr(S, D, Attr);
6318 break;
6319 case AttributeList::AT_DisableTailCalls:
6320 handleDisableTailCallsAttr(S, D, Attr);
6321 break;
6322 case AttributeList::AT_Used:
6323 handleUsedAttr(S, D, Attr);
6324 break;
6325 case AttributeList::AT_Visibility:
6326 handleVisibilityAttr(S, D, Attr, false);
6327 break;
6328 case AttributeList::AT_TypeVisibility:
6329 handleVisibilityAttr(S, D, Attr, true);
6330 break;
6331 case AttributeList::AT_WarnUnused:
6332 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
6333 break;
6334 case AttributeList::AT_WarnUnusedResult:
6335 handleWarnUnusedResult(S, D, Attr);
6336 break;
6337 case AttributeList::AT_Weak:
6338 handleSimpleAttribute<WeakAttr>(S, D, Attr);
6339 break;
6340 case AttributeList::AT_WeakRef:
6341 handleWeakRefAttr(S, D, Attr);
6342 break;
6343 case AttributeList::AT_WeakImport:
6344 handleWeakImportAttr(S, D, Attr);
6345 break;
6346 case AttributeList::AT_TransparentUnion:
6347 handleTransparentUnionAttr(S, D, Attr);
6348 break;
6349 case AttributeList::AT_ObjCException:
6350 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6351 break;
6352 case AttributeList::AT_ObjCMethodFamily:
6353 handleObjCMethodFamilyAttr(S, D, Attr);
6354 break;
6355 case AttributeList::AT_ObjCNSObject:
6356 handleObjCNSObject(S, D, Attr);
6357 break;
6358 case AttributeList::AT_ObjCIndependentClass:
6359 handleObjCIndependentClass(S, D, Attr);
6360 break;
6361 case AttributeList::AT_Blocks:
6362 handleBlocksAttr(S, D, Attr);
6363 break;
6364 case AttributeList::AT_Sentinel:
6365 handleSentinelAttr(S, D, Attr);
6366 break;
6367 case AttributeList::AT_Const:
6368 handleSimpleAttribute<ConstAttr>(S, D, Attr);
6369 break;
6370 case AttributeList::AT_Pure:
6371 handleSimpleAttribute<PureAttr>(S, D, Attr);
6372 break;
6373 case AttributeList::AT_Cleanup:
6374 handleCleanupAttr(S, D, Attr);
6375 break;
6376 case AttributeList::AT_NoDebug:
6377 handleNoDebugAttr(S, D, Attr);
6378 break;
6379 case AttributeList::AT_NoDuplicate:
6380 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6381 break;
6382 case AttributeList::AT_Convergent:
6383 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6384 break;
6385 case AttributeList::AT_NoInline:
6386 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6387 break;
6388 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6389 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6390 break;
6391 case AttributeList::AT_StdCall:
6392 case AttributeList::AT_CDecl:
6393 case AttributeList::AT_FastCall:
6394 case AttributeList::AT_ThisCall:
6395 case AttributeList::AT_Pascal:
6396 case AttributeList::AT_RegCall:
6397 case AttributeList::AT_SwiftCall:
6398 case AttributeList::AT_VectorCall:
6399 case AttributeList::AT_MSABI:
6400 case AttributeList::AT_SysVABI:
6401 case AttributeList::AT_Pcs:
6402 case AttributeList::AT_IntelOclBicc:
6403 case AttributeList::AT_PreserveMost:
6404 case AttributeList::AT_PreserveAll:
6405 handleCallConvAttr(S, D, Attr);
6406 break;
6407 case AttributeList::AT_Suppress:
6408 handleSuppressAttr(S, D, Attr);
6409 break;
6410 case AttributeList::AT_OpenCLKernel:
6411 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6412 break;
6413 case AttributeList::AT_OpenCLAccess:
6414 handleOpenCLAccessAttr(S, D, Attr);
6415 break;
6416 case AttributeList::AT_OpenCLNoSVM:
6417 handleOpenCLNoSVMAttr(S, D, Attr);
6418 break;
6419 case AttributeList::AT_SwiftContext:
6420 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
6421 break;
6422 case AttributeList::AT_SwiftErrorResult:
6423 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
6424 break;
6425 case AttributeList::AT_SwiftIndirectResult:
6426 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
6427 break;
6428 case AttributeList::AT_InternalLinkage:
6429 handleInternalLinkageAttr(S, D, Attr);
6430 break;
6431 case AttributeList::AT_LTOVisibilityPublic:
6432 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6433 break;
6434
6435 // Microsoft attributes:
6436 case AttributeList::AT_EmptyBases:
6437 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6438 break;
6439 case AttributeList::AT_LayoutVersion:
6440 handleLayoutVersion(S, D, Attr);
6441 break;
6442 case AttributeList::AT_TrivialABI:
6443 handleSimpleAttribute<TrivialABIAttr>(S, D, Attr);
6444 break;
6445 case AttributeList::AT_MSNoVTable:
6446 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
6447 break;
6448 case AttributeList::AT_MSStruct:
6449 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
6450 break;
6451 case AttributeList::AT_Uuid:
6452 handleUuidAttr(S, D, Attr);
6453 break;
6454 case AttributeList::AT_MSInheritance:
6455 handleMSInheritanceAttr(S, D, Attr);
6456 break;
6457 case AttributeList::AT_SelectAny:
6458 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6459 break;
6460 case AttributeList::AT_Thread:
6461 handleDeclspecThreadAttr(S, D, Attr);
6462 break;
6463
6464 case AttributeList::AT_AbiTag:
6465 handleAbiTagAttr(S, D, Attr);
6466 break;
6467
6468 // Thread safety attributes:
6469 case AttributeList::AT_AssertExclusiveLock:
6470 handleAssertExclusiveLockAttr(S, D, Attr);
6471 break;
6472 case AttributeList::AT_AssertSharedLock:
6473 handleAssertSharedLockAttr(S, D, Attr);
6474 break;
6475 case AttributeList::AT_GuardedVar:
6476 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6477 break;
6478 case AttributeList::AT_PtGuardedVar:
6479 handlePtGuardedVarAttr(S, D, Attr);
6480 break;
6481 case AttributeList::AT_ScopedLockable:
6482 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6483 break;
6484 case AttributeList::AT_NoSanitize:
6485 handleNoSanitizeAttr(S, D, Attr);
6486 break;
6487 case AttributeList::AT_NoSanitizeSpecific:
6488 handleNoSanitizeSpecificAttr(S, D, Attr);
6489 break;
6490 case AttributeList::AT_NoThreadSafetyAnalysis:
6491 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
6492 break;
6493 case AttributeList::AT_GuardedBy:
6494 handleGuardedByAttr(S, D, Attr);
6495 break;
6496 case AttributeList::AT_PtGuardedBy:
6497 handlePtGuardedByAttr(S, D, Attr);
6498 break;
6499 case AttributeList::AT_ExclusiveTrylockFunction:
6500 handleExclusiveTrylockFunctionAttr(S, D, Attr);
6501 break;
6502 case AttributeList::AT_LockReturned:
6503 handleLockReturnedAttr(S, D, Attr);
6504 break;
6505 case AttributeList::AT_LocksExcluded:
6506 handleLocksExcludedAttr(S, D, Attr);
6507 break;
6508 case AttributeList::AT_SharedTrylockFunction:
6509 handleSharedTrylockFunctionAttr(S, D, Attr);
6510 break;
6511 case AttributeList::AT_AcquiredBefore:
6512 handleAcquiredBeforeAttr(S, D, Attr);
6513 break;
6514 case AttributeList::AT_AcquiredAfter:
6515 handleAcquiredAfterAttr(S, D, Attr);
6516 break;
6517
6518 // Capability analysis attributes.
6519 case AttributeList::AT_Capability:
6520 case AttributeList::AT_Lockable:
6521 handleCapabilityAttr(S, D, Attr);
6522 break;
6523 case AttributeList::AT_RequiresCapability:
6524 handleRequiresCapabilityAttr(S, D, Attr);
6525 break;
6526
6527 case AttributeList::AT_AssertCapability:
6528 handleAssertCapabilityAttr(S, D, Attr);
6529 break;
6530 case AttributeList::AT_AcquireCapability:
6531 handleAcquireCapabilityAttr(S, D, Attr);
6532 break;
6533 case AttributeList::AT_ReleaseCapability:
6534 handleReleaseCapabilityAttr(S, D, Attr);
6535 break;
6536 case AttributeList::AT_TryAcquireCapability:
6537 handleTryAcquireCapabilityAttr(S, D, Attr);
6538 break;
6539
6540 // Consumed analysis attributes.
6541 case AttributeList::AT_Consumable:
6542 handleConsumableAttr(S, D, Attr);
6543 break;
6544 case AttributeList::AT_ConsumableAutoCast:
6545 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6546 break;
6547 case AttributeList::AT_ConsumableSetOnRead:
6548 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6549 break;
6550 case AttributeList::AT_CallableWhen:
6551 handleCallableWhenAttr(S, D, Attr);
6552 break;
6553 case AttributeList::AT_ParamTypestate:
6554 handleParamTypestateAttr(S, D, Attr);
6555 break;
6556 case AttributeList::AT_ReturnTypestate:
6557 handleReturnTypestateAttr(S, D, Attr);
6558 break;
6559 case AttributeList::AT_SetTypestate:
6560 handleSetTypestateAttr(S, D, Attr);
6561 break;
6562 case AttributeList::AT_TestTypestate:
6563 handleTestTypestateAttr(S, D, Attr);
6564 break;
6565
6566 // Type safety attributes.
6567 case AttributeList::AT_ArgumentWithTypeTag:
6568 handleArgumentWithTypeTagAttr(S, D, Attr);
6569 break;
6570 case AttributeList::AT_TypeTagForDatatype:
6571 handleTypeTagForDatatypeAttr(S, D, Attr);
6572 break;
6573 case AttributeList::AT_AnyX86NoCallerSavedRegisters:
6574 handleNoCallerSavedRegsAttr(S, D, Attr);
6575 break;
6576 case AttributeList::AT_RenderScriptKernel:
6577 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
6578 break;
6579 // XRay attributes.
6580 case AttributeList::AT_XRayInstrument:
6581 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6582 break;
6583 case AttributeList::AT_XRayLogArgs:
6584 handleXRayLogArgsAttr(S, D, Attr);
6585 break;
6586 }
6587}
6588
6589/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6590/// attribute list to the specified decl, ignoring any type attributes.
6591void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
6592 const AttributeList *AttrList,
6593 bool IncludeCXX11Attributes) {
6594 for (const AttributeList* l = AttrList; l; l = l->getNext())
6595 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
6596
6597 // FIXME: We should be able to handle these cases in TableGen.
6598 // GCC accepts
6599 // static int a9 __attribute__((weakref));
6600 // but that looks really pointless. We reject it.
6601 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
6602 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6603 << cast<NamedDecl>(D);
6604 D->dropAttr<WeakRefAttr>();
6605 return;
6606 }
6607
6608 // FIXME: We should be able to handle this in TableGen as well. It would be
6609 // good to have a way to specify "these attributes must appear as a group",
6610 // for these. Additionally, it would be good to have a way to specify "these
6611 // attribute must never appear as a group" for attributes like cold and hot.
6612 if (!D->hasAttr<OpenCLKernelAttr>()) {
6613 // These attributes cannot be applied to a non-kernel function.
6614 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
6615 // FIXME: This emits a different error message than
6616 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
6617 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6618 D->setInvalidDecl();
6619 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
6620 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6621 D->setInvalidDecl();
6622 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
6623 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6624 D->setInvalidDecl();
6625 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6626 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6627 << A << ExpectedKernelFunction;
6628 D->setInvalidDecl();
6629 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
6630 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6631 << A << ExpectedKernelFunction;
6632 D->setInvalidDecl();
6633 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6634 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6635 << A << ExpectedKernelFunction;
6636 D->setInvalidDecl();
6637 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6638 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6639 << A << ExpectedKernelFunction;
6640 D->setInvalidDecl();
6641 } else if (Attr *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
6642 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6643 D->setInvalidDecl();
6644 }
6645 }
6646}
6647
6648// Helper for delayed processing TransparentUnion attribute.
6649void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) {
6650 for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext())
6651 if (Attr->getKind() == AttributeList::AT_TransparentUnion) {
6652 handleTransparentUnionAttr(*this, D, *Attr);
6653 break;
6654 }
6655}
6656
6657// Annotation attributes are the only attributes allowed after an access
6658// specifier.
6659bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6660 const AttributeList *AttrList) {
6661 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6662 if (l->getKind() == AttributeList::AT_Annotate) {
6663 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
6664 } else {
6665 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6666 return true;
6667 }
6668 }
6669
6670 return false;
6671}
6672
6673/// checkUnusedDeclAttributes - Check a list of attributes to see if it
6674/// contains any decl attributes that we should warn about.
6675static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6676 for ( ; A; A = A->getNext()) {
6677 // Only warn if the attribute is an unignored, non-type attribute.
6678 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
6679 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6680
6681 if (A->getKind() == AttributeList::UnknownAttribute) {
6682 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6683 << A->getName() << A->getRange();
6684 } else {
6685 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6686 << A->getName() << A->getRange();
6687 }
6688 }
6689}
6690
6691/// checkUnusedDeclAttributes - Given a declarator which is not being
6692/// used to build a declaration, complain about any decl attributes
6693/// which might be lying around on it.
6694void Sema::checkUnusedDeclAttributes(Declarator &D) {
6695 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6696 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6697 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6698 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6699}
6700
6701/// DeclClonePragmaWeak - clone existing decl (maybe definition),
6702/// \#pragma weak needs a non-definition decl and source may not have one.
6703NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6704 SourceLocation Loc) {
6705 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND))(static_cast <bool> (isa<FunctionDecl>(ND) || isa
<VarDecl>(ND)) ? void (0) : __assert_fail ("isa<FunctionDecl>(ND) || isa<VarDecl>(ND)"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 6705, __extension__ __PRETTY_FUNCTION__))
;
6706 NamedDecl *NewD = nullptr;
6707 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
6708 FunctionDecl *NewFD;
6709 // FIXME: Missing call to CheckFunctionDeclaration().
6710 // FIXME: Mangling?
6711 // FIXME: Is the qualifier info correct?
6712 // FIXME: Is the DeclContext correct?
6713 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6714 Loc, Loc, DeclarationName(II),
6715 FD->getType(), FD->getTypeSourceInfo(),
6716 SC_None, false/*isInlineSpecified*/,
6717 FD->hasPrototype(),
6718 false/*isConstexprSpecified*/);
6719 NewD = NewFD;
6720
6721 if (FD->getQualifier())
6722 NewFD->setQualifierInfo(FD->getQualifierLoc());
6723
6724 // Fake up parameter variables; they are declared as if this were
6725 // a typedef.
6726 QualType FDTy = FD->getType();
6727 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6728 SmallVector<ParmVarDecl*, 16> Params;
6729 for (const auto &AI : FT->param_types()) {
6730 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
6731 Param->setScopeInfo(0, Params.size());
6732 Params.push_back(Param);
6733 }
6734 NewFD->setParams(Params);
6735 }
6736 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6737 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
6738 VD->getInnerLocStart(), VD->getLocation(), II,
6739 VD->getType(), VD->getTypeSourceInfo(),
6740 VD->getStorageClass());
6741 if (VD->getQualifier()) {
6742 VarDecl *NewVD = cast<VarDecl>(NewD);
6743 NewVD->setQualifierInfo(VD->getQualifierLoc());
6744 }
6745 }
6746 return NewD;
6747}
6748
6749/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
6750/// applied to it, possibly with an alias.
6751void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
6752 if (W.getUsed()) return; // only do this once
6753 W.setUsed(true);
6754 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6755 IdentifierInfo *NDId = ND->getIdentifier();
6756 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
6757 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6758 W.getLocation()));
6759 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6760 WeakTopLevelDecl.push_back(NewD);
6761 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6762 // to insert Decl at TU scope, sorry.
6763 DeclContext *SavedContext = CurContext;
6764 CurContext = Context.getTranslationUnitDecl();
6765 NewD->setDeclContext(CurContext);
6766 NewD->setLexicalDeclContext(CurContext);
6767 PushOnScopeChains(NewD, S);
6768 CurContext = SavedContext;
6769 } else { // just add weak to existing
6770 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6771 }
6772}
6773
6774void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6775 // It's valid to "forward-declare" #pragma weak, in which case we
6776 // have to do this.
6777 LoadExternalWeakUndeclaredIdentifiers();
6778 if (!WeakUndeclaredIdentifiers.empty()) {
6779 NamedDecl *ND = nullptr;
6780 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6781 if (VD->isExternC())
6782 ND = VD;
6783 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6784 if (FD->isExternC())
6785 ND = FD;
6786 if (ND) {
6787 if (IdentifierInfo *Id = ND->getIdentifier()) {
6788 auto I = WeakUndeclaredIdentifiers.find(Id);
6789 if (I != WeakUndeclaredIdentifiers.end()) {
6790 WeakInfo W = I->second;
6791 DeclApplyPragmaWeak(S, ND, W);
6792 WeakUndeclaredIdentifiers[Id] = W;
6793 }
6794 }
6795 }
6796 }
6797}
6798
6799/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6800/// it, apply them to D. This is a bit tricky because PD can have attributes
6801/// specified in many different places, and we need to find and apply them all.
6802void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
6803 // Apply decl attributes from the DeclSpec if present.
6804 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
6805 ProcessDeclAttributeList(S, D, Attrs);
6806
6807 // Walk the declarator structure, applying decl attributes that were in a type
6808 // position to the decl itself. This handles cases like:
6809 // int *__attr__(x)** D;
6810 // when X is a decl attribute.
6811 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6812 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
6813 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
6814
6815 // Finally, apply any attributes on the decl itself.
6816 if (const AttributeList *Attrs = PD.getAttributes())
6817 ProcessDeclAttributeList(S, D, Attrs);
6818
6819 // Apply additional attributes specified by '#pragma clang attribute'.
6820 AddPragmaAttributes(S, D);
6821}
6822
6823/// Is the given declaration allowed to use a forbidden type?
6824/// If so, it'll still be annotated with an attribute that makes it
6825/// illegal to actually use.
6826static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6827 const DelayedDiagnostic &diag,
6828 UnavailableAttr::ImplicitReason &reason) {
6829 // Private ivars are always okay. Unfortunately, people don't
6830 // always properly make their ivars private, even in system headers.
6831 // Plus we need to make fields okay, too.
6832 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6833 !isa<FunctionDecl>(decl))
6834 return false;
6835
6836 // Silently accept unsupported uses of __weak in both user and system
6837 // declarations when it's been disabled, for ease of integration with
6838 // -fno-objc-arc files. We do have to take some care against attempts
6839 // to define such things; for now, we've only done that for ivars
6840 // and properties.
6841 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6842 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6843 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6844 reason = UnavailableAttr::IR_ForbiddenWeak;
6845 return true;
6846 }
6847 }
6848
6849 // Allow all sorts of things in system headers.
6850 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6851 // Currently, all the failures dealt with this way are due to ARC
6852 // restrictions.
6853 reason = UnavailableAttr::IR_ARCForbiddenType;
6854 return true;
6855 }
6856
6857 return false;
6858}
6859
6860/// Handle a delayed forbidden-type diagnostic.
6861static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6862 Decl *decl) {
6863 auto reason = UnavailableAttr::IR_None;
6864 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6865 assert(reason && "didn't set reason?")(static_cast <bool> (reason && "didn't set reason?"
) ? void (0) : __assert_fail ("reason && \"didn't set reason?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 6865, __extension__ __PRETTY_FUNCTION__))
;
6866 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6867 diag.Loc));
6868 return;
6869 }
6870 if (S.getLangOpts().ObjCAutoRefCount)
6871 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
6872 // FIXME: we may want to suppress diagnostics for all
6873 // kind of forbidden type messages on unavailable functions.
6874 if (FD->hasAttr<UnavailableAttr>() &&
6875 diag.getForbiddenTypeDiagnostic() ==
6876 diag::err_arc_array_param_no_ownership) {
6877 diag.Triggered = true;
6878 return;
6879 }
6880 }
6881
6882 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6883 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6884 diag.Triggered = true;
6885}
6886
6887static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6888 const Decl *D) {
6889 // Check each AvailabilityAttr to find the one for this platform.
6890 for (const auto *A : D->attrs()) {
6891 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6892 // FIXME: this is copied from CheckAvailability. We should try to
6893 // de-duplicate.
6894
6895 // Check if this is an App Extension "platform", and if so chop off
6896 // the suffix for matching with the actual platform.
6897 StringRef ActualPlatform = Avail->getPlatform()->getName();
6898 StringRef RealizedPlatform = ActualPlatform;
6899 if (Context.getLangOpts().AppExt) {
6900 size_t suffix = RealizedPlatform.rfind("_app_extension");
6901 if (suffix != StringRef::npos)
6902 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6903 }
6904
6905 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6906
6907 // Match the platform name.
6908 if (RealizedPlatform == TargetPlatform)
6909 return Avail;
6910 }
6911 }
6912 return nullptr;
6913}
6914
6915/// The diagnostic we should emit for \c D, and the declaration that
6916/// originated it, or \c AR_Available.
6917///
6918/// \param D The declaration to check.
6919/// \param Message If non-null, this will be populated with the message from
6920/// the availability attribute that is selected.
6921static std::pair<AvailabilityResult, const NamedDecl *>
6922ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message) {
6923 AvailabilityResult Result = D->getAvailability(Message);
6924
6925 // For typedefs, if the typedef declaration appears available look
6926 // to the underlying type to see if it is more restrictive.
6927 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
6928 if (Result == AR_Available) {
6929 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
6930 D = TT->getDecl();
6931 Result = D->getAvailability(Message);
6932 continue;
6933 }
6934 }
6935 break;
6936 }
6937
6938 // Forward class declarations get their attributes from their definition.
6939 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
6940 if (IDecl->getDefinition()) {
6941 D = IDecl->getDefinition();
6942 Result = D->getAvailability(Message);
6943 }
6944 }
6945
6946 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
6947 if (Result == AR_Available) {
6948 const DeclContext *DC = ECD->getDeclContext();
6949 if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
6950 Result = TheEnumDecl->getAvailability(Message);
6951 D = TheEnumDecl;
6952 }
6953 }
6954
6955 return {Result, D};
6956}
6957
6958
6959/// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6960/// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6961/// in a deprecated context, but not the other way around.
6962static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6963 VersionTuple DeclVersion,
6964 Decl *Ctx) {
6965 assert(K != AR_Available && "Expected an unavailable declaration here!")(static_cast <bool> (K != AR_Available && "Expected an unavailable declaration here!"
) ? void (0) : __assert_fail ("K != AR_Available && \"Expected an unavailable declaration here!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 6965, __extension__ __PRETTY_FUNCTION__))
;
6966
6967 // Checks if we should emit the availability diagnostic in the context of C.
6968 auto CheckContext = [&](const Decl *C) {
6969 if (K == AR_NotYetIntroduced) {
6970 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6971 if (AA->getIntroduced() >= DeclVersion)
6972 return true;
6973 } else if (K == AR_Deprecated)
6974 if (C->isDeprecated())
6975 return true;
6976
6977 if (C->isUnavailable())
6978 return true;
6979 return false;
6980 };
6981
6982 // FIXME: This is a temporary workaround! Some existing Apple headers depends
6983 // on nested declarations in an @interface having the availability of the
6984 // interface when they really shouldn't: they are members of the enclosing
6985 // context, and can referenced from there.
6986 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
6987 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
6988 if (CheckContext(OrigCtx))
6989 return false;
6990
6991 // An implementation implicitly has the availability of the interface.
6992 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
6993 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6994 if (CheckContext(Interface))
6995 return false;
6996 }
6997 // A category implicitly has the availability of the interface.
6998 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
6999 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7000 if (CheckContext(Interface))
7001 return false;
7002 }
7003
7004 do {
7005 if (CheckContext(Ctx))
7006 return false;
7007
7008 // An implementation implicitly has the availability of the interface.
7009 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
7010 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
7011 if (CheckContext(Interface))
7012 return false;
7013 }
7014 // A category implicitly has the availability of the interface.
7015 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
7016 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7017 if (CheckContext(Interface))
7018 return false;
7019 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
7020
7021 return true;
7022}
7023
7024static bool
7025shouldDiagnoseAvailabilityByDefault(const ASTContext &Context,
7026 const VersionTuple &DeploymentVersion,
7027 const VersionTuple &DeclVersion) {
7028 const auto &Triple = Context.getTargetInfo().getTriple();
7029 VersionTuple ForceAvailabilityFromVersion;
7030 switch (Triple.getOS()) {
7031 case llvm::Triple::IOS:
7032 case llvm::Triple::TvOS:
7033 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11);
7034 break;
7035 case llvm::Triple::WatchOS:
7036 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4);
7037 break;
7038 case llvm::Triple::Darwin:
7039 case llvm::Triple::MacOSX:
7040 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13);
7041 break;
7042 default:
7043 // New targets should always warn about availability.
7044 return Triple.getVendor() == llvm::Triple::Apple;
7045 }
7046 return DeploymentVersion >= ForceAvailabilityFromVersion ||
7047 DeclVersion >= ForceAvailabilityFromVersion;
7048}
7049
7050static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) {
7051 for (Decl *Ctx = OrigCtx; Ctx;
7052 Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) {
7053 if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx))
7054 return cast<NamedDecl>(Ctx);
7055 if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) {
7056 if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx))
7057 return Imp->getClassInterface();
7058 return CD;
7059 }
7060 }
7061
7062 return dyn_cast<NamedDecl>(OrigCtx);
7063}
7064
7065namespace {
7066
7067struct AttributeInsertion {
7068 StringRef Prefix;
7069 SourceLocation Loc;
7070 StringRef Suffix;
7071
7072 static AttributeInsertion createInsertionAfter(const NamedDecl *D) {
7073 return {" ", D->getLocEnd(), ""};
7074 }
7075 static AttributeInsertion createInsertionAfter(SourceLocation Loc) {
7076 return {" ", Loc, ""};
7077 }
7078 static AttributeInsertion createInsertionBefore(const NamedDecl *D) {
7079 return {"", D->getLocStart(), "\n"};
7080 }
7081};
7082
7083} // end anonymous namespace
7084
7085/// Returns a source location in which it's appropriate to insert a new
7086/// attribute for the given declaration \D.
7087static Optional<AttributeInsertion>
7088createAttributeInsertion(const NamedDecl *D, const SourceManager &SM,
7089 const LangOptions &LangOpts) {
7090 if (isa<ObjCPropertyDecl>(D))
7091 return AttributeInsertion::createInsertionAfter(D);
7092 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7093 if (MD->hasBody())
7094 return None;
7095 return AttributeInsertion::createInsertionAfter(D);
7096 }
7097 if (const auto *TD = dyn_cast<TagDecl>(D)) {
7098 SourceLocation Loc =
7099 Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts);
7100 if (Loc.isInvalid())
7101 return None;
7102 // Insert after the 'struct'/whatever keyword.
7103 return AttributeInsertion::createInsertionAfter(Loc);
7104 }
7105 return AttributeInsertion::createInsertionBefore(D);
7106}
7107
7108/// Actually emit an availability diagnostic for a reference to an unavailable
7109/// decl.
7110///
7111/// \param Ctx The context that the reference occurred in
7112/// \param ReferringDecl The exact declaration that was referenced.
7113/// \param OffendingDecl A related decl to \c ReferringDecl that has an
7114/// availability attribute corrisponding to \c K attached to it. Note that this
7115/// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
7116/// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
7117/// and OffendingDecl is the EnumDecl.
7118static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
7119 Decl *Ctx, const NamedDecl *ReferringDecl,
7120 const NamedDecl *OffendingDecl,
7121 StringRef Message, SourceLocation Loc,
7122 const ObjCInterfaceDecl *UnknownObjCClass,
7123 const ObjCPropertyDecl *ObjCProperty,
7124 bool ObjCPropertyAccess) {
7125 // Diagnostics for deprecated or unavailable.
7126 unsigned diag, diag_message, diag_fwdclass_message;
7127 unsigned diag_available_here = diag::note_availability_specified_here;
7128 SourceLocation NoteLocation = OffendingDecl->getLocation();
7129
7130 // Matches 'diag::note_property_attribute' options.
7131 unsigned property_note_select;
7132
7133 // Matches diag::note_availability_specified_here.
7134 unsigned available_here_select_kind;
7135
7136 VersionTuple DeclVersion;
7137 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl))
7138 DeclVersion = AA->getIntroduced();
7139
7140 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
7141 return;
7142
7143 // The declaration can have multiple availability attributes, we are looking
7144 // at one of them.
7145 const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl);
7146 if (A && A->isInherited()) {
7147 for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
7148 Redecl = Redecl->getPreviousDecl()) {
7149 const AvailabilityAttr *AForRedecl =
7150 getAttrForPlatform(S.Context, Redecl);
7151 if (AForRedecl && !AForRedecl->isInherited()) {
7152 // If D is a declaration with inherited attributes, the note should
7153 // point to the declaration with actual attributes.
7154 NoteLocation = Redecl->getLocation();
7155 break;
7156 }
7157 }
7158 }
7159
7160 switch (K) {
7161 case AR_NotYetIntroduced: {
7162 // We would like to emit the diagnostic even if -Wunguarded-availability is
7163 // not specified for deployment targets >= to iOS 11 or equivalent or
7164 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7165 // later.
7166 const AvailabilityAttr *AA =
7167 getAttrForPlatform(S.getASTContext(), OffendingDecl);
7168 VersionTuple Introduced = AA->getIntroduced();
7169
7170 bool UseNewWarning = shouldDiagnoseAvailabilityByDefault(
7171 S.Context, S.Context.getTargetInfo().getPlatformMinVersion(),
7172 Introduced);
7173 unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new
7174 : diag::warn_unguarded_availability;
7175
7176 S.Diag(Loc, Warning)
7177 << OffendingDecl
7178 << AvailabilityAttr::getPrettyPlatformName(
7179 S.getASTContext().getTargetInfo().getPlatformName())
7180 << Introduced.getAsString();
7181
7182 S.Diag(OffendingDecl->getLocation(), diag::note_availability_specified_here)
7183 << OffendingDecl << /* partial */ 3;
7184
7185 if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
7186 if (auto *TD = dyn_cast<TagDecl>(Enclosing))
7187 if (TD->getDeclName().isEmpty()) {
7188 S.Diag(TD->getLocation(),
7189 diag::note_decl_unguarded_availability_silence)
7190 << /*Anonymous*/ 1 << TD->getKindName();
7191 return;
7192 }
7193 auto FixitNoteDiag =
7194 S.Diag(Enclosing->getLocation(),
7195 diag::note_decl_unguarded_availability_silence)
7196 << /*Named*/ 0 << Enclosing;
7197 // Don't offer a fixit for declarations with availability attributes.
7198 if (Enclosing->hasAttr<AvailabilityAttr>())
7199 return;
7200 if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE"))
7201 return;
7202 Optional<AttributeInsertion> Insertion = createAttributeInsertion(
7203 Enclosing, S.getSourceManager(), S.getLangOpts());
7204 if (!Insertion)
7205 return;
7206 std::string PlatformName =
7207 AvailabilityAttr::getPlatformNameSourceSpelling(
7208 S.getASTContext().getTargetInfo().getPlatformName())
7209 .lower();
7210 std::string Introduced =
7211 OffendingDecl->getVersionIntroduced().getAsString();
7212 FixitNoteDiag << FixItHint::CreateInsertion(
7213 Insertion->Loc,
7214 (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName +
7215 "(" + Introduced + "))" + Insertion->Suffix)
7216 .str());
7217 }
7218 return;
7219 }
7220 case AR_Deprecated:
7221 diag = !ObjCPropertyAccess ? diag::warn_deprecated
7222 : diag::warn_property_method_deprecated;
7223 diag_message = diag::warn_deprecated_message;
7224 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
7225 property_note_select = /* deprecated */ 0;
7226 available_here_select_kind = /* deprecated */ 2;
7227 if (const auto *Attr = OffendingDecl->getAttr<DeprecatedAttr>())
7228 NoteLocation = Attr->getLocation();
7229 break;
7230
7231 case AR_Unavailable:
7232 diag = !ObjCPropertyAccess ? diag::err_unavailable
7233 : diag::err_property_method_unavailable;
7234 diag_message = diag::err_unavailable_message;
7235 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
7236 property_note_select = /* unavailable */ 1;
7237 available_here_select_kind = /* unavailable */ 0;
7238
7239 if (auto Attr = OffendingDecl->getAttr<UnavailableAttr>()) {
7240 if (Attr->isImplicit() && Attr->getImplicitReason()) {
7241 // Most of these failures are due to extra restrictions in ARC;
7242 // reflect that in the primary diagnostic when applicable.
7243 auto flagARCError = [&] {
7244 if (S.getLangOpts().ObjCAutoRefCount &&
7245 S.getSourceManager().isInSystemHeader(
7246 OffendingDecl->getLocation()))
7247 diag = diag::err_unavailable_in_arc;
7248 };
7249
7250 switch (Attr->getImplicitReason()) {
7251 case UnavailableAttr::IR_None: break;
7252
7253 case UnavailableAttr::IR_ARCForbiddenType:
7254 flagARCError();
7255 diag_available_here = diag::note_arc_forbidden_type;
7256 break;
7257
7258 case UnavailableAttr::IR_ForbiddenWeak:
7259 if (S.getLangOpts().ObjCWeakRuntime)
7260 diag_available_here = diag::note_arc_weak_disabled;
7261 else
7262 diag_available_here = diag::note_arc_weak_no_runtime;
7263 break;
7264
7265 case UnavailableAttr::IR_ARCForbiddenConversion:
7266 flagARCError();
7267 diag_available_here = diag::note_performs_forbidden_arc_conversion;
7268 break;
7269
7270 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
7271 flagARCError();
7272 diag_available_here = diag::note_arc_init_returns_unrelated;
7273 break;
7274
7275 case UnavailableAttr::IR_ARCFieldWithOwnership:
7276 flagARCError();
7277 diag_available_here = diag::note_arc_field_with_ownership;
7278 break;
7279 }
7280 }
7281 }
7282 break;
7283
7284 case AR_Available:
7285 llvm_unreachable("Warning for availability of available declaration?")::llvm::llvm_unreachable_internal("Warning for availability of available declaration?"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7285)
;
7286 }
7287
7288 CharSourceRange UseRange;
7289 StringRef Replacement;
7290 if (K == AR_Deprecated) {
7291 if (auto Attr = OffendingDecl->getAttr<DeprecatedAttr>())
7292 Replacement = Attr->getReplacement();
7293 if (auto Attr = getAttrForPlatform(S.Context, OffendingDecl))
7294 Replacement = Attr->getReplacement();
7295
7296 if (!Replacement.empty())
7297 UseRange =
7298 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
7299 }
7300
7301 if (!Message.empty()) {
7302 S.Diag(Loc, diag_message) << ReferringDecl << Message
7303 << (UseRange.isValid() ?
7304 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
7305 if (ObjCProperty)
7306 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7307 << ObjCProperty->getDeclName() << property_note_select;
7308 } else if (!UnknownObjCClass) {
7309 S.Diag(Loc, diag) << ReferringDecl
7310 << (UseRange.isValid() ?
7311 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
7312 if (ObjCProperty)
7313 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7314 << ObjCProperty->getDeclName() << property_note_select;
7315 } else {
7316 S.Diag(Loc, diag_fwdclass_message) << ReferringDecl
7317 << (UseRange.isValid() ?
7318 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
7319 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
7320 }
7321
7322 S.Diag(NoteLocation, diag_available_here)
7323 << OffendingDecl << available_here_select_kind;
7324}
7325
7326static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
7327 Decl *Ctx) {
7328 assert(DD.Kind == DelayedDiagnostic::Availability &&(static_cast <bool> (DD.Kind == DelayedDiagnostic::Availability
&& "Expected an availability diagnostic here") ? void
(0) : __assert_fail ("DD.Kind == DelayedDiagnostic::Availability && \"Expected an availability diagnostic here\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7329, __extension__ __PRETTY_FUNCTION__))
7329 "Expected an availability diagnostic here")(static_cast <bool> (DD.Kind == DelayedDiagnostic::Availability
&& "Expected an availability diagnostic here") ? void
(0) : __assert_fail ("DD.Kind == DelayedDiagnostic::Availability && \"Expected an availability diagnostic here\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7329, __extension__ __PRETTY_FUNCTION__))
;
7330
7331 DD.Triggered = true;
7332 DoEmitAvailabilityWarning(
7333 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(),
7334 DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(), DD.Loc,
7335 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
7336}
7337
7338void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7339 assert(DelayedDiagnostics.getCurrentPool())(static_cast <bool> (DelayedDiagnostics.getCurrentPool(
)) ? void (0) : __assert_fail ("DelayedDiagnostics.getCurrentPool()"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7339, __extension__ __PRETTY_FUNCTION__))
;
7340 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
7341 DelayedDiagnostics.popWithoutEmitting(state);
7342
7343 // When delaying diagnostics to run in the context of a parsed
7344 // declaration, we only want to actually emit anything if parsing
7345 // succeeds.
7346 if (!decl) return;
7347
7348 // We emit all the active diagnostics in this pool or any of its
7349 // parents. In general, we'll get one pool for the decl spec
7350 // and a child pool for each declarator; in a decl group like:
7351 // deprecated_typedef foo, *bar, baz();
7352 // only the declarator pops will be passed decls. This is correct;
7353 // we really do need to consider delayed diagnostics from the decl spec
7354 // for each of the different declarations.
7355 const DelayedDiagnosticPool *pool = &poppedPool;
7356 do {
7357 for (DelayedDiagnosticPool::pool_iterator
7358 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7359 // This const_cast is a bit lame. Really, Triggered should be mutable.
7360 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
7361 if (diag.Triggered)
7362 continue;
7363
7364 switch (diag.Kind) {
7365 case DelayedDiagnostic::Availability:
7366 // Don't bother giving deprecation/unavailable diagnostics if
7367 // the decl is invalid.
7368 if (!decl->isInvalidDecl())
7369 handleDelayedAvailabilityCheck(*this, diag, decl);
7370 break;
7371
7372 case DelayedDiagnostic::Access:
7373 HandleDelayedAccessCheck(diag, decl);
7374 break;
7375
7376 case DelayedDiagnostic::ForbiddenType:
7377 handleDelayedForbiddenType(*this, diag, decl);
7378 break;
7379 }
7380 }
7381 } while ((pool = pool->getParent()));
7382}
7383
7384/// Given a set of delayed diagnostics, re-emit them as if they had
7385/// been delayed in the current context instead of in the given pool.
7386/// Essentially, this just moves them to the current pool.
7387void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7388 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7389 assert(curPool && "re-emitting in undelayed context not supported")(static_cast <bool> (curPool && "re-emitting in undelayed context not supported"
) ? void (0) : __assert_fail ("curPool && \"re-emitting in undelayed context not supported\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7389, __extension__ __PRETTY_FUNCTION__))
;
7390 curPool->steal(pool);
7391}
7392
7393static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR,
7394 const NamedDecl *ReferringDecl,
7395 const NamedDecl *OffendingDecl,
7396 StringRef Message, SourceLocation Loc,
7397 const ObjCInterfaceDecl *UnknownObjCClass,
7398 const ObjCPropertyDecl *ObjCProperty,
7399 bool ObjCPropertyAccess) {
7400 // Delay if we're currently parsing a declaration.
7401 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7402 S.DelayedDiagnostics.add(
7403 DelayedDiagnostic::makeAvailability(
7404 AR, Loc, ReferringDecl, OffendingDecl, UnknownObjCClass,
7405 ObjCProperty, Message, ObjCPropertyAccess));
7406 return;
7407 }
7408
7409 Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
7410 DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
7411 Message, Loc, UnknownObjCClass, ObjCProperty,
7412 ObjCPropertyAccess);
7413}
7414
7415namespace {
7416
7417/// Returns true if the given statement can be a body-like child of \p Parent.
7418bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) {
7419 switch (Parent->getStmtClass()) {
7420 case Stmt::IfStmtClass:
7421 return cast<IfStmt>(Parent)->getThen() == S ||
7422 cast<IfStmt>(Parent)->getElse() == S;
7423 case Stmt::WhileStmtClass:
7424 return cast<WhileStmt>(Parent)->getBody() == S;
7425 case Stmt::DoStmtClass:
7426 return cast<DoStmt>(Parent)->getBody() == S;
7427 case Stmt::ForStmtClass:
7428 return cast<ForStmt>(Parent)->getBody() == S;
7429 case Stmt::CXXForRangeStmtClass:
7430 return cast<CXXForRangeStmt>(Parent)->getBody() == S;
7431 case Stmt::ObjCForCollectionStmtClass:
7432 return cast<ObjCForCollectionStmt>(Parent)->getBody() == S;
7433 case Stmt::CaseStmtClass:
7434 case Stmt::DefaultStmtClass:
7435 return cast<SwitchCase>(Parent)->getSubStmt() == S;
7436 default:
7437 return false;
7438 }
7439}
7440
7441class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> {
7442 const Stmt *Target;
7443
7444public:
7445 bool VisitStmt(Stmt *S) { return S != Target; }
7446
7447 /// Returns true if the given statement is present in the given declaration.
7448 static bool isContained(const Stmt *Target, const Decl *D) {
7449 StmtUSEFinder Visitor;
7450 Visitor.Target = Target;
7451 return !Visitor.TraverseDecl(const_cast<Decl *>(D));
7452 }
7453};
7454
7455/// Traverses the AST and finds the last statement that used a given
7456/// declaration.
7457class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> {
7458 const Decl *D;
7459
7460public:
7461 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7462 if (DRE->getDecl() == D)
7463 return false;
7464 return true;
7465 }
7466
7467 static const Stmt *findLastStmtThatUsesDecl(const Decl *D,
7468 const CompoundStmt *Scope) {
7469 LastDeclUSEFinder Visitor;
7470 Visitor.D = D;
7471 for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) {
7472 const Stmt *S = *I;
7473 if (!Visitor.TraverseStmt(const_cast<Stmt *>(S)))
7474 return S;
7475 }
7476 return nullptr;
7477 }
7478};
7479
7480/// \brief This class implements -Wunguarded-availability.
7481///
7482/// This is done with a traversal of the AST of a function that makes reference
7483/// to a partially available declaration. Whenever we encounter an \c if of the
7484/// form: \c if(@available(...)), we use the version from the condition to visit
7485/// the then statement.
7486class DiagnoseUnguardedAvailability
7487 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
7488 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
7489
7490 Sema &SemaRef;
7491 Decl *Ctx;
7492
7493 /// Stack of potentially nested 'if (@available(...))'s.
7494 SmallVector<VersionTuple, 8> AvailabilityStack;
7495 SmallVector<const Stmt *, 16> StmtStack;
7496
7497 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
7498
7499public:
7500 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
7501 : SemaRef(SemaRef), Ctx(Ctx) {
7502 AvailabilityStack.push_back(
7503 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
7504 }
7505
7506 bool TraverseDecl(Decl *D) {
7507 // Avoid visiting nested functions to prevent duplicate warnings.
7508 if (!D || isa<FunctionDecl>(D))
7509 return true;
7510 return Base::TraverseDecl(D);
7511 }
7512
7513 bool TraverseStmt(Stmt *S) {
7514 if (!S)
7515 return true;
7516 StmtStack.push_back(S);
7517 bool Result = Base::TraverseStmt(S);
7518 StmtStack.pop_back();
7519 return Result;
7520 }
7521
7522 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
7523
7524 bool TraverseIfStmt(IfStmt *If);
7525
7526 bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
7527
7528 // for 'case X:' statements, don't bother looking at the 'X'; it can't lead
7529 // to any useful diagnostics.
7530 bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); }
7531
7532 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
7533 if (PRE->isClassReceiver())
7534 DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
7535 return true;
7536 }
7537
7538 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
7539 if (ObjCMethodDecl *D = Msg->getMethodDecl())
7540 DiagnoseDeclAvailability(
7541 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
7542 return true;
7543 }
7544
7545 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7546 DiagnoseDeclAvailability(DRE->getDecl(),
7547 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
7548 return true;
7549 }
7550
7551 bool VisitMemberExpr(MemberExpr *ME) {
7552 DiagnoseDeclAvailability(ME->getMemberDecl(),
7553 SourceRange(ME->getLocStart(), ME->getLocEnd()));
7554 return true;
7555 }
7556
7557 bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
7558 SemaRef.Diag(E->getLocStart(), diag::warn_at_available_unchecked_use)
7559 << (!SemaRef.getLangOpts().ObjC1);
7560 return true;
7561 }
7562
7563 bool VisitTypeLoc(TypeLoc Ty);
7564};
7565
7566void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
7567 NamedDecl *D, SourceRange Range) {
7568 AvailabilityResult Result;
7569 const NamedDecl *OffendingDecl;
7570 std::tie(Result, OffendingDecl) =
7571 ShouldDiagnoseAvailabilityOfDecl(D, nullptr);
7572 if (Result != AR_Available) {
7573 // All other diagnostic kinds have already been handled in
7574 // DiagnoseAvailabilityOfDecl.
7575 if (Result != AR_NotYetIntroduced)
7576 return;
7577
7578 const AvailabilityAttr *AA =
7579 getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
7580 VersionTuple Introduced = AA->getIntroduced();
7581
7582 if (AvailabilityStack.back() >= Introduced)
7583 return;
7584
7585 // If the context of this function is less available than D, we should not
7586 // emit a diagnostic.
7587 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
7588 return;
7589
7590 // We would like to emit the diagnostic even if -Wunguarded-availability is
7591 // not specified for deployment targets >= to iOS 11 or equivalent or
7592 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7593 // later.
7594 unsigned DiagKind =
7595 shouldDiagnoseAvailabilityByDefault(
7596 SemaRef.Context,
7597 SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced)
7598 ? diag::warn_unguarded_availability_new
7599 : diag::warn_unguarded_availability;
7600
7601 SemaRef.Diag(Range.getBegin(), DiagKind)
7602 << Range << D
7603 << AvailabilityAttr::getPrettyPlatformName(
7604 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7605 << Introduced.getAsString();
7606
7607 SemaRef.Diag(OffendingDecl->getLocation(),
7608 diag::note_availability_specified_here)
7609 << OffendingDecl << /* partial */ 3;
7610
7611 auto FixitDiag =
7612 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
7613 << Range << D
7614 << (SemaRef.getLangOpts().ObjC1 ? /*@available*/ 0
7615 : /*__builtin_available*/ 1);
7616
7617 // Find the statement which should be enclosed in the if @available check.
7618 if (StmtStack.empty())
7619 return;
7620 const Stmt *StmtOfUse = StmtStack.back();
7621 const CompoundStmt *Scope = nullptr;
7622 for (const Stmt *S : llvm::reverse(StmtStack)) {
7623 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
7624 Scope = CS;
7625 break;
7626 }
7627 if (isBodyLikeChildStmt(StmtOfUse, S)) {
7628 // The declaration won't be seen outside of the statement, so we don't
7629 // have to wrap the uses of any declared variables in if (@available).
7630 // Therefore we can avoid setting Scope here.
7631 break;
7632 }
7633 StmtOfUse = S;
7634 }
7635 const Stmt *LastStmtOfUse = nullptr;
7636 if (isa<DeclStmt>(StmtOfUse) && Scope) {
7637 for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
7638 if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
7639 LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
7640 break;
7641 }
7642 }
7643 }
7644
7645 const SourceManager &SM = SemaRef.getSourceManager();
7646 SourceLocation IfInsertionLoc =
7647 SM.getExpansionLoc(StmtOfUse->getLocStart());
7648 SourceLocation StmtEndLoc =
7649 SM.getExpansionRange(
7650 (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getLocEnd())
7651 .second;
7652 if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
7653 return;
7654
7655 StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
7656 const char *ExtraIndentation = " ";
7657 std::string FixItString;
7658 llvm::raw_string_ostream FixItOS(FixItString);
7659 FixItOS << "if (" << (SemaRef.getLangOpts().ObjC1 ? "@available"
7660 : "__builtin_available")
7661 << "("
7662 << AvailabilityAttr::getPlatformNameSourceSpelling(
7663 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7664 << " " << Introduced.getAsString() << ", *)) {\n"
7665 << Indentation << ExtraIndentation;
7666 FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
7667 SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
7668 StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
7669 /*SkipTrailingWhitespaceAndNewLine=*/false);
7670 if (ElseInsertionLoc.isInvalid())
7671 ElseInsertionLoc =
7672 Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
7673 FixItOS.str().clear();
7674 FixItOS << "\n"
7675 << Indentation << "} else {\n"
7676 << Indentation << ExtraIndentation
7677 << "// Fallback on earlier versions\n"
7678 << Indentation << "}";
7679 FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
7680 }
7681}
7682
7683bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
7684 const Type *TyPtr = Ty.getTypePtr();
7685 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
7686
7687 if (Range.isInvalid())
7688 return true;
7689
7690 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
7691 TagDecl *TD = TT->getDecl();
7692 DiagnoseDeclAvailability(TD, Range);
7693
7694 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
7695 TypedefNameDecl *D = TD->getDecl();
7696 DiagnoseDeclAvailability(D, Range);
7697
7698 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
7699 if (NamedDecl *D = ObjCO->getInterface())
7700 DiagnoseDeclAvailability(D, Range);
7701 }
7702
7703 return true;
7704}
7705
7706bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
7707 VersionTuple CondVersion;
7708 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
7709 CondVersion = E->getVersion();
7710
7711 // If we're using the '*' case here or if this check is redundant, then we
7712 // use the enclosing version to check both branches.
7713 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
7714 return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
7715 } else {
7716 // This isn't an availability checking 'if', we can just continue.
7717 return Base::TraverseIfStmt(If);
7718 }
7719
7720 AvailabilityStack.push_back(CondVersion);
7721 bool ShouldContinue = TraverseStmt(If->getThen());
7722 AvailabilityStack.pop_back();
7723
7724 return ShouldContinue && TraverseStmt(If->getElse());
7725}
7726
7727} // end anonymous namespace
7728
7729void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
7730 Stmt *Body = nullptr;
7731
7732 if (auto *FD = D->getAsFunction()) {
7733 // FIXME: We only examine the pattern decl for availability violations now,
7734 // but we should also examine instantiated templates.
7735 if (FD->isTemplateInstantiation())
7736 return;
7737
7738 Body = FD->getBody();
7739 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
7740 Body = MD->getBody();
7741 else if (auto *BD = dyn_cast<BlockDecl>(D))
7742 Body = BD->getBody();
7743
7744 assert(Body && "Need a body here!")(static_cast <bool> (Body && "Need a body here!"
) ? void (0) : __assert_fail ("Body && \"Need a body here!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7744, __extension__ __PRETTY_FUNCTION__))
;
7745
7746 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
7747}
7748
7749void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc,
7750 const ObjCInterfaceDecl *UnknownObjCClass,
7751 bool ObjCPropertyAccess,
7752 bool AvoidPartialAvailabilityChecks) {
7753 std::string Message;
7754 AvailabilityResult Result;
7755 const NamedDecl* OffendingDecl;
7756 // See if this declaration is unavailable, deprecated, or partial.
7757 std::tie(Result, OffendingDecl) = ShouldDiagnoseAvailabilityOfDecl(D, &Message);
7758 if (Result == AR_Available)
7759 return;
7760
7761 if (Result == AR_NotYetIntroduced) {
7762 if (AvoidPartialAvailabilityChecks)
7763 return;
7764
7765 // We need to know the @available context in the current function to
7766 // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
7767 // when we're done parsing the current function.
7768 if (getCurFunctionOrMethodDecl()) {
7769 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
7770 return;
7771 } else if (getCurBlock() || getCurLambda()) {
7772 getCurFunction()->HasPotentialAvailabilityViolations = true;
7773 return;
7774 }
7775 }
7776
7777 const ObjCPropertyDecl *ObjCPDecl = nullptr;
7778 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
7779 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
7780 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
7781 if (PDeclResult == Result)
7782 ObjCPDecl = PD;
7783 }
7784 }
7785
7786 EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Loc,
7787 UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);
7788}

/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Sema class, which performs semantic analysis and
11// builds ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_SEMA_H
16#define LLVM_CLANG_SEMA_SEMA_H
17
18#include "clang/AST/Attr.h"
19#include "clang/AST/Availability.h"
20#include "clang/AST/DeclarationName.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExternalASTSource.h"
25#include "clang/AST/LocInfoType.h"
26#include "clang/AST/MangleNumberingContext.h"
27#include "clang/AST/NSAPI.h"
28#include "clang/AST/PrettyPrinter.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/TypeLoc.h"
31#include "clang/AST/TypeOrdering.h"
32#include "clang/Basic/ExpressionTraits.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/ScopeInfo.h"
49#include "clang/Sema/TypoCorrection.h"
50#include "clang/Sema/Weak.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/Optional.h"
53#include "llvm/ADT/SetVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <vector>
61
62namespace llvm {
63 class APSInt;
64 template <typename ValueT> struct DenseMapInfo;
65 template <typename ValueT, typename ValueInfoT> class DenseSet;
66 class SmallBitVector;
67 struct InlineAsmIdentifierInfo;
68}
69
70namespace clang {
71 class ADLResult;
72 class ASTConsumer;
73 class ASTContext;
74 class ASTMutationListener;
75 class ASTReader;
76 class ASTWriter;
77 class ArrayType;
78 class AttributeList;
79 class BindingDecl;
80 class BlockDecl;
81 class CapturedDecl;
82 class CXXBasePath;
83 class CXXBasePaths;
84 class CXXBindTemporaryExpr;
85 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86 class CXXConstructorDecl;
87 class CXXConversionDecl;
88 class CXXDeleteExpr;
89 class CXXDestructorDecl;
90 class CXXFieldCollector;
91 class CXXMemberCallExpr;
92 class CXXMethodDecl;
93 class CXXScopeSpec;
94 class CXXTemporary;
95 class CXXTryStmt;
96 class CallExpr;
97 class ClassTemplateDecl;
98 class ClassTemplatePartialSpecializationDecl;
99 class ClassTemplateSpecializationDecl;
100 class VarTemplatePartialSpecializationDecl;
101 class CodeCompleteConsumer;
102 class CodeCompletionAllocator;
103 class CodeCompletionTUInfo;
104 class CodeCompletionResult;
105 class CoroutineBodyStmt;
106 class Decl;
107 class DeclAccessPair;
108 class DeclContext;
109 class DeclRefExpr;
110 class DeclaratorDecl;
111 class DeducedTemplateArgument;
112 class DependentDiagnostic;
113 class DesignatedInitExpr;
114 class Designation;
115 class EnableIfAttr;
116 class EnumConstantDecl;
117 class Expr;
118 class ExtVectorType;
119 class FormatAttr;
120 class FriendDecl;
121 class FunctionDecl;
122 class FunctionProtoType;
123 class FunctionTemplateDecl;
124 class ImplicitConversionSequence;
125 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
126 class InitListExpr;
127 class InitializationKind;
128 class InitializationSequence;
129 class InitializedEntity;
130 class IntegerLiteral;
131 class LabelStmt;
132 class LambdaExpr;
133 class LangOptions;
134 class LocalInstantiationScope;
135 class LookupResult;
136 class MacroInfo;
137 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
138 class ModuleLoader;
139 class MultiLevelTemplateArgumentList;
140 class NamedDecl;
141 class ObjCCategoryDecl;
142 class ObjCCategoryImplDecl;
143 class ObjCCompatibleAliasDecl;
144 class ObjCContainerDecl;
145 class ObjCImplDecl;
146 class ObjCImplementationDecl;
147 class ObjCInterfaceDecl;
148 class ObjCIvarDecl;
149 template <class T> class ObjCList;
150 class ObjCMessageExpr;
151 class ObjCMethodDecl;
152 class ObjCPropertyDecl;
153 class ObjCProtocolDecl;
154 class OMPThreadPrivateDecl;
155 class OMPDeclareReductionDecl;
156 class OMPDeclareSimdDecl;
157 class OMPClause;
158 struct OverloadCandidate;
159 class OverloadCandidateSet;
160 class OverloadExpr;
161 class ParenListExpr;
162 class ParmVarDecl;
163 class Preprocessor;
164 class PseudoDestructorTypeStorage;
165 class PseudoObjectExpr;
166 class QualType;
167 class StandardConversionSequence;
168 class Stmt;
169 class StringLiteral;
170 class SwitchStmt;
171 class TemplateArgument;
172 class TemplateArgumentList;
173 class TemplateArgumentLoc;
174 class TemplateDecl;
175 class TemplateInstantiationCallback;
176 class TemplateParameterList;
177 class TemplatePartialOrderingContext;
178 class TemplateTemplateParmDecl;
179 class Token;
180 class TypeAliasDecl;
181 class TypedefDecl;
182 class TypedefNameDecl;
183 class TypeLoc;
184 class TypoCorrectionConsumer;
185 class UnqualifiedId;
186 class UnresolvedLookupExpr;
187 class UnresolvedMemberExpr;
188 class UnresolvedSetImpl;
189 class UnresolvedSetIterator;
190 class UsingDecl;
191 class UsingShadowDecl;
192 class ValueDecl;
193 class VarDecl;
194 class VarTemplateSpecializationDecl;
195 class VisibilityAttr;
196 class VisibleDeclConsumer;
197 class IndirectFieldDecl;
198 struct DeductionFailureInfo;
199 class TemplateSpecCandidateSet;
200
201namespace sema {
202 class AccessedEntity;
203 class BlockScopeInfo;
204 class CapturedRegionScopeInfo;
205 class CapturingScopeInfo;
206 class CompoundScopeInfo;
207 class DelayedDiagnostic;
208 class DelayedDiagnosticPool;
209 class FunctionScopeInfo;
210 class LambdaScopeInfo;
211 class PossiblyUnreachableDiag;
212 class SemaPPCallbacks;
213 class TemplateDeductionInfo;
214}
215
216namespace threadSafety {
217 class BeforeSet;
218 void threadSafetyCleanup(BeforeSet* Cache);
219}
220
221// FIXME: No way to easily map from TemplateTypeParmTypes to
222// TemplateTypeParmDecls, so we have this horrible PointerUnion.
223typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
224 SourceLocation> UnexpandedParameterPack;
225
226/// Describes whether we've seen any nullability information for the given
227/// file.
228struct FileNullability {
229 /// The first pointer declarator (of any pointer kind) in the file that does
230 /// not have a corresponding nullability annotation.
231 SourceLocation PointerLoc;
232
233 /// The end location for the first pointer declarator in the file. Used for
234 /// placing fix-its.
235 SourceLocation PointerEndLoc;
236
237 /// Which kind of pointer declarator we saw.
238 uint8_t PointerKind;
239
240 /// Whether we saw any type nullability annotations in the given file.
241 bool SawTypeNullability = false;
242};
243
244/// A mapping from file IDs to a record of whether we've seen nullability
245/// information in that file.
246class FileNullabilityMap {
247 /// A mapping from file IDs to the nullability information for each file ID.
248 llvm::DenseMap<FileID, FileNullability> Map;
249
250 /// A single-element cache based on the file ID.
251 struct {
252 FileID File;
253 FileNullability Nullability;
254 } Cache;
255
256public:
257 FileNullability &operator[](FileID file) {
258 // Check the single-element cache.
259 if (file == Cache.File)
260 return Cache.Nullability;
261
262 // It's not in the single-element cache; flush the cache if we have one.
263 if (!Cache.File.isInvalid()) {
264 Map[Cache.File] = Cache.Nullability;
265 }
266
267 // Pull this entry into the cache.
268 Cache.File = file;
269 Cache.Nullability = Map[file];
270 return Cache.Nullability;
271 }
272};
273
274/// Sema - This implements semantic analysis and AST building for C.
275class Sema {
276 Sema(const Sema &) = delete;
277 void operator=(const Sema &) = delete;
278
279 ///\brief Source of additional semantic information.
280 ExternalSemaSource *ExternalSource;
281
282 ///\brief Whether Sema has generated a multiplexer and has to delete it.
283 bool isMultiplexExternalSource;
284
285 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
286
287 bool isVisibleSlow(const NamedDecl *D);
288
289 /// Determine whether two declarations should be linked together, given that
290 /// the old declaration might not be visible and the new declaration might
291 /// not have external linkage.
292 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
293 const NamedDecl *New) {
294 if (isVisible(Old))
295 return true;
296 // See comment in below overload for why it's safe to compute the linkage
297 // of the new declaration here.
298 if (New->isExternallyDeclarable()) {
299 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 300, __extension__ __PRETTY_FUNCTION__))
300 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 300, __extension__ __PRETTY_FUNCTION__))
;
301 return true;
302 }
303 return false;
304 }
305 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
306
307public:
308 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
309 typedef OpaquePtr<TemplateName> TemplateTy;
310 typedef OpaquePtr<QualType> TypeTy;
311
312 OpenCLOptions OpenCLFeatures;
313 FPOptions FPFeatures;
314
315 const LangOptions &LangOpts;
316 Preprocessor &PP;
317 ASTContext &Context;
318 ASTConsumer &Consumer;
319 DiagnosticsEngine &Diags;
320 SourceManager &SourceMgr;
321
322 /// \brief Flag indicating whether or not to collect detailed statistics.
323 bool CollectStats;
324
325 /// \brief Code-completion consumer.
326 CodeCompleteConsumer *CodeCompleter;
327
328 /// CurContext - This is the current declaration context of parsing.
329 DeclContext *CurContext;
330
331 /// \brief Generally null except when we temporarily switch decl contexts,
332 /// like in \see ActOnObjCTemporaryExitContainerContext.
333 DeclContext *OriginalLexicalContext;
334
335 /// VAListTagName - The declaration name corresponding to __va_list_tag.
336 /// This is used as part of a hack to omit that class from ADL results.
337 DeclarationName VAListTagName;
338
339 bool MSStructPragmaOn; // True when \#pragma ms_struct on
340
341 /// \brief Controls member pointer representation format under the MS ABI.
342 LangOptions::PragmaMSPointersToMembersKind
343 MSPointerToMemberRepresentationMethod;
344
345 /// Stack of active SEH __finally scopes. Can be empty.
346 SmallVector<Scope*, 2> CurrentSEHFinally;
347
348 /// \brief Source location for newly created implicit MSInheritanceAttrs
349 SourceLocation ImplicitMSInheritanceAttrLoc;
350
351 /// \brief pragma clang section kind
352 enum PragmaClangSectionKind {
353 PCSK_Invalid = 0,
354 PCSK_BSS = 1,
355 PCSK_Data = 2,
356 PCSK_Rodata = 3,
357 PCSK_Text = 4
358 };
359
360 enum PragmaClangSectionAction {
361 PCSA_Set = 0,
362 PCSA_Clear = 1
363 };
364
365 struct PragmaClangSection {
366 std::string SectionName;
367 bool Valid = false;
368 SourceLocation PragmaLocation;
369
370 void Act(SourceLocation PragmaLocation,
371 PragmaClangSectionAction Action,
372 StringLiteral* Name);
373 };
374
375 PragmaClangSection PragmaClangBSSSection;
376 PragmaClangSection PragmaClangDataSection;
377 PragmaClangSection PragmaClangRodataSection;
378 PragmaClangSection PragmaClangTextSection;
379
380 enum PragmaMsStackAction {
381 PSK_Reset = 0x0, // #pragma ()
382 PSK_Set = 0x1, // #pragma (value)
383 PSK_Push = 0x2, // #pragma (push[, id])
384 PSK_Pop = 0x4, // #pragma (pop[, id])
385 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
386 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
387 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
388 };
389
390 template<typename ValueType>
391 struct PragmaStack {
392 struct Slot {
393 llvm::StringRef StackSlotLabel;
394 ValueType Value;
395 SourceLocation PragmaLocation;
396 SourceLocation PragmaPushLocation;
397 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
398 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
399 : StackSlotLabel(StackSlotLabel), Value(Value),
400 PragmaLocation(PragmaLocation),
401 PragmaPushLocation(PragmaPushLocation) {}
402 };
403 void Act(SourceLocation PragmaLocation,
404 PragmaMsStackAction Action,
405 llvm::StringRef StackSlotLabel,
406 ValueType Value);
407
408 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
409 // method body to restore the stacks on exit, so it works like this:
410 //
411 // struct S {
412 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
413 // void Method {}
414 // #pragma <name>(pop, InternalPragmaSlot)
415 // };
416 //
417 // It works even with #pragma vtordisp, although MSVC doesn't support
418 // #pragma vtordisp(push [, id], n)
419 // syntax.
420 //
421 // Push / pop a named sentinel slot.
422 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
423 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 424, __extension__ __PRETTY_FUNCTION__))
424 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 424, __extension__ __PRETTY_FUNCTION__))
;
425 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
426 }
427
428 // Constructors.
429 explicit PragmaStack(const ValueType &Default)
430 : DefaultValue(Default), CurrentValue(Default) {}
431
432 bool hasValue() const { return CurrentValue != DefaultValue; }
433
434 SmallVector<Slot, 2> Stack;
435 ValueType DefaultValue; // Value used for PSK_Reset action.
436 ValueType CurrentValue;
437 SourceLocation CurrentPragmaLocation;
438 };
439 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
440 // we shouldn't do so if they're in a module).
441
442 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
443 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
444 ///
445 /// 0: Suppress all vtordisps
446 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
447 /// structors
448 /// 2: Always insert vtordisps to support RTTI on partially constructed
449 /// objects
450 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
451 // #pragma pack.
452 // Sentinel to represent when the stack is set to mac68k alignment.
453 static const unsigned kMac68kAlignmentSentinel = ~0U;
454 PragmaStack<unsigned> PackStack;
455 // The current #pragma pack values and locations at each #include.
456 struct PackIncludeState {
457 unsigned CurrentValue;
458 SourceLocation CurrentPragmaLocation;
459 bool HasNonDefaultValue, ShouldWarnOnInclude;
460 };
461 SmallVector<PackIncludeState, 8> PackIncludeStack;
462 // Segment #pragmas.
463 PragmaStack<StringLiteral *> DataSegStack;
464 PragmaStack<StringLiteral *> BSSSegStack;
465 PragmaStack<StringLiteral *> ConstSegStack;
466 PragmaStack<StringLiteral *> CodeSegStack;
467
468 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
469 // Actions should be performed only if we enter / exit a C++ method body.
470 class PragmaStackSentinelRAII {
471 public:
472 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
473 ~PragmaStackSentinelRAII();
474
475 private:
476 Sema &S;
477 StringRef SlotLabel;
478 bool ShouldAct;
479 };
480
481 /// A mapping that describes the nullability we've seen in each header file.
482 FileNullabilityMap NullabilityMap;
483
484 /// Last section used with #pragma init_seg.
485 StringLiteral *CurInitSeg;
486 SourceLocation CurInitSegLoc;
487
488 /// VisContext - Manages the stack for \#pragma GCC visibility.
489 void *VisContext; // Really a "PragmaVisStack*"
490
491 /// \brief This represents the stack of attributes that were pushed by
492 /// \#pragma clang attribute.
493 struct PragmaAttributeEntry {
494 SourceLocation Loc;
495 AttributeList *Attribute;
496 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
497 bool IsUsed;
498 };
499 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
500
501 /// \brief The declaration that is currently receiving an attribute from the
502 /// #pragma attribute stack.
503 const Decl *PragmaAttributeCurrentTargetDecl;
504
505 /// \brief This represents the last location of a "#pragma clang optimize off"
506 /// directive if such a directive has not been closed by an "on" yet. If
507 /// optimizations are currently "on", this is set to an invalid location.
508 SourceLocation OptimizeOffPragmaLocation;
509
510 /// \brief Flag indicating if Sema is building a recovery call expression.
511 ///
512 /// This flag is used to avoid building recovery call expressions
513 /// if Sema is already doing so, which would cause infinite recursions.
514 bool IsBuildingRecoveryCallExpr;
515
516 /// Used to control the generation of ExprWithCleanups.
517 CleanupInfo Cleanup;
518
519 /// ExprCleanupObjects - This is the stack of objects requiring
520 /// cleanup that are created by the current full expression. The
521 /// element type here is ExprWithCleanups::Object.
522 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
523
524 /// \brief Store a list of either DeclRefExprs or MemberExprs
525 /// that contain a reference to a variable (constant) that may or may not
526 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
527 /// and discarded value conversions have been applied to all subexpressions
528 /// of the enclosing full expression. This is cleared at the end of each
529 /// full expression.
530 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
531
532 /// \brief Stack containing information about each of the nested
533 /// function, block, and method scopes that are currently active.
534 ///
535 /// This array is never empty. Clients should ignore the first
536 /// element, which is used to cache a single FunctionScopeInfo
537 /// that's used to parse every top-level function.
538 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
539
540 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
541 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
542 ExtVectorDeclsType;
543
544 /// ExtVectorDecls - This is a list all the extended vector types. This allows
545 /// us to associate a raw vector type with one of the ext_vector type names.
546 /// This is only necessary for issuing pretty diagnostics.
547 ExtVectorDeclsType ExtVectorDecls;
548
549 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
550 std::unique_ptr<CXXFieldCollector> FieldCollector;
551
552 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
553
554 /// \brief Set containing all declared private fields that are not used.
555 NamedDeclSetType UnusedPrivateFields;
556
557 /// \brief Set containing all typedefs that are likely unused.
558 llvm::SmallSetVector<const TypedefNameDecl *, 4>
559 UnusedLocalTypedefNameCandidates;
560
561 /// \brief Delete-expressions to be analyzed at the end of translation unit
562 ///
563 /// This list contains class members, and locations of delete-expressions
564 /// that could not be proven as to whether they mismatch with new-expression
565 /// used in initializer of the field.
566 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
567 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
568 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
569
570 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
571
572 /// PureVirtualClassDiagSet - a set of class declarations which we have
573 /// emitted a list of pure virtual functions. Used to prevent emitting the
574 /// same list more than once.
575 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
576
577 /// ParsingInitForAutoVars - a set of declarations with auto types for which
578 /// we are currently parsing the initializer.
579 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
580
581 /// \brief Look for a locally scoped extern "C" declaration by the given name.
582 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
583
584 typedef LazyVector<VarDecl *, ExternalSemaSource,
585 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
586 TentativeDefinitionsType;
587
588 /// \brief All the tentative definitions encountered in the TU.
589 TentativeDefinitionsType TentativeDefinitions;
590
591 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
592 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
593 UnusedFileScopedDeclsType;
594
595 /// \brief The set of file scoped decls seen so far that have not been used
596 /// and must warn if not used. Only contains the first declaration.
597 UnusedFileScopedDeclsType UnusedFileScopedDecls;
598
599 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
600 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
601 DelegatingCtorDeclsType;
602
603 /// \brief All the delegating constructors seen so far in the file, used for
604 /// cycle detection at the end of the TU.
605 DelegatingCtorDeclsType DelegatingCtorDecls;
606
607 /// \brief All the overriding functions seen during a class definition
608 /// that had their exception spec checks delayed, plus the overridden
609 /// function.
610 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
611 DelayedExceptionSpecChecks;
612
613 /// \brief All the members seen during a class definition which were both
614 /// explicitly defaulted and had explicitly-specified exception
615 /// specifications, along with the function type containing their
616 /// user-specified exception specification. Those exception specifications
617 /// were overridden with the default specifications, but we still need to
618 /// check whether they are compatible with the default specification, and
619 /// we can't do that until the nesting set of class definitions is complete.
620 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
621 DelayedDefaultedMemberExceptionSpecs;
622
623 typedef llvm::MapVector<const FunctionDecl *,
624 std::unique_ptr<LateParsedTemplate>>
625 LateParsedTemplateMapT;
626 LateParsedTemplateMapT LateParsedTemplateMap;
627
628 /// \brief Callback to the parser to parse templated functions when needed.
629 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
630 typedef void LateTemplateParserCleanupCB(void *P);
631 LateTemplateParserCB *LateTemplateParser;
632 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
633 void *OpaqueParser;
634
635 void SetLateTemplateParser(LateTemplateParserCB *LTP,
636 LateTemplateParserCleanupCB *LTPCleanup,
637 void *P) {
638 LateTemplateParser = LTP;
639 LateTemplateParserCleanup = LTPCleanup;
640 OpaqueParser = P;
641 }
642
643 class DelayedDiagnostics;
644
645 class DelayedDiagnosticsState {
646 sema::DelayedDiagnosticPool *SavedPool;
647 friend class Sema::DelayedDiagnostics;
648 };
649 typedef DelayedDiagnosticsState ParsingDeclState;
650 typedef DelayedDiagnosticsState ProcessingContextState;
651
652 /// A class which encapsulates the logic for delaying diagnostics
653 /// during parsing and other processing.
654 class DelayedDiagnostics {
655 /// \brief The current pool of diagnostics into which delayed
656 /// diagnostics should go.
657 sema::DelayedDiagnosticPool *CurPool;
658
659 public:
660 DelayedDiagnostics() : CurPool(nullptr) {}
661
662 /// Adds a delayed diagnostic.
663 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
664
665 /// Determines whether diagnostics should be delayed.
666 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
667
668 /// Returns the current delayed-diagnostics pool.
669 sema::DelayedDiagnosticPool *getCurrentPool() const {
670 return CurPool;
671 }
672
673 /// Enter a new scope. Access and deprecation diagnostics will be
674 /// collected in this pool.
675 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
676 DelayedDiagnosticsState state;
677 state.SavedPool = CurPool;
678 CurPool = &pool;
679 return state;
680 }
681
682 /// Leave a delayed-diagnostic state that was previously pushed.
683 /// Do not emit any of the diagnostics. This is performed as part
684 /// of the bookkeeping of popping a pool "properly".
685 void popWithoutEmitting(DelayedDiagnosticsState state) {
686 CurPool = state.SavedPool;
687 }
688
689 /// Enter a new scope where access and deprecation diagnostics are
690 /// not delayed.
691 DelayedDiagnosticsState pushUndelayed() {
692 DelayedDiagnosticsState state;
693 state.SavedPool = CurPool;
694 CurPool = nullptr;
695 return state;
696 }
697
698 /// Undo a previous pushUndelayed().
699 void popUndelayed(DelayedDiagnosticsState state) {
700 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 700, __extension__ __PRETTY_FUNCTION__))
;
701 CurPool = state.SavedPool;
702 }
703 } DelayedDiagnostics;
704
705 /// A RAII object to temporarily push a declaration context.
706 class ContextRAII {
707 private:
708 Sema &S;
709 DeclContext *SavedContext;
710 ProcessingContextState SavedContextState;
711 QualType SavedCXXThisTypeOverride;
712
713 public:
714 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
715 : S(S), SavedContext(S.CurContext),
716 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
717 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
718 {
719 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 719, __extension__ __PRETTY_FUNCTION__))
;
720 S.CurContext = ContextToPush;
721 if (NewThisContext)
722 S.CXXThisTypeOverride = QualType();
723 }
724
725 void pop() {
726 if (!SavedContext) return;
727 S.CurContext = SavedContext;
728 S.DelayedDiagnostics.popUndelayed(SavedContextState);
729 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
730 SavedContext = nullptr;
731 }
732
733 ~ContextRAII() {
734 pop();
735 }
736 };
737
738 /// \brief RAII object to handle the state changes required to synthesize
739 /// a function body.
740 class SynthesizedFunctionScope {
741 Sema &S;
742 Sema::ContextRAII SavedContext;
743 bool PushedCodeSynthesisContext = false;
744
745 public:
746 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
747 : S(S), SavedContext(S, DC) {
748 S.PushFunctionScope();
749 S.PushExpressionEvaluationContext(
750 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
751 if (auto *FD = dyn_cast<FunctionDecl>(DC))
752 FD->setWillHaveBody(true);
753 else
754 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 754, __extension__ __PRETTY_FUNCTION__))
;
755 }
756
757 void addContextNote(SourceLocation UseLoc) {
758 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 758, __extension__ __PRETTY_FUNCTION__))
;
759
760 Sema::CodeSynthesisContext Ctx;
761 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
762 Ctx.PointOfInstantiation = UseLoc;
763 Ctx.Entity = cast<Decl>(S.CurContext);
764 S.pushCodeSynthesisContext(Ctx);
765
766 PushedCodeSynthesisContext = true;
767 }
768
769 ~SynthesizedFunctionScope() {
770 if (PushedCodeSynthesisContext)
771 S.popCodeSynthesisContext();
772 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
773 FD->setWillHaveBody(false);
774 S.PopExpressionEvaluationContext();
775 S.PopFunctionScopeInfo();
776 }
777 };
778
779 /// WeakUndeclaredIdentifiers - Identifiers contained in
780 /// \#pragma weak before declared. rare. may alias another
781 /// identifier, declared or undeclared
782 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
783
784 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
785 /// \#pragma redefine_extname before declared. Used in Solaris system headers
786 /// to define functions that occur in multiple standards to call the version
787 /// in the currently selected standard.
788 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
789
790
791 /// \brief Load weak undeclared identifiers from the external source.
792 void LoadExternalWeakUndeclaredIdentifiers();
793
794 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
795 /// \#pragma weak during processing of other Decls.
796 /// I couldn't figure out a clean way to generate these in-line, so
797 /// we store them here and handle separately -- which is a hack.
798 /// It would be best to refactor this.
799 SmallVector<Decl*,2> WeakTopLevelDecl;
800
801 IdentifierResolver IdResolver;
802
803 /// Translation Unit Scope - useful to Objective-C actions that need
804 /// to lookup file scope declarations in the "ordinary" C decl namespace.
805 /// For example, user-defined classes, built-in "id" type, etc.
806 Scope *TUScope;
807
808 /// \brief The C++ "std" namespace, where the standard library resides.
809 LazyDeclPtr StdNamespace;
810
811 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
812 /// standard library.
813 LazyDeclPtr StdBadAlloc;
814
815 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
816 /// standard library.
817 LazyDeclPtr StdAlignValT;
818
819 /// \brief The C++ "std::experimental" namespace, where the experimental parts
820 /// of the standard library resides.
821 NamespaceDecl *StdExperimentalNamespaceCache;
822
823 /// \brief The C++ "std::initializer_list" template, which is defined in
824 /// \<initializer_list>.
825 ClassTemplateDecl *StdInitializerList;
826
827 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
828 RecordDecl *CXXTypeInfoDecl;
829
830 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
831 RecordDecl *MSVCGuidDecl;
832
833 /// \brief Caches identifiers/selectors for NSFoundation APIs.
834 std::unique_ptr<NSAPI> NSAPIObj;
835
836 /// \brief The declaration of the Objective-C NSNumber class.
837 ObjCInterfaceDecl *NSNumberDecl;
838
839 /// \brief The declaration of the Objective-C NSValue class.
840 ObjCInterfaceDecl *NSValueDecl;
841
842 /// \brief Pointer to NSNumber type (NSNumber *).
843 QualType NSNumberPointer;
844
845 /// \brief Pointer to NSValue type (NSValue *).
846 QualType NSValuePointer;
847
848 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
849 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
850
851 /// \brief The declaration of the Objective-C NSString class.
852 ObjCInterfaceDecl *NSStringDecl;
853
854 /// \brief Pointer to NSString type (NSString *).
855 QualType NSStringPointer;
856
857 /// \brief The declaration of the stringWithUTF8String: method.
858 ObjCMethodDecl *StringWithUTF8StringMethod;
859
860 /// \brief The declaration of the valueWithBytes:objCType: method.
861 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
862
863 /// \brief The declaration of the Objective-C NSArray class.
864 ObjCInterfaceDecl *NSArrayDecl;
865
866 /// \brief The declaration of the arrayWithObjects:count: method.
867 ObjCMethodDecl *ArrayWithObjectsMethod;
868
869 /// \brief The declaration of the Objective-C NSDictionary class.
870 ObjCInterfaceDecl *NSDictionaryDecl;
871
872 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
873 ObjCMethodDecl *DictionaryWithObjectsMethod;
874
875 /// \brief id<NSCopying> type.
876 QualType QIDNSCopying;
877
878 /// \brief will hold 'respondsToSelector:'
879 Selector RespondsToSelectorSel;
880
881 /// A flag to remember whether the implicit forms of operator new and delete
882 /// have been declared.
883 bool GlobalNewDeleteDeclared;
884
885 /// A flag to indicate that we're in a context that permits abstract
886 /// references to fields. This is really a
887 bool AllowAbstractFieldReference;
888
889 /// \brief Describes how the expressions currently being parsed are
890 /// evaluated at run-time, if at all.
891 enum class ExpressionEvaluationContext {
892 /// \brief The current expression and its subexpressions occur within an
893 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
894 /// \c sizeof, where the type of the expression may be significant but
895 /// no code will be generated to evaluate the value of the expression at
896 /// run time.
897 Unevaluated,
898
899 /// \brief The current expression occurs within a braced-init-list within
900 /// an unevaluated operand. This is mostly like a regular unevaluated
901 /// context, except that we still instantiate constexpr functions that are
902 /// referenced here so that we can perform narrowing checks correctly.
903 UnevaluatedList,
904
905 /// \brief The current expression occurs within a discarded statement.
906 /// This behaves largely similarly to an unevaluated operand in preventing
907 /// definitions from being required, but not in other ways.
908 DiscardedStatement,
909
910 /// \brief The current expression occurs within an unevaluated
911 /// operand that unconditionally permits abstract references to
912 /// fields, such as a SIZE operator in MS-style inline assembly.
913 UnevaluatedAbstract,
914
915 /// \brief The current context is "potentially evaluated" in C++11 terms,
916 /// but the expression is evaluated at compile-time (like the values of
917 /// cases in a switch statement).
918 ConstantEvaluated,
919
920 /// \brief The current expression is potentially evaluated at run time,
921 /// which means that code may be generated to evaluate the value of the
922 /// expression at run time.
923 PotentiallyEvaluated,
924
925 /// \brief The current expression is potentially evaluated, but any
926 /// declarations referenced inside that expression are only used if
927 /// in fact the current expression is used.
928 ///
929 /// This value is used when parsing default function arguments, for which
930 /// we would like to provide diagnostics (e.g., passing non-POD arguments
931 /// through varargs) but do not want to mark declarations as "referenced"
932 /// until the default argument is used.
933 PotentiallyEvaluatedIfUsed
934 };
935
936 /// \brief Data structure used to record current or nested
937 /// expression evaluation contexts.
938 struct ExpressionEvaluationContextRecord {
939 /// \brief The expression evaluation context.
940 ExpressionEvaluationContext Context;
941
942 /// \brief Whether the enclosing context needed a cleanup.
943 CleanupInfo ParentCleanup;
944
945 /// \brief Whether we are in a decltype expression.
946 bool IsDecltype;
947
948 /// \brief The number of active cleanup objects when we entered
949 /// this expression evaluation context.
950 unsigned NumCleanupObjects;
951
952 /// \brief The number of typos encountered during this expression evaluation
953 /// context (i.e. the number of TypoExprs created).
954 unsigned NumTypos;
955
956 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
957
958 /// \brief The lambdas that are present within this context, if it
959 /// is indeed an unevaluated context.
960 SmallVector<LambdaExpr *, 2> Lambdas;
961
962 /// \brief The declaration that provides context for lambda expressions
963 /// and block literals if the normal declaration context does not
964 /// suffice, e.g., in a default function argument.
965 Decl *ManglingContextDecl;
966
967 /// \brief The context information used to mangle lambda expressions
968 /// and block literals within this context.
969 ///
970 /// This mangling information is allocated lazily, since most contexts
971 /// do not have lambda expressions or block literals.
972 std::unique_ptr<MangleNumberingContext> MangleNumbering;
973
974 /// \brief If we are processing a decltype type, a set of call expressions
975 /// for which we have deferred checking the completeness of the return type.
976 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
977
978 /// \brief If we are processing a decltype type, a set of temporary binding
979 /// expressions for which we have deferred checking the destructor.
980 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
981
982 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
983 unsigned NumCleanupObjects,
984 CleanupInfo ParentCleanup,
985 Decl *ManglingContextDecl,
986 bool IsDecltype)
987 : Context(Context), ParentCleanup(ParentCleanup),
988 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
989 NumTypos(0),
990 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
991
992 /// \brief Retrieve the mangling numbering context, used to consistently
993 /// number constructs like lambdas for mangling.
994 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
995
996 bool isUnevaluated() const {
997 return Context == ExpressionEvaluationContext::Unevaluated ||
998 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
999 Context == ExpressionEvaluationContext::UnevaluatedList;
1000 }
1001 bool isConstantEvaluated() const {
1002 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1003 }
1004 };
1005
1006 /// A stack of expression evaluation contexts.
1007 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1008
1009 /// \brief Compute the mangling number context for a lambda expression or
1010 /// block literal.
1011 ///
1012 /// \param DC - The DeclContext containing the lambda expression or
1013 /// block literal.
1014 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
1015 /// associated with the context, if relevant.
1016 MangleNumberingContext *getCurrentMangleNumberContext(
1017 const DeclContext *DC,
1018 Decl *&ManglingContextDecl);
1019
1020
1021 /// SpecialMemberOverloadResult - The overloading result for a special member
1022 /// function.
1023 ///
1024 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1025 /// integer are used to determine whether overload resolution succeeded.
1026 class SpecialMemberOverloadResult {
1027 public:
1028 enum Kind {
1029 NoMemberOrDeleted,
1030 Ambiguous,
1031 Success
1032 };
1033
1034 private:
1035 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1036
1037 public:
1038 SpecialMemberOverloadResult() : Pair() {}
1039 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1040 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1041
1042 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1043 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1044
1045 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1046 void setKind(Kind K) { Pair.setInt(K); }
1047 };
1048
1049 class SpecialMemberOverloadResultEntry
1050 : public llvm::FastFoldingSetNode,
1051 public SpecialMemberOverloadResult {
1052 public:
1053 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1054 : FastFoldingSetNode(ID)
1055 {}
1056 };
1057
1058 /// \brief A cache of special member function overload resolution results
1059 /// for C++ records.
1060 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1061
1062 /// \brief A cache of the flags available in enumerations with the flag_bits
1063 /// attribute.
1064 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1065
1066 /// \brief The kind of translation unit we are processing.
1067 ///
1068 /// When we're processing a complete translation unit, Sema will perform
1069 /// end-of-translation-unit semantic tasks (such as creating
1070 /// initializers for tentative definitions in C) once parsing has
1071 /// completed. Modules and precompiled headers perform different kinds of
1072 /// checks.
1073 TranslationUnitKind TUKind;
1074
1075 llvm::BumpPtrAllocator BumpAlloc;
1076
1077 /// \brief The number of SFINAE diagnostics that have been trapped.
1078 unsigned NumSFINAEErrors;
1079
1080 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1081 UnparsedDefaultArgInstantiationsMap;
1082
1083 /// \brief A mapping from parameters with unparsed default arguments to the
1084 /// set of instantiations of each parameter.
1085 ///
1086 /// This mapping is a temporary data structure used when parsing
1087 /// nested class templates or nested classes of class templates,
1088 /// where we might end up instantiating an inner class before the
1089 /// default arguments of its methods have been parsed.
1090 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1091
1092 // Contains the locations of the beginning of unparsed default
1093 // argument locations.
1094 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1095
1096 /// UndefinedInternals - all the used, undefined objects which require a
1097 /// definition in this translation unit.
1098 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1099
1100 /// Determine if VD, which must be a variable or function, is an external
1101 /// symbol that nonetheless can't be referenced from outside this translation
1102 /// unit because its type has no linkage and it's not extern "C".
1103 bool isExternalWithNoLinkageType(ValueDecl *VD);
1104
1105 /// Obtain a sorted list of functions that are undefined but ODR-used.
1106 void getUndefinedButUsed(
1107 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1108
1109 /// Retrieves list of suspicious delete-expressions that will be checked at
1110 /// the end of translation unit.
1111 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1112 getMismatchingDeleteExpressions() const;
1113
1114 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1115 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1116
1117 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1118 /// We need to maintain a list, since selectors can have differing signatures
1119 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1120 /// of selectors are "overloaded").
1121 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1122 /// methods inside categories with a particular selector.
1123 GlobalMethodPool MethodPool;
1124
1125 /// Method selectors used in a \@selector expression. Used for implementation
1126 /// of -Wselector.
1127 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1128
1129 /// Kinds of C++ special members.
1130 enum CXXSpecialMember {
1131 CXXDefaultConstructor,
1132 CXXCopyConstructor,
1133 CXXMoveConstructor,
1134 CXXCopyAssignment,
1135 CXXMoveAssignment,
1136 CXXDestructor,
1137 CXXInvalid
1138 };
1139
1140 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1141 SpecialMemberDecl;
1142
1143 /// The C++ special members which we are currently in the process of
1144 /// declaring. If this process recursively triggers the declaration of the
1145 /// same special member, we should act as if it is not yet declared.
1146 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1147
1148 /// The function definitions which were renamed as part of typo-correction
1149 /// to match their respective declarations. We want to keep track of them
1150 /// to ensure that we don't emit a "redefinition" error if we encounter a
1151 /// correctly named definition after the renamed definition.
1152 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1153
1154 /// Stack of types that correspond to the parameter entities that are
1155 /// currently being copy-initialized. Can be empty.
1156 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1157
1158 void ReadMethodPool(Selector Sel);
1159 void updateOutOfDateSelector(Selector Sel);
1160
1161 /// Private Helper predicate to check for 'self'.
1162 bool isSelfExpr(Expr *RExpr);
1163 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1164
1165 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1166 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1167 /// should not be used elsewhere.
1168 void EmitCurrentDiagnostic(unsigned DiagID);
1169
1170 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1171 /// statements.
1172 class FPContractStateRAII {
1173 public:
1174 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1175 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1176
1177 private:
1178 Sema& S;
1179 FPOptions OldFPFeaturesState;
1180 };
1181
1182 void addImplicitTypedef(StringRef Name, QualType T);
1183
1184public:
1185 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1186 TranslationUnitKind TUKind = TU_Complete,
1187 CodeCompleteConsumer *CompletionConsumer = nullptr);
1188 ~Sema();
1189
1190 /// \brief Perform initialization that occurs after the parser has been
1191 /// initialized but before it parses anything.
1192 void Initialize();
1193
1194 const LangOptions &getLangOpts() const { return LangOpts; }
1195 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1196 FPOptions &getFPOptions() { return FPFeatures; }
1197
1198 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1199 SourceManager &getSourceManager() const { return SourceMgr; }
1200 Preprocessor &getPreprocessor() const { return PP; }
1201 ASTContext &getASTContext() const { return Context; }
1202 ASTConsumer &getASTConsumer() const { return Consumer; }
1203 ASTMutationListener *getASTMutationListener() const;
1204 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1205
1206 ///\brief Registers an external source. If an external source already exists,
1207 /// creates a multiplex external source and appends to it.
1208 ///
1209 ///\param[in] E - A non-null external sema source.
1210 ///
1211 void addExternalSource(ExternalSemaSource *E);
1212
1213 void PrintStats() const;
1214
1215 /// \brief Helper class that creates diagnostics with optional
1216 /// template instantiation stacks.
1217 ///
1218 /// This class provides a wrapper around the basic DiagnosticBuilder
1219 /// class that emits diagnostics. SemaDiagnosticBuilder is
1220 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1221 /// does) and, if the diagnostic comes from inside a template
1222 /// instantiation, printing the template instantiation stack as
1223 /// well.
1224 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1225 Sema &SemaRef;
1226 unsigned DiagID;
1227
1228 public:
1229 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1230 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1231
1232 // This is a cunning lie. DiagnosticBuilder actually performs move
1233 // construction in its copy constructor (but due to varied uses, it's not
1234 // possible to conveniently express this as actual move construction). So
1235 // the default copy ctor here is fine, because the base class disables the
1236 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1237 // in that case anwyay.
1238 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1239
1240 ~SemaDiagnosticBuilder() {
1241 // If we aren't active, there is nothing to do.
1242 if (!isActive()) return;
1243
1244 // Otherwise, we need to emit the diagnostic. First flush the underlying
1245 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1246 // won't emit the diagnostic in its own destructor.
1247 //
1248 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1249 // do its own needless checks to see if the diagnostic needs to be
1250 // emitted. However, because we take care to ensure that the builder
1251 // objects never escape, a sufficiently smart compiler will be able to
1252 // eliminate that code.
1253 FlushCounts();
1254 Clear();
1255
1256 // Dispatch to Sema to emit the diagnostic.
1257 SemaRef.EmitCurrentDiagnostic(DiagID);
1258 }
1259
1260 /// Teach operator<< to produce an object of the correct type.
1261 template<typename T>
1262 friend const SemaDiagnosticBuilder &operator<<(
1263 const SemaDiagnosticBuilder &Diag, const T &Value) {
1264 const DiagnosticBuilder &BaseDiag = Diag;
1265 BaseDiag << Value;
1266 return Diag;
1267 }
1268 };
1269
1270 /// \brief Emit a diagnostic.
1271 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1272 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1273 return SemaDiagnosticBuilder(DB, *this, DiagID);
1274 }
1275
1276 /// \brief Emit a partial diagnostic.
1277 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1278
1279 /// \brief Build a partial diagnostic.
1280 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1281
1282 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1283
1284 /// \brief Get a string to suggest for zero-initialization of a type.
1285 std::string
1286 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1287 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1288
1289 /// \brief Calls \c Lexer::getLocForEndOfToken()
1290 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1291
1292 /// \brief Retrieve the module loader associated with the preprocessor.
1293 ModuleLoader &getModuleLoader() const;
1294
1295 void emitAndClearUnusedLocalTypedefWarnings();
1296
1297 void ActOnStartOfTranslationUnit();
1298 void ActOnEndOfTranslationUnit();
1299
1300 void CheckDelegatingCtorCycles();
1301
1302 Scope *getScopeForContext(DeclContext *Ctx);
1303
1304 void PushFunctionScope();
1305 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1306 sema::LambdaScopeInfo *PushLambdaScope();
1307
1308 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1309 /// is during Parsing. Currently it is used to pass on the depth
1310 /// when parsing generic lambda 'auto' parameters.
1311 void RecordParsingTemplateParameterDepth(unsigned Depth);
1312
1313 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1314 RecordDecl *RD,
1315 CapturedRegionKind K);
1316 void
1317 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1318 const Decl *D = nullptr,
1319 const BlockExpr *blkExpr = nullptr);
1320
1321 sema::FunctionScopeInfo *getCurFunction() const {
1322 return FunctionScopes.back();
1323 }
1324
1325 sema::FunctionScopeInfo *getEnclosingFunction() const {
1326 if (FunctionScopes.empty())
1327 return nullptr;
1328
1329 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1330 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1331 continue;
1332 return FunctionScopes[e];
1333 }
1334 return nullptr;
1335 }
1336
1337 template <typename ExprT>
1338 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1339 if (!isUnevaluatedContext())
1340 getCurFunction()->recordUseOfWeak(E, IsRead);
1341 }
1342
1343 void PushCompoundScope(bool IsStmtExpr);
1344 void PopCompoundScope();
1345
1346 sema::CompoundScopeInfo &getCurCompoundScope() const;
1347
1348 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1349
1350 /// \brief Retrieve the current block, if any.
1351 sema::BlockScopeInfo *getCurBlock();
1352
1353 /// Retrieve the current lambda scope info, if any.
1354 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1355 /// lambda scope info ignoring all inner capturing scopes that are not
1356 /// lambda scopes.
1357 sema::LambdaScopeInfo *
1358 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1359
1360 /// \brief Retrieve the current generic lambda info, if any.
1361 sema::LambdaScopeInfo *getCurGenericLambda();
1362
1363 /// \brief Retrieve the current captured region, if any.
1364 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1365
1366 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1367 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1368
1369 void ActOnComment(SourceRange Comment);
1370
1371 //===--------------------------------------------------------------------===//
1372 // Type Analysis / Processing: SemaType.cpp.
1373 //
1374
1375 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1376 const DeclSpec *DS = nullptr);
1377 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1378 const DeclSpec *DS = nullptr);
1379 QualType BuildPointerType(QualType T,
1380 SourceLocation Loc, DeclarationName Entity);
1381 QualType BuildReferenceType(QualType T, bool LValueRef,
1382 SourceLocation Loc, DeclarationName Entity);
1383 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1384 Expr *ArraySize, unsigned Quals,
1385 SourceRange Brackets, DeclarationName Entity);
1386 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1387 SourceLocation AttrLoc);
1388 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1389 SourceLocation AttrLoc);
1390
1391 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1392
1393 /// \brief Build a function type.
1394 ///
1395 /// This routine checks the function type according to C++ rules and
1396 /// under the assumption that the result type and parameter types have
1397 /// just been instantiated from a template. It therefore duplicates
1398 /// some of the behavior of GetTypeForDeclarator, but in a much
1399 /// simpler form that is only suitable for this narrow use case.
1400 ///
1401 /// \param T The return type of the function.
1402 ///
1403 /// \param ParamTypes The parameter types of the function. This array
1404 /// will be modified to account for adjustments to the types of the
1405 /// function parameters.
1406 ///
1407 /// \param Loc The location of the entity whose type involves this
1408 /// function type or, if there is no such entity, the location of the
1409 /// type that will have function type.
1410 ///
1411 /// \param Entity The name of the entity that involves the function
1412 /// type, if known.
1413 ///
1414 /// \param EPI Extra information about the function type. Usually this will
1415 /// be taken from an existing function with the same prototype.
1416 ///
1417 /// \returns A suitable function type, if there are no errors. The
1418 /// unqualified type will always be a FunctionProtoType.
1419 /// Otherwise, returns a NULL type.
1420 QualType BuildFunctionType(QualType T,
1421 MutableArrayRef<QualType> ParamTypes,
1422 SourceLocation Loc, DeclarationName Entity,
1423 const FunctionProtoType::ExtProtoInfo &EPI);
1424
1425 QualType BuildMemberPointerType(QualType T, QualType Class,
1426 SourceLocation Loc,
1427 DeclarationName Entity);
1428 QualType BuildBlockPointerType(QualType T,
1429 SourceLocation Loc, DeclarationName Entity);
1430 QualType BuildParenType(QualType T);
1431 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1432 QualType BuildReadPipeType(QualType T,
1433 SourceLocation Loc);
1434 QualType BuildWritePipeType(QualType T,
1435 SourceLocation Loc);
1436
1437 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1438 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1439 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1440 TypeSourceInfo *ReturnTypeInfo);
1441
1442 /// \brief Package the given type and TSI into a ParsedType.
1443 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1444 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1445 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1446 static QualType GetTypeFromParser(ParsedType Ty,
1447 TypeSourceInfo **TInfo = nullptr);
1448 CanThrowResult canThrow(const Expr *E);
1449 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1450 const FunctionProtoType *FPT);
1451 void UpdateExceptionSpec(FunctionDecl *FD,
1452 const FunctionProtoType::ExceptionSpecInfo &ESI);
1453 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1454 bool CheckDistantExceptionSpec(QualType T);
1455 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1456 bool CheckEquivalentExceptionSpec(
1457 const FunctionProtoType *Old, SourceLocation OldLoc,
1458 const FunctionProtoType *New, SourceLocation NewLoc);
1459 bool CheckEquivalentExceptionSpec(
1460 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1461 const FunctionProtoType *Old, SourceLocation OldLoc,
1462 const FunctionProtoType *New, SourceLocation NewLoc);
1463 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1464 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1465 const PartialDiagnostic &NestedDiagID,
1466 const PartialDiagnostic &NoteID,
1467 const FunctionProtoType *Superset,
1468 SourceLocation SuperLoc,
1469 const FunctionProtoType *Subset,
1470 SourceLocation SubLoc);
1471 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1472 const PartialDiagnostic &NoteID,
1473 const FunctionProtoType *Target,
1474 SourceLocation TargetLoc,
1475 const FunctionProtoType *Source,
1476 SourceLocation SourceLoc);
1477
1478 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1479
1480 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1481 /// in an Objective-C message declaration. Return the appropriate type.
1482 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1483
1484 /// \brief Abstract class used to diagnose incomplete types.
1485 struct TypeDiagnoser {
1486 TypeDiagnoser() {}
1487
1488 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1489 virtual ~TypeDiagnoser() {}
1490 };
1491
1492 static int getPrintable(int I) { return I; }
1493 static unsigned getPrintable(unsigned I) { return I; }
1494 static bool getPrintable(bool B) { return B; }
1495 static const char * getPrintable(const char *S) { return S; }
1496 static StringRef getPrintable(StringRef S) { return S; }
1497 static const std::string &getPrintable(const std::string &S) { return S; }
1498 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1499 return II;
1500 }
1501 static DeclarationName getPrintable(DeclarationName N) { return N; }
1502 static QualType getPrintable(QualType T) { return T; }
1503 static SourceRange getPrintable(SourceRange R) { return R; }
1504 static SourceRange getPrintable(SourceLocation L) { return L; }
1505 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1506 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1507
1508 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1509 unsigned DiagID;
1510 std::tuple<const Ts &...> Args;
1511
1512 template <std::size_t... Is>
1513 void emit(const SemaDiagnosticBuilder &DB,
1514 llvm::index_sequence<Is...>) const {
1515 // Apply all tuple elements to the builder in order.
1516 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1517 (void)Dummy;
1518 }
1519
1520 public:
1521 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1522 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1523 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 1523, __extension__ __PRETTY_FUNCTION__))
;
1524 }
1525
1526 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1527 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1528 emit(DB, llvm::index_sequence_for<Ts...>());
1529 DB << T;
1530 }
1531 };
1532
1533private:
1534 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1535 TypeDiagnoser *Diagnoser);
1536
1537 struct ModuleScope {
1538 clang::Module *Module = nullptr;
1539 bool ModuleInterface = false;
1540 VisibleModuleSet OuterVisibleModules;
1541 };
1542 /// The modules we're currently parsing.
1543 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1544
1545 /// Get the module whose scope we are currently within.
1546 Module *getCurrentModule() const {
1547 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1548 }
1549
1550 VisibleModuleSet VisibleModules;
1551
1552public:
1553 /// \brief Get the module owning an entity.
1554 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1555
1556 /// \brief Make a merged definition of an existing hidden definition \p ND
1557 /// visible at the specified location.
1558 void makeMergedDefinitionVisible(NamedDecl *ND);
1559
1560 bool isModuleVisible(const Module *M) { return VisibleModules.isVisible(M); }
1561
1562 /// Determine whether a declaration is visible to name lookup.
1563 bool isVisible(const NamedDecl *D) {
1564 return !D->isHidden() || isVisibleSlow(D);
1565 }
1566
1567 /// Determine whether any declaration of an entity is visible.
1568 bool
1569 hasVisibleDeclaration(const NamedDecl *D,
1570 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1571 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1572 }
1573 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1574 llvm::SmallVectorImpl<Module *> *Modules);
1575
1576 bool hasVisibleMergedDefinition(NamedDecl *Def);
1577 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1578
1579 /// Determine if \p D and \p Suggested have a structurally compatible
1580 /// layout as described in C11 6.2.7/1.
1581 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1582
1583 /// Determine if \p D has a visible definition. If not, suggest a declaration
1584 /// that should be made visible to expose the definition.
1585 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1586 bool OnlyNeedComplete = false);
1587 bool hasVisibleDefinition(const NamedDecl *D) {
1588 NamedDecl *Hidden;
1589 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1590 }
1591
1592 /// Determine if the template parameter \p D has a visible default argument.
1593 bool
1594 hasVisibleDefaultArgument(const NamedDecl *D,
1595 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1596
1597 /// Determine if there is a visible declaration of \p D that is an explicit
1598 /// specialization declaration for a specialization of a template. (For a
1599 /// member specialization, use hasVisibleMemberSpecialization.)
1600 bool hasVisibleExplicitSpecialization(
1601 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1602
1603 /// Determine if there is a visible declaration of \p D that is a member
1604 /// specialization declaration (as opposed to an instantiated declaration).
1605 bool hasVisibleMemberSpecialization(
1606 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1607
1608 /// Determine if \p A and \p B are equivalent internal linkage declarations
1609 /// from different modules, and thus an ambiguity error can be downgraded to
1610 /// an extension warning.
1611 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1612 const NamedDecl *B);
1613 void diagnoseEquivalentInternalLinkageDeclarations(
1614 SourceLocation Loc, const NamedDecl *D,
1615 ArrayRef<const NamedDecl *> Equiv);
1616
1617 bool isCompleteType(SourceLocation Loc, QualType T) {
1618 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1619 }
1620 bool RequireCompleteType(SourceLocation Loc, QualType T,
1621 TypeDiagnoser &Diagnoser);
1622 bool RequireCompleteType(SourceLocation Loc, QualType T,
1623 unsigned DiagID);
1624
1625 template <typename... Ts>
1626 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1627 const Ts &...Args) {
1628 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1629 return RequireCompleteType(Loc, T, Diagnoser);
1630 }
1631
1632 void completeExprArrayBound(Expr *E);
1633 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1634 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1635
1636 template <typename... Ts>
1637 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1638 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1639 return RequireCompleteExprType(E, Diagnoser);
1640 }
1641
1642 bool RequireLiteralType(SourceLocation Loc, QualType T,
1643 TypeDiagnoser &Diagnoser);
1644 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1645
1646 template <typename... Ts>
1647 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1648 const Ts &...Args) {
1649 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1650 return RequireLiteralType(Loc, T, Diagnoser);
1651 }
1652
1653 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1654 const CXXScopeSpec &SS, QualType T);
1655
1656 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1657 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1658 /// context, such as when building a type for decltype(auto).
1659 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1660 bool AsUnevaluated = true);
1661 QualType BuildUnaryTransformType(QualType BaseType,
1662 UnaryTransformType::UTTKind UKind,
1663 SourceLocation Loc);
1664
1665 //===--------------------------------------------------------------------===//
1666 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1667 //
1668
1669 struct SkipBodyInfo {
1670 SkipBodyInfo()
1671 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1672 New(nullptr) {}
1673 bool ShouldSkip;
1674 bool CheckSameAsPrevious;
1675 NamedDecl *Previous;
1676 NamedDecl *New;
1677 };
1678
1679 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1680
1681 void DiagnoseUseOfUnimplementedSelectors();
1682
1683 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1684
1685 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1686 Scope *S, CXXScopeSpec *SS = nullptr,
1687 bool isClassName = false, bool HasTrailingDot = false,
1688 ParsedType ObjectType = nullptr,
1689 bool IsCtorOrDtorName = false,
1690 bool WantNontrivialTypeSourceInfo = false,
1691 bool IsClassTemplateDeductionContext = true,
1692 IdentifierInfo **CorrectedII = nullptr);
1693 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1694 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1695 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1696 SourceLocation IILoc,
1697 Scope *S,
1698 CXXScopeSpec *SS,
1699 ParsedType &SuggestedType,
1700 bool IsTemplateName = false);
1701
1702 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1703 /// type name has failed in a dependent context. In these situations, we
1704 /// automatically form a DependentTypeName that will retry lookup in a related
1705 /// scope during instantiation.
1706 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1707 SourceLocation NameLoc,
1708 bool IsTemplateTypeArg);
1709
1710 /// \brief Describes the result of the name lookup and resolution performed
1711 /// by \c ClassifyName().
1712 enum NameClassificationKind {
1713 NC_Unknown,
1714 NC_Error,
1715 NC_Keyword,
1716 NC_Type,
1717 NC_Expression,
1718 NC_NestedNameSpecifier,
1719 NC_TypeTemplate,
1720 NC_VarTemplate,
1721 NC_FunctionTemplate
1722 };
1723
1724 class NameClassification {
1725 NameClassificationKind Kind;
1726 ExprResult Expr;
1727 TemplateName Template;
1728 ParsedType Type;
1729
1730 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1731
1732 public:
1733 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1734
1735 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1736
1737 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1738
1739 static NameClassification Error() {
1740 return NameClassification(NC_Error);
1741 }
1742
1743 static NameClassification Unknown() {
1744 return NameClassification(NC_Unknown);
1745 }
1746
1747 static NameClassification NestedNameSpecifier() {
1748 return NameClassification(NC_NestedNameSpecifier);
1749 }
1750
1751 static NameClassification TypeTemplate(TemplateName Name) {
1752 NameClassification Result(NC_TypeTemplate);
1753 Result.Template = Name;
1754 return Result;
1755 }
1756
1757 static NameClassification VarTemplate(TemplateName Name) {
1758 NameClassification Result(NC_VarTemplate);
1759 Result.Template = Name;
1760 return Result;
1761 }
1762
1763 static NameClassification FunctionTemplate(TemplateName Name) {
1764 NameClassification Result(NC_FunctionTemplate);
1765 Result.Template = Name;
1766 return Result;
1767 }
1768
1769 NameClassificationKind getKind() const { return Kind; }
1770
1771 ParsedType getType() const {
1772 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 1772, __extension__ __PRETTY_FUNCTION__))
;
1773 return Type;
1774 }
1775
1776 ExprResult getExpression() const {
1777 assert(Kind == NC_Expression)(static_cast <bool> (Kind == NC_Expression) ? void (0) :
__assert_fail ("Kind == NC_Expression", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 1777, __extension__ __PRETTY_FUNCTION__))
;
1778 return Expr;
1779 }
1780
1781 TemplateName getTemplateName() const {
1782 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 1783, __extension__ __PRETTY_FUNCTION__))
1783 Kind == NC_VarTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 1783, __extension__ __PRETTY_FUNCTION__))
;
1784 return Template;
1785 }
1786
1787 TemplateNameKind getTemplateNameKind() const {
1788 switch (Kind) {
1789 case NC_TypeTemplate:
1790 return TNK_Type_template;
1791 case NC_FunctionTemplate:
1792 return TNK_Function_template;
1793 case NC_VarTemplate:
1794 return TNK_Var_template;
1795 default:
1796 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 1796)
;
1797 }
1798 }
1799 };
1800
1801 /// \brief Perform name lookup on the given name, classifying it based on
1802 /// the results of name lookup and the following token.
1803 ///
1804 /// This routine is used by the parser to resolve identifiers and help direct
1805 /// parsing. When the identifier cannot be found, this routine will attempt
1806 /// to correct the typo and classify based on the resulting name.
1807 ///
1808 /// \param S The scope in which we're performing name lookup.
1809 ///
1810 /// \param SS The nested-name-specifier that precedes the name.
1811 ///
1812 /// \param Name The identifier. If typo correction finds an alternative name,
1813 /// this pointer parameter will be updated accordingly.
1814 ///
1815 /// \param NameLoc The location of the identifier.
1816 ///
1817 /// \param NextToken The token following the identifier. Used to help
1818 /// disambiguate the name.
1819 ///
1820 /// \param IsAddressOfOperand True if this name is the operand of a unary
1821 /// address of ('&') expression, assuming it is classified as an
1822 /// expression.
1823 ///
1824 /// \param CCC The correction callback, if typo correction is desired.
1825 NameClassification
1826 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1827 SourceLocation NameLoc, const Token &NextToken,
1828 bool IsAddressOfOperand,
1829 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1830
1831 /// Describes the detailed kind of a template name. Used in diagnostics.
1832 enum class TemplateNameKindForDiagnostics {
1833 ClassTemplate,
1834 FunctionTemplate,
1835 VarTemplate,
1836 AliasTemplate,
1837 TemplateTemplateParam,
1838 DependentTemplate
1839 };
1840 TemplateNameKindForDiagnostics
1841 getTemplateNameKindForDiagnostics(TemplateName Name);
1842
1843 /// Determine whether it's plausible that E was intended to be a
1844 /// template-name.
1845 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1846 if (!getLangOpts().CPlusPlus || E.isInvalid())
1847 return false;
1848 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1849 return !DRE->hasExplicitTemplateArgs();
1850 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1851 return !ME->hasExplicitTemplateArgs();
1852 // Any additional cases recognized here should also be handled by
1853 // diagnoseExprIntendedAsTemplateName.
1854 return false;
1855 }
1856 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1857 SourceLocation Less,
1858 SourceLocation Greater);
1859
1860 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1861
1862 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1863 MultiTemplateParamsArg TemplateParameterLists);
1864 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1865 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1866 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1867 DeclarationName Name,
1868 SourceLocation Loc);
1869 void
1870 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1871 SourceLocation FallbackLoc,
1872 SourceLocation ConstQualLoc = SourceLocation(),
1873 SourceLocation VolatileQualLoc = SourceLocation(),
1874 SourceLocation RestrictQualLoc = SourceLocation(),
1875 SourceLocation AtomicQualLoc = SourceLocation(),
1876 SourceLocation UnalignedQualLoc = SourceLocation());
1877
1878 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1879 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1880 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1881 const LookupResult &R);
1882 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1883 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1884 const LookupResult &R);
1885 void CheckShadow(Scope *S, VarDecl *D);
1886
1887 /// Warn if 'E', which is an expression that is about to be modified, refers
1888 /// to a shadowing declaration.
1889 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1890
1891 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1892
1893private:
1894 /// Map of current shadowing declarations to shadowed declarations. Warn if
1895 /// it looks like the user is trying to modify the shadowing declaration.
1896 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1897
1898public:
1899 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1900 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1901 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1902 TypedefNameDecl *NewTD);
1903 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1904 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1905 TypeSourceInfo *TInfo,
1906 LookupResult &Previous);
1907 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1908 LookupResult &Previous, bool &Redeclaration);
1909 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1910 TypeSourceInfo *TInfo,
1911 LookupResult &Previous,
1912 MultiTemplateParamsArg TemplateParamLists,
1913 bool &AddToScope,
1914 ArrayRef<BindingDecl *> Bindings = None);
1915 NamedDecl *
1916 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1917 MultiTemplateParamsArg TemplateParamLists);
1918 // Returns true if the variable declaration is a redeclaration
1919 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1920 void CheckVariableDeclarationType(VarDecl *NewVD);
1921 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1922 Expr *Init);
1923 void CheckCompleteVariableDeclaration(VarDecl *VD);
1924 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1925 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1926
1927 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1928 TypeSourceInfo *TInfo,
1929 LookupResult &Previous,
1930 MultiTemplateParamsArg TemplateParamLists,
1931 bool &AddToScope);
1932 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1933
1934 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1935 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1936
1937 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1938 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1939 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1940 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1941 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1942 // Returns true if the function declaration is a redeclaration
1943 bool CheckFunctionDeclaration(Scope *S,
1944 FunctionDecl *NewFD, LookupResult &Previous,
1945 bool IsMemberSpecialization);
1946 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1947 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1948 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1949 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1950 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1951 SourceLocation Loc,
1952 QualType T);
1953 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1954 SourceLocation NameLoc, IdentifierInfo *Name,
1955 QualType T, TypeSourceInfo *TSInfo,
1956 StorageClass SC);
1957 void ActOnParamDefaultArgument(Decl *param,
1958 SourceLocation EqualLoc,
1959 Expr *defarg);
1960 void ActOnParamUnparsedDefaultArgument(Decl *param,
1961 SourceLocation EqualLoc,
1962 SourceLocation ArgLoc);
1963 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1964 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1965 SourceLocation EqualLoc);
1966
1967 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1968 void ActOnUninitializedDecl(Decl *dcl);
1969 void ActOnInitializerError(Decl *Dcl);
1970
1971 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1972 void ActOnCXXForRangeDecl(Decl *D);
1973 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1974 IdentifierInfo *Ident,
1975 ParsedAttributes &Attrs,
1976 SourceLocation AttrEnd);
1977 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1978 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1979 void FinalizeDeclaration(Decl *D);
1980 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1981 ArrayRef<Decl *> Group);
1982 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1983
1984 /// Should be called on all declarations that might have attached
1985 /// documentation comments.
1986 void ActOnDocumentableDecl(Decl *D);
1987 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1988
1989 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1990 SourceLocation LocAfterDecls);
1991 void CheckForFunctionRedefinition(
1992 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1993 SkipBodyInfo *SkipBody = nullptr);
1994 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1995 MultiTemplateParamsArg TemplateParamLists,
1996 SkipBodyInfo *SkipBody = nullptr);
1997 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1998 SkipBodyInfo *SkipBody = nullptr);
1999 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2000 bool isObjCMethodDecl(Decl *D) {
2001 return D && isa<ObjCMethodDecl>(D);
2002 }
2003
2004 /// \brief Determine whether we can delay parsing the body of a function or
2005 /// function template until it is used, assuming we don't care about emitting
2006 /// code for that function.
2007 ///
2008 /// This will be \c false if we may need the body of the function in the
2009 /// middle of parsing an expression (where it's impractical to switch to
2010 /// parsing a different function), for instance, if it's constexpr in C++11
2011 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2012 bool canDelayFunctionBody(const Declarator &D);
2013
2014 /// \brief Determine whether we can skip parsing the body of a function
2015 /// definition, assuming we don't care about analyzing its body or emitting
2016 /// code for that function.
2017 ///
2018 /// This will be \c false only if we may need the body of the function in
2019 /// order to parse the rest of the program (for instance, if it is
2020 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2021 bool canSkipFunctionBody(Decl *D);
2022
2023 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2024 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2025 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2026 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2027 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2028
2029 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2030 /// attribute for which parsing is delayed.
2031 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2032
2033 /// \brief Diagnose any unused parameters in the given sequence of
2034 /// ParmVarDecl pointers.
2035 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2036
2037 /// \brief Diagnose whether the size of parameters or return value of a
2038 /// function or obj-c method definition is pass-by-value and larger than a
2039 /// specified threshold.
2040 void
2041 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2042 QualType ReturnTy, NamedDecl *D);
2043
2044 void DiagnoseInvalidJumps(Stmt *Body);
2045 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2046 SourceLocation AsmLoc,
2047 SourceLocation RParenLoc);
2048
2049 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
2050 Decl *ActOnEmptyDeclaration(Scope *S,
2051 AttributeList *AttrList,
2052 SourceLocation SemiLoc);
2053
2054 enum class ModuleDeclKind {
2055 Interface, ///< 'export module X;'
2056 Implementation, ///< 'module X;'
2057 Partition, ///< 'module partition X;'
2058 };
2059
2060 /// The parser has processed a module-declaration that begins the definition
2061 /// of a module interface or implementation.
2062 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2063 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2064 ModuleIdPath Path);
2065
2066 /// \brief The parser has processed a module import declaration.
2067 ///
2068 /// \param AtLoc The location of the '@' symbol, if any.
2069 ///
2070 /// \param ImportLoc The location of the 'import' keyword.
2071 ///
2072 /// \param Path The module access path.
2073 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
2074 ModuleIdPath Path);
2075
2076 /// \brief The parser has processed a module import translated from a
2077 /// #include or similar preprocessing directive.
2078 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2079 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2080
2081 /// \brief The parsed has entered a submodule.
2082 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2083 /// \brief The parser has left a submodule.
2084 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2085
2086 /// \brief Create an implicit import of the given module at the given
2087 /// source location, for error recovery, if possible.
2088 ///
2089 /// This routine is typically used when an entity found by name lookup
2090 /// is actually hidden within a module that we know about but the user
2091 /// has forgotten to import.
2092 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2093 Module *Mod);
2094
2095 /// Kinds of missing import. Note, the values of these enumerators correspond
2096 /// to %select values in diagnostics.
2097 enum class MissingImportKind {
2098 Declaration,
2099 Definition,
2100 DefaultArgument,
2101 ExplicitSpecialization,
2102 PartialSpecialization
2103 };
2104
2105 /// \brief Diagnose that the specified declaration needs to be visible but
2106 /// isn't, and suggest a module import that would resolve the problem.
2107 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2108 MissingImportKind MIK, bool Recover = true);
2109 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2110 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2111 MissingImportKind MIK, bool Recover);
2112
2113 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2114 SourceLocation LBraceLoc);
2115 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2116 SourceLocation RBraceLoc);
2117
2118 /// \brief We've found a use of a templated declaration that would trigger an
2119 /// implicit instantiation. Check that any relevant explicit specializations
2120 /// and partial specializations are visible, and diagnose if not.
2121 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2122
2123 /// \brief We've found a use of a template specialization that would select a
2124 /// partial specialization. Check that the partial specialization is visible,
2125 /// and diagnose if not.
2126 void checkPartialSpecializationVisibility(SourceLocation Loc,
2127 NamedDecl *Spec);
2128
2129 /// \brief Retrieve a suitable printing policy.
2130 PrintingPolicy getPrintingPolicy() const {
2131 return getPrintingPolicy(Context, PP);
2132 }
2133
2134 /// \brief Retrieve a suitable printing policy.
2135 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2136 const Preprocessor &PP);
2137
2138 /// Scope actions.
2139 void ActOnPopScope(SourceLocation Loc, Scope *S);
2140 void ActOnTranslationUnitScope(Scope *S);
2141
2142 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2143 RecordDecl *&AnonRecord);
2144 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2145 MultiTemplateParamsArg TemplateParams,
2146 bool IsExplicitInstantiation,
2147 RecordDecl *&AnonRecord);
2148
2149 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2150 AccessSpecifier AS,
2151 RecordDecl *Record,
2152 const PrintingPolicy &Policy);
2153
2154 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2155 RecordDecl *Record);
2156
2157 /// Common ways to introduce type names without a tag for use in diagnostics.
2158 /// Keep in sync with err_tag_reference_non_tag.
2159 enum NonTagKind {
2160 NTK_NonStruct,
2161 NTK_NonClass,
2162 NTK_NonUnion,
2163 NTK_NonEnum,
2164 NTK_Typedef,
2165 NTK_TypeAlias,
2166 NTK_Template,
2167 NTK_TypeAliasTemplate,
2168 NTK_TemplateTemplateArgument,
2169 };
2170
2171 /// Given a non-tag type declaration, returns an enum useful for indicating
2172 /// what kind of non-tag type this is.
2173 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2174
2175 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2176 TagTypeKind NewTag, bool isDefinition,
2177 SourceLocation NewTagLoc,
2178 const IdentifierInfo *Name);
2179
2180 enum TagUseKind {
2181 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2182 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2183 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2184 TUK_Friend // Friend declaration: 'friend struct foo;'
2185 };
2186
2187 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2188 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2189 SourceLocation NameLoc, AttributeList *Attr,
2190 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2191 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2192 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2193 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2194 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2195 SkipBodyInfo *SkipBody = nullptr);
2196
2197 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2198 unsigned TagSpec, SourceLocation TagLoc,
2199 CXXScopeSpec &SS,
2200 IdentifierInfo *Name, SourceLocation NameLoc,
2201 AttributeList *Attr,
2202 MultiTemplateParamsArg TempParamLists);
2203
2204 TypeResult ActOnDependentTag(Scope *S,
2205 unsigned TagSpec,
2206 TagUseKind TUK,
2207 const CXXScopeSpec &SS,
2208 IdentifierInfo *Name,
2209 SourceLocation TagLoc,
2210 SourceLocation NameLoc);
2211
2212 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2213 IdentifierInfo *ClassName,
2214 SmallVectorImpl<Decl *> &Decls);
2215 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2216 Declarator &D, Expr *BitfieldWidth);
2217
2218 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2219 Declarator &D, Expr *BitfieldWidth,
2220 InClassInitStyle InitStyle,
2221 AccessSpecifier AS);
2222 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2223 SourceLocation DeclStart,
2224 Declarator &D, Expr *BitfieldWidth,
2225 InClassInitStyle InitStyle,
2226 AccessSpecifier AS,
2227 AttributeList *MSPropertyAttr);
2228
2229 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2230 TypeSourceInfo *TInfo,
2231 RecordDecl *Record, SourceLocation Loc,
2232 bool Mutable, Expr *BitfieldWidth,
2233 InClassInitStyle InitStyle,
2234 SourceLocation TSSL,
2235 AccessSpecifier AS, NamedDecl *PrevDecl,
2236 Declarator *D = nullptr);
2237
2238 bool CheckNontrivialField(FieldDecl *FD);
2239 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2240
2241 enum TrivialABIHandling {
2242 /// The triviality of a method unaffected by "trivial_abi".
2243 TAH_IgnoreTrivialABI,
2244
2245 /// The triviality of a method affected by "trivial_abi".
2246 TAH_ConsiderTrivialABI
2247 };
2248
2249 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2250 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2251 bool Diagnose = false);
2252 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2253 void ActOnLastBitfield(SourceLocation DeclStart,
2254 SmallVectorImpl<Decl *> &AllIvarDecls);
2255 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2256 Declarator &D, Expr *BitfieldWidth,
2257 tok::ObjCKeywordKind visibility);
2258
2259 // This is used for both record definitions and ObjC interface declarations.
2260 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2261 ArrayRef<Decl *> Fields,
2262 SourceLocation LBrac, SourceLocation RBrac,
2263 AttributeList *AttrList);
2264
2265 /// ActOnTagStartDefinition - Invoked when we have entered the
2266 /// scope of a tag's definition (e.g., for an enumeration, class,
2267 /// struct, or union).
2268 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2269
2270 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2271 /// Differently from C++, actually parse the body and reject / error out
2272 /// in case of a structural mismatch.
2273 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2274 SkipBodyInfo &SkipBody);
2275
2276 typedef void *SkippedDefinitionContext;
2277
2278 /// \brief Invoked when we enter a tag definition that we're skipping.
2279 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2280
2281 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2282
2283 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2284 /// C++ record definition's base-specifiers clause and are starting its
2285 /// member declarations.
2286 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2287 SourceLocation FinalLoc,
2288 bool IsFinalSpelledSealed,
2289 SourceLocation LBraceLoc);
2290
2291 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2292 /// the definition of a tag (enumeration, class, struct, or union).
2293 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2294 SourceRange BraceRange);
2295
2296 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2297
2298 void ActOnObjCContainerFinishDefinition();
2299
2300 /// \brief Invoked when we must temporarily exit the objective-c container
2301 /// scope for parsing/looking-up C constructs.
2302 ///
2303 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2304 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2305 void ActOnObjCReenterContainerContext(DeclContext *DC);
2306
2307 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2308 /// error parsing the definition of a tag.
2309 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2310
2311 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2312 EnumConstantDecl *LastEnumConst,
2313 SourceLocation IdLoc,
2314 IdentifierInfo *Id,
2315 Expr *val);
2316 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2317 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2318 QualType EnumUnderlyingTy, bool IsFixed,
2319 const EnumDecl *Prev);
2320
2321 /// Determine whether the body of an anonymous enumeration should be skipped.
2322 /// \param II The name of the first enumerator.
2323 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2324 SourceLocation IILoc);
2325
2326 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2327 SourceLocation IdLoc, IdentifierInfo *Id,
2328 AttributeList *Attrs, SourceLocation EqualLoc,
2329 Expr *Val);
2330 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2331 Decl *EnumDecl,
2332 ArrayRef<Decl *> Elements,
2333 Scope *S, AttributeList *Attr);
2334
2335 DeclContext *getContainingDC(DeclContext *DC);
2336
2337 /// Set the current declaration context until it gets popped.
2338 void PushDeclContext(Scope *S, DeclContext *DC);
2339 void PopDeclContext();
2340
2341 /// EnterDeclaratorContext - Used when we must lookup names in the context
2342 /// of a declarator's nested name specifier.
2343 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2344 void ExitDeclaratorContext(Scope *S);
2345
2346 /// Push the parameters of D, which must be a function, into scope.
2347 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2348 void ActOnExitFunctionContext();
2349
2350 DeclContext *getFunctionLevelDeclContext();
2351
2352 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2353 /// to the function decl for the function being parsed. If we're currently
2354 /// in a 'block', this returns the containing context.
2355 FunctionDecl *getCurFunctionDecl();
2356
2357 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2358 /// the method decl for the method being parsed. If we're currently
2359 /// in a 'block', this returns the containing context.
2360 ObjCMethodDecl *getCurMethodDecl();
2361
2362 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2363 /// or C function we're in, otherwise return null. If we're currently
2364 /// in a 'block', this returns the containing context.
2365 NamedDecl *getCurFunctionOrMethodDecl();
2366
2367 /// Add this decl to the scope shadowed decl chains.
2368 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2369
2370 /// \brief Make the given externally-produced declaration visible at the
2371 /// top level scope.
2372 ///
2373 /// \param D The externally-produced declaration to push.
2374 ///
2375 /// \param Name The name of the externally-produced declaration.
2376 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2377
2378 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2379 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2380 /// true if 'D' belongs to the given declaration context.
2381 ///
2382 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2383 /// enclosing namespace set of the context, rather than contained
2384 /// directly within it.
2385 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2386 bool AllowInlineNamespace = false);
2387
2388 /// Finds the scope corresponding to the given decl context, if it
2389 /// happens to be an enclosing scope. Otherwise return NULL.
2390 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2391
2392 /// Subroutines of ActOnDeclarator().
2393 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2394 TypeSourceInfo *TInfo);
2395 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2396
2397 /// \brief Describes the kind of merge to perform for availability
2398 /// attributes (including "deprecated", "unavailable", and "availability").
2399 enum AvailabilityMergeKind {
2400 /// \brief Don't merge availability attributes at all.
2401 AMK_None,
2402 /// \brief Merge availability attributes for a redeclaration, which requires
2403 /// an exact match.
2404 AMK_Redeclaration,
2405 /// \brief Merge availability attributes for an override, which requires
2406 /// an exact match or a weakening of constraints.
2407 AMK_Override,
2408 /// \brief Merge availability attributes for an implementation of
2409 /// a protocol requirement.
2410 AMK_ProtocolImplementation,
2411 };
2412
2413 /// Attribute merging methods. Return true if a new attribute was added.
2414 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2415 IdentifierInfo *Platform,
2416 bool Implicit,
2417 VersionTuple Introduced,
2418 VersionTuple Deprecated,
2419 VersionTuple Obsoleted,
2420 bool IsUnavailable,
2421 StringRef Message,
2422 bool IsStrict, StringRef Replacement,
2423 AvailabilityMergeKind AMK,
2424 unsigned AttrSpellingListIndex);
2425 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2426 TypeVisibilityAttr::VisibilityType Vis,
2427 unsigned AttrSpellingListIndex);
2428 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2429 VisibilityAttr::VisibilityType Vis,
2430 unsigned AttrSpellingListIndex);
2431 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2432 unsigned AttrSpellingListIndex, StringRef Uuid);
2433 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2434 unsigned AttrSpellingListIndex);
2435 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2436 unsigned AttrSpellingListIndex);
2437 MSInheritanceAttr *
2438 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2439 unsigned AttrSpellingListIndex,
2440 MSInheritanceAttr::Spelling SemanticSpelling);
2441 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2442 IdentifierInfo *Format, int FormatIdx,
2443 int FirstArg, unsigned AttrSpellingListIndex);
2444 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2445 unsigned AttrSpellingListIndex);
2446 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2447 IdentifierInfo *Ident,
2448 unsigned AttrSpellingListIndex);
2449 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2450 unsigned AttrSpellingListIndex);
2451 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2452 unsigned AttrSpellingListIndex);
2453 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2454 IdentifierInfo *Ident,
2455 unsigned AttrSpellingListIndex);
2456 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2457 unsigned AttrSpellingListIndex);
2458
2459 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2460 AvailabilityMergeKind AMK = AMK_Redeclaration);
2461 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2462 LookupResult &OldDecls);
2463 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2464 bool MergeTypeWithOld);
2465 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2466 Scope *S, bool MergeTypeWithOld);
2467 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2468 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2469 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2470 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2471 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2472 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2473 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2474
2475 // AssignmentAction - This is used by all the assignment diagnostic functions
2476 // to represent what is actually causing the operation
2477 enum AssignmentAction {
2478 AA_Assigning,
2479 AA_Passing,
2480 AA_Returning,
2481 AA_Converting,
2482 AA_Initializing,
2483 AA_Sending,
2484 AA_Casting,
2485 AA_Passing_CFAudited
2486 };
2487
2488 /// C++ Overloading.
2489 enum OverloadKind {
2490 /// This is a legitimate overload: the existing declarations are
2491 /// functions or function templates with different signatures.
2492 Ovl_Overload,
2493
2494 /// This is not an overload because the signature exactly matches
2495 /// an existing declaration.
2496 Ovl_Match,
2497
2498 /// This is not an overload because the lookup results contain a
2499 /// non-function.
2500 Ovl_NonFunction
2501 };
2502 OverloadKind CheckOverload(Scope *S,
2503 FunctionDecl *New,
2504 const LookupResult &OldDecls,
2505 NamedDecl *&OldDecl,
2506 bool IsForUsingDecl);
2507 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2508 bool ConsiderCudaAttrs = true);
2509
2510 /// \brief Checks availability of the function depending on the current
2511 /// function context.Inside an unavailable function,unavailability is ignored.
2512 ///
2513 /// \returns true if \p FD is unavailable and current context is inside
2514 /// an available function, false otherwise.
2515 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2516
2517 ImplicitConversionSequence
2518 TryImplicitConversion(Expr *From, QualType ToType,
2519 bool SuppressUserConversions,
2520 bool AllowExplicit,
2521 bool InOverloadResolution,
2522 bool CStyle,
2523 bool AllowObjCWritebackConversion);
2524
2525 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2526 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2527 bool IsComplexPromotion(QualType FromType, QualType ToType);
2528 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2529 bool InOverloadResolution,
2530 QualType& ConvertedType, bool &IncompatibleObjC);
2531 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2532 QualType& ConvertedType, bool &IncompatibleObjC);
2533 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2534 QualType &ConvertedType);
2535 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2536 QualType& ConvertedType);
2537 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2538 const FunctionProtoType *NewType,
2539 unsigned *ArgPos = nullptr);
2540 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2541 QualType FromType, QualType ToType);
2542
2543 void maybeExtendBlockObject(ExprResult &E);
2544 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2545 bool CheckPointerConversion(Expr *From, QualType ToType,
2546 CastKind &Kind,
2547 CXXCastPath& BasePath,
2548 bool IgnoreBaseAccess,
2549 bool Diagnose = true);
2550 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2551 bool InOverloadResolution,
2552 QualType &ConvertedType);
2553 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2554 CastKind &Kind,
2555 CXXCastPath &BasePath,
2556 bool IgnoreBaseAccess);
2557 bool IsQualificationConversion(QualType FromType, QualType ToType,
2558 bool CStyle, bool &ObjCLifetimeConversion);
2559 bool IsFunctionConversion(QualType FromType, QualType ToType,
2560 QualType &ResultTy);
2561 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2562 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2563
2564 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2565 const VarDecl *NRVOCandidate,
2566 QualType ResultType,
2567 Expr *Value,
2568 bool AllowNRVO = true);
2569
2570 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2571 ExprResult Init);
2572 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2573 SourceLocation EqualLoc,
2574 ExprResult Init,
2575 bool TopLevelOfInitList = false,
2576 bool AllowExplicit = false);
2577 ExprResult PerformObjectArgumentInitialization(Expr *From,
2578 NestedNameSpecifier *Qualifier,
2579 NamedDecl *FoundDecl,
2580 CXXMethodDecl *Method);
2581
2582 ExprResult PerformContextuallyConvertToBool(Expr *From);
2583 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2584
2585 /// Contexts in which a converted constant expression is required.
2586 enum CCEKind {
2587 CCEK_CaseValue, ///< Expression in a case label.
2588 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2589 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2590 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2591 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2592 };
2593 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2594 llvm::APSInt &Value, CCEKind CCE);
2595 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2596 APValue &Value, CCEKind CCE);
2597
2598 /// \brief Abstract base class used to perform a contextual implicit
2599 /// conversion from an expression to any type passing a filter.
2600 class ContextualImplicitConverter {
2601 public:
2602 bool Suppress;
2603 bool SuppressConversion;
2604
2605 ContextualImplicitConverter(bool Suppress = false,
2606 bool SuppressConversion = false)
2607 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2608
2609 /// \brief Determine whether the specified type is a valid destination type
2610 /// for this conversion.
2611 virtual bool match(QualType T) = 0;
2612
2613 /// \brief Emits a diagnostic complaining that the expression does not have
2614 /// integral or enumeration type.
2615 virtual SemaDiagnosticBuilder
2616 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2617
2618 /// \brief Emits a diagnostic when the expression has incomplete class type.
2619 virtual SemaDiagnosticBuilder
2620 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2621
2622 /// \brief Emits a diagnostic when the only matching conversion function
2623 /// is explicit.
2624 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2625 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2626
2627 /// \brief Emits a note for the explicit conversion function.
2628 virtual SemaDiagnosticBuilder
2629 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2630
2631 /// \brief Emits a diagnostic when there are multiple possible conversion
2632 /// functions.
2633 virtual SemaDiagnosticBuilder
2634 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2635
2636 /// \brief Emits a note for one of the candidate conversions.
2637 virtual SemaDiagnosticBuilder
2638 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2639
2640 /// \brief Emits a diagnostic when we picked a conversion function
2641 /// (for cases when we are not allowed to pick a conversion function).
2642 virtual SemaDiagnosticBuilder diagnoseConversion(
2643 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2644
2645 virtual ~ContextualImplicitConverter() {}
2646 };
2647
2648 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2649 bool AllowScopedEnumerations;
2650
2651 public:
2652 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2653 bool Suppress, bool SuppressConversion)
2654 : ContextualImplicitConverter(Suppress, SuppressConversion),
2655 AllowScopedEnumerations(AllowScopedEnumerations) {}
2656
2657 /// Match an integral or (possibly scoped) enumeration type.
2658 bool match(QualType T) override;
2659
2660 SemaDiagnosticBuilder
2661 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2662 return diagnoseNotInt(S, Loc, T);
2663 }
2664
2665 /// \brief Emits a diagnostic complaining that the expression does not have
2666 /// integral or enumeration type.
2667 virtual SemaDiagnosticBuilder
2668 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2669 };
2670
2671 /// Perform a contextual implicit conversion.
2672 ExprResult PerformContextualImplicitConversion(
2673 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2674
2675
2676 enum ObjCSubscriptKind {
2677 OS_Array,
2678 OS_Dictionary,
2679 OS_Error
2680 };
2681 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2682
2683 // Note that LK_String is intentionally after the other literals, as
2684 // this is used for diagnostics logic.
2685 enum ObjCLiteralKind {
2686 LK_Array,
2687 LK_Dictionary,
2688 LK_Numeric,
2689 LK_Boxed,
2690 LK_String,
2691 LK_Block,
2692 LK_None
2693 };
2694 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2695
2696 ExprResult PerformObjectMemberConversion(Expr *From,
2697 NestedNameSpecifier *Qualifier,
2698 NamedDecl *FoundDecl,
2699 NamedDecl *Member);
2700
2701 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2702 // TODO: make this is a typesafe union.
2703 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2704 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2705
2706 void AddOverloadCandidate(FunctionDecl *Function,
2707 DeclAccessPair FoundDecl,
2708 ArrayRef<Expr *> Args,
2709 OverloadCandidateSet &CandidateSet,
2710 bool SuppressUserConversions = false,
2711 bool PartialOverloading = false,
2712 bool AllowExplicit = false,
2713 ConversionSequenceList EarlyConversions = None);
2714 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2715 ArrayRef<Expr *> Args,
2716 OverloadCandidateSet &CandidateSet,
2717 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2718 bool SuppressUserConversions = false,
2719 bool PartialOverloading = false,
2720 bool FirstArgumentIsBase = false);
2721 void AddMethodCandidate(DeclAccessPair FoundDecl,
2722 QualType ObjectType,
2723 Expr::Classification ObjectClassification,
2724 ArrayRef<Expr *> Args,
2725 OverloadCandidateSet& CandidateSet,
2726 bool SuppressUserConversion = false);
2727 void AddMethodCandidate(CXXMethodDecl *Method,
2728 DeclAccessPair FoundDecl,
2729 CXXRecordDecl *ActingContext, QualType ObjectType,
2730 Expr::Classification ObjectClassification,
2731 ArrayRef<Expr *> Args,
2732 OverloadCandidateSet& CandidateSet,
2733 bool SuppressUserConversions = false,
2734 bool PartialOverloading = false,
2735 ConversionSequenceList EarlyConversions = None);
2736 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2737 DeclAccessPair FoundDecl,
2738 CXXRecordDecl *ActingContext,
2739 TemplateArgumentListInfo *ExplicitTemplateArgs,
2740 QualType ObjectType,
2741 Expr::Classification ObjectClassification,
2742 ArrayRef<Expr *> Args,
2743 OverloadCandidateSet& CandidateSet,
2744 bool SuppressUserConversions = false,
2745 bool PartialOverloading = false);
2746 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2747 DeclAccessPair FoundDecl,
2748 TemplateArgumentListInfo *ExplicitTemplateArgs,
2749 ArrayRef<Expr *> Args,
2750 OverloadCandidateSet& CandidateSet,
2751 bool SuppressUserConversions = false,
2752 bool PartialOverloading = false);
2753 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2754 ArrayRef<QualType> ParamTypes,
2755 ArrayRef<Expr *> Args,
2756 OverloadCandidateSet &CandidateSet,
2757 ConversionSequenceList &Conversions,
2758 bool SuppressUserConversions,
2759 CXXRecordDecl *ActingContext = nullptr,
2760 QualType ObjectType = QualType(),
2761 Expr::Classification
2762 ObjectClassification = {});
2763 void AddConversionCandidate(CXXConversionDecl *Conversion,
2764 DeclAccessPair FoundDecl,
2765 CXXRecordDecl *ActingContext,
2766 Expr *From, QualType ToType,
2767 OverloadCandidateSet& CandidateSet,
2768 bool AllowObjCConversionOnExplicit,
2769 bool AllowResultConversion = true);
2770 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2771 DeclAccessPair FoundDecl,
2772 CXXRecordDecl *ActingContext,
2773 Expr *From, QualType ToType,
2774 OverloadCandidateSet &CandidateSet,
2775 bool AllowObjCConversionOnExplicit,
2776 bool AllowResultConversion = true);
2777 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2778 DeclAccessPair FoundDecl,
2779 CXXRecordDecl *ActingContext,
2780 const FunctionProtoType *Proto,
2781 Expr *Object, ArrayRef<Expr *> Args,
2782 OverloadCandidateSet& CandidateSet);
2783 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2784 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2785 OverloadCandidateSet& CandidateSet,
2786 SourceRange OpRange = SourceRange());
2787 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
2788 OverloadCandidateSet& CandidateSet,
2789 bool IsAssignmentOperator = false,
2790 unsigned NumContextualBoolArguments = 0);
2791 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2792 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2793 OverloadCandidateSet& CandidateSet);
2794 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2795 SourceLocation Loc,
2796 ArrayRef<Expr *> Args,
2797 TemplateArgumentListInfo *ExplicitTemplateArgs,
2798 OverloadCandidateSet& CandidateSet,
2799 bool PartialOverloading = false);
2800
2801 // Emit as a 'note' the specific overload candidate
2802 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2803 QualType DestType = QualType(),
2804 bool TakingAddress = false);
2805
2806 // Emit as a series of 'note's all template and non-templates identified by
2807 // the expression Expr
2808 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2809 bool TakingAddress = false);
2810
2811 /// Check the enable_if expressions on the given function. Returns the first
2812 /// failing attribute, or NULL if they were all successful.
2813 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2814 bool MissingImplicitThis = false);
2815
2816 /// Find the failed Boolean condition within a given Boolean
2817 /// constant expression, and describe it with a string.
2818 ///
2819 /// \param AllowTopLevelCond Whether to allow the result to be the
2820 /// complete top-level condition.
2821 std::pair<Expr *, std::string>
2822 findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond);
2823
2824 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2825 /// non-ArgDependent DiagnoseIfAttrs.
2826 ///
2827 /// Argument-dependent diagnose_if attributes should be checked each time a
2828 /// function is used as a direct callee of a function call.
2829 ///
2830 /// Returns true if any errors were emitted.
2831 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2832 const Expr *ThisArg,
2833 ArrayRef<const Expr *> Args,
2834 SourceLocation Loc);
2835
2836 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2837 /// ArgDependent DiagnoseIfAttrs.
2838 ///
2839 /// Argument-independent diagnose_if attributes should be checked on every use
2840 /// of a function.
2841 ///
2842 /// Returns true if any errors were emitted.
2843 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
2844 SourceLocation Loc);
2845
2846 /// Returns whether the given function's address can be taken or not,
2847 /// optionally emitting a diagnostic if the address can't be taken.
2848 ///
2849 /// Returns false if taking the address of the function is illegal.
2850 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2851 bool Complain = false,
2852 SourceLocation Loc = SourceLocation());
2853
2854 // [PossiblyAFunctionType] --> [Return]
2855 // NonFunctionType --> NonFunctionType
2856 // R (A) --> R(A)
2857 // R (*)(A) --> R (A)
2858 // R (&)(A) --> R (A)
2859 // R (S::*)(A) --> R (A)
2860 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2861
2862 FunctionDecl *
2863 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2864 QualType TargetType,
2865 bool Complain,
2866 DeclAccessPair &Found,
2867 bool *pHadMultipleCandidates = nullptr);
2868
2869 FunctionDecl *
2870 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2871 DeclAccessPair &FoundResult);
2872
2873 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2874 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2875
2876 FunctionDecl *
2877 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2878 bool Complain = false,
2879 DeclAccessPair *Found = nullptr);
2880
2881 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2882 ExprResult &SrcExpr,
2883 bool DoFunctionPointerConverion = false,
2884 bool Complain = false,
2885 SourceRange OpRangeForComplaining = SourceRange(),
2886 QualType DestTypeForComplaining = QualType(),
2887 unsigned DiagIDForComplaining = 0);
2888
2889
2890 Expr *FixOverloadedFunctionReference(Expr *E,
2891 DeclAccessPair FoundDecl,
2892 FunctionDecl *Fn);
2893 ExprResult FixOverloadedFunctionReference(ExprResult,
2894 DeclAccessPair FoundDecl,
2895 FunctionDecl *Fn);
2896
2897 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2898 ArrayRef<Expr *> Args,
2899 OverloadCandidateSet &CandidateSet,
2900 bool PartialOverloading = false);
2901
2902 // An enum used to represent the different possible results of building a
2903 // range-based for loop.
2904 enum ForRangeStatus {
2905 FRS_Success,
2906 FRS_NoViableFunction,
2907 FRS_DiagnosticIssued
2908 };
2909
2910 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2911 SourceLocation RangeLoc,
2912 const DeclarationNameInfo &NameInfo,
2913 LookupResult &MemberLookup,
2914 OverloadCandidateSet *CandidateSet,
2915 Expr *Range, ExprResult *CallExpr);
2916
2917 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2918 UnresolvedLookupExpr *ULE,
2919 SourceLocation LParenLoc,
2920 MultiExprArg Args,
2921 SourceLocation RParenLoc,
2922 Expr *ExecConfig,
2923 bool AllowTypoCorrection=true,
2924 bool CalleesAddressIsTaken=false);
2925
2926 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2927 MultiExprArg Args, SourceLocation RParenLoc,
2928 OverloadCandidateSet *CandidateSet,
2929 ExprResult *Result);
2930
2931 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2932 UnaryOperatorKind Opc,
2933 const UnresolvedSetImpl &Fns,
2934 Expr *input, bool RequiresADL = true);
2935
2936 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2937 BinaryOperatorKind Opc,
2938 const UnresolvedSetImpl &Fns,
2939 Expr *LHS, Expr *RHS,
2940 bool RequiresADL = true);
2941
2942 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2943 SourceLocation RLoc,
2944 Expr *Base,Expr *Idx);
2945
2946 ExprResult
2947 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2948 SourceLocation LParenLoc,
2949 MultiExprArg Args,
2950 SourceLocation RParenLoc);
2951 ExprResult
2952 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2953 MultiExprArg Args,
2954 SourceLocation RParenLoc);
2955
2956 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2957 SourceLocation OpLoc,
2958 bool *NoArrowOperatorFound = nullptr);
2959
2960 /// CheckCallReturnType - Checks that a call expression's return type is
2961 /// complete. Returns true on failure. The location passed in is the location
2962 /// that best represents the call.
2963 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2964 CallExpr *CE, FunctionDecl *FD);
2965
2966 /// Helpers for dealing with blocks and functions.
2967 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2968 bool CheckParameterNames);
2969 void CheckCXXDefaultArguments(FunctionDecl *FD);
2970 void CheckExtraCXXDefaultArguments(Declarator &D);
2971 Scope *getNonFieldDeclScope(Scope *S);
2972
2973 /// \name Name lookup
2974 ///
2975 /// These routines provide name lookup that is used during semantic
2976 /// analysis to resolve the various kinds of names (identifiers,
2977 /// overloaded operator names, constructor names, etc.) into zero or
2978 /// more declarations within a particular scope. The major entry
2979 /// points are LookupName, which performs unqualified name lookup,
2980 /// and LookupQualifiedName, which performs qualified name lookup.
2981 ///
2982 /// All name lookup is performed based on some specific criteria,
2983 /// which specify what names will be visible to name lookup and how
2984 /// far name lookup should work. These criteria are important both
2985 /// for capturing language semantics (certain lookups will ignore
2986 /// certain names, for example) and for performance, since name
2987 /// lookup is often a bottleneck in the compilation of C++. Name
2988 /// lookup criteria is specified via the LookupCriteria enumeration.
2989 ///
2990 /// The results of name lookup can vary based on the kind of name
2991 /// lookup performed, the current language, and the translation
2992 /// unit. In C, for example, name lookup will either return nothing
2993 /// (no entity found) or a single declaration. In C++, name lookup
2994 /// can additionally refer to a set of overloaded functions or
2995 /// result in an ambiguity. All of the possible results of name
2996 /// lookup are captured by the LookupResult class, which provides
2997 /// the ability to distinguish among them.
2998 //@{
2999
3000 /// @brief Describes the kind of name lookup to perform.
3001 enum LookupNameKind {
3002 /// Ordinary name lookup, which finds ordinary names (functions,
3003 /// variables, typedefs, etc.) in C and most kinds of names
3004 /// (functions, variables, members, types, etc.) in C++.
3005 LookupOrdinaryName = 0,
3006 /// Tag name lookup, which finds the names of enums, classes,
3007 /// structs, and unions.
3008 LookupTagName,
3009 /// Label name lookup.
3010 LookupLabel,
3011 /// Member name lookup, which finds the names of
3012 /// class/struct/union members.
3013 LookupMemberName,
3014 /// Look up of an operator name (e.g., operator+) for use with
3015 /// operator overloading. This lookup is similar to ordinary name
3016 /// lookup, but will ignore any declarations that are class members.
3017 LookupOperatorName,
3018 /// Look up of a name that precedes the '::' scope resolution
3019 /// operator in C++. This lookup completely ignores operator, object,
3020 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3021 LookupNestedNameSpecifierName,
3022 /// Look up a namespace name within a C++ using directive or
3023 /// namespace alias definition, ignoring non-namespace names (C++
3024 /// [basic.lookup.udir]p1).
3025 LookupNamespaceName,
3026 /// Look up all declarations in a scope with the given name,
3027 /// including resolved using declarations. This is appropriate
3028 /// for checking redeclarations for a using declaration.
3029 LookupUsingDeclName,
3030 /// Look up an ordinary name that is going to be redeclared as a
3031 /// name with linkage. This lookup ignores any declarations that
3032 /// are outside of the current scope unless they have linkage. See
3033 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3034 LookupRedeclarationWithLinkage,
3035 /// Look up a friend of a local class. This lookup does not look
3036 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3037 LookupLocalFriendName,
3038 /// Look up the name of an Objective-C protocol.
3039 LookupObjCProtocolName,
3040 /// Look up implicit 'self' parameter of an objective-c method.
3041 LookupObjCImplicitSelfParam,
3042 /// \brief Look up the name of an OpenMP user-defined reduction operation.
3043 LookupOMPReductionName,
3044 /// \brief Look up any declaration with any name.
3045 LookupAnyName
3046 };
3047
3048 /// \brief Specifies whether (or how) name lookup is being performed for a
3049 /// redeclaration (vs. a reference).
3050 enum RedeclarationKind {
3051 /// \brief The lookup is a reference to this name that is not for the
3052 /// purpose of redeclaring the name.
3053 NotForRedeclaration = 0,
3054 /// \brief The lookup results will be used for redeclaration of a name,
3055 /// if an entity by that name already exists and is visible.
3056 ForVisibleRedeclaration,
3057 /// \brief The lookup results will be used for redeclaration of a name
3058 /// with external linkage; non-visible lookup results with external linkage
3059 /// may also be found.
3060 ForExternalRedeclaration
3061 };
3062
3063 RedeclarationKind forRedeclarationInCurContext() {
3064 // A declaration with an owning module for linkage can never link against
3065 // anything that is not visible. We don't need to check linkage here; if
3066 // the context has internal linkage, redeclaration lookup won't find things
3067 // from other TUs, and we can't safely compute linkage yet in general.
3068 if (cast<Decl>(CurContext)
3069 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3070 return ForVisibleRedeclaration;
3071 return ForExternalRedeclaration;
3072 }
3073
3074 /// \brief The possible outcomes of name lookup for a literal operator.
3075 enum LiteralOperatorLookupResult {
3076 /// \brief The lookup resulted in an error.
3077 LOLR_Error,
3078 /// \brief The lookup found no match but no diagnostic was issued.
3079 LOLR_ErrorNoDiagnostic,
3080 /// \brief The lookup found a single 'cooked' literal operator, which
3081 /// expects a normal literal to be built and passed to it.
3082 LOLR_Cooked,
3083 /// \brief The lookup found a single 'raw' literal operator, which expects
3084 /// a string literal containing the spelling of the literal token.
3085 LOLR_Raw,
3086 /// \brief The lookup found an overload set of literal operator templates,
3087 /// which expect the characters of the spelling of the literal token to be
3088 /// passed as a non-type template argument pack.
3089 LOLR_Template,
3090 /// \brief The lookup found an overload set of literal operator templates,
3091 /// which expect the character type and characters of the spelling of the
3092 /// string literal token to be passed as template arguments.
3093 LOLR_StringTemplate
3094 };
3095
3096 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3097 CXXSpecialMember SM,
3098 bool ConstArg,
3099 bool VolatileArg,
3100 bool RValueThis,
3101 bool ConstThis,
3102 bool VolatileThis);
3103
3104 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3105 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3106 TypoRecoveryCallback;
3107
3108private:
3109 bool CppLookupName(LookupResult &R, Scope *S);
3110
3111 struct TypoExprState {
3112 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3113 TypoDiagnosticGenerator DiagHandler;
3114 TypoRecoveryCallback RecoveryHandler;
3115 TypoExprState();
3116 TypoExprState(TypoExprState &&other) noexcept;
3117 TypoExprState &operator=(TypoExprState &&other) noexcept;
3118 };
3119
3120 /// \brief The set of unhandled TypoExprs and their associated state.
3121 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3122
3123 /// \brief Creates a new TypoExpr AST node.
3124 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3125 TypoDiagnosticGenerator TDG,
3126 TypoRecoveryCallback TRC);
3127
3128 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
3129 //
3130 // The boolean value will be true to indicate that the namespace was loaded
3131 // from an AST/PCH file, or false otherwise.
3132 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3133
3134 /// \brief Whether we have already loaded known namespaces from an extenal
3135 /// source.
3136 bool LoadedExternalKnownNamespaces;
3137
3138 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3139 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3140 /// should be skipped entirely.
3141 std::unique_ptr<TypoCorrectionConsumer>
3142 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3143 Sema::LookupNameKind LookupKind, Scope *S,
3144 CXXScopeSpec *SS,
3145 std::unique_ptr<CorrectionCandidateCallback> CCC,
3146 DeclContext *MemberContext, bool EnteringContext,
3147 const ObjCObjectPointerType *OPT,
3148 bool ErrorRecovery);
3149
3150public:
3151 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3152
3153 /// \brief Clears the state of the given TypoExpr.
3154 void clearDelayedTypo(TypoExpr *TE);
3155
3156 /// \brief Look up a name, looking for a single declaration. Return
3157 /// null if the results were absent, ambiguous, or overloaded.
3158 ///
3159 /// It is preferable to use the elaborated form and explicitly handle
3160 /// ambiguity and overloaded.
3161 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3162 SourceLocation Loc,
3163 LookupNameKind NameKind,
3164 RedeclarationKind Redecl
3165 = NotForRedeclaration);
3166 bool LookupName(LookupResult &R, Scope *S,
3167 bool AllowBuiltinCreation = false);
3168 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3169 bool InUnqualifiedLookup = false);
3170 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3171 CXXScopeSpec &SS);
3172 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3173 bool AllowBuiltinCreation = false,
3174 bool EnteringContext = false);
3175 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3176 RedeclarationKind Redecl
3177 = NotForRedeclaration);
3178 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3179
3180 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3181 QualType T1, QualType T2,
3182 UnresolvedSetImpl &Functions);
3183
3184 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3185 SourceLocation GnuLabelLoc = SourceLocation());
3186
3187 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3188 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3189 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3190 unsigned Quals);
3191 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3192 bool RValueThis, unsigned ThisQuals);
3193 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3194 unsigned Quals);
3195 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3196 bool RValueThis, unsigned ThisQuals);
3197 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3198
3199 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3200 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3201 ArrayRef<QualType> ArgTys,
3202 bool AllowRaw,
3203 bool AllowTemplate,
3204 bool AllowStringTemplate,
3205 bool DiagnoseMissing);
3206 bool isKnownName(StringRef name);
3207
3208 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3209 ArrayRef<Expr *> Args, ADLResult &Functions);
3210
3211 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3212 VisibleDeclConsumer &Consumer,
3213 bool IncludeGlobalScope = true,
3214 bool LoadExternal = true);
3215 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3216 VisibleDeclConsumer &Consumer,
3217 bool IncludeGlobalScope = true,
3218 bool IncludeDependentBases = false,
3219 bool LoadExternal = true);
3220
3221 enum CorrectTypoKind {
3222 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3223 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3224 };
3225
3226 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3227 Sema::LookupNameKind LookupKind,
3228 Scope *S, CXXScopeSpec *SS,
3229 std::unique_ptr<CorrectionCandidateCallback> CCC,
3230 CorrectTypoKind Mode,
3231 DeclContext *MemberContext = nullptr,
3232 bool EnteringContext = false,
3233 const ObjCObjectPointerType *OPT = nullptr,
3234 bool RecordFailure = true);
3235
3236 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3237 Sema::LookupNameKind LookupKind, Scope *S,
3238 CXXScopeSpec *SS,
3239 std::unique_ptr<CorrectionCandidateCallback> CCC,
3240 TypoDiagnosticGenerator TDG,
3241 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3242 DeclContext *MemberContext = nullptr,
3243 bool EnteringContext = false,
3244 const ObjCObjectPointerType *OPT = nullptr);
3245
3246 /// \brief Process any TypoExprs in the given Expr and its children,
3247 /// generating diagnostics as appropriate and returning a new Expr if there
3248 /// were typos that were all successfully corrected and ExprError if one or
3249 /// more typos could not be corrected.
3250 ///
3251 /// \param E The Expr to check for TypoExprs.
3252 ///
3253 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3254 /// initializer.
3255 ///
3256 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3257 /// it is an acceptable/usable result from a single combination of typo
3258 /// corrections. As long as the filter returns ExprError, different
3259 /// combinations of corrections will be tried until all are exhausted.
3260 ExprResult
3261 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3262 llvm::function_ref<ExprResult(Expr *)> Filter =
3263 [](Expr *E) -> ExprResult { return E; });
3264
3265 ExprResult
3266 CorrectDelayedTyposInExpr(Expr *E,
3267 llvm::function_ref<ExprResult(Expr *)> Filter) {
3268 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3269 }
3270
3271 ExprResult
3272 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3273 llvm::function_ref<ExprResult(Expr *)> Filter =
3274 [](Expr *E) -> ExprResult { return E; }) {
3275 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3276 }
3277
3278 ExprResult
3279 CorrectDelayedTyposInExpr(ExprResult ER,
3280 llvm::function_ref<ExprResult(Expr *)> Filter) {
3281 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3282 }
3283
3284 void diagnoseTypo(const TypoCorrection &Correction,
3285 const PartialDiagnostic &TypoDiag,
3286 bool ErrorRecovery = true);
3287
3288 void diagnoseTypo(const TypoCorrection &Correction,
3289 const PartialDiagnostic &TypoDiag,
3290 const PartialDiagnostic &PrevNote,
3291 bool ErrorRecovery = true);
3292
3293 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3294
3295 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3296 ArrayRef<Expr *> Args,
3297 AssociatedNamespaceSet &AssociatedNamespaces,
3298 AssociatedClassSet &AssociatedClasses);
3299
3300 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3301 bool ConsiderLinkage, bool AllowInlineNamespace);
3302
3303 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3304
3305 void DiagnoseAmbiguousLookup(LookupResult &Result);
3306 //@}
3307
3308 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3309 SourceLocation IdLoc,
3310 bool TypoCorrection = false);
3311 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3312 Scope *S, bool ForRedeclaration,
3313 SourceLocation Loc);
3314 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3315 Scope *S);
3316 void AddKnownFunctionAttributes(FunctionDecl *FD);
3317
3318 // More parsing and symbol table subroutines.
3319
3320 void ProcessPragmaWeak(Scope *S, Decl *D);
3321 // Decl attributes - this routine is the top level dispatcher.
3322 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3323 // Helper for delayed processing of attributes.
3324 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3325 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3326 bool IncludeCXX11Attributes = true);
3327 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3328 const AttributeList *AttrList);
3329
3330 void checkUnusedDeclAttributes(Declarator &D);
3331
3332 /// Determine if type T is a valid subject for a nonnull and similar
3333 /// attributes. By default, we look through references (the behavior used by
3334 /// nonnull), but if the second parameter is true, then we treat a reference
3335 /// type as valid.
3336 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3337
3338 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3339 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3340 const FunctionDecl *FD = nullptr);
3341 bool CheckNoReturnAttr(const AttributeList &attr);
3342 bool CheckNoCallerSavedRegsAttr(const AttributeList &attr);
3343 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3344 unsigned ArgNum, StringRef &Str,
3345 SourceLocation *ArgLocation = nullptr);
3346 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3347 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3348 bool checkMSInheritanceAttrOnDefinition(
3349 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3350 MSInheritanceAttr::Spelling SemanticSpelling);
3351
3352 void CheckAlignasUnderalignment(Decl *D);
3353
3354 /// Adjust the calling convention of a method to be the ABI default if it
3355 /// wasn't specified explicitly. This handles method types formed from
3356 /// function type typedefs and typename template arguments.
3357 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3358 SourceLocation Loc);
3359
3360 // Check if there is an explicit attribute, but only look through parens.
3361 // The intent is to look for an attribute on the current declarator, but not
3362 // one that came from a typedef.
3363 bool hasExplicitCallingConv(QualType &T);
3364
3365 /// Get the outermost AttributedType node that sets a calling convention.
3366 /// Valid types should not have multiple attributes with different CCs.
3367 const AttributedType *getCallingConvAttributedType(QualType T) const;
3368
3369 /// Check whether a nullability type specifier can be added to the given
3370 /// type.
3371 ///
3372 /// \param type The type to which the nullability specifier will be
3373 /// added. On success, this type will be updated appropriately.
3374 ///
3375 /// \param nullability The nullability specifier to add.
3376 ///
3377 /// \param nullabilityLoc The location of the nullability specifier.
3378 ///
3379 /// \param isContextSensitive Whether this nullability specifier was
3380 /// written as a context-sensitive keyword (in an Objective-C
3381 /// method) or an Objective-C property attribute, rather than as an
3382 /// underscored type specifier.
3383 ///
3384 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3385 /// array type (e.g., because it will decay to a pointer).
3386 ///
3387 /// \returns true if nullability cannot be applied, false otherwise.
3388 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3389 SourceLocation nullabilityLoc,
3390 bool isContextSensitive,
3391 bool allowArrayTypes);
3392
3393 /// \brief Stmt attributes - this routine is the top level dispatcher.
3394 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3395 SourceRange Range);
3396
3397 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3398 ObjCMethodDecl *MethodDecl,
3399 bool IsProtocolMethodDecl);
3400
3401 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3402 ObjCMethodDecl *Overridden,
3403 bool IsProtocolMethodDecl);
3404
3405 /// WarnExactTypedMethods - This routine issues a warning if method
3406 /// implementation declaration matches exactly that of its declaration.
3407 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3408 ObjCMethodDecl *MethodDecl,
3409 bool IsProtocolMethodDecl);
3410
3411 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3412
3413 /// CheckImplementationIvars - This routine checks if the instance variables
3414 /// listed in the implelementation match those listed in the interface.
3415 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3416 ObjCIvarDecl **Fields, unsigned nIvars,
3417 SourceLocation Loc);
3418
3419 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3420 /// remains unimplemented in the class or category \@implementation.
3421 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3422 ObjCContainerDecl* IDecl,
3423 bool IncompleteImpl = false);
3424
3425 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3426 /// which must be implemented by this implementation.
3427 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3428 ObjCContainerDecl *CDecl,
3429 bool SynthesizeProperties);
3430
3431 /// Diagnose any null-resettable synthesized setters.
3432 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3433
3434 /// DefaultSynthesizeProperties - This routine default synthesizes all
3435 /// properties which must be synthesized in the class's \@implementation.
3436 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3437 ObjCInterfaceDecl *IDecl,
3438 SourceLocation AtEnd);
3439 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3440
3441 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3442 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3443 /// declared in class 'IFace'.
3444 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3445 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3446
3447 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3448 /// backs the property is not used in the property's accessor.
3449 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3450 const ObjCImplementationDecl *ImplD);
3451
3452 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3453 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3454 /// It also returns ivar's property on success.
3455 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3456 const ObjCPropertyDecl *&PDecl) const;
3457
3458 /// Called by ActOnProperty to handle \@property declarations in
3459 /// class extensions.
3460 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3461 SourceLocation AtLoc,
3462 SourceLocation LParenLoc,
3463 FieldDeclarator &FD,
3464 Selector GetterSel,
3465 SourceLocation GetterNameLoc,
3466 Selector SetterSel,
3467 SourceLocation SetterNameLoc,
3468 const bool isReadWrite,
3469 unsigned &Attributes,
3470 const unsigned AttributesAsWritten,
3471 QualType T,
3472 TypeSourceInfo *TSI,
3473 tok::ObjCKeywordKind MethodImplKind);
3474
3475 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3476 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3477 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3478 ObjCContainerDecl *CDecl,
3479 SourceLocation AtLoc,
3480 SourceLocation LParenLoc,
3481 FieldDeclarator &FD,
3482 Selector GetterSel,
3483 SourceLocation GetterNameLoc,
3484 Selector SetterSel,
3485 SourceLocation SetterNameLoc,
3486 const bool isReadWrite,
3487 const unsigned Attributes,
3488 const unsigned AttributesAsWritten,
3489 QualType T,
3490 TypeSourceInfo *TSI,
3491 tok::ObjCKeywordKind MethodImplKind,
3492 DeclContext *lexicalDC = nullptr);
3493
3494 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3495 /// warning) when atomic property has one but not the other user-declared
3496 /// setter or getter.
3497 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3498 ObjCInterfaceDecl* IDecl);
3499
3500 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3501
3502 void DiagnoseMissingDesignatedInitOverrides(
3503 const ObjCImplementationDecl *ImplD,
3504 const ObjCInterfaceDecl *IFD);
3505
3506 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3507
3508 enum MethodMatchStrategy {
3509 MMS_loose,
3510 MMS_strict
3511 };
3512
3513 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3514 /// true, or false, accordingly.
3515 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3516 const ObjCMethodDecl *PrevMethod,
3517 MethodMatchStrategy strategy = MMS_strict);
3518
3519 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3520 /// or protocol against those declared in their implementations.
3521 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3522 const SelectorSet &ClsMap,
3523 SelectorSet &InsMapSeen,
3524 SelectorSet &ClsMapSeen,
3525 ObjCImplDecl* IMPDecl,
3526 ObjCContainerDecl* IDecl,
3527 bool &IncompleteImpl,
3528 bool ImmediateClass,
3529 bool WarnCategoryMethodImpl=false);
3530
3531 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3532 /// category matches with those implemented in its primary class and
3533 /// warns each time an exact match is found.
3534 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3535
3536 /// \brief Add the given method to the list of globally-known methods.
3537 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3538
3539private:
3540 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3541 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3542 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3543
3544 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3545 /// optionally warns if there are multiple signatures.
3546 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3547 bool receiverIdOrClass,
3548 bool instance);
3549
3550public:
3551 /// \brief - Returns instance or factory methods in global method pool for
3552 /// given selector. It checks the desired kind first, if none is found, and
3553 /// parameter checkTheOther is set, it then checks the other kind. If no such
3554 /// method or only one method is found, function returns false; otherwise, it
3555 /// returns true.
3556 bool
3557 CollectMultipleMethodsInGlobalPool(Selector Sel,
3558 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3559 bool InstanceFirst, bool CheckTheOther,
3560 const ObjCObjectType *TypeBound = nullptr);
3561
3562 bool
3563 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3564 SourceRange R, bool receiverIdOrClass,
3565 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3566
3567 void
3568 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3569 Selector Sel, SourceRange R,
3570 bool receiverIdOrClass);
3571
3572private:
3573 /// \brief - Returns a selector which best matches given argument list or
3574 /// nullptr if none could be found
3575 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3576 bool IsInstance,
3577 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3578
3579
3580 /// \brief Record the typo correction failure and return an empty correction.
3581 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3582 bool RecordFailure = true) {
3583 if (RecordFailure)
3584 TypoCorrectionFailures[Typo].insert(TypoLoc);
3585 return TypoCorrection();
3586 }
3587
3588public:
3589 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3590 /// unit are added to a global pool. This allows us to efficiently associate
3591 /// a selector with a method declaraation for purposes of typechecking
3592 /// messages sent to "id" (where the class of the object is unknown).
3593 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3594 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3595 }
3596
3597 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3598 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3599 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3600 }
3601
3602 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3603 /// pool.
3604 void AddAnyMethodToGlobalPool(Decl *D);
3605
3606 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3607 /// there are multiple signatures.
3608 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3609 bool receiverIdOrClass=false) {
3610 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3611 /*instance*/true);
3612 }
3613
3614 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3615 /// there are multiple signatures.
3616 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3617 bool receiverIdOrClass=false) {
3618 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3619 /*instance*/false);
3620 }
3621
3622 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3623 QualType ObjectType=QualType());
3624 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3625 /// implementation.
3626 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3627
3628 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3629 /// initialization.
3630 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3631 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3632
3633 //===--------------------------------------------------------------------===//
3634 // Statement Parsing Callbacks: SemaStmt.cpp.
3635public:
3636 class FullExprArg {
3637 public:
3638 FullExprArg() : E(nullptr) { }
3639 FullExprArg(Sema &actions) : E(nullptr) { }
3640
3641 ExprResult release() {
3642 return E;
3643 }
3644
3645 Expr *get() const { return E; }
3646
3647 Expr *operator->() {
3648 return E;
3649 }
3650
3651 private:
3652 // FIXME: No need to make the entire Sema class a friend when it's just
3653 // Sema::MakeFullExpr that needs access to the constructor below.
3654 friend class Sema;
3655
3656 explicit FullExprArg(Expr *expr) : E(expr) {}
3657
3658 Expr *E;
3659 };
3660
3661 FullExprArg MakeFullExpr(Expr *Arg) {
3662 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3663 }
3664 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3665 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3666 }
3667 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3668 ExprResult FE =
3669 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3670 /*DiscardedValue*/ true);
3671 return FullExprArg(FE.get());
3672 }
3673
3674 StmtResult ActOnExprStmt(ExprResult Arg);
3675 StmtResult ActOnExprStmtError();
3676
3677 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3678 bool HasLeadingEmptyMacro = false);
3679
3680 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
3681 void ActOnFinishOfCompoundStmt();
3682 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3683 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3684
3685 /// \brief A RAII object to enter scope of a compound statement.
3686 class CompoundScopeRAII {
3687 public:
3688 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
3689 S.ActOnStartOfCompoundStmt(IsStmtExpr);
3690 }
3691
3692 ~CompoundScopeRAII() {
3693 S.ActOnFinishOfCompoundStmt();
3694 }
3695
3696 private:
3697 Sema &S;
3698 };
3699
3700 /// An RAII helper that pops function a function scope on exit.
3701 struct FunctionScopeRAII {
3702 Sema &S;
3703 bool Active;
3704 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3705 ~FunctionScopeRAII() {
3706 if (Active)
3707 S.PopFunctionScopeInfo();
3708 }
3709 void disable() { Active = false; }
3710 };
3711
3712 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3713 SourceLocation StartLoc,
3714 SourceLocation EndLoc);
3715 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3716 StmtResult ActOnForEachLValueExpr(Expr *E);
3717 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3718 SourceLocation DotDotDotLoc, Expr *RHSVal,
3719 SourceLocation ColonLoc);
3720 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3721
3722 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3723 SourceLocation ColonLoc,
3724 Stmt *SubStmt, Scope *CurScope);
3725 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3726 SourceLocation ColonLoc, Stmt *SubStmt);
3727
3728 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3729 ArrayRef<const Attr*> Attrs,
3730 Stmt *SubStmt);
3731
3732 class ConditionResult;
3733 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3734 Stmt *InitStmt,
3735 ConditionResult Cond, Stmt *ThenVal,
3736 SourceLocation ElseLoc, Stmt *ElseVal);
3737 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3738 Stmt *InitStmt,
3739 ConditionResult Cond, Stmt *ThenVal,
3740 SourceLocation ElseLoc, Stmt *ElseVal);
3741 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3742 Stmt *InitStmt,
3743 ConditionResult Cond);
3744 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3745 Stmt *Switch, Stmt *Body);
3746 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3747 Stmt *Body);
3748 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3749 SourceLocation WhileLoc, SourceLocation CondLParen,
3750 Expr *Cond, SourceLocation CondRParen);
3751
3752 StmtResult ActOnForStmt(SourceLocation ForLoc,
3753 SourceLocation LParenLoc,
3754 Stmt *First,
3755 ConditionResult Second,
3756 FullExprArg Third,
3757 SourceLocation RParenLoc,
3758 Stmt *Body);
3759 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3760 Expr *collection);
3761 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3762 Stmt *First, Expr *collection,
3763 SourceLocation RParenLoc);
3764 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3765
3766 enum BuildForRangeKind {
3767 /// Initial building of a for-range statement.
3768 BFRK_Build,
3769 /// Instantiation or recovery rebuild of a for-range statement. Don't
3770 /// attempt any typo-correction.
3771 BFRK_Rebuild,
3772 /// Determining whether a for-range statement could be built. Avoid any
3773 /// unnecessary or irreversible actions.
3774 BFRK_Check
3775 };
3776
3777 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3778 SourceLocation CoawaitLoc,
3779 Stmt *LoopVar,
3780 SourceLocation ColonLoc, Expr *Collection,
3781 SourceLocation RParenLoc,
3782 BuildForRangeKind Kind);
3783 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3784 SourceLocation CoawaitLoc,
3785 SourceLocation ColonLoc,
3786 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3787 Expr *Cond, Expr *Inc,
3788 Stmt *LoopVarDecl,
3789 SourceLocation RParenLoc,
3790 BuildForRangeKind Kind);
3791 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3792
3793 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3794 SourceLocation LabelLoc,
3795 LabelDecl *TheDecl);
3796 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3797 SourceLocation StarLoc,
3798 Expr *DestExp);
3799 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3800 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3801
3802 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3803 CapturedRegionKind Kind, unsigned NumParams);
3804 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3805 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3806 CapturedRegionKind Kind,
3807 ArrayRef<CapturedParamNameType> Params);
3808 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3809 void ActOnCapturedRegionError();
3810 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3811 SourceLocation Loc,
3812 unsigned NumParams);
3813 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3814 bool AllowParamOrMoveConstructible);
3815 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3816 bool AllowParamOrMoveConstructible);
3817
3818 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3819 Scope *CurScope);
3820 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3821 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3822
3823 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3824 bool IsVolatile, unsigned NumOutputs,
3825 unsigned NumInputs, IdentifierInfo **Names,
3826 MultiExprArg Constraints, MultiExprArg Exprs,
3827 Expr *AsmString, MultiExprArg Clobbers,
3828 SourceLocation RParenLoc);
3829
3830 void FillInlineAsmIdentifierInfo(Expr *Res,
3831 llvm::InlineAsmIdentifierInfo &Info);
3832 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3833 SourceLocation TemplateKWLoc,
3834 UnqualifiedId &Id,
3835 bool IsUnevaluatedContext);
3836 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3837 unsigned &Offset, SourceLocation AsmLoc);
3838 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3839 SourceLocation AsmLoc);
3840 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3841 ArrayRef<Token> AsmToks,
3842 StringRef AsmString,
3843 unsigned NumOutputs, unsigned NumInputs,
3844 ArrayRef<StringRef> Constraints,
3845 ArrayRef<StringRef> Clobbers,
3846 ArrayRef<Expr*> Exprs,
3847 SourceLocation EndLoc);
3848 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3849 SourceLocation Location,
3850 bool AlwaysCreate);
3851
3852 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3853 SourceLocation StartLoc,
3854 SourceLocation IdLoc, IdentifierInfo *Id,
3855 bool Invalid = false);
3856
3857 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3858
3859 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3860 Decl *Parm, Stmt *Body);
3861
3862 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3863
3864 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3865 MultiStmtArg Catch, Stmt *Finally);
3866
3867 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3868 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3869 Scope *CurScope);
3870 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3871 Expr *operand);
3872 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3873 Expr *SynchExpr,
3874 Stmt *SynchBody);
3875
3876 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3877
3878 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3879 SourceLocation StartLoc,
3880 SourceLocation IdLoc,
3881 IdentifierInfo *Id);
3882
3883 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3884
3885 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3886 Decl *ExDecl, Stmt *HandlerBlock);
3887 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3888 ArrayRef<Stmt *> Handlers);
3889
3890 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3891 SourceLocation TryLoc, Stmt *TryBlock,
3892 Stmt *Handler);
3893 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3894 Expr *FilterExpr,
3895 Stmt *Block);
3896 void ActOnStartSEHFinallyBlock();
3897 void ActOnAbortSEHFinallyBlock();
3898 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3899 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3900
3901 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3902
3903 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3904
3905 /// \brief If it's a file scoped decl that must warn if not used, keep track
3906 /// of it.
3907 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3908
3909 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3910 /// whose result is unused, warn.
3911 void DiagnoseUnusedExprResult(const Stmt *S);
3912 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3913 void DiagnoseUnusedDecl(const NamedDecl *ND);
3914
3915 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3916 /// statement as a \p Body, and it is located on the same line.
3917 ///
3918 /// This helps prevent bugs due to typos, such as:
3919 /// if (condition);
3920 /// do_stuff();
3921 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3922 const Stmt *Body,
3923 unsigned DiagID);
3924
3925 /// Warn if a for/while loop statement \p S, which is followed by
3926 /// \p PossibleBody, has a suspicious null statement as a body.
3927 void DiagnoseEmptyLoopBody(const Stmt *S,
3928 const Stmt *PossibleBody);
3929
3930 /// Warn if a value is moved to itself.
3931 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3932 SourceLocation OpLoc);
3933
3934 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3935 /// _Nonnull one.
3936 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3937 SourceLocation Loc);
3938
3939 /// Warn when implicitly casting 0 to nullptr.
3940 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3941
3942 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3943 return DelayedDiagnostics.push(pool);
3944 }
3945 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3946
3947 typedef ProcessingContextState ParsingClassState;
3948 ParsingClassState PushParsingClass() {
3949 return DelayedDiagnostics.pushUndelayed();
3950 }
3951 void PopParsingClass(ParsingClassState state) {
3952 DelayedDiagnostics.popUndelayed(state);
3953 }
3954
3955 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3956
3957 void DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc,
3958 const ObjCInterfaceDecl *UnknownObjCClass,
3959 bool ObjCPropertyAccess,
3960 bool AvoidPartialAvailabilityChecks = false);
3961
3962 bool makeUnavailableInSystemHeader(SourceLocation loc,
3963 UnavailableAttr::ImplicitReason reason);
3964
3965 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3966 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3967
3968 //===--------------------------------------------------------------------===//
3969 // Expression Parsing Callbacks: SemaExpr.cpp.
3970
3971 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3972 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3973 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
3974 bool ObjCPropertyAccess = false,
3975 bool AvoidPartialAvailabilityChecks = false);
3976 void NoteDeletedFunction(FunctionDecl *FD);
3977 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3978 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3979 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3980 ObjCMethodDecl *Getter,
3981 SourceLocation Loc);
3982 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3983 ArrayRef<Expr *> Args);
3984
3985 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3986 Decl *LambdaContextDecl = nullptr,
3987 bool IsDecltype = false);
3988 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3989 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3990 ReuseLambdaContextDecl_t,
3991 bool IsDecltype = false);
3992 void PopExpressionEvaluationContext();
3993
3994 void DiscardCleanupsInEvaluationContext();
3995
3996 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3997 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3998
3999 ExprResult ActOnConstantExpression(ExprResult Res);
4000
4001 // Functions for marking a declaration referenced. These functions also
4002 // contain the relevant logic for marking if a reference to a function or
4003 // variable is an odr-use (in the C++11 sense). There are separate variants
4004 // for expressions referring to a decl; these exist because odr-use marking
4005 // needs to be delayed for some constant variables when we build one of the
4006 // named expressions.
4007 //
4008 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4009 // should usually be true. This only needs to be set to false if the lack of
4010 // odr-use cannot be determined from the current context (for instance,
4011 // because the name denotes a virtual function and was written without an
4012 // explicit nested-name-specifier).
4013 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4014 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4015 bool MightBeOdrUse = true);
4016 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4017 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4018 void MarkMemberReferenced(MemberExpr *E);
4019
4020 void UpdateMarkingForLValueToRValue(Expr *E);
4021 void CleanupVarDeclMarking();
4022
4023 enum TryCaptureKind {
4024 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4025 };
4026
4027 /// \brief Try to capture the given variable.
4028 ///
4029 /// \param Var The variable to capture.
4030 ///
4031 /// \param Loc The location at which the capture occurs.
4032 ///
4033 /// \param Kind The kind of capture, which may be implicit (for either a
4034 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4035 ///
4036 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4037 /// an explicit lambda capture.
4038 ///
4039 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4040 /// captures or diagnose errors. If false, this routine merely check whether
4041 /// the capture can occur without performing the capture itself or complaining
4042 /// if the variable cannot be captured.
4043 ///
4044 /// \param CaptureType Will be set to the type of the field used to capture
4045 /// this variable in the innermost block or lambda. Only valid when the
4046 /// variable can be captured.
4047 ///
4048 /// \param DeclRefType Will be set to the type of a reference to the capture
4049 /// from within the current scope. Only valid when the variable can be
4050 /// captured.
4051 ///
4052 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4053 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4054 /// This is useful when enclosing lambdas must speculatively capture
4055 /// variables that may or may not be used in certain specializations of
4056 /// a nested generic lambda.
4057 ///
4058 /// \returns true if an error occurred (i.e., the variable cannot be
4059 /// captured) and false if the capture succeeded.
4060 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4061 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4062 QualType &CaptureType,
4063 QualType &DeclRefType,
4064 const unsigned *const FunctionScopeIndexToStopAt);
4065
4066 /// \brief Try to capture the given variable.
4067 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4068 TryCaptureKind Kind = TryCapture_Implicit,
4069 SourceLocation EllipsisLoc = SourceLocation());
4070
4071 /// \brief Checks if the variable must be captured.
4072 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4073
4074 /// \brief Given a variable, determine the type that a reference to that
4075 /// variable will have in the given scope.
4076 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4077
4078 /// Mark all of the declarations referenced within a particular AST node as
4079 /// referenced. Used when template instantiation instantiates a non-dependent
4080 /// type -- entities referenced by the type are now referenced.
4081 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4082 void MarkDeclarationsReferencedInExpr(Expr *E,
4083 bool SkipLocalVariables = false);
4084
4085 /// \brief Try to recover by turning the given expression into a
4086 /// call. Returns true if recovery was attempted or an error was
4087 /// emitted; this may also leave the ExprResult invalid.
4088 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4089 bool ForceComplain = false,
4090 bool (*IsPlausibleResult)(QualType) = nullptr);
4091
4092 /// \brief Figure out if an expression could be turned into a call.
4093 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4094 UnresolvedSetImpl &NonTemplateOverloads);
4095
4096 /// \brief Conditionally issue a diagnostic based on the current
4097 /// evaluation context.
4098 ///
4099 /// \param Statement If Statement is non-null, delay reporting the
4100 /// diagnostic until the function body is parsed, and then do a basic
4101 /// reachability analysis to determine if the statement is reachable.
4102 /// If it is unreachable, the diagnostic will not be emitted.
4103 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4104 const PartialDiagnostic &PD);
4105
4106 // Primary Expressions.
4107 SourceRange getExprRange(Expr *E) const;
4108
4109 ExprResult ActOnIdExpression(
4110 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4111 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4112 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
4113 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4114
4115 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4116 TemplateArgumentListInfo &Buffer,
4117 DeclarationNameInfo &NameInfo,
4118 const TemplateArgumentListInfo *&TemplateArgs);
4119
4120 bool
4121 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4122 std::unique_ptr<CorrectionCandidateCallback> CCC,
4123 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4124 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4125
4126 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4127 IdentifierInfo *II,
4128 bool AllowBuiltinCreation=false);
4129
4130 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4131 SourceLocation TemplateKWLoc,
4132 const DeclarationNameInfo &NameInfo,
4133 bool isAddressOfOperand,
4134 const TemplateArgumentListInfo *TemplateArgs);
4135
4136 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4137 ExprValueKind VK,
4138 SourceLocation Loc,
4139 const CXXScopeSpec *SS = nullptr);
4140 ExprResult
4141 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4142 const DeclarationNameInfo &NameInfo,
4143 const CXXScopeSpec *SS = nullptr,
4144 NamedDecl *FoundD = nullptr,
4145 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4146 ExprResult
4147 BuildAnonymousStructUnionMemberReference(
4148 const CXXScopeSpec &SS,
4149 SourceLocation nameLoc,
4150 IndirectFieldDecl *indirectField,
4151 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4152 Expr *baseObjectExpr = nullptr,
4153 SourceLocation opLoc = SourceLocation());
4154
4155 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4156 SourceLocation TemplateKWLoc,
4157 LookupResult &R,
4158 const TemplateArgumentListInfo *TemplateArgs,
4159 const Scope *S);
4160 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4161 SourceLocation TemplateKWLoc,
4162 LookupResult &R,
4163 const TemplateArgumentListInfo *TemplateArgs,
4164 bool IsDefiniteInstance,
4165 const Scope *S);
4166 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4167 const LookupResult &R,
4168 bool HasTrailingLParen);
4169
4170 ExprResult
4171 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4172 const DeclarationNameInfo &NameInfo,
4173 bool IsAddressOfOperand, const Scope *S,
4174 TypeSourceInfo **RecoveryTSI = nullptr);
4175
4176 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4177 SourceLocation TemplateKWLoc,
4178 const DeclarationNameInfo &NameInfo,
4179 const TemplateArgumentListInfo *TemplateArgs);
4180
4181 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4182 LookupResult &R,
4183 bool NeedsADL,
4184 bool AcceptInvalidDecl = false);
4185 ExprResult BuildDeclarationNameExpr(
4186 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4187 NamedDecl *FoundD = nullptr,
4188 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4189 bool AcceptInvalidDecl = false);
4190
4191 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4192 DeclarationNameInfo &SuffixInfo,
4193 ArrayRef<Expr *> Args,
4194 SourceLocation LitEndLoc,
4195 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4196
4197 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4198 PredefinedExpr::IdentType IT);
4199 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4200 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4201
4202 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4203
4204 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4205 ExprResult ActOnCharacterConstant(const Token &Tok,
4206 Scope *UDLScope = nullptr);
4207 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4208 ExprResult ActOnParenListExpr(SourceLocation L,
4209 SourceLocation R,
4210 MultiExprArg Val);
4211
4212 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4213 /// fragments (e.g. "foo" "bar" L"baz").
4214 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4215 Scope *UDLScope = nullptr);
4216
4217 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4218 SourceLocation DefaultLoc,
4219 SourceLocation RParenLoc,
4220 Expr *ControllingExpr,
4221 ArrayRef<ParsedType> ArgTypes,
4222 ArrayRef<Expr *> ArgExprs);
4223 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4224 SourceLocation DefaultLoc,
4225 SourceLocation RParenLoc,
4226 Expr *ControllingExpr,
4227 ArrayRef<TypeSourceInfo *> Types,
4228 ArrayRef<Expr *> Exprs);
4229
4230 // Binary/Unary Operators. 'Tok' is the token for the operator.
4231 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4232 Expr *InputExpr);
4233 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4234 UnaryOperatorKind Opc, Expr *Input);
4235 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4236 tok::TokenKind Op, Expr *Input);
4237
4238 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4239
4240 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4241 SourceLocation OpLoc,
4242 UnaryExprOrTypeTrait ExprKind,
4243 SourceRange R);
4244 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4245 UnaryExprOrTypeTrait ExprKind);
4246 ExprResult
4247 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4248 UnaryExprOrTypeTrait ExprKind,
4249 bool IsType, void *TyOrEx,
4250 SourceRange ArgRange);
4251
4252 ExprResult CheckPlaceholderExpr(Expr *E);
4253 bool CheckVecStepExpr(Expr *E);
4254
4255 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4256 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4257 SourceRange ExprRange,
4258 UnaryExprOrTypeTrait ExprKind);
4259 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4260 SourceLocation OpLoc,
4261 IdentifierInfo &Name,
4262 SourceLocation NameLoc,
4263 SourceLocation RParenLoc);
4264 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4265 tok::TokenKind Kind, Expr *Input);
4266
4267 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4268 Expr *Idx, SourceLocation RLoc);
4269 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4270 Expr *Idx, SourceLocation RLoc);
4271 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4272 Expr *LowerBound, SourceLocation ColonLoc,
4273 Expr *Length, SourceLocation RBLoc);
4274
4275 // This struct is for use by ActOnMemberAccess to allow
4276 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4277 // changing the access operator from a '.' to a '->' (to see if that is the
4278 // change needed to fix an error about an unknown member, e.g. when the class
4279 // defines a custom operator->).
4280 struct ActOnMemberAccessExtraArgs {
4281 Scope *S;
4282 UnqualifiedId &Id;
4283 Decl *ObjCImpDecl;
4284 };
4285
4286 ExprResult BuildMemberReferenceExpr(
4287 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4288 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4289 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4290 const TemplateArgumentListInfo *TemplateArgs,
4291 const Scope *S,
4292 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4293
4294 ExprResult
4295 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4296 bool IsArrow, const CXXScopeSpec &SS,
4297 SourceLocation TemplateKWLoc,
4298 NamedDecl *FirstQualifierInScope, LookupResult &R,
4299 const TemplateArgumentListInfo *TemplateArgs,
4300 const Scope *S,
4301 bool SuppressQualifierCheck = false,
4302 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4303
4304 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4305 SourceLocation OpLoc,
4306 const CXXScopeSpec &SS, FieldDecl *Field,
4307 DeclAccessPair FoundDecl,
4308 const DeclarationNameInfo &MemberNameInfo);
4309
4310 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4311
4312 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4313 const CXXScopeSpec &SS,
4314 const LookupResult &R);
4315
4316 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4317 bool IsArrow, SourceLocation OpLoc,
4318 const CXXScopeSpec &SS,
4319 SourceLocation TemplateKWLoc,
4320 NamedDecl *FirstQualifierInScope,
4321 const DeclarationNameInfo &NameInfo,
4322 const TemplateArgumentListInfo *TemplateArgs);
4323
4324 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4325 SourceLocation OpLoc,
4326 tok::TokenKind OpKind,
4327 CXXScopeSpec &SS,
4328 SourceLocation TemplateKWLoc,
4329 UnqualifiedId &Member,
4330 Decl *ObjCImpDecl);
4331
4332 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4333 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4334 FunctionDecl *FDecl,
4335 const FunctionProtoType *Proto,
4336 ArrayRef<Expr *> Args,
4337 SourceLocation RParenLoc,
4338 bool ExecConfig = false);
4339 void CheckStaticArrayArgument(SourceLocation CallLoc,
4340 ParmVarDecl *Param,
4341 const Expr *ArgExpr);
4342
4343 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4344 /// This provides the location of the left/right parens and a list of comma
4345 /// locations.
4346 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4347 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4348 Expr *ExecConfig = nullptr,
4349 bool IsExecConfig = false);
4350 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4351 SourceLocation LParenLoc,
4352 ArrayRef<Expr *> Arg,
4353 SourceLocation RParenLoc,
4354 Expr *Config = nullptr,
4355 bool IsExecConfig = false);
4356
4357 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4358 MultiExprArg ExecConfig,
4359 SourceLocation GGGLoc);
4360
4361 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4362 Declarator &D, ParsedType &Ty,
4363 SourceLocation RParenLoc, Expr *CastExpr);
4364 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4365 TypeSourceInfo *Ty,
4366 SourceLocation RParenLoc,
4367 Expr *Op);
4368 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4369
4370 /// \brief Build an altivec or OpenCL literal.
4371 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4372 SourceLocation RParenLoc, Expr *E,
4373 TypeSourceInfo *TInfo);
4374
4375 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4376
4377 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4378 ParsedType Ty,
4379 SourceLocation RParenLoc,
4380 Expr *InitExpr);
4381
4382 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4383 TypeSourceInfo *TInfo,
4384 SourceLocation RParenLoc,
4385 Expr *LiteralExpr);
4386
4387 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4388 MultiExprArg InitArgList,
4389 SourceLocation RBraceLoc);
4390
4391 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4392 SourceLocation Loc,
4393 bool GNUSyntax,
4394 ExprResult Init);
4395
4396private:
4397 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4398
4399public:
4400 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4401 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4402 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4403 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4404 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4405 Expr *LHSExpr, Expr *RHSExpr);
4406
4407 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4408
4409 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4410 /// in the case of a the GNU conditional expr extension.
4411 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4412 SourceLocation ColonLoc,
4413 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4414
4415 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4416 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4417 LabelDecl *TheDecl);
4418
4419 void ActOnStartStmtExpr();
4420 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4421 SourceLocation RPLoc); // "({..})"
4422 void ActOnStmtExprError();
4423
4424 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4425 struct OffsetOfComponent {
4426 SourceLocation LocStart, LocEnd;
4427 bool isBrackets; // true if [expr], false if .ident
4428 union {
4429 IdentifierInfo *IdentInfo;
4430 Expr *E;
4431 } U;
4432 };
4433
4434 /// __builtin_offsetof(type, a.b[123][456].c)
4435 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4436 TypeSourceInfo *TInfo,
4437 ArrayRef<OffsetOfComponent> Components,
4438 SourceLocation RParenLoc);
4439 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4440 SourceLocation BuiltinLoc,
4441 SourceLocation TypeLoc,
4442 ParsedType ParsedArgTy,
4443 ArrayRef<OffsetOfComponent> Components,
4444 SourceLocation RParenLoc);
4445
4446 // __builtin_choose_expr(constExpr, expr1, expr2)
4447 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4448 Expr *CondExpr, Expr *LHSExpr,
4449 Expr *RHSExpr, SourceLocation RPLoc);
4450
4451 // __builtin_va_arg(expr, type)
4452 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4453 SourceLocation RPLoc);
4454 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4455 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4456
4457 // __null
4458 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4459
4460 bool CheckCaseExpression(Expr *E);
4461
4462 /// \brief Describes the result of an "if-exists" condition check.
4463 enum IfExistsResult {
4464 /// \brief The symbol exists.
4465 IER_Exists,
4466
4467 /// \brief The symbol does not exist.
4468 IER_DoesNotExist,
4469
4470 /// \brief The name is a dependent name, so the results will differ
4471 /// from one instantiation to the next.
4472 IER_Dependent,
4473
4474 /// \brief An error occurred.
4475 IER_Error
4476 };
4477
4478 IfExistsResult
4479 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4480 const DeclarationNameInfo &TargetNameInfo);
4481
4482 IfExistsResult
4483 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4484 bool IsIfExists, CXXScopeSpec &SS,
4485 UnqualifiedId &Name);
4486
4487 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4488 bool IsIfExists,
4489 NestedNameSpecifierLoc QualifierLoc,
4490 DeclarationNameInfo NameInfo,
4491 Stmt *Nested);
4492 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4493 bool IsIfExists,
4494 CXXScopeSpec &SS, UnqualifiedId &Name,
4495 Stmt *Nested);
4496
4497 //===------------------------- "Block" Extension ------------------------===//
4498
4499 /// ActOnBlockStart - This callback is invoked when a block literal is
4500 /// started.
4501 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4502
4503 /// ActOnBlockArguments - This callback allows processing of block arguments.
4504 /// If there are no arguments, this is still invoked.
4505 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4506 Scope *CurScope);
4507
4508 /// ActOnBlockError - If there is an error parsing a block, this callback
4509 /// is invoked to pop the information about the block from the action impl.
4510 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4511
4512 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4513 /// literal was successfully completed. ^(int x){...}
4514 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4515 Scope *CurScope);
4516
4517 //===---------------------------- Clang Extensions ----------------------===//
4518
4519 /// __builtin_convertvector(...)
4520 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4521 SourceLocation BuiltinLoc,
4522 SourceLocation RParenLoc);
4523
4524 //===---------------------------- OpenCL Features -----------------------===//
4525
4526 /// __builtin_astype(...)
4527 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4528 SourceLocation BuiltinLoc,
4529 SourceLocation RParenLoc);
4530
4531 //===---------------------------- C++ Features --------------------------===//
4532
4533 // Act on C++ namespaces
4534 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4535 SourceLocation NamespaceLoc,
4536 SourceLocation IdentLoc,
4537 IdentifierInfo *Ident,
4538 SourceLocation LBrace,
4539 AttributeList *AttrList,
4540 UsingDirectiveDecl * &UsingDecl);
4541 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4542
4543 NamespaceDecl *getStdNamespace() const;
4544 NamespaceDecl *getOrCreateStdNamespace();
4545
4546 NamespaceDecl *lookupStdExperimentalNamespace();
4547
4548 CXXRecordDecl *getStdBadAlloc() const;
4549 EnumDecl *getStdAlignValT() const;
4550
4551 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4552 /// it is and Element is not NULL, assigns the element type to Element.
4553 bool isStdInitializerList(QualType Ty, QualType *Element);
4554
4555 /// \brief Looks for the std::initializer_list template and instantiates it
4556 /// with Element, or emits an error if it's not found.
4557 ///
4558 /// \returns The instantiated template, or null on error.
4559 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4560
4561 /// \brief Determine whether Ctor is an initializer-list constructor, as
4562 /// defined in [dcl.init.list]p2.
4563 bool isInitListConstructor(const FunctionDecl *Ctor);
4564
4565 Decl *ActOnUsingDirective(Scope *CurScope,
4566 SourceLocation UsingLoc,
4567 SourceLocation NamespcLoc,
4568 CXXScopeSpec &SS,
4569 SourceLocation IdentLoc,
4570 IdentifierInfo *NamespcName,
4571 AttributeList *AttrList);
4572
4573 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4574
4575 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4576 SourceLocation NamespaceLoc,
4577 SourceLocation AliasLoc,
4578 IdentifierInfo *Alias,
4579 CXXScopeSpec &SS,
4580 SourceLocation IdentLoc,
4581 IdentifierInfo *Ident);
4582
4583 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4584 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4585 const LookupResult &PreviousDecls,
4586 UsingShadowDecl *&PrevShadow);
4587 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4588 NamedDecl *Target,
4589 UsingShadowDecl *PrevDecl);
4590
4591 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4592 bool HasTypenameKeyword,
4593 const CXXScopeSpec &SS,
4594 SourceLocation NameLoc,
4595 const LookupResult &Previous);
4596 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4597 bool HasTypename,
4598 const CXXScopeSpec &SS,
4599 const DeclarationNameInfo &NameInfo,
4600 SourceLocation NameLoc);
4601
4602 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4603 SourceLocation UsingLoc,
4604 bool HasTypenameKeyword,
4605 SourceLocation TypenameLoc,
4606 CXXScopeSpec &SS,
4607 DeclarationNameInfo NameInfo,
4608 SourceLocation EllipsisLoc,
4609 AttributeList *AttrList,
4610 bool IsInstantiation);
4611 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4612 ArrayRef<NamedDecl *> Expansions);
4613
4614 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4615
4616 /// Given a derived-class using shadow declaration for a constructor and the
4617 /// correspnding base class constructor, find or create the implicit
4618 /// synthesized derived class constructor to use for this initialization.
4619 CXXConstructorDecl *
4620 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4621 ConstructorUsingShadowDecl *DerivedShadow);
4622
4623 Decl *ActOnUsingDeclaration(Scope *CurScope,
4624 AccessSpecifier AS,
4625 SourceLocation UsingLoc,
4626 SourceLocation TypenameLoc,
4627 CXXScopeSpec &SS,
4628 UnqualifiedId &Name,
4629 SourceLocation EllipsisLoc,
4630 AttributeList *AttrList);
4631 Decl *ActOnAliasDeclaration(Scope *CurScope,
4632 AccessSpecifier AS,
4633 MultiTemplateParamsArg TemplateParams,
4634 SourceLocation UsingLoc,
4635 UnqualifiedId &Name,
4636 AttributeList *AttrList,
4637 TypeResult Type,
4638 Decl *DeclFromDeclSpec);
4639
4640 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4641 /// including handling of its default argument expressions.
4642 ///
4643 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4644 ExprResult
4645 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4646 NamedDecl *FoundDecl,
4647 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4648 bool HadMultipleCandidates, bool IsListInitialization,
4649 bool IsStdInitListInitialization,
4650 bool RequiresZeroInit, unsigned ConstructKind,
4651 SourceRange ParenRange);
4652
4653 /// Build a CXXConstructExpr whose constructor has already been resolved if
4654 /// it denotes an inherited constructor.
4655 ExprResult
4656 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4657 CXXConstructorDecl *Constructor, bool Elidable,
4658 MultiExprArg Exprs,
4659 bool HadMultipleCandidates, bool IsListInitialization,
4660 bool IsStdInitListInitialization,
4661 bool RequiresZeroInit, unsigned ConstructKind,
4662 SourceRange ParenRange);
4663
4664 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4665 // the constructor can be elidable?
4666 ExprResult
4667 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4668 NamedDecl *FoundDecl,
4669 CXXConstructorDecl *Constructor, bool Elidable,
4670 MultiExprArg Exprs, bool HadMultipleCandidates,
4671 bool IsListInitialization,
4672 bool IsStdInitListInitialization, bool RequiresZeroInit,
4673 unsigned ConstructKind, SourceRange ParenRange);
4674
4675 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4676
4677
4678 /// Instantiate or parse a C++ default argument expression as necessary.
4679 /// Return true on error.
4680 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4681 ParmVarDecl *Param);
4682
4683 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4684 /// the default expr if needed.
4685 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4686 FunctionDecl *FD,
4687 ParmVarDecl *Param);
4688
4689 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4690 /// constructed variable.
4691 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4692
4693 /// \brief Helper class that collects exception specifications for
4694 /// implicitly-declared special member functions.
4695 class ImplicitExceptionSpecification {
4696 // Pointer to allow copying
4697 Sema *Self;
4698 // We order exception specifications thus:
4699 // noexcept is the most restrictive, but is only used in C++11.
4700 // throw() comes next.
4701 // Then a throw(collected exceptions)
4702 // Finally no specification, which is expressed as noexcept(false).
4703 // throw(...) is used instead if any called function uses it.
4704 ExceptionSpecificationType ComputedEST;
4705 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4706 SmallVector<QualType, 4> Exceptions;
4707
4708 void ClearExceptions() {
4709 ExceptionsSeen.clear();
4710 Exceptions.clear();
4711 }
4712
4713 public:
4714 explicit ImplicitExceptionSpecification(Sema &Self)
4715 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4716 if (!Self.getLangOpts().CPlusPlus11)
4717 ComputedEST = EST_DynamicNone;
4718 }
4719
4720 /// \brief Get the computed exception specification type.
4721 ExceptionSpecificationType getExceptionSpecType() const {
4722 assert(ComputedEST != EST_ComputedNoexcept &&(static_cast <bool> (ComputedEST != EST_ComputedNoexcept
&& "noexcept(expr) should not be a possible result")
? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 4723, __extension__ __PRETTY_FUNCTION__))
4723 "noexcept(expr) should not be a possible result")(static_cast <bool> (ComputedEST != EST_ComputedNoexcept
&& "noexcept(expr) should not be a possible result")
? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 4723, __extension__ __PRETTY_FUNCTION__))
;
4724 return ComputedEST;
4725 }
4726
4727 /// \brief The number of exceptions in the exception specification.
4728 unsigned size() const { return Exceptions.size(); }
4729
4730 /// \brief The set of exceptions in the exception specification.
4731 const QualType *data() const { return Exceptions.data(); }
4732
4733 /// \brief Integrate another called method into the collected data.
4734 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4735
4736 /// \brief Integrate an invoked expression into the collected data.
4737 void CalledExpr(Expr *E);
4738
4739 /// \brief Overwrite an EPI's exception specification with this
4740 /// computed exception specification.
4741 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4742 FunctionProtoType::ExceptionSpecInfo ESI;
4743 ESI.Type = getExceptionSpecType();
4744 if (ESI.Type == EST_Dynamic) {
4745 ESI.Exceptions = Exceptions;
4746 } else if (ESI.Type == EST_None) {
4747 /// C++11 [except.spec]p14:
4748 /// The exception-specification is noexcept(false) if the set of
4749 /// potential exceptions of the special member function contains "any"
4750 ESI.Type = EST_ComputedNoexcept;
4751 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4752 tok::kw_false).get();
4753 }
4754 return ESI;
4755 }
4756 };
4757
4758 /// \brief Determine what sort of exception specification a defaulted
4759 /// copy constructor of a class will have.
4760 ImplicitExceptionSpecification
4761 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4762 CXXMethodDecl *MD);
4763
4764 /// \brief Determine what sort of exception specification a defaulted
4765 /// default constructor of a class will have, and whether the parameter
4766 /// will be const.
4767 ImplicitExceptionSpecification
4768 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4769
4770 /// \brief Determine what sort of exception specification a defautled
4771 /// copy assignment operator of a class will have, and whether the
4772 /// parameter will be const.
4773 ImplicitExceptionSpecification
4774 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4775
4776 /// \brief Determine what sort of exception specification a defaulted move
4777 /// constructor of a class will have.
4778 ImplicitExceptionSpecification
4779 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4780
4781 /// \brief Determine what sort of exception specification a defaulted move
4782 /// assignment operator of a class will have.
4783 ImplicitExceptionSpecification
4784 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4785
4786 /// \brief Determine what sort of exception specification a defaulted
4787 /// destructor of a class will have.
4788 ImplicitExceptionSpecification
4789 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4790
4791 /// \brief Determine what sort of exception specification an inheriting
4792 /// constructor of a class will have.
4793 ImplicitExceptionSpecification
4794 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4795 CXXConstructorDecl *CD);
4796
4797 /// \brief Evaluate the implicit exception specification for a defaulted
4798 /// special member function.
4799 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4800
4801 /// \brief Check the given exception-specification and update the
4802 /// exception specification information with the results.
4803 void checkExceptionSpecification(bool IsTopLevel,
4804 ExceptionSpecificationType EST,
4805 ArrayRef<ParsedType> DynamicExceptions,
4806 ArrayRef<SourceRange> DynamicExceptionRanges,
4807 Expr *NoexceptExpr,
4808 SmallVectorImpl<QualType> &Exceptions,
4809 FunctionProtoType::ExceptionSpecInfo &ESI);
4810
4811 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4812 /// parse an exception specification to work around a libstdc++ bug.
4813 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4814
4815 /// \brief Add an exception-specification to the given member function
4816 /// (or member function template). The exception-specification was parsed
4817 /// after the method itself was declared.
4818 void actOnDelayedExceptionSpecification(Decl *Method,
4819 ExceptionSpecificationType EST,
4820 SourceRange SpecificationRange,
4821 ArrayRef<ParsedType> DynamicExceptions,
4822 ArrayRef<SourceRange> DynamicExceptionRanges,
4823 Expr *NoexceptExpr);
4824
4825 class InheritedConstructorInfo;
4826
4827 /// \brief Determine if a special member function should have a deleted
4828 /// definition when it is defaulted.
4829 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4830 InheritedConstructorInfo *ICI = nullptr,
4831 bool Diagnose = false);
4832
4833 /// \brief Declare the implicit default constructor for the given class.
4834 ///
4835 /// \param ClassDecl The class declaration into which the implicit
4836 /// default constructor will be added.
4837 ///
4838 /// \returns The implicitly-declared default constructor.
4839 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4840 CXXRecordDecl *ClassDecl);
4841
4842 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4843 /// defining this constructor as the default constructor.
4844 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4845 CXXConstructorDecl *Constructor);
4846
4847 /// \brief Declare the implicit destructor for the given class.
4848 ///
4849 /// \param ClassDecl The class declaration into which the implicit
4850 /// destructor will be added.
4851 ///
4852 /// \returns The implicitly-declared destructor.
4853 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4854
4855 /// DefineImplicitDestructor - Checks for feasibility of
4856 /// defining this destructor as the default destructor.
4857 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4858 CXXDestructorDecl *Destructor);
4859
4860 /// \brief Build an exception spec for destructors that don't have one.
4861 ///
4862 /// C++11 says that user-defined destructors with no exception spec get one
4863 /// that looks as if the destructor was implicitly declared.
4864 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4865 CXXDestructorDecl *Destructor);
4866
4867 /// \brief Define the specified inheriting constructor.
4868 void DefineInheritingConstructor(SourceLocation UseLoc,
4869 CXXConstructorDecl *Constructor);
4870
4871 /// \brief Declare the implicit copy constructor for the given class.
4872 ///
4873 /// \param ClassDecl The class declaration into which the implicit
4874 /// copy constructor will be added.
4875 ///
4876 /// \returns The implicitly-declared copy constructor.
4877 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4878
4879 /// DefineImplicitCopyConstructor - Checks for feasibility of
4880 /// defining this constructor as the copy constructor.
4881 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4882 CXXConstructorDecl *Constructor);
4883
4884 /// \brief Declare the implicit move constructor for the given class.
4885 ///
4886 /// \param ClassDecl The Class declaration into which the implicit
4887 /// move constructor will be added.
4888 ///
4889 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4890 /// declared.
4891 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4892
4893 /// DefineImplicitMoveConstructor - Checks for feasibility of
4894 /// defining this constructor as the move constructor.
4895 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4896 CXXConstructorDecl *Constructor);
4897
4898 /// \brief Declare the implicit copy assignment operator for the given class.
4899 ///
4900 /// \param ClassDecl The class declaration into which the implicit
4901 /// copy assignment operator will be added.
4902 ///
4903 /// \returns The implicitly-declared copy assignment operator.
4904 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4905
4906 /// \brief Defines an implicitly-declared copy assignment operator.
4907 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4908 CXXMethodDecl *MethodDecl);
4909
4910 /// \brief Declare the implicit move assignment operator for the given class.
4911 ///
4912 /// \param ClassDecl The Class declaration into which the implicit
4913 /// move assignment operator will be added.
4914 ///
4915 /// \returns The implicitly-declared move assignment operator, or NULL if it
4916 /// wasn't declared.
4917 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4918
4919 /// \brief Defines an implicitly-declared move assignment operator.
4920 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4921 CXXMethodDecl *MethodDecl);
4922
4923 /// \brief Force the declaration of any implicitly-declared members of this
4924 /// class.
4925 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4926
4927 /// \brief Check a completed declaration of an implicit special member.
4928 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4929
4930 /// \brief Determine whether the given function is an implicitly-deleted
4931 /// special member function.
4932 bool isImplicitlyDeleted(FunctionDecl *FD);
4933
4934 /// \brief Check whether 'this' shows up in the type of a static member
4935 /// function after the (naturally empty) cv-qualifier-seq would be.
4936 ///
4937 /// \returns true if an error occurred.
4938 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4939
4940 /// \brief Whether this' shows up in the exception specification of a static
4941 /// member function.
4942 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4943
4944 /// \brief Check whether 'this' shows up in the attributes of the given
4945 /// static member function.
4946 ///
4947 /// \returns true if an error occurred.
4948 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4949
4950 /// MaybeBindToTemporary - If the passed in expression has a record type with
4951 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4952 /// it simply returns the passed in expression.
4953 ExprResult MaybeBindToTemporary(Expr *E);
4954
4955 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4956 MultiExprArg ArgsPtr,
4957 SourceLocation Loc,
4958 SmallVectorImpl<Expr*> &ConvertedArgs,
4959 bool AllowExplicit = false,
4960 bool IsListInitialization = false);
4961
4962 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4963 SourceLocation NameLoc,
4964 IdentifierInfo &Name);
4965
4966 ParsedType getDestructorName(SourceLocation TildeLoc,
4967 IdentifierInfo &II, SourceLocation NameLoc,
4968 Scope *S, CXXScopeSpec &SS,
4969 ParsedType ObjectType,
4970 bool EnteringContext);
4971
4972 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4973 ParsedType ObjectType);
4974
4975 // Checks that reinterpret casts don't have undefined behavior.
4976 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4977 bool IsDereference, SourceRange Range);
4978
4979 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4980 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4981 tok::TokenKind Kind,
4982 SourceLocation LAngleBracketLoc,
4983 Declarator &D,
4984 SourceLocation RAngleBracketLoc,
4985 SourceLocation LParenLoc,
4986 Expr *E,
4987 SourceLocation RParenLoc);
4988
4989 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4990 tok::TokenKind Kind,
4991 TypeSourceInfo *Ty,
4992 Expr *E,
4993 SourceRange AngleBrackets,
4994 SourceRange Parens);
4995
4996 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4997 SourceLocation TypeidLoc,
4998 TypeSourceInfo *Operand,
4999 SourceLocation RParenLoc);
5000 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5001 SourceLocation TypeidLoc,
5002 Expr *Operand,
5003 SourceLocation RParenLoc);
5004
5005 /// ActOnCXXTypeid - Parse typeid( something ).
5006 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5007 SourceLocation LParenLoc, bool isType,
5008 void *TyOrExpr,
5009 SourceLocation RParenLoc);
5010
5011 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5012 SourceLocation TypeidLoc,
5013 TypeSourceInfo *Operand,
5014 SourceLocation RParenLoc);
5015 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5016 SourceLocation TypeidLoc,
5017 Expr *Operand,
5018 SourceLocation RParenLoc);
5019
5020 /// ActOnCXXUuidof - Parse __uuidof( something ).
5021 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5022 SourceLocation LParenLoc, bool isType,
5023 void *TyOrExpr,
5024 SourceLocation RParenLoc);
5025
5026 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
5027 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5028 tok::TokenKind Operator,
5029 SourceLocation EllipsisLoc, Expr *RHS,
5030 SourceLocation RParenLoc);
5031 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5032 BinaryOperatorKind Operator,
5033 SourceLocation EllipsisLoc, Expr *RHS,
5034 SourceLocation RParenLoc);
5035 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5036 BinaryOperatorKind Operator);
5037
5038 //// ActOnCXXThis - Parse 'this' pointer.
5039 ExprResult ActOnCXXThis(SourceLocation loc);
5040
5041 /// \brief Try to retrieve the type of the 'this' pointer.
5042 ///
5043 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5044 QualType getCurrentThisType();
5045
5046 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
5047 /// current context not being a non-static member function. In such cases,
5048 /// this provides the type used for 'this'.
5049 QualType CXXThisTypeOverride;
5050
5051 /// \brief RAII object used to temporarily allow the C++ 'this' expression
5052 /// to be used, with the given qualifiers on the current class type.
5053 class CXXThisScopeRAII {
5054 Sema &S;
5055 QualType OldCXXThisTypeOverride;
5056 bool Enabled;
5057
5058 public:
5059 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
5060 /// using the given declaration (which is either a class template or a
5061 /// class) along with the given qualifiers.
5062 /// along with the qualifiers placed on '*this'.
5063 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
5064 bool Enabled = true);
5065
5066 ~CXXThisScopeRAII();
5067 };
5068
5069 /// \brief Make sure the value of 'this' is actually available in the current
5070 /// context, if it is a potentially evaluated context.
5071 ///
5072 /// \param Loc The location at which the capture of 'this' occurs.
5073 ///
5074 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5075 /// capture list.
5076 ///
5077 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5078 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5079 /// This is useful when enclosing lambdas must speculatively capture
5080 /// 'this' that may or may not be used in certain specializations of
5081 /// a nested generic lambda (depending on whether the name resolves to
5082 /// a non-static member function or a static function).
5083 /// \return returns 'true' if failed, 'false' if success.
5084 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5085 bool BuildAndDiagnose = true,
5086 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5087 bool ByCopy = false);
5088
5089 /// \brief Determine whether the given type is the type of *this that is used
5090 /// outside of the body of a member function for a type that is currently
5091 /// being defined.
5092 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5093
5094 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5095 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5096
5097
5098 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5099 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5100
5101 ExprResult
5102 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5103 SourceLocation AtLoc, SourceLocation RParen);
5104
5105 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5106 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5107
5108 //// ActOnCXXThrow - Parse throw expressions.
5109 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5110 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5111 bool IsThrownVarInScope);
5112 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5113
5114 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5115 /// Can be interpreted either as function-style casting ("int(x)")
5116 /// or class type construction ("ClassType(x,y,z)")
5117 /// or creation of a value-initialized type ("int()").
5118 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5119 SourceLocation LParenOrBraceLoc,
5120 MultiExprArg Exprs,
5121 SourceLocation RParenOrBraceLoc,
5122 bool ListInitialization);
5123
5124 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5125 SourceLocation LParenLoc,
5126 MultiExprArg Exprs,
5127 SourceLocation RParenLoc,
5128 bool ListInitialization);
5129
5130 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5131 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5132 SourceLocation PlacementLParen,
5133 MultiExprArg PlacementArgs,
5134 SourceLocation PlacementRParen,
5135 SourceRange TypeIdParens, Declarator &D,
5136 Expr *Initializer);
5137 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5138 SourceLocation PlacementLParen,
5139 MultiExprArg PlacementArgs,
5140 SourceLocation PlacementRParen,
5141 SourceRange TypeIdParens,
5142 QualType AllocType,
5143 TypeSourceInfo *AllocTypeInfo,
5144 Expr *ArraySize,
5145 SourceRange DirectInitRange,
5146 Expr *Initializer);
5147
5148 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5149 SourceRange R);
5150 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5151 bool UseGlobal, QualType AllocType, bool IsArray,
5152 bool &PassAlignment, MultiExprArg PlaceArgs,
5153 FunctionDecl *&OperatorNew,
5154 FunctionDecl *&OperatorDelete);
5155 void DeclareGlobalNewDelete();
5156 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5157 ArrayRef<QualType> Params);
5158
5159 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5160 DeclarationName Name, FunctionDecl* &Operator,
5161 bool Diagnose = true);
5162 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5163 bool CanProvideSize,
5164 bool Overaligned,
5165 DeclarationName Name);
5166 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5167 CXXRecordDecl *RD);
5168
5169 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5170 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5171 bool UseGlobal, bool ArrayForm,
5172 Expr *Operand);
5173 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5174 bool IsDelete, bool CallCanBeVirtual,
5175 bool WarnOnNonAbstractTypes,
5176 SourceLocation DtorLoc);
5177
5178 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5179 Expr *Operand, SourceLocation RParen);
5180 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5181 SourceLocation RParen);
5182
5183 /// \brief Parsed one of the type trait support pseudo-functions.
5184 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5185 ArrayRef<ParsedType> Args,
5186 SourceLocation RParenLoc);
5187 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5188 ArrayRef<TypeSourceInfo *> Args,
5189 SourceLocation RParenLoc);
5190
5191 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5192 /// pseudo-functions.
5193 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5194 SourceLocation KWLoc,
5195 ParsedType LhsTy,
5196 Expr *DimExpr,
5197 SourceLocation RParen);
5198
5199 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5200 SourceLocation KWLoc,
5201 TypeSourceInfo *TSInfo,
5202 Expr *DimExpr,
5203 SourceLocation RParen);
5204
5205 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5206 /// pseudo-functions.
5207 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5208 SourceLocation KWLoc,
5209 Expr *Queried,
5210 SourceLocation RParen);
5211
5212 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5213 SourceLocation KWLoc,
5214 Expr *Queried,
5215 SourceLocation RParen);
5216
5217 ExprResult ActOnStartCXXMemberReference(Scope *S,
5218 Expr *Base,
5219 SourceLocation OpLoc,
5220 tok::TokenKind OpKind,
5221 ParsedType &ObjectType,
5222 bool &MayBePseudoDestructor);
5223
5224 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5225 SourceLocation OpLoc,
5226 tok::TokenKind OpKind,
5227 const CXXScopeSpec &SS,
5228 TypeSourceInfo *ScopeType,
5229 SourceLocation CCLoc,
5230 SourceLocation TildeLoc,
5231 PseudoDestructorTypeStorage DestroyedType);
5232
5233 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5234 SourceLocation OpLoc,
5235 tok::TokenKind OpKind,
5236 CXXScopeSpec &SS,
5237 UnqualifiedId &FirstTypeName,
5238 SourceLocation CCLoc,
5239 SourceLocation TildeLoc,
5240 UnqualifiedId &SecondTypeName);
5241
5242 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5243 SourceLocation OpLoc,
5244 tok::TokenKind OpKind,
5245 SourceLocation TildeLoc,
5246 const DeclSpec& DS);
5247
5248 /// MaybeCreateExprWithCleanups - If the current full-expression
5249 /// requires any cleanups, surround it with a ExprWithCleanups node.
5250 /// Otherwise, just returns the passed-in expression.
5251 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5252 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5253 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5254
5255 MaterializeTemporaryExpr *
5256 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5257 bool BoundToLvalueReference);
5258
5259 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5260 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5261 : SourceLocation());
5262 }
5263 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5264 bool DiscardedValue = false,
5265 bool IsConstexpr = false,
5266 bool IsLambdaInitCaptureInitializer = false);
5267 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5268
5269 // Marks SS invalid if it represents an incomplete type.
5270 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5271
5272 DeclContext *computeDeclContext(QualType T);
5273 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5274 bool EnteringContext = false);
5275 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5276 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5277
5278 /// \brief The parser has parsed a global nested-name-specifier '::'.
5279 ///
5280 /// \param CCLoc The location of the '::'.
5281 ///
5282 /// \param SS The nested-name-specifier, which will be updated in-place
5283 /// to reflect the parsed nested-name-specifier.
5284 ///
5285 /// \returns true if an error occurred, false otherwise.
5286 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5287
5288 /// \brief The parser has parsed a '__super' nested-name-specifier.
5289 ///
5290 /// \param SuperLoc The location of the '__super' keyword.
5291 ///
5292 /// \param ColonColonLoc The location of the '::'.
5293 ///
5294 /// \param SS The nested-name-specifier, which will be updated in-place
5295 /// to reflect the parsed nested-name-specifier.
5296 ///
5297 /// \returns true if an error occurred, false otherwise.
5298 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5299 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5300
5301 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5302 bool *CanCorrect = nullptr);
5303 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5304
5305 /// \brief Keeps information about an identifier in a nested-name-spec.
5306 ///
5307 struct NestedNameSpecInfo {
5308 /// \brief The type of the object, if we're parsing nested-name-specifier in
5309 /// a member access expression.
5310 ParsedType ObjectType;
5311
5312 /// \brief The identifier preceding the '::'.
5313 IdentifierInfo *Identifier;
5314
5315 /// \brief The location of the identifier.
5316 SourceLocation IdentifierLoc;
5317
5318 /// \brief The location of the '::'.
5319 SourceLocation CCLoc;
5320
5321 /// \brief Creates info object for the most typical case.
5322 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5323 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5324 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5325 CCLoc(ColonColonLoc) {
5326 }
5327
5328 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5329 SourceLocation ColonColonLoc, QualType ObjectType)
5330 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5331 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5332 }
5333 };
5334
5335 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5336 NestedNameSpecInfo &IdInfo);
5337
5338 bool BuildCXXNestedNameSpecifier(Scope *S,
5339 NestedNameSpecInfo &IdInfo,
5340 bool EnteringContext,
5341 CXXScopeSpec &SS,
5342 NamedDecl *ScopeLookupResult,
5343 bool ErrorRecoveryLookup,
5344 bool *IsCorrectedToColon = nullptr,
5345 bool OnlyNamespace = false);
5346
5347 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5348 ///
5349 /// \param S The scope in which this nested-name-specifier occurs.
5350 ///
5351 /// \param IdInfo Parser information about an identifier in the
5352 /// nested-name-spec.
5353 ///
5354 /// \param EnteringContext Whether we're entering the context nominated by
5355 /// this nested-name-specifier.
5356 ///
5357 /// \param SS The nested-name-specifier, which is both an input
5358 /// parameter (the nested-name-specifier before this type) and an
5359 /// output parameter (containing the full nested-name-specifier,
5360 /// including this new type).
5361 ///
5362 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5363 /// error recovery. In this case do not emit error message.
5364 ///
5365 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5366 /// are allowed. The bool value pointed by this parameter is set to 'true'
5367 /// if the identifier is treated as if it was followed by ':', not '::'.
5368 ///
5369 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5370 ///
5371 /// \returns true if an error occurred, false otherwise.
5372 bool ActOnCXXNestedNameSpecifier(Scope *S,
5373 NestedNameSpecInfo &IdInfo,
5374 bool EnteringContext,
5375 CXXScopeSpec &SS,
5376 bool ErrorRecoveryLookup = false,
5377 bool *IsCorrectedToColon = nullptr,
5378 bool OnlyNamespace = false);
5379
5380 ExprResult ActOnDecltypeExpression(Expr *E);
5381
5382 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5383 const DeclSpec &DS,
5384 SourceLocation ColonColonLoc);
5385
5386 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5387 NestedNameSpecInfo &IdInfo,
5388 bool EnteringContext);
5389
5390 /// \brief The parser has parsed a nested-name-specifier
5391 /// 'template[opt] template-name < template-args >::'.
5392 ///
5393 /// \param S The scope in which this nested-name-specifier occurs.
5394 ///
5395 /// \param SS The nested-name-specifier, which is both an input
5396 /// parameter (the nested-name-specifier before this type) and an
5397 /// output parameter (containing the full nested-name-specifier,
5398 /// including this new type).
5399 ///
5400 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5401 /// \param TemplateName the template name.
5402 /// \param TemplateNameLoc The location of the template name.
5403 /// \param LAngleLoc The location of the opening angle bracket ('<').
5404 /// \param TemplateArgs The template arguments.
5405 /// \param RAngleLoc The location of the closing angle bracket ('>').
5406 /// \param CCLoc The location of the '::'.
5407 ///
5408 /// \param EnteringContext Whether we're entering the context of the
5409 /// nested-name-specifier.
5410 ///
5411 ///
5412 /// \returns true if an error occurred, false otherwise.
5413 bool ActOnCXXNestedNameSpecifier(Scope *S,
5414 CXXScopeSpec &SS,
5415 SourceLocation TemplateKWLoc,
5416 TemplateTy TemplateName,
5417 SourceLocation TemplateNameLoc,
5418 SourceLocation LAngleLoc,
5419 ASTTemplateArgsPtr TemplateArgs,
5420 SourceLocation RAngleLoc,
5421 SourceLocation CCLoc,
5422 bool EnteringContext);
5423
5424 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5425 /// that the parser can use later to reconstruct the given
5426 /// nested-name-specifier.
5427 ///
5428 /// \param SS A nested-name-specifier.
5429 ///
5430 /// \returns A pointer containing all of the information in the
5431 /// nested-name-specifier \p SS.
5432 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5433
5434 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5435 /// the nested-name-specifier structure.
5436 ///
5437 /// \param Annotation The annotation pointer, produced by
5438 /// \c SaveNestedNameSpecifierAnnotation().
5439 ///
5440 /// \param AnnotationRange The source range corresponding to the annotation.
5441 ///
5442 /// \param SS The nested-name-specifier that will be updated with the contents
5443 /// of the annotation pointer.
5444 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5445 SourceRange AnnotationRange,
5446 CXXScopeSpec &SS);
5447
5448 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5449
5450 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5451 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5452 /// After this method is called, according to [C++ 3.4.3p3], names should be
5453 /// looked up in the declarator-id's scope, until the declarator is parsed and
5454 /// ActOnCXXExitDeclaratorScope is called.
5455 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5456 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5457
5458 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5459 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5460 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5461 /// Used to indicate that names should revert to being looked up in the
5462 /// defining scope.
5463 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5464
5465 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5466 /// initializer for the declaration 'Dcl'.
5467 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5468 /// static data member of class X, names should be looked up in the scope of
5469 /// class X.
5470 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5471
5472 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5473 /// initializer for the declaration 'Dcl'.
5474 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5475
5476 /// \brief Create a new lambda closure type.
5477 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5478 TypeSourceInfo *Info,
5479 bool KnownDependent,
5480 LambdaCaptureDefault CaptureDefault);
5481
5482 /// \brief Start the definition of a lambda expression.
5483 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5484 SourceRange IntroducerRange,
5485 TypeSourceInfo *MethodType,
5486 SourceLocation EndLoc,
5487 ArrayRef<ParmVarDecl *> Params,
5488 bool IsConstexprSpecified);
5489
5490 /// \brief Endow the lambda scope info with the relevant properties.
5491 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5492 CXXMethodDecl *CallOperator,
5493 SourceRange IntroducerRange,
5494 LambdaCaptureDefault CaptureDefault,
5495 SourceLocation CaptureDefaultLoc,
5496 bool ExplicitParams,
5497 bool ExplicitResultType,
5498 bool Mutable);
5499
5500 /// \brief Perform initialization analysis of the init-capture and perform
5501 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5502 /// not being used to initialize a reference.
5503 ParsedType actOnLambdaInitCaptureInitialization(
5504 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5505 LambdaCaptureInitKind InitKind, Expr *&Init) {
5506 return ParsedType::make(buildLambdaInitCaptureInitialization(
5507 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5508 }
5509 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5510 IdentifierInfo *Id,
5511 bool DirectInit, Expr *&Init);
5512
5513 /// \brief Create a dummy variable within the declcontext of the lambda's
5514 /// call operator, for name lookup purposes for a lambda init capture.
5515 ///
5516 /// CodeGen handles emission of lambda captures, ignoring these dummy
5517 /// variables appropriately.
5518 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5519 QualType InitCaptureType,
5520 IdentifierInfo *Id,
5521 unsigned InitStyle, Expr *Init);
5522
5523 /// \brief Build the implicit field for an init-capture.
5524 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5525
5526 /// \brief Note that we have finished the explicit captures for the
5527 /// given lambda.
5528 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5529
5530 /// \brief Introduce the lambda parameters into scope.
5531 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5532
5533 /// \brief Deduce a block or lambda's return type based on the return
5534 /// statements present in the body.
5535 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5536
5537 /// ActOnStartOfLambdaDefinition - This is called just before we start
5538 /// parsing the body of a lambda; it analyzes the explicit captures and
5539 /// arguments, and sets up various data-structures for the body of the
5540 /// lambda.
5541 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5542 Declarator &ParamInfo, Scope *CurScope);
5543
5544 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5545 /// is invoked to pop the information about the lambda.
5546 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5547 bool IsInstantiation = false);
5548
5549 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5550 /// was successfully completed.
5551 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5552 Scope *CurScope);
5553
5554 /// \brief Does copying/destroying the captured variable have side effects?
5555 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5556
5557 /// \brief Diagnose if an explicit lambda capture is unused.
5558 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5559
5560 /// \brief Complete a lambda-expression having processed and attached the
5561 /// lambda body.
5562 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5563 sema::LambdaScopeInfo *LSI);
5564
5565 /// Get the return type to use for a lambda's conversion function(s) to
5566 /// function pointer type, given the type of the call operator.
5567 QualType
5568 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
5569
5570 /// \brief Define the "body" of the conversion from a lambda object to a
5571 /// function pointer.
5572 ///
5573 /// This routine doesn't actually define a sensible body; rather, it fills
5574 /// in the initialization expression needed to copy the lambda object into
5575 /// the block, and IR generation actually generates the real body of the
5576 /// block pointer conversion.
5577 void DefineImplicitLambdaToFunctionPointerConversion(
5578 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5579
5580 /// \brief Define the "body" of the conversion from a lambda object to a
5581 /// block pointer.
5582 ///
5583 /// This routine doesn't actually define a sensible body; rather, it fills
5584 /// in the initialization expression needed to copy the lambda object into
5585 /// the block, and IR generation actually generates the real body of the
5586 /// block pointer conversion.
5587 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5588 CXXConversionDecl *Conv);
5589
5590 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5591 SourceLocation ConvLocation,
5592 CXXConversionDecl *Conv,
5593 Expr *Src);
5594
5595 // ParseObjCStringLiteral - Parse Objective-C string literals.
5596 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5597 ArrayRef<Expr *> Strings);
5598
5599 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5600
5601 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5602 /// numeric literal expression. Type of the expression will be "NSNumber *"
5603 /// or "id" if NSNumber is unavailable.
5604 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5605 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5606 bool Value);
5607 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5608
5609 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5610 /// '@' prefixed parenthesized expression. The type of the expression will
5611 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5612 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5613 /// "const char *" or C structure with attribute 'objc_boxable'.
5614 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5615
5616 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5617 Expr *IndexExpr,
5618 ObjCMethodDecl *getterMethod,
5619 ObjCMethodDecl *setterMethod);
5620
5621 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5622 MutableArrayRef<ObjCDictionaryElement> Elements);
5623
5624 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5625 TypeSourceInfo *EncodedTypeInfo,
5626 SourceLocation RParenLoc);
5627 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5628 CXXConversionDecl *Method,
5629 bool HadMultipleCandidates);
5630
5631 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5632 SourceLocation EncodeLoc,
5633 SourceLocation LParenLoc,
5634 ParsedType Ty,
5635 SourceLocation RParenLoc);
5636
5637 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5638 ExprResult ParseObjCSelectorExpression(Selector Sel,
5639 SourceLocation AtLoc,
5640 SourceLocation SelLoc,
5641 SourceLocation LParenLoc,
5642 SourceLocation RParenLoc,
5643 bool WarnMultipleSelectors);
5644
5645 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5646 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5647 SourceLocation AtLoc,
5648 SourceLocation ProtoLoc,
5649 SourceLocation LParenLoc,
5650 SourceLocation ProtoIdLoc,
5651 SourceLocation RParenLoc);
5652
5653 //===--------------------------------------------------------------------===//
5654 // C++ Declarations
5655 //
5656 Decl *ActOnStartLinkageSpecification(Scope *S,
5657 SourceLocation ExternLoc,
5658 Expr *LangStr,
5659 SourceLocation LBraceLoc);
5660 Decl *ActOnFinishLinkageSpecification(Scope *S,
5661 Decl *LinkageSpec,
5662 SourceLocation RBraceLoc);
5663
5664
5665 //===--------------------------------------------------------------------===//
5666 // C++ Classes
5667 //
5668 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5669 const CXXScopeSpec *SS = nullptr);
5670 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5671
5672 bool ActOnAccessSpecifier(AccessSpecifier Access,
5673 SourceLocation ASLoc,
5674 SourceLocation ColonLoc,
5675 AttributeList *Attrs = nullptr);
5676
5677 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5678 Declarator &D,
5679 MultiTemplateParamsArg TemplateParameterLists,
5680 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5681 InClassInitStyle InitStyle);
5682
5683 void ActOnStartCXXInClassMemberInitializer();
5684 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5685 SourceLocation EqualLoc,
5686 Expr *Init);
5687
5688 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5689 Scope *S,
5690 CXXScopeSpec &SS,
5691 IdentifierInfo *MemberOrBase,
5692 ParsedType TemplateTypeTy,
5693 const DeclSpec &DS,
5694 SourceLocation IdLoc,
5695 SourceLocation LParenLoc,
5696 ArrayRef<Expr *> Args,
5697 SourceLocation RParenLoc,
5698 SourceLocation EllipsisLoc);
5699
5700 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5701 Scope *S,
5702 CXXScopeSpec &SS,
5703 IdentifierInfo *MemberOrBase,
5704 ParsedType TemplateTypeTy,
5705 const DeclSpec &DS,
5706 SourceLocation IdLoc,
5707 Expr *InitList,
5708 SourceLocation EllipsisLoc);
5709
5710 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5711 Scope *S,
5712 CXXScopeSpec &SS,
5713 IdentifierInfo *MemberOrBase,
5714 ParsedType TemplateTypeTy,
5715 const DeclSpec &DS,
5716 SourceLocation IdLoc,
5717 Expr *Init,
5718 SourceLocation EllipsisLoc);
5719
5720 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5721 Expr *Init,
5722 SourceLocation IdLoc);
5723
5724 MemInitResult BuildBaseInitializer(QualType BaseType,
5725 TypeSourceInfo *BaseTInfo,
5726 Expr *Init,
5727 CXXRecordDecl *ClassDecl,
5728 SourceLocation EllipsisLoc);
5729
5730 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5731 Expr *Init,
5732 CXXRecordDecl *ClassDecl);
5733
5734 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5735 CXXCtorInitializer *Initializer);
5736
5737 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5738 ArrayRef<CXXCtorInitializer *> Initializers = None);
5739
5740 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5741
5742
5743 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5744 /// mark all the non-trivial destructors of its members and bases as
5745 /// referenced.
5746 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5747 CXXRecordDecl *Record);
5748
5749 /// \brief The list of classes whose vtables have been used within
5750 /// this translation unit, and the source locations at which the
5751 /// first use occurred.
5752 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5753
5754 /// \brief The list of vtables that are required but have not yet been
5755 /// materialized.
5756 SmallVector<VTableUse, 16> VTableUses;
5757
5758 /// \brief The set of classes whose vtables have been used within
5759 /// this translation unit, and a bit that will be true if the vtable is
5760 /// required to be emitted (otherwise, it should be emitted only if needed
5761 /// by code generation).
5762 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5763
5764 /// \brief Load any externally-stored vtable uses.
5765 void LoadExternalVTableUses();
5766
5767 /// \brief Note that the vtable for the given class was used at the
5768 /// given location.
5769 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5770 bool DefinitionRequired = false);
5771
5772 /// \brief Mark the exception specifications of all virtual member functions
5773 /// in the given class as needed.
5774 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5775 const CXXRecordDecl *RD);
5776
5777 /// MarkVirtualMembersReferenced - Will mark all members of the given
5778 /// CXXRecordDecl referenced.
5779 void MarkVirtualMembersReferenced(SourceLocation Loc,
5780 const CXXRecordDecl *RD);
5781
5782 /// \brief Define all of the vtables that have been used in this
5783 /// translation unit and reference any virtual members used by those
5784 /// vtables.
5785 ///
5786 /// \returns true if any work was done, false otherwise.
5787 bool DefineUsedVTables();
5788
5789 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5790
5791 void ActOnMemInitializers(Decl *ConstructorDecl,
5792 SourceLocation ColonLoc,
5793 ArrayRef<CXXCtorInitializer*> MemInits,
5794 bool AnyErrors);
5795
5796 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5797 /// ensure that referenceDLLExportedClassMethods is called some point later
5798 /// when all outer classes of Class are complete.
5799 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5800
5801 void referenceDLLExportedClassMethods();
5802
5803 void propagateDLLAttrToBaseClassTemplate(
5804 CXXRecordDecl *Class, Attr *ClassAttr,
5805 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5806 SourceLocation BaseLoc);
5807
5808 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5809
5810 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
5811 /// conditions that are needed for the attribute to have an effect.
5812 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
5813
5814 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5815 Decl *TagDecl,
5816 SourceLocation LBrac,
5817 SourceLocation RBrac,
5818 AttributeList *AttrList);
5819 void ActOnFinishCXXMemberDecls();
5820 void ActOnFinishCXXNonNestedClass(Decl *D);
5821
5822 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5823 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5824 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5825 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5826 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5827 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5828 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5829 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5830 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5831 CachedTokens &Toks);
5832 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5833 bool IsInsideALocalClassWithinATemplateFunction();
5834
5835 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5836 Expr *AssertExpr,
5837 Expr *AssertMessageExpr,
5838 SourceLocation RParenLoc);
5839 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5840 Expr *AssertExpr,
5841 StringLiteral *AssertMessageExpr,
5842 SourceLocation RParenLoc,
5843 bool Failed);
5844
5845 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5846 SourceLocation FriendLoc,
5847 TypeSourceInfo *TSInfo);
5848 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5849 MultiTemplateParamsArg TemplateParams);
5850 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5851 MultiTemplateParamsArg TemplateParams);
5852
5853 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5854 StorageClass& SC);
5855 void CheckConstructor(CXXConstructorDecl *Constructor);
5856 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5857 StorageClass& SC);
5858 bool CheckDestructor(CXXDestructorDecl *Destructor);
5859 void CheckConversionDeclarator(Declarator &D, QualType &R,
5860 StorageClass& SC);
5861 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5862 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5863 StorageClass &SC);
5864 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5865
5866 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5867 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5868 const FunctionProtoType *T);
5869 void CheckDelayedMemberExceptionSpecs();
5870
5871 //===--------------------------------------------------------------------===//
5872 // C++ Derived Classes
5873 //
5874
5875 /// ActOnBaseSpecifier - Parsed a base specifier
5876 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5877 SourceRange SpecifierRange,
5878 bool Virtual, AccessSpecifier Access,
5879 TypeSourceInfo *TInfo,
5880 SourceLocation EllipsisLoc);
5881
5882 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5883 SourceRange SpecifierRange,
5884 ParsedAttributes &Attrs,
5885 bool Virtual, AccessSpecifier Access,
5886 ParsedType basetype,
5887 SourceLocation BaseLoc,
5888 SourceLocation EllipsisLoc);
5889
5890 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5891 MutableArrayRef<CXXBaseSpecifier *> Bases);
5892 void ActOnBaseSpecifiers(Decl *ClassDecl,
5893 MutableArrayRef<CXXBaseSpecifier *> Bases);
5894
5895 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5896 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5897 CXXBasePaths &Paths);
5898
5899 // FIXME: I don't like this name.
5900 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5901
5902 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5903 SourceLocation Loc, SourceRange Range,
5904 CXXCastPath *BasePath = nullptr,
5905 bool IgnoreAccess = false);
5906 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5907 unsigned InaccessibleBaseID,
5908 unsigned AmbigiousBaseConvID,
5909 SourceLocation Loc, SourceRange Range,
5910 DeclarationName Name,
5911 CXXCastPath *BasePath,
5912 bool IgnoreAccess = false);
5913
5914 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5915
5916 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5917 const CXXMethodDecl *Old);
5918
5919 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5920 /// covariant, according to C++ [class.virtual]p5.
5921 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5922 const CXXMethodDecl *Old);
5923
5924 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5925 /// spec is a subset of base spec.
5926 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5927 const CXXMethodDecl *Old);
5928
5929 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5930
5931 /// CheckOverrideControl - Check C++11 override control semantics.
5932 void CheckOverrideControl(NamedDecl *D);
5933
5934 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5935 /// not used in the declaration of an overriding method.
5936 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5937
5938 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5939 /// overrides a virtual member function marked 'final', according to
5940 /// C++11 [class.virtual]p4.
5941 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5942 const CXXMethodDecl *Old);
5943
5944
5945 //===--------------------------------------------------------------------===//
5946 // C++ Access Control
5947 //
5948
5949 enum AccessResult {
5950 AR_accessible,
5951 AR_inaccessible,
5952 AR_dependent,
5953 AR_delayed
5954 };
5955
5956 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5957 NamedDecl *PrevMemberDecl,
5958 AccessSpecifier LexicalAS);
5959
5960 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5961 DeclAccessPair FoundDecl);
5962 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5963 DeclAccessPair FoundDecl);
5964 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5965 SourceRange PlacementRange,
5966 CXXRecordDecl *NamingClass,
5967 DeclAccessPair FoundDecl,
5968 bool Diagnose = true);
5969 AccessResult CheckConstructorAccess(SourceLocation Loc,
5970 CXXConstructorDecl *D,
5971 DeclAccessPair FoundDecl,
5972 const InitializedEntity &Entity,
5973 bool IsCopyBindingRefToTemp = false);
5974 AccessResult CheckConstructorAccess(SourceLocation Loc,
5975 CXXConstructorDecl *D,
5976 DeclAccessPair FoundDecl,
5977 const InitializedEntity &Entity,
5978 const PartialDiagnostic &PDiag);
5979 AccessResult CheckDestructorAccess(SourceLocation Loc,
5980 CXXDestructorDecl *Dtor,
5981 const PartialDiagnostic &PDiag,
5982 QualType objectType = QualType());
5983 AccessResult CheckFriendAccess(NamedDecl *D);
5984 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5985 CXXRecordDecl *NamingClass,
5986 DeclAccessPair Found);
5987 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5988 Expr *ObjectExpr,
5989 Expr *ArgExpr,
5990 DeclAccessPair FoundDecl);
5991 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5992 DeclAccessPair FoundDecl);
5993 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5994 QualType Base, QualType Derived,
5995 const CXXBasePath &Path,
5996 unsigned DiagID,
5997 bool ForceCheck = false,
5998 bool ForceUnprivileged = false);
5999 void CheckLookupAccess(const LookupResult &R);
6000 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
6001 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
6002 AccessSpecifier access,
6003 QualType objectType);
6004
6005 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6006 const MultiLevelTemplateArgumentList &TemplateArgs);
6007 void PerformDependentDiagnostics(const DeclContext *Pattern,
6008 const MultiLevelTemplateArgumentList &TemplateArgs);
6009
6010 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6011
6012 /// \brief When true, access checking violations are treated as SFINAE
6013 /// failures rather than hard errors.
6014 bool AccessCheckingSFINAE;
6015
6016 enum AbstractDiagSelID {
6017 AbstractNone = -1,
6018 AbstractReturnType,
6019 AbstractParamType,
6020 AbstractVariableType,
6021 AbstractFieldType,
6022 AbstractIvarType,
6023 AbstractSynthesizedIvarType,
6024 AbstractArrayType
6025 };
6026
6027 bool isAbstractType(SourceLocation Loc, QualType T);
6028 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6029 TypeDiagnoser &Diagnoser);
6030 template <typename... Ts>
6031 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6032 const Ts &...Args) {
6033 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6034 return RequireNonAbstractType(Loc, T, Diagnoser);
6035 }
6036
6037 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6038
6039 //===--------------------------------------------------------------------===//
6040 // C++ Overloaded Operators [C++ 13.5]
6041 //
6042
6043 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6044
6045 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6046
6047 //===--------------------------------------------------------------------===//
6048 // C++ Templates [C++ 14]
6049 //
6050 void FilterAcceptableTemplateNames(LookupResult &R,
6051 bool AllowFunctionTemplates = true);
6052 bool hasAnyAcceptableTemplateNames(LookupResult &R,
6053 bool AllowFunctionTemplates = true);
6054
6055 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6056 QualType ObjectType, bool EnteringContext,
6057 bool &MemberOfUnknownSpecialization);
6058
6059 TemplateNameKind isTemplateName(Scope *S,
6060 CXXScopeSpec &SS,
6061 bool hasTemplateKeyword,
6062 UnqualifiedId &Name,
6063 ParsedType ObjectType,
6064 bool EnteringContext,
6065 TemplateTy &Template,
6066 bool &MemberOfUnknownSpecialization);
6067
6068 /// Determine whether a particular identifier might be the name in a C++1z
6069 /// deduction-guide declaration.
6070 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6071 SourceLocation NameLoc,
6072 ParsedTemplateTy *Template = nullptr);
6073
6074 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6075 SourceLocation IILoc,
6076 Scope *S,
6077 const CXXScopeSpec *SS,
6078 TemplateTy &SuggestedTemplate,
6079 TemplateNameKind &SuggestedKind);
6080
6081 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6082 NamedDecl *Instantiation,
6083 bool InstantiatedFromMember,
6084 const NamedDecl *Pattern,
6085 const NamedDecl *PatternDef,
6086 TemplateSpecializationKind TSK,
6087 bool Complain = true);
6088
6089 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6090 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6091
6092 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6093 SourceLocation EllipsisLoc,
6094 SourceLocation KeyLoc,
6095 IdentifierInfo *ParamName,
6096 SourceLocation ParamNameLoc,
6097 unsigned Depth, unsigned Position,
6098 SourceLocation EqualLoc,
6099 ParsedType DefaultArg);
6100
6101 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6102 SourceLocation Loc);
6103 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6104
6105 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6106 unsigned Depth,
6107 unsigned Position,
6108 SourceLocation EqualLoc,
6109 Expr *DefaultArg);
6110 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6111 SourceLocation TmpLoc,
6112 TemplateParameterList *Params,
6113 SourceLocation EllipsisLoc,
6114 IdentifierInfo *ParamName,
6115 SourceLocation ParamNameLoc,
6116 unsigned Depth,
6117 unsigned Position,
6118 SourceLocation EqualLoc,
6119 ParsedTemplateArgument DefaultArg);
6120
6121 TemplateParameterList *
6122 ActOnTemplateParameterList(unsigned Depth,
6123 SourceLocation ExportLoc,
6124 SourceLocation TemplateLoc,
6125 SourceLocation LAngleLoc,
6126 ArrayRef<NamedDecl *> Params,
6127 SourceLocation RAngleLoc,
6128 Expr *RequiresClause);
6129
6130 /// \brief The context in which we are checking a template parameter list.
6131 enum TemplateParamListContext {
6132 TPC_ClassTemplate,
6133 TPC_VarTemplate,
6134 TPC_FunctionTemplate,
6135 TPC_ClassTemplateMember,
6136 TPC_FriendClassTemplate,
6137 TPC_FriendFunctionTemplate,
6138 TPC_FriendFunctionTemplateDefinition,
6139 TPC_TypeAliasTemplate
6140 };
6141
6142 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6143 TemplateParameterList *OldParams,
6144 TemplateParamListContext TPC);
6145 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6146 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6147 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6148 ArrayRef<TemplateParameterList *> ParamLists,
6149 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6150
6151 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
6152 SourceLocation KWLoc, CXXScopeSpec &SS,
6153 IdentifierInfo *Name, SourceLocation NameLoc,
6154 AttributeList *Attr,
6155 TemplateParameterList *TemplateParams,
6156 AccessSpecifier AS,
6157 SourceLocation ModulePrivateLoc,
6158 SourceLocation FriendLoc,
6159 unsigned NumOuterTemplateParamLists,
6160 TemplateParameterList **OuterTemplateParamLists,
6161 SkipBodyInfo *SkipBody = nullptr);
6162
6163 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6164 QualType NTTPType,
6165 SourceLocation Loc);
6166
6167 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6168 TemplateArgumentListInfo &Out);
6169
6170 void NoteAllFoundTemplates(TemplateName Name);
6171
6172 QualType CheckTemplateIdType(TemplateName Template,
6173 SourceLocation TemplateLoc,
6174 TemplateArgumentListInfo &TemplateArgs);
6175
6176 TypeResult
6177 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6178 TemplateTy Template, IdentifierInfo *TemplateII,
6179 SourceLocation TemplateIILoc,
6180 SourceLocation LAngleLoc,
6181 ASTTemplateArgsPtr TemplateArgs,
6182 SourceLocation RAngleLoc,
6183 bool IsCtorOrDtorName = false,
6184 bool IsClassName = false);
6185
6186 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6187 /// such as \c class T::template apply<U>.
6188 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6189 TypeSpecifierType TagSpec,
6190 SourceLocation TagLoc,
6191 CXXScopeSpec &SS,
6192 SourceLocation TemplateKWLoc,
6193 TemplateTy TemplateD,
6194 SourceLocation TemplateLoc,
6195 SourceLocation LAngleLoc,
6196 ASTTemplateArgsPtr TemplateArgsIn,
6197 SourceLocation RAngleLoc);
6198
6199 DeclResult ActOnVarTemplateSpecialization(
6200 Scope *S, Declarator &D, TypeSourceInfo *DI,
6201 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6202 StorageClass SC, bool IsPartialSpecialization);
6203
6204 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6205 SourceLocation TemplateLoc,
6206 SourceLocation TemplateNameLoc,
6207 const TemplateArgumentListInfo &TemplateArgs);
6208
6209 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6210 const DeclarationNameInfo &NameInfo,
6211 VarTemplateDecl *Template,
6212 SourceLocation TemplateLoc,
6213 const TemplateArgumentListInfo *TemplateArgs);
6214
6215 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6216 SourceLocation TemplateKWLoc,
6217 LookupResult &R,
6218 bool RequiresADL,
6219 const TemplateArgumentListInfo *TemplateArgs);
6220
6221 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6222 SourceLocation TemplateKWLoc,
6223 const DeclarationNameInfo &NameInfo,
6224 const TemplateArgumentListInfo *TemplateArgs);
6225
6226 TemplateNameKind ActOnDependentTemplateName(
6227 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6228 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6229 TemplateTy &Template, bool AllowInjectedClassName = false);
6230
6231 DeclResult
6232 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6233 SourceLocation KWLoc,
6234 SourceLocation ModulePrivateLoc,
6235 TemplateIdAnnotation &TemplateId,
6236 AttributeList *Attr,
6237 MultiTemplateParamsArg TemplateParameterLists,
6238 SkipBodyInfo *SkipBody = nullptr);
6239
6240 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6241 TemplateDecl *PrimaryTemplate,
6242 unsigned NumExplicitArgs,
6243 ArrayRef<TemplateArgument> Args);
6244 void CheckTemplatePartialSpecialization(
6245 ClassTemplatePartialSpecializationDecl *Partial);
6246 void CheckTemplatePartialSpecialization(
6247 VarTemplatePartialSpecializationDecl *Partial);
6248
6249 Decl *ActOnTemplateDeclarator(Scope *S,
6250 MultiTemplateParamsArg TemplateParameterLists,
6251 Declarator &D);
6252
6253 bool
6254 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6255 TemplateSpecializationKind NewTSK,
6256 NamedDecl *PrevDecl,
6257 TemplateSpecializationKind PrevTSK,
6258 SourceLocation PrevPtOfInstantiation,
6259 bool &SuppressNew);
6260
6261 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6262 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6263 LookupResult &Previous);
6264
6265 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6266 TemplateArgumentListInfo *ExplicitTemplateArgs,
6267 LookupResult &Previous);
6268 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6269 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6270
6271 DeclResult
6272 ActOnExplicitInstantiation(Scope *S,
6273 SourceLocation ExternLoc,
6274 SourceLocation TemplateLoc,
6275 unsigned TagSpec,
6276 SourceLocation KWLoc,
6277 const CXXScopeSpec &SS,
6278 TemplateTy Template,
6279 SourceLocation TemplateNameLoc,
6280 SourceLocation LAngleLoc,
6281 ASTTemplateArgsPtr TemplateArgs,
6282 SourceLocation RAngleLoc,
6283 AttributeList *Attr);
6284
6285 DeclResult
6286 ActOnExplicitInstantiation(Scope *S,
6287 SourceLocation ExternLoc,
6288 SourceLocation TemplateLoc,
6289 unsigned TagSpec,
6290 SourceLocation KWLoc,
6291 CXXScopeSpec &SS,
6292 IdentifierInfo *Name,
6293 SourceLocation NameLoc,
6294 AttributeList *Attr);
6295
6296 DeclResult ActOnExplicitInstantiation(Scope *S,
6297 SourceLocation ExternLoc,
6298 SourceLocation TemplateLoc,
6299 Declarator &D);
6300
6301 TemplateArgumentLoc
6302 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6303 SourceLocation TemplateLoc,
6304 SourceLocation RAngleLoc,
6305 Decl *Param,
6306 SmallVectorImpl<TemplateArgument>
6307 &Converted,
6308 bool &HasDefaultArg);
6309
6310 /// \brief Specifies the context in which a particular template
6311 /// argument is being checked.
6312 enum CheckTemplateArgumentKind {
6313 /// \brief The template argument was specified in the code or was
6314 /// instantiated with some deduced template arguments.
6315 CTAK_Specified,
6316
6317 /// \brief The template argument was deduced via template argument
6318 /// deduction.
6319 CTAK_Deduced,
6320
6321 /// \brief The template argument was deduced from an array bound
6322 /// via template argument deduction.
6323 CTAK_DeducedFromArrayBound
6324 };
6325
6326 bool CheckTemplateArgument(NamedDecl *Param,
6327 TemplateArgumentLoc &Arg,
6328 NamedDecl *Template,
6329 SourceLocation TemplateLoc,
6330 SourceLocation RAngleLoc,
6331 unsigned ArgumentPackIndex,
6332 SmallVectorImpl<TemplateArgument> &Converted,
6333 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6334
6335 /// \brief Check that the given template arguments can be be provided to
6336 /// the given template, converting the arguments along the way.
6337 ///
6338 /// \param Template The template to which the template arguments are being
6339 /// provided.
6340 ///
6341 /// \param TemplateLoc The location of the template name in the source.
6342 ///
6343 /// \param TemplateArgs The list of template arguments. If the template is
6344 /// a template template parameter, this function may extend the set of
6345 /// template arguments to also include substituted, defaulted template
6346 /// arguments.
6347 ///
6348 /// \param PartialTemplateArgs True if the list of template arguments is
6349 /// intentionally partial, e.g., because we're checking just the initial
6350 /// set of template arguments.
6351 ///
6352 /// \param Converted Will receive the converted, canonicalized template
6353 /// arguments.
6354 ///
6355 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6356 /// contain the converted forms of the template arguments as written.
6357 /// Otherwise, \p TemplateArgs will not be modified.
6358 ///
6359 /// \returns true if an error occurred, false otherwise.
6360 bool CheckTemplateArgumentList(TemplateDecl *Template,
6361 SourceLocation TemplateLoc,
6362 TemplateArgumentListInfo &TemplateArgs,
6363 bool PartialTemplateArgs,
6364 SmallVectorImpl<TemplateArgument> &Converted,
6365 bool UpdateArgsWithConversions = true);
6366
6367 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6368 TemplateArgumentLoc &Arg,
6369 SmallVectorImpl<TemplateArgument> &Converted);
6370
6371 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6372 TypeSourceInfo *Arg);
6373 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6374 QualType InstantiatedParamType, Expr *Arg,
6375 TemplateArgument &Converted,
6376 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6377 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6378 TemplateArgumentLoc &Arg,
6379 unsigned ArgumentPackIndex);
6380
6381 ExprResult
6382 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6383 QualType ParamType,
6384 SourceLocation Loc);
6385 ExprResult
6386 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6387 SourceLocation Loc);
6388
6389 /// \brief Enumeration describing how template parameter lists are compared
6390 /// for equality.
6391 enum TemplateParameterListEqualKind {
6392 /// \brief We are matching the template parameter lists of two templates
6393 /// that might be redeclarations.
6394 ///
6395 /// \code
6396 /// template<typename T> struct X;
6397 /// template<typename T> struct X;
6398 /// \endcode
6399 TPL_TemplateMatch,
6400
6401 /// \brief We are matching the template parameter lists of two template
6402 /// template parameters as part of matching the template parameter lists
6403 /// of two templates that might be redeclarations.
6404 ///
6405 /// \code
6406 /// template<template<int I> class TT> struct X;
6407 /// template<template<int Value> class Other> struct X;
6408 /// \endcode
6409 TPL_TemplateTemplateParmMatch,
6410
6411 /// \brief We are matching the template parameter lists of a template
6412 /// template argument against the template parameter lists of a template
6413 /// template parameter.
6414 ///
6415 /// \code
6416 /// template<template<int Value> class Metafun> struct X;
6417 /// template<int Value> struct integer_c;
6418 /// X<integer_c> xic;
6419 /// \endcode
6420 TPL_TemplateTemplateArgumentMatch
6421 };
6422
6423 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6424 TemplateParameterList *Old,
6425 bool Complain,
6426 TemplateParameterListEqualKind Kind,
6427 SourceLocation TemplateArgLoc
6428 = SourceLocation());
6429
6430 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6431
6432 /// \brief Called when the parser has parsed a C++ typename
6433 /// specifier, e.g., "typename T::type".
6434 ///
6435 /// \param S The scope in which this typename type occurs.
6436 /// \param TypenameLoc the location of the 'typename' keyword
6437 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6438 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6439 /// \param IdLoc the location of the identifier.
6440 TypeResult
6441 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6442 const CXXScopeSpec &SS, const IdentifierInfo &II,
6443 SourceLocation IdLoc);
6444
6445 /// \brief Called when the parser has parsed a C++ typename
6446 /// specifier that ends in a template-id, e.g.,
6447 /// "typename MetaFun::template apply<T1, T2>".
6448 ///
6449 /// \param S The scope in which this typename type occurs.
6450 /// \param TypenameLoc the location of the 'typename' keyword
6451 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6452 /// \param TemplateLoc the location of the 'template' keyword, if any.
6453 /// \param TemplateName The template name.
6454 /// \param TemplateII The identifier used to name the template.
6455 /// \param TemplateIILoc The location of the template name.
6456 /// \param LAngleLoc The location of the opening angle bracket ('<').
6457 /// \param TemplateArgs The template arguments.
6458 /// \param RAngleLoc The location of the closing angle bracket ('>').
6459 TypeResult
6460 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6461 const CXXScopeSpec &SS,
6462 SourceLocation TemplateLoc,
6463 TemplateTy TemplateName,
6464 IdentifierInfo *TemplateII,
6465 SourceLocation TemplateIILoc,
6466 SourceLocation LAngleLoc,
6467 ASTTemplateArgsPtr TemplateArgs,
6468 SourceLocation RAngleLoc);
6469
6470 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6471 SourceLocation KeywordLoc,
6472 NestedNameSpecifierLoc QualifierLoc,
6473 const IdentifierInfo &II,
6474 SourceLocation IILoc);
6475
6476 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6477 SourceLocation Loc,
6478 DeclarationName Name);
6479 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6480
6481 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6482 bool RebuildTemplateParamsInCurrentInstantiation(
6483 TemplateParameterList *Params);
6484
6485 std::string
6486 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6487 const TemplateArgumentList &Args);
6488
6489 std::string
6490 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6491 const TemplateArgument *Args,
6492 unsigned NumArgs);
6493
6494 //===--------------------------------------------------------------------===//
6495 // C++ Variadic Templates (C++0x [temp.variadic])
6496 //===--------------------------------------------------------------------===//
6497
6498 /// Determine whether an unexpanded parameter pack might be permitted in this
6499 /// location. Useful for error recovery.
6500 bool isUnexpandedParameterPackPermitted();
6501
6502 /// \brief The context in which an unexpanded parameter pack is
6503 /// being diagnosed.
6504 ///
6505 /// Note that the values of this enumeration line up with the first
6506 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6507 enum UnexpandedParameterPackContext {
6508 /// \brief An arbitrary expression.
6509 UPPC_Expression = 0,
6510
6511 /// \brief The base type of a class type.
6512 UPPC_BaseType,
6513
6514 /// \brief The type of an arbitrary declaration.
6515 UPPC_DeclarationType,
6516
6517 /// \brief The type of a data member.
6518 UPPC_DataMemberType,
6519
6520 /// \brief The size of a bit-field.
6521 UPPC_BitFieldWidth,
6522
6523 /// \brief The expression in a static assertion.
6524 UPPC_StaticAssertExpression,
6525
6526 /// \brief The fixed underlying type of an enumeration.
6527 UPPC_FixedUnderlyingType,
6528
6529 /// \brief The enumerator value.
6530 UPPC_EnumeratorValue,
6531
6532 /// \brief A using declaration.
6533 UPPC_UsingDeclaration,
6534
6535 /// \brief A friend declaration.
6536 UPPC_FriendDeclaration,
6537
6538 /// \brief A declaration qualifier.
6539 UPPC_DeclarationQualifier,
6540
6541 /// \brief An initializer.
6542 UPPC_Initializer,
6543
6544 /// \brief A default argument.
6545 UPPC_DefaultArgument,
6546
6547 /// \brief The type of a non-type template parameter.
6548 UPPC_NonTypeTemplateParameterType,
6549
6550 /// \brief The type of an exception.
6551 UPPC_ExceptionType,
6552
6553 /// \brief Partial specialization.
6554 UPPC_PartialSpecialization,
6555
6556 /// \brief Microsoft __if_exists.
6557 UPPC_IfExists,
6558
6559 /// \brief Microsoft __if_not_exists.
6560 UPPC_IfNotExists,
6561
6562 /// \brief Lambda expression.
6563 UPPC_Lambda,
6564
6565 /// \brief Block expression,
6566 UPPC_Block
6567 };
6568
6569 /// \brief Diagnose unexpanded parameter packs.
6570 ///
6571 /// \param Loc The location at which we should emit the diagnostic.
6572 ///
6573 /// \param UPPC The context in which we are diagnosing unexpanded
6574 /// parameter packs.
6575 ///
6576 /// \param Unexpanded the set of unexpanded parameter packs.
6577 ///
6578 /// \returns true if an error occurred, false otherwise.
6579 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6580 UnexpandedParameterPackContext UPPC,
6581 ArrayRef<UnexpandedParameterPack> Unexpanded);
6582
6583 /// \brief If the given type contains an unexpanded parameter pack,
6584 /// diagnose the error.
6585 ///
6586 /// \param Loc The source location where a diagnostc should be emitted.
6587 ///
6588 /// \param T The type that is being checked for unexpanded parameter
6589 /// packs.
6590 ///
6591 /// \returns true if an error occurred, false otherwise.
6592 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6593 UnexpandedParameterPackContext UPPC);
6594
6595 /// \brief If the given expression contains an unexpanded parameter
6596 /// pack, diagnose the error.
6597 ///
6598 /// \param E The expression that is being checked for unexpanded
6599 /// parameter packs.
6600 ///
6601 /// \returns true if an error occurred, false otherwise.
6602 bool DiagnoseUnexpandedParameterPack(Expr *E,
6603 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6604
6605 /// \brief If the given nested-name-specifier contains an unexpanded
6606 /// parameter pack, diagnose the error.
6607 ///
6608 /// \param SS The nested-name-specifier that is being checked for
6609 /// unexpanded parameter packs.
6610 ///
6611 /// \returns true if an error occurred, false otherwise.
6612 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6613 UnexpandedParameterPackContext UPPC);
6614
6615 /// \brief If the given name contains an unexpanded parameter pack,
6616 /// diagnose the error.
6617 ///
6618 /// \param NameInfo The name (with source location information) that
6619 /// is being checked for unexpanded parameter packs.
6620 ///
6621 /// \returns true if an error occurred, false otherwise.
6622 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6623 UnexpandedParameterPackContext UPPC);
6624
6625 /// \brief If the given template name contains an unexpanded parameter pack,
6626 /// diagnose the error.
6627 ///
6628 /// \param Loc The location of the template name.
6629 ///
6630 /// \param Template The template name that is being checked for unexpanded
6631 /// parameter packs.
6632 ///
6633 /// \returns true if an error occurred, false otherwise.
6634 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6635 TemplateName Template,
6636 UnexpandedParameterPackContext UPPC);
6637
6638 /// \brief If the given template argument contains an unexpanded parameter
6639 /// pack, diagnose the error.
6640 ///
6641 /// \param Arg The template argument that is being checked for unexpanded
6642 /// parameter packs.
6643 ///
6644 /// \returns true if an error occurred, false otherwise.
6645 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6646 UnexpandedParameterPackContext UPPC);
6647
6648 /// \brief Collect the set of unexpanded parameter packs within the given
6649 /// template argument.
6650 ///
6651 /// \param Arg The template argument that will be traversed to find
6652 /// unexpanded parameter packs.
6653 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6654 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6655
6656 /// \brief Collect the set of unexpanded parameter packs within the given
6657 /// template argument.
6658 ///
6659 /// \param Arg The template argument that will be traversed to find
6660 /// unexpanded parameter packs.
6661 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6662 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6663
6664 /// \brief Collect the set of unexpanded parameter packs within the given
6665 /// type.
6666 ///
6667 /// \param T The type that will be traversed to find
6668 /// unexpanded parameter packs.
6669 void collectUnexpandedParameterPacks(QualType T,
6670 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6671
6672 /// \brief Collect the set of unexpanded parameter packs within the given
6673 /// type.
6674 ///
6675 /// \param TL The type that will be traversed to find
6676 /// unexpanded parameter packs.
6677 void collectUnexpandedParameterPacks(TypeLoc TL,
6678 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6679
6680 /// \brief Collect the set of unexpanded parameter packs within the given
6681 /// nested-name-specifier.
6682 ///
6683 /// \param NNS The nested-name-specifier that will be traversed to find
6684 /// unexpanded parameter packs.
6685 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6686 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6687
6688 /// \brief Collect the set of unexpanded parameter packs within the given
6689 /// name.
6690 ///
6691 /// \param NameInfo The name that will be traversed to find
6692 /// unexpanded parameter packs.
6693 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6694 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6695
6696 /// \brief Invoked when parsing a template argument followed by an
6697 /// ellipsis, which creates a pack expansion.
6698 ///
6699 /// \param Arg The template argument preceding the ellipsis, which
6700 /// may already be invalid.
6701 ///
6702 /// \param EllipsisLoc The location of the ellipsis.
6703 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6704 SourceLocation EllipsisLoc);
6705
6706 /// \brief Invoked when parsing a type followed by an ellipsis, which
6707 /// creates a pack expansion.
6708 ///
6709 /// \param Type The type preceding the ellipsis, which will become
6710 /// the pattern of the pack expansion.
6711 ///
6712 /// \param EllipsisLoc The location of the ellipsis.
6713 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6714
6715 /// \brief Construct a pack expansion type from the pattern of the pack
6716 /// expansion.
6717 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6718 SourceLocation EllipsisLoc,
6719 Optional<unsigned> NumExpansions);
6720
6721 /// \brief Construct a pack expansion type from the pattern of the pack
6722 /// expansion.
6723 QualType CheckPackExpansion(QualType Pattern,
6724 SourceRange PatternRange,
6725 SourceLocation EllipsisLoc,
6726 Optional<unsigned> NumExpansions);
6727
6728 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6729 /// creates a pack expansion.
6730 ///
6731 /// \param Pattern The expression preceding the ellipsis, which will become
6732 /// the pattern of the pack expansion.
6733 ///
6734 /// \param EllipsisLoc The location of the ellipsis.
6735 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6736
6737 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6738 /// creates a pack expansion.
6739 ///
6740 /// \param Pattern The expression preceding the ellipsis, which will become
6741 /// the pattern of the pack expansion.
6742 ///
6743 /// \param EllipsisLoc The location of the ellipsis.
6744 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6745 Optional<unsigned> NumExpansions);
6746
6747 /// \brief Determine whether we could expand a pack expansion with the
6748 /// given set of parameter packs into separate arguments by repeatedly
6749 /// transforming the pattern.
6750 ///
6751 /// \param EllipsisLoc The location of the ellipsis that identifies the
6752 /// pack expansion.
6753 ///
6754 /// \param PatternRange The source range that covers the entire pattern of
6755 /// the pack expansion.
6756 ///
6757 /// \param Unexpanded The set of unexpanded parameter packs within the
6758 /// pattern.
6759 ///
6760 /// \param ShouldExpand Will be set to \c true if the transformer should
6761 /// expand the corresponding pack expansions into separate arguments. When
6762 /// set, \c NumExpansions must also be set.
6763 ///
6764 /// \param RetainExpansion Whether the caller should add an unexpanded
6765 /// pack expansion after all of the expanded arguments. This is used
6766 /// when extending explicitly-specified template argument packs per
6767 /// C++0x [temp.arg.explicit]p9.
6768 ///
6769 /// \param NumExpansions The number of separate arguments that will be in
6770 /// the expanded form of the corresponding pack expansion. This is both an
6771 /// input and an output parameter, which can be set by the caller if the
6772 /// number of expansions is known a priori (e.g., due to a prior substitution)
6773 /// and will be set by the callee when the number of expansions is known.
6774 /// The callee must set this value when \c ShouldExpand is \c true; it may
6775 /// set this value in other cases.
6776 ///
6777 /// \returns true if an error occurred (e.g., because the parameter packs
6778 /// are to be instantiated with arguments of different lengths), false
6779 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6780 /// must be set.
6781 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6782 SourceRange PatternRange,
6783 ArrayRef<UnexpandedParameterPack> Unexpanded,
6784 const MultiLevelTemplateArgumentList &TemplateArgs,
6785 bool &ShouldExpand,
6786 bool &RetainExpansion,
6787 Optional<unsigned> &NumExpansions);
6788
6789 /// \brief Determine the number of arguments in the given pack expansion
6790 /// type.
6791 ///
6792 /// This routine assumes that the number of arguments in the expansion is
6793 /// consistent across all of the unexpanded parameter packs in its pattern.
6794 ///
6795 /// Returns an empty Optional if the type can't be expanded.
6796 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6797 const MultiLevelTemplateArgumentList &TemplateArgs);
6798
6799 /// \brief Determine whether the given declarator contains any unexpanded
6800 /// parameter packs.
6801 ///
6802 /// This routine is used by the parser to disambiguate function declarators
6803 /// with an ellipsis prior to the ')', e.g.,
6804 ///
6805 /// \code
6806 /// void f(T...);
6807 /// \endcode
6808 ///
6809 /// To determine whether we have an (unnamed) function parameter pack or
6810 /// a variadic function.
6811 ///
6812 /// \returns true if the declarator contains any unexpanded parameter packs,
6813 /// false otherwise.
6814 bool containsUnexpandedParameterPacks(Declarator &D);
6815
6816 /// \brief Returns the pattern of the pack expansion for a template argument.
6817 ///
6818 /// \param OrigLoc The template argument to expand.
6819 ///
6820 /// \param Ellipsis Will be set to the location of the ellipsis.
6821 ///
6822 /// \param NumExpansions Will be set to the number of expansions that will
6823 /// be generated from this pack expansion, if known a priori.
6824 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6825 TemplateArgumentLoc OrigLoc,
6826 SourceLocation &Ellipsis,
6827 Optional<unsigned> &NumExpansions) const;
6828
6829 /// Given a template argument that contains an unexpanded parameter pack, but
6830 /// which has already been substituted, attempt to determine the number of
6831 /// elements that will be produced once this argument is fully-expanded.
6832 ///
6833 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6834 /// avoid actually expanding the pack where possible.
6835 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6836
6837 //===--------------------------------------------------------------------===//
6838 // C++ Template Argument Deduction (C++ [temp.deduct])
6839 //===--------------------------------------------------------------------===//
6840
6841 /// Adjust the type \p ArgFunctionType to match the calling convention,
6842 /// noreturn, and optionally the exception specification of \p FunctionType.
6843 /// Deduction often wants to ignore these properties when matching function
6844 /// types.
6845 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6846 bool AdjustExceptionSpec = false);
6847
6848 /// \brief Describes the result of template argument deduction.
6849 ///
6850 /// The TemplateDeductionResult enumeration describes the result of
6851 /// template argument deduction, as returned from
6852 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6853 /// structure provides additional information about the results of
6854 /// template argument deduction, e.g., the deduced template argument
6855 /// list (if successful) or the specific template parameters or
6856 /// deduced arguments that were involved in the failure.
6857 enum TemplateDeductionResult {
6858 /// \brief Template argument deduction was successful.
6859 TDK_Success = 0,
6860 /// \brief The declaration was invalid; do nothing.
6861 TDK_Invalid,
6862 /// \brief Template argument deduction exceeded the maximum template
6863 /// instantiation depth (which has already been diagnosed).
6864 TDK_InstantiationDepth,
6865 /// \brief Template argument deduction did not deduce a value
6866 /// for every template parameter.
6867 TDK_Incomplete,
6868 /// \brief Template argument deduction produced inconsistent
6869 /// deduced values for the given template parameter.
6870 TDK_Inconsistent,
6871 /// \brief Template argument deduction failed due to inconsistent
6872 /// cv-qualifiers on a template parameter type that would
6873 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6874 /// but were given a non-const "X".
6875 TDK_Underqualified,
6876 /// \brief Substitution of the deduced template argument values
6877 /// resulted in an error.
6878 TDK_SubstitutionFailure,
6879 /// \brief After substituting deduced template arguments, a dependent
6880 /// parameter type did not match the corresponding argument.
6881 TDK_DeducedMismatch,
6882 /// \brief After substituting deduced template arguments, an element of
6883 /// a dependent parameter type did not match the corresponding element
6884 /// of the corresponding argument (when deducing from an initializer list).
6885 TDK_DeducedMismatchNested,
6886 /// \brief A non-depnedent component of the parameter did not match the
6887 /// corresponding component of the argument.
6888 TDK_NonDeducedMismatch,
6889 /// \brief When performing template argument deduction for a function
6890 /// template, there were too many call arguments.
6891 TDK_TooManyArguments,
6892 /// \brief When performing template argument deduction for a function
6893 /// template, there were too few call arguments.
6894 TDK_TooFewArguments,
6895 /// \brief The explicitly-specified template arguments were not valid
6896 /// template arguments for the given template.
6897 TDK_InvalidExplicitArguments,
6898 /// \brief Checking non-dependent argument conversions failed.
6899 TDK_NonDependentConversionFailure,
6900 /// \brief Deduction failed; that's all we know.
6901 TDK_MiscellaneousDeductionFailure,
6902 /// \brief CUDA Target attributes do not match.
6903 TDK_CUDATargetMismatch
6904 };
6905
6906 TemplateDeductionResult
6907 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6908 const TemplateArgumentList &TemplateArgs,
6909 sema::TemplateDeductionInfo &Info);
6910
6911 TemplateDeductionResult
6912 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6913 const TemplateArgumentList &TemplateArgs,
6914 sema::TemplateDeductionInfo &Info);
6915
6916 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6917 FunctionTemplateDecl *FunctionTemplate,
6918 TemplateArgumentListInfo &ExplicitTemplateArgs,
6919 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6920 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6921 sema::TemplateDeductionInfo &Info);
6922
6923 /// brief A function argument from which we performed template argument
6924 // deduction for a call.
6925 struct OriginalCallArg {
6926 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6927 unsigned ArgIdx, QualType OriginalArgType)
6928 : OriginalParamType(OriginalParamType),
6929 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6930 OriginalArgType(OriginalArgType) {}
6931
6932 QualType OriginalParamType;
6933 bool DecomposedParam;
6934 unsigned ArgIdx;
6935 QualType OriginalArgType;
6936 };
6937
6938 TemplateDeductionResult FinishTemplateArgumentDeduction(
6939 FunctionTemplateDecl *FunctionTemplate,
6940 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6941 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6942 sema::TemplateDeductionInfo &Info,
6943 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6944 bool PartialOverloading = false,
6945 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6946
6947 TemplateDeductionResult DeduceTemplateArguments(
6948 FunctionTemplateDecl *FunctionTemplate,
6949 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6950 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6951 bool PartialOverloading,
6952 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6953
6954 TemplateDeductionResult
6955 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6956 TemplateArgumentListInfo *ExplicitTemplateArgs,
6957 QualType ArgFunctionType,
6958 FunctionDecl *&Specialization,
6959 sema::TemplateDeductionInfo &Info,
6960 bool IsAddressOfFunction = false);
6961
6962 TemplateDeductionResult
6963 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6964 QualType ToType,
6965 CXXConversionDecl *&Specialization,
6966 sema::TemplateDeductionInfo &Info);
6967
6968 TemplateDeductionResult
6969 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6970 TemplateArgumentListInfo *ExplicitTemplateArgs,
6971 FunctionDecl *&Specialization,
6972 sema::TemplateDeductionInfo &Info,
6973 bool IsAddressOfFunction = false);
6974
6975 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6976 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6977 /// \brief Substitute Replacement for auto in TypeWithAuto
6978 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6979 QualType Replacement);
6980 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6981 /// \p Replacement. This does not retain any \c auto type sugar.
6982 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6983
6984 /// \brief Result type of DeduceAutoType.
6985 enum DeduceAutoResult {
6986 DAR_Succeeded,
6987 DAR_Failed,
6988 DAR_FailedAlreadyDiagnosed
6989 };
6990
6991 DeduceAutoResult
6992 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6993 Optional<unsigned> DependentDeductionDepth = None);
6994 DeduceAutoResult
6995 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6996 Optional<unsigned> DependentDeductionDepth = None);
6997 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6998 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6999 bool Diagnose = true);
7000
7001 /// \brief Declare implicit deduction guides for a class template if we've
7002 /// not already done so.
7003 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7004 SourceLocation Loc);
7005
7006 QualType DeduceTemplateSpecializationFromInitializer(
7007 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7008 const InitializationKind &Kind, MultiExprArg Init);
7009
7010 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7011 QualType Type, TypeSourceInfo *TSI,
7012 SourceRange Range, bool DirectInit,
7013 Expr *Init);
7014
7015 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7016
7017 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7018 SourceLocation ReturnLoc,
7019 Expr *&RetExpr, AutoType *AT);
7020
7021 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7022 FunctionTemplateDecl *FT2,
7023 SourceLocation Loc,
7024 TemplatePartialOrderingContext TPOC,
7025 unsigned NumCallArguments1,
7026 unsigned NumCallArguments2);
7027 UnresolvedSetIterator
7028 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7029 TemplateSpecCandidateSet &FailedCandidates,
7030 SourceLocation Loc,
7031 const PartialDiagnostic &NoneDiag,
7032 const PartialDiagnostic &AmbigDiag,
7033 const PartialDiagnostic &CandidateDiag,
7034 bool Complain = true, QualType TargetType = QualType());
7035
7036 ClassTemplatePartialSpecializationDecl *
7037 getMoreSpecializedPartialSpecialization(
7038 ClassTemplatePartialSpecializationDecl *PS1,
7039 ClassTemplatePartialSpecializationDecl *PS2,
7040 SourceLocation Loc);
7041
7042 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7043 sema::TemplateDeductionInfo &Info);
7044
7045 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7046 VarTemplatePartialSpecializationDecl *PS1,
7047 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7048
7049 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7050 sema::TemplateDeductionInfo &Info);
7051
7052 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7053 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
7054
7055 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7056 bool OnlyDeduced,
7057 unsigned Depth,
7058 llvm::SmallBitVector &Used);
7059 void MarkDeducedTemplateParameters(
7060 const FunctionTemplateDecl *FunctionTemplate,
7061 llvm::SmallBitVector &Deduced) {
7062 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
7063 }
7064 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
7065 const FunctionTemplateDecl *FunctionTemplate,
7066 llvm::SmallBitVector &Deduced);
7067
7068 //===--------------------------------------------------------------------===//
7069 // C++ Template Instantiation
7070 //
7071
7072 MultiLevelTemplateArgumentList
7073 getTemplateInstantiationArgs(NamedDecl *D,
7074 const TemplateArgumentList *Innermost = nullptr,
7075 bool RelativeToPrimary = false,
7076 const FunctionDecl *Pattern = nullptr);
7077
7078 /// A context in which code is being synthesized (where a source location
7079 /// alone is not sufficient to identify the context). This covers template
7080 /// instantiation and various forms of implicitly-generated functions.
7081 struct CodeSynthesisContext {
7082 /// \brief The kind of template instantiation we are performing
7083 enum SynthesisKind {
7084 /// We are instantiating a template declaration. The entity is
7085 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7086 TemplateInstantiation,
7087
7088 /// We are instantiating a default argument for a template
7089 /// parameter. The Entity is the template parameter whose argument is
7090 /// being instantiated, the Template is the template, and the
7091 /// TemplateArgs/NumTemplateArguments provide the template arguments as
7092 /// specified.
7093 DefaultTemplateArgumentInstantiation,
7094
7095 /// We are instantiating a default argument for a function.
7096 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7097 /// provides the template arguments as specified.
7098 DefaultFunctionArgumentInstantiation,
7099
7100 /// We are substituting explicit template arguments provided for
7101 /// a function template. The entity is a FunctionTemplateDecl.
7102 ExplicitTemplateArgumentSubstitution,
7103
7104 /// We are substituting template argument determined as part of
7105 /// template argument deduction for either a class template
7106 /// partial specialization or a function template. The
7107 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7108 /// a TemplateDecl.
7109 DeducedTemplateArgumentSubstitution,
7110
7111 /// We are substituting prior template arguments into a new
7112 /// template parameter. The template parameter itself is either a
7113 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7114 PriorTemplateArgumentSubstitution,
7115
7116 /// We are checking the validity of a default template argument that
7117 /// has been used when naming a template-id.
7118 DefaultTemplateArgumentChecking,
7119
7120 /// We are instantiating the exception specification for a function
7121 /// template which was deferred until it was needed.
7122 ExceptionSpecInstantiation,
7123
7124 /// We are declaring an implicit special member function.
7125 DeclaringSpecialMember,
7126
7127 /// We are defining a synthesized function (such as a defaulted special
7128 /// member).
7129 DefiningSynthesizedFunction,
7130
7131 /// Added for Template instantiation observation.
7132 /// Memoization means we are _not_ instantiating a template because
7133 /// it is already instantiated (but we entered a context where we
7134 /// would have had to if it was not already instantiated).
7135 Memoization
7136 } Kind;
7137
7138 /// \brief Was the enclosing context a non-instantiation SFINAE context?
7139 bool SavedInNonInstantiationSFINAEContext;
7140
7141 /// \brief The point of instantiation or synthesis within the source code.
7142 SourceLocation PointOfInstantiation;
7143
7144 /// \brief The entity that is being synthesized.
7145 Decl *Entity;
7146
7147 /// \brief The template (or partial specialization) in which we are
7148 /// performing the instantiation, for substitutions of prior template
7149 /// arguments.
7150 NamedDecl *Template;
7151
7152 /// \brief The list of template arguments we are substituting, if they
7153 /// are not part of the entity.
7154 const TemplateArgument *TemplateArgs;
7155
7156 // FIXME: Wrap this union around more members, or perhaps store the
7157 // kind-specific members in the RAII object owning the context.
7158 union {
7159 /// \brief The number of template arguments in TemplateArgs.
7160 unsigned NumTemplateArgs;
7161
7162 /// \brief The special member being declared or defined.
7163 CXXSpecialMember SpecialMember;
7164 };
7165
7166 ArrayRef<TemplateArgument> template_arguments() const {
7167 assert(Kind != DeclaringSpecialMember)(static_cast <bool> (Kind != DeclaringSpecialMember) ? void
(0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 7167, __extension__ __PRETTY_FUNCTION__))
;
7168 return {TemplateArgs, NumTemplateArgs};
7169 }
7170
7171 /// \brief The template deduction info object associated with the
7172 /// substitution or checking of explicit or deduced template arguments.
7173 sema::TemplateDeductionInfo *DeductionInfo;
7174
7175 /// \brief The source range that covers the construct that cause
7176 /// the instantiation, e.g., the template-id that causes a class
7177 /// template instantiation.
7178 SourceRange InstantiationRange;
7179
7180 CodeSynthesisContext()
7181 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7182 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7183
7184 /// \brief Determines whether this template is an actual instantiation
7185 /// that should be counted toward the maximum instantiation depth.
7186 bool isInstantiationRecord() const;
7187 };
7188
7189 /// \brief List of active code synthesis contexts.
7190 ///
7191 /// This vector is treated as a stack. As synthesis of one entity requires
7192 /// synthesis of another, additional contexts are pushed onto the stack.
7193 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7194
7195 /// Specializations whose definitions are currently being instantiated.
7196 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7197
7198 /// Non-dependent types used in templates that have already been instantiated
7199 /// by some template instantiation.
7200 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7201
7202 /// \brief Extra modules inspected when performing a lookup during a template
7203 /// instantiation. Computed lazily.
7204 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7205
7206 /// \brief Cache of additional modules that should be used for name lookup
7207 /// within the current template instantiation. Computed lazily; use
7208 /// getLookupModules() to get a complete set.
7209 llvm::DenseSet<Module*> LookupModulesCache;
7210
7211 /// \brief Get the set of additional modules that should be checked during
7212 /// name lookup. A module and its imports become visible when instanting a
7213 /// template defined within it.
7214 llvm::DenseSet<Module*> &getLookupModules();
7215
7216 /// \brief Map from the most recent declaration of a namespace to the most
7217 /// recent visible declaration of that namespace.
7218 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7219
7220 /// \brief Whether we are in a SFINAE context that is not associated with
7221 /// template instantiation.
7222 ///
7223 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7224 /// of a template instantiation or template argument deduction.
7225 bool InNonInstantiationSFINAEContext;
7226
7227 /// \brief The number of \p CodeSynthesisContexts that are not template
7228 /// instantiations and, therefore, should not be counted as part of the
7229 /// instantiation depth.
7230 ///
7231 /// When the instantiation depth reaches the user-configurable limit
7232 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7233 // FIXME: Should we have a similar limit for other forms of synthesis?
7234 unsigned NonInstantiationEntries;
7235
7236 /// \brief The depth of the context stack at the point when the most recent
7237 /// error or warning was produced.
7238 ///
7239 /// This value is used to suppress printing of redundant context stacks
7240 /// when there are multiple errors or warnings in the same instantiation.
7241 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7242 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7243
7244 /// \brief The template instantiation callbacks to trace or track
7245 /// instantiations (objects can be chained).
7246 ///
7247 /// This callbacks is used to print, trace or track template
7248 /// instantiations as they are being constructed.
7249 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
7250 TemplateInstCallbacks;
7251
7252 /// \brief The current index into pack expansion arguments that will be
7253 /// used for substitution of parameter packs.
7254 ///
7255 /// The pack expansion index will be -1 to indicate that parameter packs
7256 /// should be instantiated as themselves. Otherwise, the index specifies
7257 /// which argument within the parameter pack will be used for substitution.
7258 int ArgumentPackSubstitutionIndex;
7259
7260 /// \brief RAII object used to change the argument pack substitution index
7261 /// within a \c Sema object.
7262 ///
7263 /// See \c ArgumentPackSubstitutionIndex for more information.
7264 class ArgumentPackSubstitutionIndexRAII {
7265 Sema &Self;
7266 int OldSubstitutionIndex;
7267
7268 public:
7269 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7270 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7271 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7272 }
7273
7274 ~ArgumentPackSubstitutionIndexRAII() {
7275 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7276 }
7277 };
7278
7279 friend class ArgumentPackSubstitutionRAII;
7280
7281 /// \brief For each declaration that involved template argument deduction, the
7282 /// set of diagnostics that were suppressed during that template argument
7283 /// deduction.
7284 ///
7285 /// FIXME: Serialize this structure to the AST file.
7286 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7287 SuppressedDiagnosticsMap;
7288 SuppressedDiagnosticsMap SuppressedDiagnostics;
7289
7290 /// \brief A stack object to be created when performing template
7291 /// instantiation.
7292 ///
7293 /// Construction of an object of type \c InstantiatingTemplate
7294 /// pushes the current instantiation onto the stack of active
7295 /// instantiations. If the size of this stack exceeds the maximum
7296 /// number of recursive template instantiations, construction
7297 /// produces an error and evaluates true.
7298 ///
7299 /// Destruction of this object will pop the named instantiation off
7300 /// the stack.
7301 struct InstantiatingTemplate {
7302 /// \brief Note that we are instantiating a class template,
7303 /// function template, variable template, alias template,
7304 /// or a member thereof.
7305 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7306 Decl *Entity,
7307 SourceRange InstantiationRange = SourceRange());
7308
7309 struct ExceptionSpecification {};
7310 /// \brief Note that we are instantiating an exception specification
7311 /// of a function template.
7312 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7313 FunctionDecl *Entity, ExceptionSpecification,
7314 SourceRange InstantiationRange = SourceRange());
7315
7316 /// \brief Note that we are instantiating a default argument in a
7317 /// template-id.
7318 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7319 TemplateParameter Param, TemplateDecl *Template,
7320 ArrayRef<TemplateArgument> TemplateArgs,
7321 SourceRange InstantiationRange = SourceRange());
7322
7323 /// \brief Note that we are substituting either explicitly-specified or
7324 /// deduced template arguments during function template argument deduction.
7325 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7326 FunctionTemplateDecl *FunctionTemplate,
7327 ArrayRef<TemplateArgument> TemplateArgs,
7328 CodeSynthesisContext::SynthesisKind Kind,
7329 sema::TemplateDeductionInfo &DeductionInfo,
7330 SourceRange InstantiationRange = SourceRange());
7331
7332 /// \brief Note that we are instantiating as part of template
7333 /// argument deduction for a class template declaration.
7334 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7335 TemplateDecl *Template,
7336 ArrayRef<TemplateArgument> TemplateArgs,
7337 sema::TemplateDeductionInfo &DeductionInfo,
7338 SourceRange InstantiationRange = SourceRange());
7339
7340 /// \brief Note that we are instantiating as part of template
7341 /// argument deduction for a class template partial
7342 /// specialization.
7343 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7344 ClassTemplatePartialSpecializationDecl *PartialSpec,
7345 ArrayRef<TemplateArgument> TemplateArgs,
7346 sema::TemplateDeductionInfo &DeductionInfo,
7347 SourceRange InstantiationRange = SourceRange());
7348
7349 /// \brief Note that we are instantiating as part of template
7350 /// argument deduction for a variable template partial
7351 /// specialization.
7352 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7353 VarTemplatePartialSpecializationDecl *PartialSpec,
7354 ArrayRef<TemplateArgument> TemplateArgs,
7355 sema::TemplateDeductionInfo &DeductionInfo,
7356 SourceRange InstantiationRange = SourceRange());
7357
7358 /// \brief Note that we are instantiating a default argument for a function
7359 /// parameter.
7360 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7361 ParmVarDecl *Param,
7362 ArrayRef<TemplateArgument> TemplateArgs,
7363 SourceRange InstantiationRange = SourceRange());
7364
7365 /// \brief Note that we are substituting prior template arguments into a
7366 /// non-type parameter.
7367 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7368 NamedDecl *Template,
7369 NonTypeTemplateParmDecl *Param,
7370 ArrayRef<TemplateArgument> TemplateArgs,
7371 SourceRange InstantiationRange);
7372
7373 /// \brief Note that we are substituting prior template arguments into a
7374 /// template template parameter.
7375 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7376 NamedDecl *Template,
7377 TemplateTemplateParmDecl *Param,
7378 ArrayRef<TemplateArgument> TemplateArgs,
7379 SourceRange InstantiationRange);
7380
7381 /// \brief Note that we are checking the default template argument
7382 /// against the template parameter for a given template-id.
7383 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7384 TemplateDecl *Template,
7385 NamedDecl *Param,
7386 ArrayRef<TemplateArgument> TemplateArgs,
7387 SourceRange InstantiationRange);
7388
7389
7390 /// \brief Note that we have finished instantiating this template.
7391 void Clear();
7392
7393 ~InstantiatingTemplate() { Clear(); }
7394
7395 /// \brief Determines whether we have exceeded the maximum
7396 /// recursive template instantiations.
7397 bool isInvalid() const { return Invalid; }
7398
7399 /// \brief Determine whether we are already instantiating this
7400 /// specialization in some surrounding active instantiation.
7401 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7402
7403 private:
7404 Sema &SemaRef;
7405 bool Invalid;
7406 bool AlreadyInstantiating;
7407 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7408 SourceRange InstantiationRange);
7409
7410 InstantiatingTemplate(
7411 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7412 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7413 Decl *Entity, NamedDecl *Template = nullptr,
7414 ArrayRef<TemplateArgument> TemplateArgs = None,
7415 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7416
7417 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7418
7419 InstantiatingTemplate&
7420 operator=(const InstantiatingTemplate&) = delete;
7421 };
7422
7423 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7424 void popCodeSynthesisContext();
7425
7426 /// Determine whether we are currently performing template instantiation.
7427 bool inTemplateInstantiation() const {
7428 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7429 }
7430
7431 void PrintContextStack() {
7432 if (!CodeSynthesisContexts.empty() &&
7433 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7434 PrintInstantiationStack();
7435 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7436 }
7437 if (PragmaAttributeCurrentTargetDecl)
7438 PrintPragmaAttributeInstantiationPoint();
7439 }
7440 void PrintInstantiationStack();
7441
7442 void PrintPragmaAttributeInstantiationPoint();
7443
7444 /// \brief Determines whether we are currently in a context where
7445 /// template argument substitution failures are not considered
7446 /// errors.
7447 ///
7448 /// \returns An empty \c Optional if we're not in a SFINAE context.
7449 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7450 /// template-deduction context object, which can be used to capture
7451 /// diagnostics that will be suppressed.
7452 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7453
7454 /// \brief Determines whether we are currently in a context that
7455 /// is not evaluated as per C++ [expr] p5.
7456 bool isUnevaluatedContext() const {
7457 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 7458, __extension__ __PRETTY_FUNCTION__))
7458 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 7458, __extension__ __PRETTY_FUNCTION__))
;
7459 return ExprEvalContexts.back().isUnevaluated();
7460 }
7461
7462 /// \brief RAII class used to determine whether SFINAE has
7463 /// trapped any errors that occur during template argument
7464 /// deduction.
7465 class SFINAETrap {
7466 Sema &SemaRef;
7467 unsigned PrevSFINAEErrors;
7468 bool PrevInNonInstantiationSFINAEContext;
7469 bool PrevAccessCheckingSFINAE;
7470 bool PrevLastDiagnosticIgnored;
7471
7472 public:
7473 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7474 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7475 PrevInNonInstantiationSFINAEContext(
7476 SemaRef.InNonInstantiationSFINAEContext),
7477 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
7478 PrevLastDiagnosticIgnored(
7479 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
7480 {
7481 if (!SemaRef.isSFINAEContext())
7482 SemaRef.InNonInstantiationSFINAEContext = true;
7483 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7484 }
7485
7486 ~SFINAETrap() {
7487 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7488 SemaRef.InNonInstantiationSFINAEContext
7489 = PrevInNonInstantiationSFINAEContext;
7490 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7491 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
7492 PrevLastDiagnosticIgnored);
7493 }
7494
7495 /// \brief Determine whether any SFINAE errors have been trapped.
7496 bool hasErrorOccurred() const {
7497 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7498 }
7499 };
7500
7501 /// \brief RAII class used to indicate that we are performing provisional
7502 /// semantic analysis to determine the validity of a construct, so
7503 /// typo-correction and diagnostics in the immediate context (not within
7504 /// implicitly-instantiated templates) should be suppressed.
7505 class TentativeAnalysisScope {
7506 Sema &SemaRef;
7507 // FIXME: Using a SFINAETrap for this is a hack.
7508 SFINAETrap Trap;
7509 bool PrevDisableTypoCorrection;
7510 public:
7511 explicit TentativeAnalysisScope(Sema &SemaRef)
7512 : SemaRef(SemaRef), Trap(SemaRef, true),
7513 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7514 SemaRef.DisableTypoCorrection = true;
7515 }
7516 ~TentativeAnalysisScope() {
7517 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7518 }
7519 };
7520
7521 /// \brief The current instantiation scope used to store local
7522 /// variables.
7523 LocalInstantiationScope *CurrentInstantiationScope;
7524
7525 /// \brief Tracks whether we are in a context where typo correction is
7526 /// disabled.
7527 bool DisableTypoCorrection;
7528
7529 /// \brief The number of typos corrected by CorrectTypo.
7530 unsigned TyposCorrected;
7531
7532 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7533 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7534
7535 /// \brief A cache containing identifiers for which typo correction failed and
7536 /// their locations, so that repeated attempts to correct an identifier in a
7537 /// given location are ignored if typo correction already failed for it.
7538 IdentifierSourceLocations TypoCorrectionFailures;
7539
7540 /// \brief Worker object for performing CFG-based warnings.
7541 sema::AnalysisBasedWarnings AnalysisWarnings;
7542 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7543
7544 /// \brief An entity for which implicit template instantiation is required.
7545 ///
7546 /// The source location associated with the declaration is the first place in
7547 /// the source code where the declaration was "used". It is not necessarily
7548 /// the point of instantiation (which will be either before or after the
7549 /// namespace-scope declaration that triggered this implicit instantiation),
7550 /// However, it is the location that diagnostics should generally refer to,
7551 /// because users will need to know what code triggered the instantiation.
7552 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7553
7554 /// \brief The queue of implicit template instantiations that are required
7555 /// but have not yet been performed.
7556 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7557
7558 class GlobalEagerInstantiationScope {
7559 public:
7560 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
7561 : S(S), Enabled(Enabled) {
7562 if (!Enabled) return;
7563
7564 SavedPendingInstantiations.swap(S.PendingInstantiations);
7565 SavedVTableUses.swap(S.VTableUses);
7566 }
7567
7568 void perform() {
7569 if (Enabled) {
7570 S.DefineUsedVTables();
7571 S.PerformPendingInstantiations();
7572 }
7573 }
7574
7575 ~GlobalEagerInstantiationScope() {
7576 if (!Enabled) return;
7577
7578 // Restore the set of pending vtables.
7579 assert(S.VTableUses.empty() &&(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 7580, __extension__ __PRETTY_FUNCTION__))
7580 "VTableUses should be empty before it is discarded.")(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 7580, __extension__ __PRETTY_FUNCTION__))
;
7581 S.VTableUses.swap(SavedVTableUses);
7582
7583 // Restore the set of pending implicit instantiations.
7584 assert(S.PendingInstantiations.empty() &&(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 7585, __extension__ __PRETTY_FUNCTION__))
7585 "PendingInstantiations should be empty before it is discarded.")(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 7585, __extension__ __PRETTY_FUNCTION__))
;
7586 S.PendingInstantiations.swap(SavedPendingInstantiations);
7587 }
7588
7589 private:
7590 Sema &S;
7591 SmallVector<VTableUse, 16> SavedVTableUses;
7592 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7593 bool Enabled;
7594 };
7595
7596 /// \brief The queue of implicit template instantiations that are required
7597 /// and must be performed within the current local scope.
7598 ///
7599 /// This queue is only used for member functions of local classes in
7600 /// templates, which must be instantiated in the same scope as their
7601 /// enclosing function, so that they can reference function-local
7602 /// types, static variables, enumerators, etc.
7603 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7604
7605 class LocalEagerInstantiationScope {
7606 public:
7607 LocalEagerInstantiationScope(Sema &S) : S(S) {
7608 SavedPendingLocalImplicitInstantiations.swap(
7609 S.PendingLocalImplicitInstantiations);
7610 }
7611
7612 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
7613
7614 ~LocalEagerInstantiationScope() {
7615 assert(S.PendingLocalImplicitInstantiations.empty() &&(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 7616, __extension__ __PRETTY_FUNCTION__))
7616 "there shouldn't be any pending local implicit instantiations")(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 7616, __extension__ __PRETTY_FUNCTION__))
;
7617 SavedPendingLocalImplicitInstantiations.swap(
7618 S.PendingLocalImplicitInstantiations);
7619 }
7620
7621 private:
7622 Sema &S;
7623 std::deque<PendingImplicitInstantiation>
7624 SavedPendingLocalImplicitInstantiations;
7625 };
7626
7627 /// A helper class for building up ExtParameterInfos.
7628 class ExtParameterInfoBuilder {
7629 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7630 bool HasInteresting = false;
7631
7632 public:
7633 /// Set the ExtParameterInfo for the parameter at the given index,
7634 ///
7635 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7636 assert(Infos.size() <= index)(static_cast <bool> (Infos.size() <= index) ? void (
0) : __assert_fail ("Infos.size() <= index", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 7636, __extension__ __PRETTY_FUNCTION__))
;
7637 Infos.resize(index);
7638 Infos.push_back(info);
7639
7640 if (!HasInteresting)
7641 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7642 }
7643
7644 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7645 /// ExtParameterInfo array we've built up.
7646 const FunctionProtoType::ExtParameterInfo *
7647 getPointerOrNull(unsigned numParams) {
7648 if (!HasInteresting) return nullptr;
7649 Infos.resize(numParams);
7650 return Infos.data();
7651 }
7652 };
7653
7654 void PerformPendingInstantiations(bool LocalOnly = false);
7655
7656 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7657 const MultiLevelTemplateArgumentList &TemplateArgs,
7658 SourceLocation Loc, DeclarationName Entity,
7659 bool AllowDeducedTST = false);
7660
7661 QualType SubstType(QualType T,
7662 const MultiLevelTemplateArgumentList &TemplateArgs,
7663 SourceLocation Loc, DeclarationName Entity);
7664
7665 TypeSourceInfo *SubstType(TypeLoc TL,
7666 const MultiLevelTemplateArgumentList &TemplateArgs,
7667 SourceLocation Loc, DeclarationName Entity);
7668
7669 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7670 const MultiLevelTemplateArgumentList &TemplateArgs,
7671 SourceLocation Loc,
7672 DeclarationName Entity,
7673 CXXRecordDecl *ThisContext,
7674 unsigned ThisTypeQuals);
7675 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7676 const MultiLevelTemplateArgumentList &Args);
7677 bool SubstExceptionSpec(SourceLocation Loc,
7678 FunctionProtoType::ExceptionSpecInfo &ESI,
7679 SmallVectorImpl<QualType> &ExceptionStorage,
7680 const MultiLevelTemplateArgumentList &Args);
7681 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7682 const MultiLevelTemplateArgumentList &TemplateArgs,
7683 int indexAdjustment,
7684 Optional<unsigned> NumExpansions,
7685 bool ExpectParameterPack);
7686 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7687 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7688 const MultiLevelTemplateArgumentList &TemplateArgs,
7689 SmallVectorImpl<QualType> &ParamTypes,
7690 SmallVectorImpl<ParmVarDecl *> *OutParams,
7691 ExtParameterInfoBuilder &ParamInfos);
7692 ExprResult SubstExpr(Expr *E,
7693 const MultiLevelTemplateArgumentList &TemplateArgs);
7694
7695 /// \brief Substitute the given template arguments into a list of
7696 /// expressions, expanding pack expansions if required.
7697 ///
7698 /// \param Exprs The list of expressions to substitute into.
7699 ///
7700 /// \param IsCall Whether this is some form of call, in which case
7701 /// default arguments will be dropped.
7702 ///
7703 /// \param TemplateArgs The set of template arguments to substitute.
7704 ///
7705 /// \param Outputs Will receive all of the substituted arguments.
7706 ///
7707 /// \returns true if an error occurred, false otherwise.
7708 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7709 const MultiLevelTemplateArgumentList &TemplateArgs,
7710 SmallVectorImpl<Expr *> &Outputs);
7711
7712 StmtResult SubstStmt(Stmt *S,
7713 const MultiLevelTemplateArgumentList &TemplateArgs);
7714
7715 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7716 const MultiLevelTemplateArgumentList &TemplateArgs);
7717
7718 ExprResult SubstInitializer(Expr *E,
7719 const MultiLevelTemplateArgumentList &TemplateArgs,
7720 bool CXXDirectInit);
7721
7722 bool
7723 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7724 CXXRecordDecl *Pattern,
7725 const MultiLevelTemplateArgumentList &TemplateArgs);
7726
7727 bool
7728 InstantiateClass(SourceLocation PointOfInstantiation,
7729 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7730 const MultiLevelTemplateArgumentList &TemplateArgs,
7731 TemplateSpecializationKind TSK,
7732 bool Complain = true);
7733
7734 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7735 EnumDecl *Instantiation, EnumDecl *Pattern,
7736 const MultiLevelTemplateArgumentList &TemplateArgs,
7737 TemplateSpecializationKind TSK);
7738
7739 bool InstantiateInClassInitializer(
7740 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7741 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7742
7743 struct LateInstantiatedAttribute {
7744 const Attr *TmplAttr;
7745 LocalInstantiationScope *Scope;
7746 Decl *NewDecl;
7747
7748 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7749 Decl *D)
7750 : TmplAttr(A), Scope(S), NewDecl(D)
7751 { }
7752 };
7753 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7754
7755 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7756 const Decl *Pattern, Decl *Inst,
7757 LateInstantiatedAttrVec *LateAttrs = nullptr,
7758 LocalInstantiationScope *OuterMostScope = nullptr);
7759
7760 void
7761 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7762 const Decl *Pattern, Decl *Inst,
7763 LateInstantiatedAttrVec *LateAttrs = nullptr,
7764 LocalInstantiationScope *OuterMostScope = nullptr);
7765
7766 bool usesPartialOrExplicitSpecialization(
7767 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
7768
7769 bool
7770 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7771 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7772 TemplateSpecializationKind TSK,
7773 bool Complain = true);
7774
7775 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7776 CXXRecordDecl *Instantiation,
7777 const MultiLevelTemplateArgumentList &TemplateArgs,
7778 TemplateSpecializationKind TSK);
7779
7780 void InstantiateClassTemplateSpecializationMembers(
7781 SourceLocation PointOfInstantiation,
7782 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7783 TemplateSpecializationKind TSK);
7784
7785 NestedNameSpecifierLoc
7786 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7787 const MultiLevelTemplateArgumentList &TemplateArgs);
7788
7789 DeclarationNameInfo
7790 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7791 const MultiLevelTemplateArgumentList &TemplateArgs);
7792 TemplateName
7793 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7794 SourceLocation Loc,
7795 const MultiLevelTemplateArgumentList &TemplateArgs);
7796 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7797 TemplateArgumentListInfo &Result,
7798 const MultiLevelTemplateArgumentList &TemplateArgs);
7799
7800 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7801 FunctionDecl *Function);
7802 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
7803 const TemplateArgumentList *Args,
7804 SourceLocation Loc);
7805 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7806 FunctionDecl *Function,
7807 bool Recursive = false,
7808 bool DefinitionRequired = false,
7809 bool AtEndOfTU = false);
7810 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7811 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7812 const TemplateArgumentList &TemplateArgList,
7813 const TemplateArgumentListInfo &TemplateArgsInfo,
7814 SmallVectorImpl<TemplateArgument> &Converted,
7815 SourceLocation PointOfInstantiation, void *InsertPos,
7816 LateInstantiatedAttrVec *LateAttrs = nullptr,
7817 LocalInstantiationScope *StartingScope = nullptr);
7818 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7819 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7820 const MultiLevelTemplateArgumentList &TemplateArgs);
7821 void
7822 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7823 const MultiLevelTemplateArgumentList &TemplateArgs,
7824 LateInstantiatedAttrVec *LateAttrs,
7825 DeclContext *Owner,
7826 LocalInstantiationScope *StartingScope,
7827 bool InstantiatingVarTemplate = false);
7828 void InstantiateVariableInitializer(
7829 VarDecl *Var, VarDecl *OldVar,
7830 const MultiLevelTemplateArgumentList &TemplateArgs);
7831 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7832 VarDecl *Var, bool Recursive = false,
7833 bool DefinitionRequired = false,
7834 bool AtEndOfTU = false);
7835
7836 void InstantiateMemInitializers(CXXConstructorDecl *New,
7837 const CXXConstructorDecl *Tmpl,
7838 const MultiLevelTemplateArgumentList &TemplateArgs);
7839
7840 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7841 const MultiLevelTemplateArgumentList &TemplateArgs,
7842 bool FindingInstantiatedContext = false);
7843 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7844 const MultiLevelTemplateArgumentList &TemplateArgs);
7845
7846 // Objective-C declarations.
7847 enum ObjCContainerKind {
7848 OCK_None = -1,
7849 OCK_Interface = 0,
7850 OCK_Protocol,
7851 OCK_Category,
7852 OCK_ClassExtension,
7853 OCK_Implementation,
7854 OCK_CategoryImplementation
7855 };
7856 ObjCContainerKind getObjCContainerKind() const;
7857
7858 DeclResult actOnObjCTypeParam(Scope *S,
7859 ObjCTypeParamVariance variance,
7860 SourceLocation varianceLoc,
7861 unsigned index,
7862 IdentifierInfo *paramName,
7863 SourceLocation paramLoc,
7864 SourceLocation colonLoc,
7865 ParsedType typeBound);
7866
7867 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7868 ArrayRef<Decl *> typeParams,
7869 SourceLocation rAngleLoc);
7870 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7871
7872 Decl *ActOnStartClassInterface(Scope *S,
7873 SourceLocation AtInterfaceLoc,
7874 IdentifierInfo *ClassName,
7875 SourceLocation ClassLoc,
7876 ObjCTypeParamList *typeParamList,
7877 IdentifierInfo *SuperName,
7878 SourceLocation SuperLoc,
7879 ArrayRef<ParsedType> SuperTypeArgs,
7880 SourceRange SuperTypeArgsRange,
7881 Decl * const *ProtoRefs,
7882 unsigned NumProtoRefs,
7883 const SourceLocation *ProtoLocs,
7884 SourceLocation EndProtoLoc,
7885 AttributeList *AttrList);
7886
7887 void ActOnSuperClassOfClassInterface(Scope *S,
7888 SourceLocation AtInterfaceLoc,
7889 ObjCInterfaceDecl *IDecl,
7890 IdentifierInfo *ClassName,
7891 SourceLocation ClassLoc,
7892 IdentifierInfo *SuperName,
7893 SourceLocation SuperLoc,
7894 ArrayRef<ParsedType> SuperTypeArgs,
7895 SourceRange SuperTypeArgsRange);
7896
7897 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7898 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7899 IdentifierInfo *SuperName,
7900 SourceLocation SuperLoc);
7901
7902 Decl *ActOnCompatibilityAlias(
7903 SourceLocation AtCompatibilityAliasLoc,
7904 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7905 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7906
7907 bool CheckForwardProtocolDeclarationForCircularDependency(
7908 IdentifierInfo *PName,
7909 SourceLocation &PLoc, SourceLocation PrevLoc,
7910 const ObjCList<ObjCProtocolDecl> &PList);
7911
7912 Decl *ActOnStartProtocolInterface(
7913 SourceLocation AtProtoInterfaceLoc,
7914 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7915 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7916 const SourceLocation *ProtoLocs,
7917 SourceLocation EndProtoLoc,
7918 AttributeList *AttrList);
7919
7920 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7921 IdentifierInfo *ClassName,
7922 SourceLocation ClassLoc,
7923 ObjCTypeParamList *typeParamList,
7924 IdentifierInfo *CategoryName,
7925 SourceLocation CategoryLoc,
7926 Decl * const *ProtoRefs,
7927 unsigned NumProtoRefs,
7928 const SourceLocation *ProtoLocs,
7929 SourceLocation EndProtoLoc,
7930 AttributeList *AttrList);
7931
7932 Decl *ActOnStartClassImplementation(
7933 SourceLocation AtClassImplLoc,
7934 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7935 IdentifierInfo *SuperClassname,
7936 SourceLocation SuperClassLoc);
7937
7938 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7939 IdentifierInfo *ClassName,
7940 SourceLocation ClassLoc,
7941 IdentifierInfo *CatName,
7942 SourceLocation CatLoc);
7943
7944 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7945 ArrayRef<Decl *> Decls);
7946
7947 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7948 IdentifierInfo **IdentList,
7949 SourceLocation *IdentLocs,
7950 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7951 unsigned NumElts);
7952
7953 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7954 ArrayRef<IdentifierLocPair> IdentList,
7955 AttributeList *attrList);
7956
7957 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7958 ArrayRef<IdentifierLocPair> ProtocolId,
7959 SmallVectorImpl<Decl *> &Protocols);
7960
7961 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7962 SourceLocation ProtocolLoc,
7963 IdentifierInfo *TypeArgId,
7964 SourceLocation TypeArgLoc,
7965 bool SelectProtocolFirst = false);
7966
7967 /// Given a list of identifiers (and their locations), resolve the
7968 /// names to either Objective-C protocol qualifiers or type
7969 /// arguments, as appropriate.
7970 void actOnObjCTypeArgsOrProtocolQualifiers(
7971 Scope *S,
7972 ParsedType baseType,
7973 SourceLocation lAngleLoc,
7974 ArrayRef<IdentifierInfo *> identifiers,
7975 ArrayRef<SourceLocation> identifierLocs,
7976 SourceLocation rAngleLoc,
7977 SourceLocation &typeArgsLAngleLoc,
7978 SmallVectorImpl<ParsedType> &typeArgs,
7979 SourceLocation &typeArgsRAngleLoc,
7980 SourceLocation &protocolLAngleLoc,
7981 SmallVectorImpl<Decl *> &protocols,
7982 SourceLocation &protocolRAngleLoc,
7983 bool warnOnIncompleteProtocols);
7984
7985 /// Build a an Objective-C protocol-qualified 'id' type where no
7986 /// base type was specified.
7987 TypeResult actOnObjCProtocolQualifierType(
7988 SourceLocation lAngleLoc,
7989 ArrayRef<Decl *> protocols,
7990 ArrayRef<SourceLocation> protocolLocs,
7991 SourceLocation rAngleLoc);
7992
7993 /// Build a specialized and/or protocol-qualified Objective-C type.
7994 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7995 Scope *S,
7996 SourceLocation Loc,
7997 ParsedType BaseType,
7998 SourceLocation TypeArgsLAngleLoc,
7999 ArrayRef<ParsedType> TypeArgs,
8000 SourceLocation TypeArgsRAngleLoc,
8001 SourceLocation ProtocolLAngleLoc,
8002 ArrayRef<Decl *> Protocols,
8003 ArrayRef<SourceLocation> ProtocolLocs,
8004 SourceLocation ProtocolRAngleLoc);
8005
8006 /// Build an Objective-C type parameter type.
8007 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
8008 SourceLocation ProtocolLAngleLoc,
8009 ArrayRef<ObjCProtocolDecl *> Protocols,
8010 ArrayRef<SourceLocation> ProtocolLocs,
8011 SourceLocation ProtocolRAngleLoc,
8012 bool FailOnError = false);
8013
8014 /// Build an Objective-C object pointer type.
8015 QualType BuildObjCObjectType(QualType BaseType,
8016 SourceLocation Loc,
8017 SourceLocation TypeArgsLAngleLoc,
8018 ArrayRef<TypeSourceInfo *> TypeArgs,
8019 SourceLocation TypeArgsRAngleLoc,
8020 SourceLocation ProtocolLAngleLoc,
8021 ArrayRef<ObjCProtocolDecl *> Protocols,
8022 ArrayRef<SourceLocation> ProtocolLocs,
8023 SourceLocation ProtocolRAngleLoc,
8024 bool FailOnError = false);
8025
8026 /// Check the application of the Objective-C '__kindof' qualifier to
8027 /// the given type.
8028 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
8029
8030 /// Ensure attributes are consistent with type.
8031 /// \param [in, out] Attributes The attributes to check; they will
8032 /// be modified to be consistent with \p PropertyTy.
8033 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
8034 SourceLocation Loc,
8035 unsigned &Attributes,
8036 bool propertyInPrimaryClass);
8037
8038 /// Process the specified property declaration and create decls for the
8039 /// setters and getters as needed.
8040 /// \param property The property declaration being processed
8041 void ProcessPropertyDecl(ObjCPropertyDecl *property);
8042
8043
8044 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
8045 ObjCPropertyDecl *SuperProperty,
8046 const IdentifierInfo *Name,
8047 bool OverridingProtocolProperty);
8048
8049 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
8050 ObjCInterfaceDecl *ID);
8051
8052 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
8053 ArrayRef<Decl *> allMethods = None,
8054 ArrayRef<DeclGroupPtrTy> allTUVars = None);
8055
8056 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
8057 SourceLocation LParenLoc,
8058 FieldDeclarator &FD, ObjCDeclSpec &ODS,
8059 Selector GetterSel, Selector SetterSel,
8060 tok::ObjCKeywordKind MethodImplKind,
8061 DeclContext *lexicalDC = nullptr);
8062
8063 Decl *ActOnPropertyImplDecl(Scope *S,
8064 SourceLocation AtLoc,
8065 SourceLocation PropertyLoc,
8066 bool ImplKind,
8067 IdentifierInfo *PropertyId,
8068 IdentifierInfo *PropertyIvar,
8069 SourceLocation PropertyIvarLoc,
8070 ObjCPropertyQueryKind QueryKind);
8071
8072 enum ObjCSpecialMethodKind {
8073 OSMK_None,
8074 OSMK_Alloc,
8075 OSMK_New,
8076 OSMK_Copy,
8077 OSMK_RetainingInit,
8078 OSMK_NonRetainingInit
8079 };
8080
8081 struct ObjCArgInfo {
8082 IdentifierInfo *Name;
8083 SourceLocation NameLoc;
8084 // The Type is null if no type was specified, and the DeclSpec is invalid
8085 // in this case.
8086 ParsedType Type;
8087 ObjCDeclSpec DeclSpec;
8088
8089 /// ArgAttrs - Attribute list for this argument.
8090 AttributeList *ArgAttrs;
8091 };
8092
8093 Decl *ActOnMethodDeclaration(
8094 Scope *S,
8095 SourceLocation BeginLoc, // location of the + or -.
8096 SourceLocation EndLoc, // location of the ; or {.
8097 tok::TokenKind MethodType,
8098 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
8099 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
8100 // optional arguments. The number of types/arguments is obtained
8101 // from the Sel.getNumArgs().
8102 ObjCArgInfo *ArgInfo,
8103 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
8104 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
8105 bool isVariadic, bool MethodDefinition);
8106
8107 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8108 const ObjCObjectPointerType *OPT,
8109 bool IsInstance);
8110 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8111 bool IsInstance);
8112
8113 bool CheckARCMethodDecl(ObjCMethodDecl *method);
8114 bool inferObjCARCLifetime(ValueDecl *decl);
8115
8116 ExprResult
8117 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8118 Expr *BaseExpr,
8119 SourceLocation OpLoc,
8120 DeclarationName MemberName,
8121 SourceLocation MemberLoc,
8122 SourceLocation SuperLoc, QualType SuperType,
8123 bool Super);
8124
8125 ExprResult
8126 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8127 IdentifierInfo &propertyName,
8128 SourceLocation receiverNameLoc,
8129 SourceLocation propertyNameLoc);
8130
8131 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8132
8133 /// \brief Describes the kind of message expression indicated by a message
8134 /// send that starts with an identifier.
8135 enum ObjCMessageKind {
8136 /// \brief The message is sent to 'super'.
8137 ObjCSuperMessage,
8138 /// \brief The message is an instance message.
8139 ObjCInstanceMessage,
8140 /// \brief The message is a class message, and the identifier is a type
8141 /// name.
8142 ObjCClassMessage
8143 };
8144
8145 ObjCMessageKind getObjCMessageKind(Scope *S,
8146 IdentifierInfo *Name,
8147 SourceLocation NameLoc,
8148 bool IsSuper,
8149 bool HasTrailingDot,
8150 ParsedType &ReceiverType);
8151
8152 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8153 Selector Sel,
8154 SourceLocation LBracLoc,
8155 ArrayRef<SourceLocation> SelectorLocs,
8156 SourceLocation RBracLoc,
8157 MultiExprArg Args);
8158
8159 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8160 QualType ReceiverType,
8161 SourceLocation SuperLoc,
8162 Selector Sel,
8163 ObjCMethodDecl *Method,
8164 SourceLocation LBracLoc,
8165 ArrayRef<SourceLocation> SelectorLocs,
8166 SourceLocation RBracLoc,
8167 MultiExprArg Args,
8168 bool isImplicit = false);
8169
8170 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8171 bool isSuperReceiver,
8172 SourceLocation Loc,
8173 Selector Sel,
8174 ObjCMethodDecl *Method,
8175 MultiExprArg Args);
8176
8177 ExprResult ActOnClassMessage(Scope *S,
8178 ParsedType Receiver,
8179 Selector Sel,
8180 SourceLocation LBracLoc,
8181 ArrayRef<SourceLocation> SelectorLocs,
8182 SourceLocation RBracLoc,
8183 MultiExprArg Args);
8184
8185 ExprResult BuildInstanceMessage(Expr *Receiver,
8186 QualType ReceiverType,
8187 SourceLocation SuperLoc,
8188 Selector Sel,
8189 ObjCMethodDecl *Method,
8190 SourceLocation LBracLoc,
8191 ArrayRef<SourceLocation> SelectorLocs,
8192 SourceLocation RBracLoc,
8193 MultiExprArg Args,
8194 bool isImplicit = false);
8195
8196 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8197 QualType ReceiverType,
8198 SourceLocation Loc,
8199 Selector Sel,
8200 ObjCMethodDecl *Method,
8201 MultiExprArg Args);
8202
8203 ExprResult ActOnInstanceMessage(Scope *S,
8204 Expr *Receiver,
8205 Selector Sel,
8206 SourceLocation LBracLoc,
8207 ArrayRef<SourceLocation> SelectorLocs,
8208 SourceLocation RBracLoc,
8209 MultiExprArg Args);
8210
8211 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8212 ObjCBridgeCastKind Kind,
8213 SourceLocation BridgeKeywordLoc,
8214 TypeSourceInfo *TSInfo,
8215 Expr *SubExpr);
8216
8217 ExprResult ActOnObjCBridgedCast(Scope *S,
8218 SourceLocation LParenLoc,
8219 ObjCBridgeCastKind Kind,
8220 SourceLocation BridgeKeywordLoc,
8221 ParsedType Type,
8222 SourceLocation RParenLoc,
8223 Expr *SubExpr);
8224
8225 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8226
8227 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8228
8229 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8230 CastKind &Kind);
8231
8232 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8233 QualType DestType, QualType SrcType,
8234 ObjCInterfaceDecl *&RelatedClass,
8235 ObjCMethodDecl *&ClassMethod,
8236 ObjCMethodDecl *&InstanceMethod,
8237 TypedefNameDecl *&TDNDecl,
8238 bool CfToNs, bool Diagnose = true);
8239
8240 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8241 QualType DestType, QualType SrcType,
8242 Expr *&SrcExpr, bool Diagnose = true);
8243
8244 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8245 bool Diagnose = true);
8246
8247 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8248
8249 /// \brief Check whether the given new method is a valid override of the
8250 /// given overridden method, and set any properties that should be inherited.
8251 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8252 const ObjCMethodDecl *Overridden);
8253
8254 /// \brief Describes the compatibility of a result type with its method.
8255 enum ResultTypeCompatibilityKind {
8256 RTC_Compatible,
8257 RTC_Incompatible,
8258 RTC_Unknown
8259 };
8260
8261 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8262 ObjCInterfaceDecl *CurrentClass,
8263 ResultTypeCompatibilityKind RTC);
8264
8265 enum PragmaOptionsAlignKind {
8266 POAK_Native, // #pragma options align=native
8267 POAK_Natural, // #pragma options align=natural
8268 POAK_Packed, // #pragma options align=packed
8269 POAK_Power, // #pragma options align=power
8270 POAK_Mac68k, // #pragma options align=mac68k
8271 POAK_Reset // #pragma options align=reset
8272 };
8273
8274 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8275 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8276 PragmaClangSectionAction Action,
8277 PragmaClangSectionKind SecKind, StringRef SecName);
8278
8279 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8280 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8281 SourceLocation PragmaLoc);
8282
8283 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8284 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8285 StringRef SlotLabel, Expr *Alignment);
8286
8287 enum class PragmaPackDiagnoseKind {
8288 NonDefaultStateAtInclude,
8289 ChangedStateAtExit
8290 };
8291
8292 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
8293 SourceLocation IncludeLoc);
8294 void DiagnoseUnterminatedPragmaPack();
8295
8296 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8297 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8298
8299 /// ActOnPragmaMSComment - Called on well formed
8300 /// \#pragma comment(kind, "arg").
8301 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8302 StringRef Arg);
8303
8304 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8305 /// pointers_to_members(representation method[, general purpose
8306 /// representation]).
8307 void ActOnPragmaMSPointersToMembers(
8308 LangOptions::PragmaMSPointersToMembersKind Kind,
8309 SourceLocation PragmaLoc);
8310
8311 /// \brief Called on well formed \#pragma vtordisp().
8312 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8313 SourceLocation PragmaLoc,
8314 MSVtorDispAttr::Mode Value);
8315
8316 enum PragmaSectionKind {
8317 PSK_DataSeg,
8318 PSK_BSSSeg,
8319 PSK_ConstSeg,
8320 PSK_CodeSeg,
8321 };
8322
8323 bool UnifySection(StringRef SectionName,
8324 int SectionFlags,
8325 DeclaratorDecl *TheDecl);
8326 bool UnifySection(StringRef SectionName,
8327 int SectionFlags,
8328 SourceLocation PragmaSectionLocation);
8329
8330 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8331 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8332 PragmaMsStackAction Action,
8333 llvm::StringRef StackSlotLabel,
8334 StringLiteral *SegmentName,
8335 llvm::StringRef PragmaName);
8336
8337 /// \brief Called on well formed \#pragma section().
8338 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8339 int SectionFlags, StringLiteral *SegmentName);
8340
8341 /// \brief Called on well-formed \#pragma init_seg().
8342 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8343 StringLiteral *SegmentName);
8344
8345 /// \brief Called on #pragma clang __debug dump II
8346 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8347
8348 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8349 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8350 StringRef Value);
8351
8352 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8353 void ActOnPragmaUnused(const Token &Identifier,
8354 Scope *curScope,
8355 SourceLocation PragmaLoc);
8356
8357 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8358 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8359 SourceLocation PragmaLoc);
8360
8361 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8362 SourceLocation Loc);
8363 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8364
8365 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8366 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8367 SourceLocation PragmaLoc,
8368 SourceLocation WeakNameLoc);
8369
8370 /// ActOnPragmaRedefineExtname - Called on well formed
8371 /// \#pragma redefine_extname oldname newname.
8372 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8373 IdentifierInfo* AliasName,
8374 SourceLocation PragmaLoc,
8375 SourceLocation WeakNameLoc,
8376 SourceLocation AliasNameLoc);
8377
8378 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8379 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8380 IdentifierInfo* AliasName,
8381 SourceLocation PragmaLoc,
8382 SourceLocation WeakNameLoc,
8383 SourceLocation AliasNameLoc);
8384
8385 /// ActOnPragmaFPContract - Called on well formed
8386 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8387 /// \#pragma clang fp contract
8388 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8389
8390 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8391 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8392 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8393
8394 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8395 void AddMsStructLayoutForRecord(RecordDecl *RD);
8396
8397 /// FreePackedContext - Deallocate and null out PackContext.
8398 void FreePackedContext();
8399
8400 /// PushNamespaceVisibilityAttr - Note that we've entered a
8401 /// namespace with a visibility attribute.
8402 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8403 SourceLocation Loc);
8404
8405 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8406 /// add an appropriate visibility attribute.
8407 void AddPushedVisibilityAttribute(Decl *RD);
8408
8409 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8410 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8411 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8412
8413 /// FreeVisContext - Deallocate and null out VisContext.
8414 void FreeVisContext();
8415
8416 /// AddCFAuditedAttribute - Check whether we're currently within
8417 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8418 /// the appropriate attribute.
8419 void AddCFAuditedAttribute(Decl *D);
8420
8421 /// \brief Called on well-formed '\#pragma clang attribute push'.
8422 void ActOnPragmaAttributePush(AttributeList &Attribute,
8423 SourceLocation PragmaLoc,
8424 attr::ParsedSubjectMatchRuleSet Rules);
8425
8426 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8427 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8428
8429 /// \brief Adds the attributes that have been specified using the
8430 /// '\#pragma clang attribute push' directives to the given declaration.
8431 void AddPragmaAttributes(Scope *S, Decl *D);
8432
8433 void DiagnoseUnterminatedPragmaAttribute();
8434
8435 /// \brief Called on well formed \#pragma clang optimize.
8436 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8437
8438 /// \brief Get the location for the currently active "\#pragma clang optimize
8439 /// off". If this location is invalid, then the state of the pragma is "on".
8440 SourceLocation getOptimizeOffPragmaLocation() const {
8441 return OptimizeOffPragmaLocation;
8442 }
8443
8444 /// \brief Only called on function definitions; if there is a pragma in scope
8445 /// with the effect of a range-based optnone, consider marking the function
8446 /// with attribute optnone.
8447 void AddRangeBasedOptnone(FunctionDecl *FD);
8448
8449 /// \brief Adds the 'optnone' attribute to the function declaration if there
8450 /// are no conflicts; Loc represents the location causing the 'optnone'
8451 /// attribute to be added (usually because of a pragma).
8452 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8453
8454 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8455 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8456 unsigned SpellingListIndex, bool IsPackExpansion);
8457 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8458 unsigned SpellingListIndex, bool IsPackExpansion);
8459
8460 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8461 /// declaration.
8462 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8463 unsigned SpellingListIndex);
8464
8465 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8466 /// declaration.
8467 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8468 unsigned SpellingListIndex);
8469
8470 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8471 /// declaration.
8472 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8473 unsigned SpellingListIndex);
8474
8475 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8476 /// declaration.
8477 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8478 Expr *MinBlocks, unsigned SpellingListIndex);
8479
8480 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8481 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8482 unsigned SpellingListIndex, bool InInstantiation = false);
8483
8484 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8485 ParameterABI ABI, unsigned SpellingListIndex);
8486
8487 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8488 unsigned SpellingListIndex, bool isNSConsumed,
8489 bool isTemplateInstantiation);
8490
8491 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
8492
8493 //===--------------------------------------------------------------------===//
8494 // C++ Coroutines TS
8495 //
8496 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
8497 StringRef Keyword);
8498 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8499 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8500 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8501
8502 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8503 bool IsImplicit = false);
8504 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8505 UnresolvedLookupExpr* Lookup);
8506 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8507 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8508 bool IsImplicit = false);
8509 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8510 bool buildCoroutineParameterMoves(SourceLocation Loc);
8511 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8512 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8513
8514 //===--------------------------------------------------------------------===//
8515 // OpenCL extensions.
8516 //
8517private:
8518 std::string CurrOpenCLExtension;
8519 /// Extensions required by an OpenCL type.
8520 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8521 /// Extensions required by an OpenCL declaration.
8522 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8523public:
8524 llvm::StringRef getCurrentOpenCLExtension() const {
8525 return CurrOpenCLExtension;
8526 }
8527 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8528 CurrOpenCLExtension = Ext;
8529 }
8530
8531 /// \brief Set OpenCL extensions for a type which can only be used when these
8532 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8533 /// \param Exts A space separated list of OpenCL extensions.
8534 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8535
8536 /// \brief Set OpenCL extensions for a declaration which can only be
8537 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8538 /// nothing.
8539 /// \param Exts A space separated list of OpenCL extensions.
8540 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8541
8542 /// \brief Set current OpenCL extensions for a type which can only be used
8543 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8544 /// empty, do nothing.
8545 void setCurrentOpenCLExtensionForType(QualType T);
8546
8547 /// \brief Set current OpenCL extensions for a declaration which
8548 /// can only be used when these OpenCL extensions are enabled. If current
8549 /// OpenCL extension is empty, do nothing.
8550 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8551
8552 bool isOpenCLDisabledDecl(Decl *FD);
8553
8554 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8555 /// is disabled due to required OpenCL extensions being disabled. If so,
8556 /// emit diagnostics.
8557 /// \return true if type is disabled.
8558 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8559
8560 /// \brief Check if declaration \p D used by expression \p E
8561 /// is disabled due to required OpenCL extensions being disabled. If so,
8562 /// emit diagnostics.
8563 /// \return true if type is disabled.
8564 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
8565
8566 //===--------------------------------------------------------------------===//
8567 // OpenMP directives and clauses.
8568 //
8569private:
8570 void *VarDataSharingAttributesStack;
8571 /// Set to true inside '#pragma omp declare target' region.
8572 bool IsInOpenMPDeclareTargetContext = false;
8573 /// \brief Initialization of data-sharing attributes stack.
8574 void InitDataSharingAttributesStack();
8575 void DestroyDataSharingAttributesStack();
8576 ExprResult
8577 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8578 bool StrictlyPositive = true);
8579 /// Returns OpenMP nesting level for current directive.
8580 unsigned getOpenMPNestingLevel() const;
8581
8582 /// Adjusts the function scopes index for the target-based regions.
8583 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
8584 unsigned Level) const;
8585
8586 /// Push new OpenMP function region for non-capturing function.
8587 void pushOpenMPFunctionRegion();
8588
8589 /// Pop OpenMP function region for non-capturing function.
8590 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8591
8592 /// Checks if a type or a declaration is disabled due to the owning extension
8593 /// being disabled, and emits diagnostic messages if it is disabled.
8594 /// \param D type or declaration to be checked.
8595 /// \param DiagLoc source location for the diagnostic message.
8596 /// \param DiagInfo information to be emitted for the diagnostic message.
8597 /// \param SrcRange source range of the declaration.
8598 /// \param Map maps type or declaration to the extensions.
8599 /// \param Selector selects diagnostic message: 0 for type and 1 for
8600 /// declaration.
8601 /// \return true if the type or declaration is disabled.
8602 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8603 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8604 MapT &Map, unsigned Selector = 0,
8605 SourceRange SrcRange = SourceRange());
8606
8607public:
8608 /// \brief Return true if the provided declaration \a VD should be captured by
8609 /// reference.
8610 /// \param Level Relative level of nested OpenMP construct for that the check
8611 /// is performed.
8612 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8613
8614 /// \brief Check if the specified variable is used in one of the private
8615 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8616 /// constructs.
8617 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8618 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8619 ExprObjectKind OK, SourceLocation Loc);
8620
8621 /// \brief Check if the specified variable is used in 'private' clause.
8622 /// \param Level Relative level of nested OpenMP construct for that the check
8623 /// is performed.
8624 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8625
8626 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
8627 /// for \p FD based on DSA for the provided corresponding captured declaration
8628 /// \p D.
8629 void setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level);
8630
8631 /// \brief Check if the specified variable is captured by 'target' directive.
8632 /// \param Level Relative level of nested OpenMP construct for that the check
8633 /// is performed.
8634 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8635
8636 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8637 Expr *Op);
8638 /// \brief Called on start of new data sharing attribute block.
8639 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8640 const DeclarationNameInfo &DirName, Scope *CurScope,
8641 SourceLocation Loc);
8642 /// \brief Start analysis of clauses.
8643 void StartOpenMPClause(OpenMPClauseKind K);
8644 /// \brief End analysis of clauses.
8645 void EndOpenMPClause();
8646 /// \brief Called on end of data sharing attribute block.
8647 void EndOpenMPDSABlock(Stmt *CurDirective);
8648
8649 /// \brief Check if the current region is an OpenMP loop region and if it is,
8650 /// mark loop control variable, used in \p Init for loop initialization, as
8651 /// private by default.
8652 /// \param Init First part of the for loop.
8653 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8654
8655 // OpenMP directives and clauses.
8656 /// \brief Called on correct id-expression from the '#pragma omp
8657 /// threadprivate'.
8658 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8659 CXXScopeSpec &ScopeSpec,
8660 const DeclarationNameInfo &Id);
8661 /// \brief Called on well-formed '#pragma omp threadprivate'.
8662 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8663 SourceLocation Loc,
8664 ArrayRef<Expr *> VarList);
8665 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8666 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8667 SourceLocation Loc,
8668 ArrayRef<Expr *> VarList);
8669 /// \brief Check if the specified type is allowed to be used in 'omp declare
8670 /// reduction' construct.
8671 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8672 TypeResult ParsedType);
8673 /// \brief Called on start of '#pragma omp declare reduction'.
8674 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8675 Scope *S, DeclContext *DC, DeclarationName Name,
8676 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8677 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8678 /// \brief Initialize declare reduction construct initializer.
8679 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8680 /// \brief Finish current declare reduction construct initializer.
8681 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8682 /// \brief Initialize declare reduction construct initializer.
8683 /// \return omp_priv variable.
8684 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8685 /// \brief Finish current declare reduction construct initializer.
8686 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
8687 VarDecl *OmpPrivParm);
8688 /// \brief Called at the end of '#pragma omp declare reduction'.
8689 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8690 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8691
8692 /// Called on the start of target region i.e. '#pragma omp declare target'.
8693 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8694 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8695 void ActOnFinishOpenMPDeclareTargetDirective();
8696 /// Called on correct id-expression from the '#pragma omp declare target'.
8697 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8698 const DeclarationNameInfo &Id,
8699 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8700 NamedDeclSetType &SameDirectiveDecls);
8701 /// Check declaration inside target region.
8702 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
8703 SourceLocation IdLoc = SourceLocation());
8704 /// Return true inside OpenMP declare target region.
8705 bool isInOpenMPDeclareTargetContext() const {
8706 return IsInOpenMPDeclareTargetContext;
8707 }
8708 /// Return true inside OpenMP target region.
8709 bool isInOpenMPTargetExecutionDirective() const;
8710 /// Return true if (un)supported features for the current target should be
8711 /// diagnosed if OpenMP (offloading) is enabled.
8712 bool shouldDiagnoseTargetSupportFromOpenMP() const {
8713 return !getLangOpts().OpenMPIsDevice || isInOpenMPDeclareTargetContext() ||
8714 isInOpenMPTargetExecutionDirective();
8715 }
8716
8717 /// Return the number of captured regions created for an OpenMP directive.
8718 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8719
8720 /// \brief Initialization of captured region for OpenMP region.
8721 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8722 /// \brief End of OpenMP region.
8723 ///
8724 /// \param S Statement associated with the current OpenMP region.
8725 /// \param Clauses List of clauses for the current OpenMP region.
8726 ///
8727 /// \returns Statement for finished OpenMP region.
8728 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8729 StmtResult ActOnOpenMPExecutableDirective(
8730 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8731 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8732 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8733 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8734 /// of the associated statement.
8735 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8736 Stmt *AStmt,
8737 SourceLocation StartLoc,
8738 SourceLocation EndLoc);
8739 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8740 /// of the associated statement.
8741 StmtResult ActOnOpenMPSimdDirective(
8742 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8743 SourceLocation EndLoc,
8744 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8745 /// \brief Called on well-formed '\#pragma omp for' after parsing
8746 /// of the associated statement.
8747 StmtResult ActOnOpenMPForDirective(
8748 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8749 SourceLocation EndLoc,
8750 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8751 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8752 /// of the associated statement.
8753 StmtResult ActOnOpenMPForSimdDirective(
8754 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8755 SourceLocation EndLoc,
8756 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8757 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8758 /// of the associated statement.
8759 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8760 Stmt *AStmt, SourceLocation StartLoc,
8761 SourceLocation EndLoc);
8762 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8763 /// associated statement.
8764 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8765 SourceLocation EndLoc);
8766 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8767 /// associated statement.
8768 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8769 Stmt *AStmt, SourceLocation StartLoc,
8770 SourceLocation EndLoc);
8771 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8772 /// associated statement.
8773 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8774 SourceLocation EndLoc);
8775 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8776 /// associated statement.
8777 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8778 ArrayRef<OMPClause *> Clauses,
8779 Stmt *AStmt, SourceLocation StartLoc,
8780 SourceLocation EndLoc);
8781 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8782 /// of the associated statement.
8783 StmtResult ActOnOpenMPParallelForDirective(
8784 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8785 SourceLocation EndLoc,
8786 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8787 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8788 /// parsing of the associated statement.
8789 StmtResult ActOnOpenMPParallelForSimdDirective(
8790 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8791 SourceLocation EndLoc,
8792 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8793 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8794 /// parsing of the associated statement.
8795 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8796 Stmt *AStmt,
8797 SourceLocation StartLoc,
8798 SourceLocation EndLoc);
8799 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8800 /// associated statement.
8801 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8802 Stmt *AStmt, SourceLocation StartLoc,
8803 SourceLocation EndLoc);
8804 /// \brief Called on well-formed '\#pragma omp taskyield'.
8805 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8806 SourceLocation EndLoc);
8807 /// \brief Called on well-formed '\#pragma omp barrier'.
8808 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8809 SourceLocation EndLoc);
8810 /// \brief Called on well-formed '\#pragma omp taskwait'.
8811 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8812 SourceLocation EndLoc);
8813 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8814 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8815 Stmt *AStmt, SourceLocation StartLoc,
8816 SourceLocation EndLoc);
8817 /// \brief Called on well-formed '\#pragma omp flush'.
8818 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8819 SourceLocation StartLoc,
8820 SourceLocation EndLoc);
8821 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8822 /// associated statement.
8823 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8824 Stmt *AStmt, SourceLocation StartLoc,
8825 SourceLocation EndLoc);
8826 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8827 /// associated statement.
8828 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8829 Stmt *AStmt, SourceLocation StartLoc,
8830 SourceLocation EndLoc);
8831 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8832 /// associated statement.
8833 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8834 Stmt *AStmt, SourceLocation StartLoc,
8835 SourceLocation EndLoc);
8836 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8837 /// the associated statement.
8838 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8839 Stmt *AStmt, SourceLocation StartLoc,
8840 SourceLocation EndLoc);
8841 /// \brief Called on well-formed '\#pragma omp target enter data' after
8842 /// parsing of the associated statement.
8843 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8844 SourceLocation StartLoc,
8845 SourceLocation EndLoc,
8846 Stmt *AStmt);
8847 /// \brief Called on well-formed '\#pragma omp target exit data' after
8848 /// parsing of the associated statement.
8849 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8850 SourceLocation StartLoc,
8851 SourceLocation EndLoc,
8852 Stmt *AStmt);
8853 /// \brief Called on well-formed '\#pragma omp target parallel' after
8854 /// parsing of the associated statement.
8855 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8856 Stmt *AStmt,
8857 SourceLocation StartLoc,
8858 SourceLocation EndLoc);
8859 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8860 /// parsing of the associated statement.
8861 StmtResult ActOnOpenMPTargetParallelForDirective(
8862 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8863 SourceLocation EndLoc,
8864 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8865 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8866 /// associated statement.
8867 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8868 Stmt *AStmt, SourceLocation StartLoc,
8869 SourceLocation EndLoc);
8870 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8871 StmtResult
8872 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8873 SourceLocation EndLoc,
8874 OpenMPDirectiveKind CancelRegion);
8875 /// \brief Called on well-formed '\#pragma omp cancel'.
8876 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8877 SourceLocation StartLoc,
8878 SourceLocation EndLoc,
8879 OpenMPDirectiveKind CancelRegion);
8880 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8881 /// associated statement.
8882 StmtResult ActOnOpenMPTaskLoopDirective(
8883 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8884 SourceLocation EndLoc,
8885 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8886 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8887 /// the associated statement.
8888 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8889 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8890 SourceLocation EndLoc,
8891 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8892 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8893 /// of the associated statement.
8894 StmtResult ActOnOpenMPDistributeDirective(
8895 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8896 SourceLocation EndLoc,
8897 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8898 /// \brief Called on well-formed '\#pragma omp target update'.
8899 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8900 SourceLocation StartLoc,
8901 SourceLocation EndLoc,
8902 Stmt *AStmt);
8903 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8904 /// parsing of the associated statement.
8905 StmtResult ActOnOpenMPDistributeParallelForDirective(
8906 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8907 SourceLocation EndLoc,
8908 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8909 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8910 /// after parsing of the associated statement.
8911 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8912 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8913 SourceLocation EndLoc,
8914 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8915 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8916 /// parsing of the associated statement.
8917 StmtResult ActOnOpenMPDistributeSimdDirective(
8918 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8919 SourceLocation EndLoc,
8920 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8921 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8922 /// parsing of the associated statement.
8923 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8924 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8925 SourceLocation EndLoc,
8926 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8927 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8928 /// the associated statement.
8929 StmtResult ActOnOpenMPTargetSimdDirective(
8930 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8931 SourceLocation EndLoc,
8932 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8933 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8934 /// the associated statement.
8935 StmtResult ActOnOpenMPTeamsDistributeDirective(
8936 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8937 SourceLocation EndLoc,
8938 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8939 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8940 /// of the associated statement.
8941 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8942 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8943 SourceLocation EndLoc,
8944 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8945 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8946 /// after parsing of the associated statement.
8947 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8948 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8949 SourceLocation EndLoc,
8950 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8951 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8952 /// after parsing of the associated statement.
8953 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8954 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8955 SourceLocation EndLoc,
8956 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8957 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8958 /// associated statement.
8959 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8960 Stmt *AStmt,
8961 SourceLocation StartLoc,
8962 SourceLocation EndLoc);
8963 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8964 /// of the associated statement.
8965 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8966 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8967 SourceLocation EndLoc,
8968 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8969 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8970 /// after parsing of the associated statement.
8971 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8972 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8973 SourceLocation EndLoc,
8974 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8975 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8976 /// simd' after parsing of the associated statement.
8977 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8978 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8979 SourceLocation EndLoc,
8980 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8981 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8982 /// parsing of the associated statement.
8983 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8984 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8985 SourceLocation EndLoc,
8986 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8987
8988 /// Checks correctness of linear modifiers.
8989 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8990 SourceLocation LinLoc);
8991 /// Checks that the specified declaration matches requirements for the linear
8992 /// decls.
8993 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8994 OpenMPLinearClauseKind LinKind, QualType Type);
8995
8996 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8997 /// the associated method/function.
8998 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8999 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
9000 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
9001 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
9002 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
9003
9004 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
9005 Expr *Expr,
9006 SourceLocation StartLoc,
9007 SourceLocation LParenLoc,
9008 SourceLocation EndLoc);
9009 /// \brief Called on well-formed 'if' clause.
9010 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9011 Expr *Condition, SourceLocation StartLoc,
9012 SourceLocation LParenLoc,
9013 SourceLocation NameModifierLoc,
9014 SourceLocation ColonLoc,
9015 SourceLocation EndLoc);
9016 /// \brief Called on well-formed 'final' clause.
9017 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
9018 SourceLocation LParenLoc,
9019 SourceLocation EndLoc);
9020 /// \brief Called on well-formed 'num_threads' clause.
9021 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9022 SourceLocation StartLoc,
9023 SourceLocation LParenLoc,
9024 SourceLocation EndLoc);
9025 /// \brief Called on well-formed 'safelen' clause.
9026 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
9027 SourceLocation StartLoc,
9028 SourceLocation LParenLoc,
9029 SourceLocation EndLoc);
9030 /// \brief Called on well-formed 'simdlen' clause.
9031 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
9032 SourceLocation LParenLoc,
9033 SourceLocation EndLoc);
9034 /// \brief Called on well-formed 'collapse' clause.
9035 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
9036 SourceLocation StartLoc,
9037 SourceLocation LParenLoc,
9038 SourceLocation EndLoc);
9039 /// \brief Called on well-formed 'ordered' clause.
9040 OMPClause *
9041 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
9042 SourceLocation LParenLoc = SourceLocation(),
9043 Expr *NumForLoops = nullptr);
9044 /// \brief Called on well-formed 'grainsize' clause.
9045 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
9046 SourceLocation LParenLoc,
9047 SourceLocation EndLoc);
9048 /// \brief Called on well-formed 'num_tasks' clause.
9049 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
9050 SourceLocation LParenLoc,
9051 SourceLocation EndLoc);
9052 /// \brief Called on well-formed 'hint' clause.
9053 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
9054 SourceLocation LParenLoc,
9055 SourceLocation EndLoc);
9056
9057 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
9058 unsigned Argument,
9059 SourceLocation ArgumentLoc,
9060 SourceLocation StartLoc,
9061 SourceLocation LParenLoc,
9062 SourceLocation EndLoc);
9063 /// \brief Called on well-formed 'default' clause.
9064 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9065 SourceLocation KindLoc,
9066 SourceLocation StartLoc,
9067 SourceLocation LParenLoc,
9068 SourceLocation EndLoc);
9069 /// \brief Called on well-formed 'proc_bind' clause.
9070 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9071 SourceLocation KindLoc,
9072 SourceLocation StartLoc,
9073 SourceLocation LParenLoc,
9074 SourceLocation EndLoc);
9075
9076 OMPClause *ActOnOpenMPSingleExprWithArgClause(
9077 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
9078 SourceLocation StartLoc, SourceLocation LParenLoc,
9079 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
9080 SourceLocation EndLoc);
9081 /// \brief Called on well-formed 'schedule' clause.
9082 OMPClause *ActOnOpenMPScheduleClause(
9083 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9084 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9085 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9086 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
9087
9088 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
9089 SourceLocation EndLoc);
9090 /// \brief Called on well-formed 'nowait' clause.
9091 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9092 SourceLocation EndLoc);
9093 /// \brief Called on well-formed 'untied' clause.
9094 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9095 SourceLocation EndLoc);
9096 /// \brief Called on well-formed 'mergeable' clause.
9097 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9098 SourceLocation EndLoc);
9099 /// \brief Called on well-formed 'read' clause.
9100 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
9101 SourceLocation EndLoc);
9102 /// \brief Called on well-formed 'write' clause.
9103 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
9104 SourceLocation EndLoc);
9105 /// \brief Called on well-formed 'update' clause.
9106 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9107 SourceLocation EndLoc);
9108 /// \brief Called on well-formed 'capture' clause.
9109 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9110 SourceLocation EndLoc);
9111 /// \brief Called on well-formed 'seq_cst' clause.
9112 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9113 SourceLocation EndLoc);
9114 /// \brief Called on well-formed 'threads' clause.
9115 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9116 SourceLocation EndLoc);
9117 /// \brief Called on well-formed 'simd' clause.
9118 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9119 SourceLocation EndLoc);
9120 /// \brief Called on well-formed 'nogroup' clause.
9121 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9122 SourceLocation EndLoc);
9123
9124 OMPClause *ActOnOpenMPVarListClause(
9125 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
9126 SourceLocation StartLoc, SourceLocation LParenLoc,
9127 SourceLocation ColonLoc, SourceLocation EndLoc,
9128 CXXScopeSpec &ReductionIdScopeSpec,
9129 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9130 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9131 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9132 SourceLocation DepLinMapLoc);
9133 /// \brief Called on well-formed 'private' clause.
9134 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9135 SourceLocation StartLoc,
9136 SourceLocation LParenLoc,
9137 SourceLocation EndLoc);
9138 /// \brief Called on well-formed 'firstprivate' clause.
9139 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9140 SourceLocation StartLoc,
9141 SourceLocation LParenLoc,
9142 SourceLocation EndLoc);
9143 /// \brief Called on well-formed 'lastprivate' clause.
9144 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9145 SourceLocation StartLoc,
9146 SourceLocation LParenLoc,
9147 SourceLocation EndLoc);
9148 /// \brief Called on well-formed 'shared' clause.
9149 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9150 SourceLocation StartLoc,
9151 SourceLocation LParenLoc,
9152 SourceLocation EndLoc);
9153 /// \brief Called on well-formed 'reduction' clause.
9154 OMPClause *ActOnOpenMPReductionClause(
9155 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9156 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9157 CXXScopeSpec &ReductionIdScopeSpec,
9158 const DeclarationNameInfo &ReductionId,
9159 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9160 /// Called on well-formed 'task_reduction' clause.
9161 OMPClause *ActOnOpenMPTaskReductionClause(
9162 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9163 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9164 CXXScopeSpec &ReductionIdScopeSpec,
9165 const DeclarationNameInfo &ReductionId,
9166 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9167 /// Called on well-formed 'in_reduction' clause.
9168 OMPClause *ActOnOpenMPInReductionClause(
9169 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9170 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9171 CXXScopeSpec &ReductionIdScopeSpec,
9172 const DeclarationNameInfo &ReductionId,
9173 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9174 /// \brief Called on well-formed 'linear' clause.
9175 OMPClause *
9176 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9177 SourceLocation StartLoc, SourceLocation LParenLoc,
9178 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
9179 SourceLocation ColonLoc, SourceLocation EndLoc);
9180 /// \brief Called on well-formed 'aligned' clause.
9181 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
9182 Expr *Alignment,
9183 SourceLocation StartLoc,
9184 SourceLocation LParenLoc,
9185 SourceLocation ColonLoc,
9186 SourceLocation EndLoc);
9187 /// \brief Called on well-formed 'copyin' clause.
9188 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9189 SourceLocation StartLoc,
9190 SourceLocation LParenLoc,
9191 SourceLocation EndLoc);
9192 /// \brief Called on well-formed 'copyprivate' clause.
9193 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9194 SourceLocation StartLoc,
9195 SourceLocation LParenLoc,
9196 SourceLocation EndLoc);
9197 /// \brief Called on well-formed 'flush' pseudo clause.
9198 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9199 SourceLocation StartLoc,
9200 SourceLocation LParenLoc,
9201 SourceLocation EndLoc);
9202 /// \brief Called on well-formed 'depend' clause.
9203 OMPClause *
9204 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
9205 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
9206 SourceLocation StartLoc, SourceLocation LParenLoc,
9207 SourceLocation EndLoc);
9208 /// \brief Called on well-formed 'device' clause.
9209 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9210 SourceLocation LParenLoc,
9211 SourceLocation EndLoc);
9212 /// \brief Called on well-formed 'map' clause.
9213 OMPClause *
9214 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9215 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9216 SourceLocation MapLoc, SourceLocation ColonLoc,
9217 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9218 SourceLocation LParenLoc, SourceLocation EndLoc);
9219 /// \brief Called on well-formed 'num_teams' clause.
9220 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9221 SourceLocation LParenLoc,
9222 SourceLocation EndLoc);
9223 /// \brief Called on well-formed 'thread_limit' clause.
9224 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9225 SourceLocation StartLoc,
9226 SourceLocation LParenLoc,
9227 SourceLocation EndLoc);
9228 /// \brief Called on well-formed 'priority' clause.
9229 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9230 SourceLocation LParenLoc,
9231 SourceLocation EndLoc);
9232 /// \brief Called on well-formed 'dist_schedule' clause.
9233 OMPClause *ActOnOpenMPDistScheduleClause(
9234 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9235 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9236 SourceLocation CommaLoc, SourceLocation EndLoc);
9237 /// \brief Called on well-formed 'defaultmap' clause.
9238 OMPClause *ActOnOpenMPDefaultmapClause(
9239 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9240 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9241 SourceLocation KindLoc, SourceLocation EndLoc);
9242 /// \brief Called on well-formed 'to' clause.
9243 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
9244 SourceLocation StartLoc,
9245 SourceLocation LParenLoc,
9246 SourceLocation EndLoc);
9247 /// \brief Called on well-formed 'from' clause.
9248 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
9249 SourceLocation StartLoc,
9250 SourceLocation LParenLoc,
9251 SourceLocation EndLoc);
9252 /// Called on well-formed 'use_device_ptr' clause.
9253 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9254 SourceLocation StartLoc,
9255 SourceLocation LParenLoc,
9256 SourceLocation EndLoc);
9257 /// Called on well-formed 'is_device_ptr' clause.
9258 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9259 SourceLocation StartLoc,
9260 SourceLocation LParenLoc,
9261 SourceLocation EndLoc);
9262
9263 /// \brief The kind of conversion being performed.
9264 enum CheckedConversionKind {
9265 /// \brief An implicit conversion.
9266 CCK_ImplicitConversion,
9267 /// \brief A C-style cast.
9268 CCK_CStyleCast,
9269 /// \brief A functional-style cast.
9270 CCK_FunctionalCast,
9271 /// \brief A cast other than a C-style cast.
9272 CCK_OtherCast
9273 };
9274
9275 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9276 /// cast. If there is already an implicit cast, merge into the existing one.
9277 /// If isLvalue, the result of the cast is an lvalue.
9278 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9279 ExprValueKind VK = VK_RValue,
9280 const CXXCastPath *BasePath = nullptr,
9281 CheckedConversionKind CCK
9282 = CCK_ImplicitConversion);
9283
9284 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9285 /// to the conversion from scalar type ScalarTy to the Boolean type.
9286 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9287
9288 /// IgnoredValueConversions - Given that an expression's result is
9289 /// syntactically ignored, perform any conversions that are
9290 /// required.
9291 ExprResult IgnoredValueConversions(Expr *E);
9292
9293 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9294 // functions and arrays to their respective pointers (C99 6.3.2.1).
9295 ExprResult UsualUnaryConversions(Expr *E);
9296
9297 /// CallExprUnaryConversions - a special case of an unary conversion
9298 /// performed on a function designator of a call expression.
9299 ExprResult CallExprUnaryConversions(Expr *E);
9300
9301 // DefaultFunctionArrayConversion - converts functions and arrays
9302 // to their respective pointers (C99 6.3.2.1).
9303 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9304
9305 // DefaultFunctionArrayLvalueConversion - converts functions and
9306 // arrays to their respective pointers and performs the
9307 // lvalue-to-rvalue conversion.
9308 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9309 bool Diagnose = true);
9310
9311 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9312 // the operand. This is DefaultFunctionArrayLvalueConversion,
9313 // except that it assumes the operand isn't of function or array
9314 // type.
9315 ExprResult DefaultLvalueConversion(Expr *E);
9316
9317 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9318 // do not have a prototype. Integer promotions are performed on each
9319 // argument, and arguments that have type float are promoted to double.
9320 ExprResult DefaultArgumentPromotion(Expr *E);
9321
9322 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9323 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9324 /// we don't have xvalues there.
9325 ExprResult TemporaryMaterializationConversion(Expr *E);
9326
9327 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9328 enum VariadicCallType {
9329 VariadicFunction,
9330 VariadicBlock,
9331 VariadicMethod,
9332 VariadicConstructor,
9333 VariadicDoesNotApply
9334 };
9335
9336 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9337 const FunctionProtoType *Proto,
9338 Expr *Fn);
9339
9340 // Used for determining in which context a type is allowed to be passed to a
9341 // vararg function.
9342 enum VarArgKind {
9343 VAK_Valid,
9344 VAK_ValidInCXX11,
9345 VAK_Undefined,
9346 VAK_MSVCUndefined,
9347 VAK_Invalid
9348 };
9349
9350 // Determines which VarArgKind fits an expression.
9351 VarArgKind isValidVarArgType(const QualType &Ty);
9352
9353 /// Check to see if the given expression is a valid argument to a variadic
9354 /// function, issuing a diagnostic if not.
9355 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9356
9357 /// Check to see if a given expression could have '.c_str()' called on it.
9358 bool hasCStrMethod(const Expr *E);
9359
9360 /// GatherArgumentsForCall - Collector argument expressions for various
9361 /// form of call prototypes.
9362 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9363 const FunctionProtoType *Proto,
9364 unsigned FirstParam, ArrayRef<Expr *> Args,
9365 SmallVectorImpl<Expr *> &AllArgs,
9366 VariadicCallType CallType = VariadicDoesNotApply,
9367 bool AllowExplicit = false,
9368 bool IsListInitialization = false);
9369
9370 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9371 // will create a runtime trap if the resulting type is not a POD type.
9372 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9373 FunctionDecl *FDecl);
9374
9375 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9376 // operands and then handles various conversions that are common to binary
9377 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9378 // routine returns the first non-arithmetic type found. The client is
9379 // responsible for emitting appropriate error diagnostics.
9380 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9381 bool IsCompAssign = false);
9382
9383 /// AssignConvertType - All of the 'assignment' semantic checks return this
9384 /// enum to indicate whether the assignment was allowed. These checks are
9385 /// done for simple assignments, as well as initialization, return from
9386 /// function, argument passing, etc. The query is phrased in terms of a
9387 /// source and destination type.
9388 enum AssignConvertType {
9389 /// Compatible - the types are compatible according to the standard.
9390 Compatible,
9391
9392 /// PointerToInt - The assignment converts a pointer to an int, which we
9393 /// accept as an extension.
9394 PointerToInt,
9395
9396 /// IntToPointer - The assignment converts an int to a pointer, which we
9397 /// accept as an extension.
9398 IntToPointer,
9399
9400 /// FunctionVoidPointer - The assignment is between a function pointer and
9401 /// void*, which the standard doesn't allow, but we accept as an extension.
9402 FunctionVoidPointer,
9403
9404 /// IncompatiblePointer - The assignment is between two pointers types that
9405 /// are not compatible, but we accept them as an extension.
9406 IncompatiblePointer,
9407
9408 /// IncompatiblePointerSign - The assignment is between two pointers types
9409 /// which point to integers which have a different sign, but are otherwise
9410 /// identical. This is a subset of the above, but broken out because it's by
9411 /// far the most common case of incompatible pointers.
9412 IncompatiblePointerSign,
9413
9414 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9415 /// c/v/r qualifiers, which we accept as an extension.
9416 CompatiblePointerDiscardsQualifiers,
9417
9418 /// IncompatiblePointerDiscardsQualifiers - The assignment
9419 /// discards qualifiers that we don't permit to be discarded,
9420 /// like address spaces.
9421 IncompatiblePointerDiscardsQualifiers,
9422
9423 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9424 /// nested pointer types, and the qualifiers other than the first two
9425 /// levels differ e.g. char ** -> const char **, but we accept them as an
9426 /// extension.
9427 IncompatibleNestedPointerQualifiers,
9428
9429 /// IncompatibleVectors - The assignment is between two vector types that
9430 /// have the same size, which we accept as an extension.
9431 IncompatibleVectors,
9432
9433 /// IntToBlockPointer - The assignment converts an int to a block
9434 /// pointer. We disallow this.
9435 IntToBlockPointer,
9436
9437 /// IncompatibleBlockPointer - The assignment is between two block
9438 /// pointers types that are not compatible.
9439 IncompatibleBlockPointer,
9440
9441 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9442 /// id type and something else (that is incompatible with it). For example,
9443 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9444 IncompatibleObjCQualifiedId,
9445
9446 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9447 /// object with __weak qualifier.
9448 IncompatibleObjCWeakRef,
9449
9450 /// Incompatible - We reject this conversion outright, it is invalid to
9451 /// represent it in the AST.
9452 Incompatible
9453 };
9454
9455 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9456 /// assignment conversion type specified by ConvTy. This returns true if the
9457 /// conversion was invalid or false if the conversion was accepted.
9458 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9459 SourceLocation Loc,
9460 QualType DstType, QualType SrcType,
9461 Expr *SrcExpr, AssignmentAction Action,
9462 bool *Complained = nullptr);
9463
9464 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9465 /// enum. If AllowMask is true, then we also allow the complement of a valid
9466 /// value, to be used as a mask.
9467 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9468 bool AllowMask) const;
9469
9470 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9471 /// integer not in the range of enum values.
9472 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9473 Expr *SrcExpr);
9474
9475 /// CheckAssignmentConstraints - Perform type checking for assignment,
9476 /// argument passing, variable initialization, and function return values.
9477 /// C99 6.5.16.
9478 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9479 QualType LHSType,
9480 QualType RHSType);
9481
9482 /// Check assignment constraints and optionally prepare for a conversion of
9483 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9484 /// is true.
9485 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9486 ExprResult &RHS,
9487 CastKind &Kind,
9488 bool ConvertRHS = true);
9489
9490 /// Check assignment constraints for an assignment of RHS to LHSType.
9491 ///
9492 /// \param LHSType The destination type for the assignment.
9493 /// \param RHS The source expression for the assignment.
9494 /// \param Diagnose If \c true, diagnostics may be produced when checking
9495 /// for assignability. If a diagnostic is produced, \p RHS will be
9496 /// set to ExprError(). Note that this function may still return
9497 /// without producing a diagnostic, even for an invalid assignment.
9498 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9499 /// in an audited Core Foundation API and does not need to be checked
9500 /// for ARC retain issues.
9501 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9502 /// conversions necessary to perform the assignment. If \c false,
9503 /// \p Diagnose must also be \c false.
9504 AssignConvertType CheckSingleAssignmentConstraints(
9505 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9506 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9507
9508 // \brief If the lhs type is a transparent union, check whether we
9509 // can initialize the transparent union with the given expression.
9510 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9511 ExprResult &RHS);
9512
9513 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9514
9515 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9516
9517 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9518 AssignmentAction Action,
9519 bool AllowExplicit = false);
9520 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9521 AssignmentAction Action,
9522 bool AllowExplicit,
9523 ImplicitConversionSequence& ICS);
9524 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9525 const ImplicitConversionSequence& ICS,
9526 AssignmentAction Action,
9527 CheckedConversionKind CCK
9528 = CCK_ImplicitConversion);
9529 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9530 const StandardConversionSequence& SCS,
9531 AssignmentAction Action,
9532 CheckedConversionKind CCK);
9533
9534 /// the following "Check" methods will return a valid/converted QualType
9535 /// or a null QualType (indicating an error diagnostic was issued).
9536
9537 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9538 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9539 ExprResult &RHS);
9540 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9541 ExprResult &RHS);
9542 QualType CheckPointerToMemberOperands( // C++ 5.5
9543 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9544 SourceLocation OpLoc, bool isIndirect);
9545 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9546 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9547 bool IsDivide);
9548 QualType CheckRemainderOperands( // C99 6.5.5
9549 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9550 bool IsCompAssign = false);
9551 QualType CheckAdditionOperands( // C99 6.5.6
9552 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9553 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9554 QualType CheckSubtractionOperands( // C99 6.5.6
9555 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9556 QualType* CompLHSTy = nullptr);
9557 QualType CheckShiftOperands( // C99 6.5.7
9558 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9559 BinaryOperatorKind Opc, bool IsCompAssign = false);
9560 QualType CheckCompareOperands( // C99 6.5.8/9
9561 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9562 BinaryOperatorKind Opc, bool isRelational);
9563 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9564 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9565 BinaryOperatorKind Opc);
9566 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9567 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9568 BinaryOperatorKind Opc);
9569 // CheckAssignmentOperands is used for both simple and compound assignment.
9570 // For simple assignment, pass both expressions and a null converted type.
9571 // For compound assignment, pass both expressions and the converted type.
9572 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9573 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9574
9575 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9576 UnaryOperatorKind Opcode, Expr *Op);
9577 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9578 BinaryOperatorKind Opcode,
9579 Expr *LHS, Expr *RHS);
9580 ExprResult checkPseudoObjectRValue(Expr *E);
9581 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9582
9583 QualType CheckConditionalOperands( // C99 6.5.15
9584 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9585 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9586 QualType CXXCheckConditionalOperands( // C++ 5.16
9587 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9588 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9589 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9590 bool ConvertArgs = true);
9591 QualType FindCompositePointerType(SourceLocation Loc,
9592 ExprResult &E1, ExprResult &E2,
9593 bool ConvertArgs = true) {
9594 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9595 QualType Composite =
9596 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9597 E1 = E1Tmp;
9598 E2 = E2Tmp;
9599 return Composite;
9600 }
9601
9602 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9603 SourceLocation QuestionLoc);
9604
9605 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9606 SourceLocation QuestionLoc);
9607
9608 void DiagnoseAlwaysNonNullPointer(Expr *E,
9609 Expr::NullPointerConstantKind NullType,
9610 bool IsEqual, SourceRange Range);
9611
9612 /// type checking for vector binary operators.
9613 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9614 SourceLocation Loc, bool IsCompAssign,
9615 bool AllowBothBool, bool AllowBoolConversion);
9616 QualType GetSignedVectorType(QualType V);
9617 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9618 SourceLocation Loc,
9619 BinaryOperatorKind Opc);
9620 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9621 SourceLocation Loc);
9622
9623 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9624 bool isLaxVectorConversion(QualType srcType, QualType destType);
9625
9626 /// type checking declaration initializers (C99 6.7.8)
9627 bool CheckForConstantInitializer(Expr *e, QualType t);
9628
9629 // type checking C++ declaration initializers (C++ [dcl.init]).
9630
9631 /// ReferenceCompareResult - Expresses the result of comparing two
9632 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9633 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9634 enum ReferenceCompareResult {
9635 /// Ref_Incompatible - The two types are incompatible, so direct
9636 /// reference binding is not possible.
9637 Ref_Incompatible = 0,
9638 /// Ref_Related - The two types are reference-related, which means
9639 /// that their unqualified forms (T1 and T2) are either the same
9640 /// or T1 is a base class of T2.
9641 Ref_Related,
9642 /// Ref_Compatible - The two types are reference-compatible.
9643 Ref_Compatible
9644 };
9645
9646 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9647 QualType T1, QualType T2,
9648 bool &DerivedToBase,
9649 bool &ObjCConversion,
9650 bool &ObjCLifetimeConversion);
9651
9652 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9653 Expr *CastExpr, CastKind &CastKind,
9654 ExprValueKind &VK, CXXCastPath &Path);
9655
9656 /// \brief Force an expression with unknown-type to an expression of the
9657 /// given type.
9658 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9659
9660 /// \brief Type-check an expression that's being passed to an
9661 /// __unknown_anytype parameter.
9662 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9663 Expr *result, QualType &paramType);
9664
9665 // CheckVectorCast - check type constraints for vectors.
9666 // Since vectors are an extension, there are no C standard reference for this.
9667 // We allow casting between vectors and integer datatypes of the same size.
9668 // returns true if the cast is invalid
9669 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9670 CastKind &Kind);
9671
9672 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9673 /// implicit casts if necessary.
9674 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9675
9676 // CheckExtVectorCast - check type constraints for extended vectors.
9677 // Since vectors are an extension, there are no C standard reference for this.
9678 // We allow casting between vectors and integer datatypes of the same size,
9679 // or vectors and the element type of that vector.
9680 // returns the cast expr
9681 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9682 CastKind &Kind);
9683
9684 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9685 SourceLocation LParenLoc,
9686 Expr *CastExpr,
9687 SourceLocation RParenLoc);
9688
9689 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9690
9691 /// \brief Checks for invalid conversions and casts between
9692 /// retainable pointers and other pointer kinds for ARC and Weak.
9693 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9694 QualType castType, Expr *&op,
9695 CheckedConversionKind CCK,
9696 bool Diagnose = true,
9697 bool DiagnoseCFAudited = false,
9698 BinaryOperatorKind Opc = BO_PtrMemD
9699 );
9700
9701 Expr *stripARCUnbridgedCast(Expr *e);
9702 void diagnoseARCUnbridgedCast(Expr *e);
9703
9704 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9705 QualType ExprType);
9706
9707 /// checkRetainCycles - Check whether an Objective-C message send
9708 /// might create an obvious retain cycle.
9709 void checkRetainCycles(ObjCMessageExpr *msg);
9710 void checkRetainCycles(Expr *receiver, Expr *argument);
9711 void checkRetainCycles(VarDecl *Var, Expr *Init);
9712
9713 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9714 /// to weak/__unsafe_unretained type.
9715 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9716
9717 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9718 /// to weak/__unsafe_unretained expression.
9719 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9720
9721 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9722 /// \param Method - May be null.
9723 /// \param [out] ReturnType - The return type of the send.
9724 /// \return true iff there were any incompatible types.
9725 bool CheckMessageArgumentTypes(QualType ReceiverType,
9726 MultiExprArg Args, Selector Sel,
9727 ArrayRef<SourceLocation> SelectorLocs,
9728 ObjCMethodDecl *Method, bool isClassMessage,
9729 bool isSuperMessage,
9730 SourceLocation lbrac, SourceLocation rbrac,
9731 SourceRange RecRange,
9732 QualType &ReturnType, ExprValueKind &VK);
9733
9734 /// \brief Determine the result of a message send expression based on
9735 /// the type of the receiver, the method expected to receive the message,
9736 /// and the form of the message send.
9737 QualType getMessageSendResultType(QualType ReceiverType,
9738 ObjCMethodDecl *Method,
9739 bool isClassMessage, bool isSuperMessage);
9740
9741 /// \brief If the given expression involves a message send to a method
9742 /// with a related result type, emit a note describing what happened.
9743 void EmitRelatedResultTypeNote(const Expr *E);
9744
9745 /// \brief Given that we had incompatible pointer types in a return
9746 /// statement, check whether we're in a method with a related result
9747 /// type, and if so, emit a note describing what happened.
9748 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9749
9750 class ConditionResult {
9751 Decl *ConditionVar;
9752 FullExprArg Condition;
9753 bool Invalid;
9754 bool HasKnownValue;
9755 bool KnownValue;
9756
9757 friend class Sema;
9758 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9759 bool IsConstexpr)
9760 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9761 HasKnownValue(IsConstexpr && Condition.get() &&
9762 !Condition.get()->isValueDependent()),
9763 KnownValue(HasKnownValue &&
9764 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9765 explicit ConditionResult(bool Invalid)
9766 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9767 HasKnownValue(false), KnownValue(false) {}
9768
9769 public:
9770 ConditionResult() : ConditionResult(false) {}
9771 bool isInvalid() const { return Invalid; }
9772 std::pair<VarDecl *, Expr *> get() const {
9773 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9774 Condition.get());
9775 }
9776 llvm::Optional<bool> getKnownValue() const {
9777 if (!HasKnownValue)
9778 return None;
9779 return KnownValue;
9780 }
9781 };
9782 static ConditionResult ConditionError() { return ConditionResult(true); }
9783
9784 enum class ConditionKind {
9785 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9786 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9787 Switch ///< An integral condition for a 'switch' statement.
9788 };
9789
9790 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9791 Expr *SubExpr, ConditionKind CK);
9792
9793 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9794 SourceLocation StmtLoc,
9795 ConditionKind CK);
9796
9797 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9798
9799 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9800 SourceLocation StmtLoc,
9801 ConditionKind CK);
9802 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9803
9804 /// CheckBooleanCondition - Diagnose problems involving the use of
9805 /// the given expression as a boolean condition (e.g. in an if
9806 /// statement). Also performs the standard function and array
9807 /// decays, possibly changing the input variable.
9808 ///
9809 /// \param Loc - A location associated with the condition, e.g. the
9810 /// 'if' keyword.
9811 /// \return true iff there were any errors
9812 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9813 bool IsConstexpr = false);
9814
9815 /// DiagnoseAssignmentAsCondition - Given that an expression is
9816 /// being used as a boolean condition, warn if it's an assignment.
9817 void DiagnoseAssignmentAsCondition(Expr *E);
9818
9819 /// \brief Redundant parentheses over an equality comparison can indicate
9820 /// that the user intended an assignment used as condition.
9821 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9822
9823 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9824 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9825
9826 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9827 /// the specified width and sign. If an overflow occurs, detect it and emit
9828 /// the specified diagnostic.
9829 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9830 unsigned NewWidth, bool NewSign,
9831 SourceLocation Loc, unsigned DiagID);
9832
9833 /// Checks that the Objective-C declaration is declared in the global scope.
9834 /// Emits an error and marks the declaration as invalid if it's not declared
9835 /// in the global scope.
9836 bool CheckObjCDeclScope(Decl *D);
9837
9838 /// \brief Abstract base class used for diagnosing integer constant
9839 /// expression violations.
9840 class VerifyICEDiagnoser {
9841 public:
9842 bool Suppress;
9843
9844 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9845
9846 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9847 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9848 virtual ~VerifyICEDiagnoser() { }
9849 };
9850
9851 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9852 /// and reports the appropriate diagnostics. Returns false on success.
9853 /// Can optionally return the value of the expression.
9854 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9855 VerifyICEDiagnoser &Diagnoser,
9856 bool AllowFold = true);
9857 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9858 unsigned DiagID,
9859 bool AllowFold = true);
9860 ExprResult VerifyIntegerConstantExpression(Expr *E,
9861 llvm::APSInt *Result = nullptr);
9862
9863 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9864 /// the correct width, and that the field type is valid.
9865 /// Returns false on success.
9866 /// Can optionally return whether the bit-field is of width 0
9867 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9868 QualType FieldTy, bool IsMsStruct,
9869 Expr *BitWidth, bool *ZeroWidth = nullptr);
9870
9871private:
9872 unsigned ForceCUDAHostDeviceDepth = 0;
9873
9874public:
9875 /// Increments our count of the number of times we've seen a pragma forcing
9876 /// functions to be __host__ __device__. So long as this count is greater
9877 /// than zero, all functions encountered will be __host__ __device__.
9878 void PushForceCUDAHostDevice();
9879
9880 /// Decrements our count of the number of times we've seen a pragma forcing
9881 /// functions to be __host__ __device__. Returns false if the count is 0
9882 /// before incrementing, so you can emit an error.
9883 bool PopForceCUDAHostDevice();
9884
9885 /// Diagnostics that are emitted only if we discover that the given function
9886 /// must be codegen'ed. Because handling these correctly adds overhead to
9887 /// compilation, this is currently only enabled for CUDA compilations.
9888 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9889 std::vector<PartialDiagnosticAt>>
9890 CUDADeferredDiags;
9891
9892 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9893 /// key in a hashtable, both the FD and location are hashed.
9894 struct FunctionDeclAndLoc {
9895 CanonicalDeclPtr<FunctionDecl> FD;
9896 SourceLocation Loc;
9897 };
9898
9899 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9900 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9901 /// same deferred diag twice.
9902 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9903
9904 /// An inverse call graph, mapping known-emitted functions to one of their
9905 /// known-emitted callers (plus the location of the call).
9906 ///
9907 /// Functions that we can tell a priori must be emitted aren't added to this
9908 /// map.
9909 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9910 /* Caller = */ FunctionDeclAndLoc>
9911 CUDAKnownEmittedFns;
9912
9913 /// A partial call graph maintained during CUDA compilation to support
9914 /// deferred diagnostics.
9915 ///
9916 /// Functions are only added here if, at the time they're considered, they are
9917 /// not known-emitted. As soon as we discover that a function is
9918 /// known-emitted, we remove it and everything it transitively calls from this
9919 /// set and add those functions to CUDAKnownEmittedFns.
9920 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9921 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9922 SourceLocation>>
9923 CUDACallGraph;
9924
9925 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9926 ///
9927 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9928 /// which are not allowed to appear inside __device__ functions and are
9929 /// allowed to appear in __host__ __device__ functions only if the host+device
9930 /// function is never codegen'ed.
9931 ///
9932 /// To handle this, we use the notion of "deferred diagnostics", where we
9933 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9934 ///
9935 /// This class lets you emit either a regular diagnostic, a deferred
9936 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9937 /// its constructor, thus simplifying the process of creating these "maybe
9938 /// deferred" diagnostics.
9939 class CUDADiagBuilder {
9940 public:
9941 enum Kind {
9942 /// Emit no diagnostics.
9943 K_Nop,
9944 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9945 K_Immediate,
9946 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9947 /// emit a call stack showing how this function can be reached by an a
9948 /// priori known-emitted function.
9949 K_ImmediateWithCallStack,
9950 /// Create a deferred diagnostic, which is emitted only if the function
9951 /// it's attached to is codegen'ed. Also emit a call stack as with
9952 /// K_ImmediateWithCallStack.
9953 K_Deferred
9954 };
9955
9956 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9957 FunctionDecl *Fn, Sema &S);
9958 ~CUDADiagBuilder();
9959
9960 /// Convertible to bool: True if we immediately emitted an error, false if
9961 /// we didn't emit an error or we created a deferred error.
9962 ///
9963 /// Example usage:
9964 ///
9965 /// if (CUDADiagBuilder(...) << foo << bar)
9966 /// return ExprError();
9967 ///
9968 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9969 /// want to use these instead of creating a CUDADiagBuilder yourself.
9970 operator bool() const { return ImmediateDiag.hasValue(); }
9971
9972 template <typename T>
9973 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9974 const T &Value) {
9975 if (Diag.ImmediateDiag.hasValue())
5
Assuming the condition is false
6
Taking false branch
9976 *Diag.ImmediateDiag << Value;
9977 else if (Diag.PartialDiag.hasValue())
7
Assuming the condition is true
8
Taking true branch
9978 *Diag.PartialDiag << Value;
9
Calling 'operator<<'
20
Returned allocated memory
9979 return Diag;
9980 }
9981
9982 private:
9983 Sema &S;
9984 SourceLocation Loc;
9985 unsigned DiagID;
9986 FunctionDecl *Fn;
9987 bool ShowCallStack;
9988
9989 // Invariant: At most one of these Optionals has a value.
9990 // FIXME: Switch these to a Variant once that exists.
9991 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9992 llvm::Optional<PartialDiagnostic> PartialDiag;
9993 };
9994
9995 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9996 /// is "used as device code".
9997 ///
9998 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9999 /// - If CurContext is a __device__ or __global__ function, emits the
10000 /// diagnostics immediately.
10001 /// - If CurContext is a __host__ __device__ function and we are compiling for
10002 /// the device, creates a diagnostic which is emitted if and when we realize
10003 /// that the function will be codegen'ed.
10004 ///
10005 /// Example usage:
10006 ///
10007 /// // Variable-length arrays are not allowed in CUDA device code.
10008 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
10009 /// return ExprError();
10010 /// // Otherwise, continue parsing as normal.
10011 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
10012
10013 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
10014 /// is "used as host code".
10015 ///
10016 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
10017 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
10018
10019 enum CUDAFunctionTarget {
10020 CFT_Device,
10021 CFT_Global,
10022 CFT_Host,
10023 CFT_HostDevice,
10024 CFT_InvalidTarget
10025 };
10026
10027 /// Determines whether the given function is a CUDA device/host/kernel/etc.
10028 /// function.
10029 ///
10030 /// Use this rather than examining the function's attributes yourself -- you
10031 /// will get it wrong. Returns CFT_Host if D is null.
10032 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
10033 bool IgnoreImplicitHDAttr = false);
10034 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
10035
10036 /// Gets the CUDA target for the current context.
10037 CUDAFunctionTarget CurrentCUDATarget() {
10038 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
10039 }
10040
10041 // CUDA function call preference. Must be ordered numerically from
10042 // worst to best.
10043 enum CUDAFunctionPreference {
10044 CFP_Never, // Invalid caller/callee combination.
10045 CFP_WrongSide, // Calls from host-device to host or device
10046 // function that do not match current compilation
10047 // mode.
10048 CFP_HostDevice, // Any calls to host/device functions.
10049 CFP_SameSide, // Calls from host-device to host or device
10050 // function matching current compilation mode.
10051 CFP_Native, // host-to-host or device-to-device calls.
10052 };
10053
10054 /// Identifies relative preference of a given Caller/Callee
10055 /// combination, based on their host/device attributes.
10056 /// \param Caller function which needs address of \p Callee.
10057 /// nullptr in case of global context.
10058 /// \param Callee target function
10059 ///
10060 /// \returns preference value for particular Caller/Callee combination.
10061 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
10062 const FunctionDecl *Callee);
10063
10064 /// Determines whether Caller may invoke Callee, based on their CUDA
10065 /// host/device attributes. Returns false if the call is not allowed.
10066 ///
10067 /// Note: Will return true for CFP_WrongSide calls. These may appear in
10068 /// semantically correct CUDA programs, but only if they're never codegen'ed.
10069 bool IsAllowedCUDACall(const FunctionDecl *Caller,
10070 const FunctionDecl *Callee) {
10071 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
10072 }
10073
10074 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
10075 /// depending on FD and the current compilation settings.
10076 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
10077 const LookupResult &Previous);
10078
10079public:
10080 /// Check whether we're allowed to call Callee from the current context.
10081 ///
10082 /// - If the call is never allowed in a semantically-correct program
10083 /// (CFP_Never), emits an error and returns false.
10084 ///
10085 /// - If the call is allowed in semantically-correct programs, but only if
10086 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
10087 /// be emitted if and when the caller is codegen'ed, and returns true.
10088 ///
10089 /// Will only create deferred diagnostics for a given SourceLocation once,
10090 /// so you can safely call this multiple times without generating duplicate
10091 /// deferred errors.
10092 ///
10093 /// - Otherwise, returns true without emitting any diagnostics.
10094 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
10095
10096 /// Set __device__ or __host__ __device__ attributes on the given lambda
10097 /// operator() method.
10098 ///
10099 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
10100 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
10101 /// functions become __host__ __device__ themselves.
10102 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
10103
10104 /// Finds a function in \p Matches with highest calling priority
10105 /// from \p Caller context and erases all functions with lower
10106 /// calling priority.
10107 void EraseUnwantedCUDAMatches(
10108 const FunctionDecl *Caller,
10109 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
10110
10111 /// Given a implicit special member, infer its CUDA target from the
10112 /// calls it needs to make to underlying base/field special members.
10113 /// \param ClassDecl the class for which the member is being created.
10114 /// \param CSM the kind of special member.
10115 /// \param MemberDecl the special member itself.
10116 /// \param ConstRHS true if this is a copy operation with a const object on
10117 /// its RHS.
10118 /// \param Diagnose true if this call should emit diagnostics.
10119 /// \return true if there was an error inferring.
10120 /// The result of this call is implicit CUDA target attribute(s) attached to
10121 /// the member declaration.
10122 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
10123 CXXSpecialMember CSM,
10124 CXXMethodDecl *MemberDecl,
10125 bool ConstRHS,
10126 bool Diagnose);
10127
10128 /// \return true if \p CD can be considered empty according to CUDA
10129 /// (E.2.3.1 in CUDA 7.5 Programming guide).
10130 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
10131 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
10132
10133 /// Check whether NewFD is a valid overload for CUDA. Emits
10134 /// diagnostics and invalidates NewFD if not.
10135 void checkCUDATargetOverload(FunctionDecl *NewFD,
10136 const LookupResult &Previous);
10137 /// Copies target attributes from the template TD to the function FD.
10138 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
10139
10140 /// \name Code completion
10141 //@{
10142 /// \brief Describes the context in which code completion occurs.
10143 enum ParserCompletionContext {
10144 /// \brief Code completion occurs at top-level or namespace context.
10145 PCC_Namespace,
10146 /// \brief Code completion occurs within a class, struct, or union.
10147 PCC_Class,
10148 /// \brief Code completion occurs within an Objective-C interface, protocol,
10149 /// or category.
10150 PCC_ObjCInterface,
10151 /// \brief Code completion occurs within an Objective-C implementation or
10152 /// category implementation
10153 PCC_ObjCImplementation,
10154 /// \brief Code completion occurs within the list of instance variables
10155 /// in an Objective-C interface, protocol, category, or implementation.
10156 PCC_ObjCInstanceVariableList,
10157 /// \brief Code completion occurs following one or more template
10158 /// headers.
10159 PCC_Template,
10160 /// \brief Code completion occurs following one or more template
10161 /// headers within a class.
10162 PCC_MemberTemplate,
10163 /// \brief Code completion occurs within an expression.
10164 PCC_Expression,
10165 /// \brief Code completion occurs within a statement, which may
10166 /// also be an expression or a declaration.
10167 PCC_Statement,
10168 /// \brief Code completion occurs at the beginning of the
10169 /// initialization statement (or expression) in a for loop.
10170 PCC_ForInit,
10171 /// \brief Code completion occurs within the condition of an if,
10172 /// while, switch, or for statement.
10173 PCC_Condition,
10174 /// \brief Code completion occurs within the body of a function on a
10175 /// recovery path, where we do not have a specific handle on our position
10176 /// in the grammar.
10177 PCC_RecoveryInFunction,
10178 /// \brief Code completion occurs where only a type is permitted.
10179 PCC_Type,
10180 /// \brief Code completion occurs in a parenthesized expression, which
10181 /// might also be a type cast.
10182 PCC_ParenthesizedExpression,
10183 /// \brief Code completion occurs within a sequence of declaration
10184 /// specifiers within a function, method, or block.
10185 PCC_LocalDeclarationSpecifiers
10186 };
10187
10188 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
10189 void CodeCompleteOrdinaryName(Scope *S,
10190 ParserCompletionContext CompletionContext);
10191 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
10192 bool AllowNonIdentifiers,
10193 bool AllowNestedNameSpecifiers);
10194
10195 struct CodeCompleteExpressionData;
10196 void CodeCompleteExpression(Scope *S,
10197 const CodeCompleteExpressionData &Data);
10198 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
10199 SourceLocation OpLoc, bool IsArrow,
10200 bool IsBaseExprStatement);
10201 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
10202 void CodeCompleteTag(Scope *S, unsigned TagSpec);
10203 void CodeCompleteTypeQualifiers(DeclSpec &DS);
10204 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
10205 const VirtSpecifiers *VS = nullptr);
10206 void CodeCompleteBracketDeclarator(Scope *S);
10207 void CodeCompleteCase(Scope *S);
10208 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
10209 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
10210 ArrayRef<Expr *> Args);
10211 void CodeCompleteInitializer(Scope *S, Decl *D);
10212 void CodeCompleteReturn(Scope *S);
10213 void CodeCompleteAfterIf(Scope *S);
10214 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
10215
10216 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
10217 bool EnteringContext);
10218 void CodeCompleteUsing(Scope *S);
10219 void CodeCompleteUsingDirective(Scope *S);
10220 void CodeCompleteNamespaceDecl(Scope *S);
10221 void CodeCompleteNamespaceAliasDecl(Scope *S);
10222 void CodeCompleteOperatorName(Scope *S);
10223 void CodeCompleteConstructorInitializer(
10224 Decl *Constructor,
10225 ArrayRef<CXXCtorInitializer *> Initializers);
10226
10227 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
10228 bool AfterAmpersand);
10229
10230 void CodeCompleteObjCAtDirective(Scope *S);
10231 void CodeCompleteObjCAtVisibility(Scope *S);
10232 void CodeCompleteObjCAtStatement(Scope *S);
10233 void CodeCompleteObjCAtExpression(Scope *S);
10234 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
10235 void CodeCompleteObjCPropertyGetter(Scope *S);
10236 void CodeCompleteObjCPropertySetter(Scope *S);
10237 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
10238 bool IsParameter);
10239 void CodeCompleteObjCMessageReceiver(Scope *S);
10240 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
10241 ArrayRef<IdentifierInfo *> SelIdents,
10242 bool AtArgumentExpression);
10243 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
10244 ArrayRef<IdentifierInfo *> SelIdents,
10245 bool AtArgumentExpression,
10246 bool IsSuper = false);
10247 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
10248 ArrayRef<IdentifierInfo *> SelIdents,
10249 bool AtArgumentExpression,
10250 ObjCInterfaceDecl *Super = nullptr);
10251 void CodeCompleteObjCForCollection(Scope *S,
10252 DeclGroupPtrTy IterationVar);
10253 void CodeCompleteObjCSelector(Scope *S,
10254 ArrayRef<IdentifierInfo *> SelIdents);
10255 void CodeCompleteObjCProtocolReferences(
10256 ArrayRef<IdentifierLocPair> Protocols);
10257 void CodeCompleteObjCProtocolDecl(Scope *S);
10258 void CodeCompleteObjCInterfaceDecl(Scope *S);
10259 void CodeCompleteObjCSuperclass(Scope *S,
10260 IdentifierInfo *ClassName,
10261 SourceLocation ClassNameLoc);
10262 void CodeCompleteObjCImplementationDecl(Scope *S);
10263 void CodeCompleteObjCInterfaceCategory(Scope *S,
10264 IdentifierInfo *ClassName,
10265 SourceLocation ClassNameLoc);
10266 void CodeCompleteObjCImplementationCategory(Scope *S,
10267 IdentifierInfo *ClassName,
10268 SourceLocation ClassNameLoc);
10269 void CodeCompleteObjCPropertyDefinition(Scope *S);
10270 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10271 IdentifierInfo *PropertyName);
10272 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
10273 ParsedType ReturnType);
10274 void CodeCompleteObjCMethodDeclSelector(Scope *S,
10275 bool IsInstanceMethod,
10276 bool AtParameterName,
10277 ParsedType ReturnType,
10278 ArrayRef<IdentifierInfo *> SelIdents);
10279 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10280 SourceLocation ClassNameLoc,
10281 bool IsBaseExprStatement);
10282 void CodeCompletePreprocessorDirective(bool InConditional);
10283 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10284 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10285 void CodeCompletePreprocessorExpression();
10286 void CodeCompletePreprocessorMacroArgument(Scope *S,
10287 IdentifierInfo *Macro,
10288 MacroInfo *MacroInfo,
10289 unsigned Argument);
10290 void CodeCompleteNaturalLanguage();
10291 void CodeCompleteAvailabilityPlatformName();
10292 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10293 CodeCompletionTUInfo &CCTUInfo,
10294 SmallVectorImpl<CodeCompletionResult> &Results);
10295 //@}
10296
10297 //===--------------------------------------------------------------------===//
10298 // Extra semantic analysis beyond the C type system
10299
10300public:
10301 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10302 unsigned ByteNo) const;
10303
10304private:
10305 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10306 const ArraySubscriptExpr *ASE=nullptr,
10307 bool AllowOnePastEnd=true, bool IndexNegated=false);
10308 void CheckArrayAccess(const Expr *E);
10309 // Used to grab the relevant information from a FormatAttr and a
10310 // FunctionDeclaration.
10311 struct FormatStringInfo {
10312 unsigned FormatIdx;
10313 unsigned FirstDataArg;
10314 bool HasVAListArg;
10315 };
10316
10317 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10318 FormatStringInfo *FSI);
10319 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10320 const FunctionProtoType *Proto);
10321 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10322 ArrayRef<const Expr *> Args);
10323 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10324 const FunctionProtoType *Proto);
10325 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10326 void CheckConstructorCall(FunctionDecl *FDecl,
10327 ArrayRef<const Expr *> Args,
10328 const FunctionProtoType *Proto,
10329 SourceLocation Loc);
10330
10331 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10332 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10333 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10334 VariadicCallType CallType);
10335
10336 bool CheckObjCString(Expr *Arg);
10337 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10338
10339 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10340 unsigned BuiltinID, CallExpr *TheCall);
10341
10342 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10343 unsigned MaxWidth);
10344 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10345 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10346
10347 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10348 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10349 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10350 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10351 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10352 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10353 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10354
10355 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10356 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
10357 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10358 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10359 bool SemaBuiltinVSX(CallExpr *TheCall);
10360 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10361
10362public:
10363 // Used by C++ template instantiation.
10364 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10365 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10366 SourceLocation BuiltinLoc,
10367 SourceLocation RParenLoc);
10368
10369private:
10370 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10371 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10372 bool SemaBuiltinAssume(CallExpr *TheCall);
10373 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10374 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10375 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10376 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10377 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10378 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10379 AtomicExpr::AtomicOp Op);
10380 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10381 llvm::APSInt &Result);
10382 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10383 int Low, int High);
10384 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10385 unsigned Multiple);
10386 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10387 int ArgNum, unsigned ExpectedFieldNum,
10388 bool AllowName);
10389public:
10390 enum FormatStringType {
10391 FST_Scanf,
10392 FST_Printf,
10393 FST_NSString,
10394 FST_Strftime,
10395 FST_Strfmon,
10396 FST_Kprintf,
10397 FST_FreeBSDKPrintf,
10398 FST_OSTrace,
10399 FST_OSLog,
10400 FST_Unknown
10401 };
10402 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10403
10404 bool FormatStringHasSArg(const StringLiteral *FExpr);
10405
10406 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10407
10408private:
10409 bool CheckFormatArguments(const FormatAttr *Format,
10410 ArrayRef<const Expr *> Args,
10411 bool IsCXXMember,
10412 VariadicCallType CallType,
10413 SourceLocation Loc, SourceRange Range,
10414 llvm::SmallBitVector &CheckedVarArgs);
10415 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10416 bool HasVAListArg, unsigned format_idx,
10417 unsigned firstDataArg, FormatStringType Type,
10418 VariadicCallType CallType,
10419 SourceLocation Loc, SourceRange range,
10420 llvm::SmallBitVector &CheckedVarArgs);
10421
10422 void CheckAbsoluteValueFunction(const CallExpr *Call,
10423 const FunctionDecl *FDecl);
10424
10425 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10426
10427 void CheckMemaccessArguments(const CallExpr *Call,
10428 unsigned BId,
10429 IdentifierInfo *FnName);
10430
10431 void CheckStrlcpycatArguments(const CallExpr *Call,
10432 IdentifierInfo *FnName);
10433
10434 void CheckStrncatArguments(const CallExpr *Call,
10435 IdentifierInfo *FnName);
10436
10437 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10438 SourceLocation ReturnLoc,
10439 bool isObjCMethod = false,
10440 const AttrVec *Attrs = nullptr,
10441 const FunctionDecl *FD = nullptr);
10442
10443public:
10444 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
10445
10446private:
10447 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10448 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10449 void CheckForIntOverflow(Expr *E);
10450 void CheckUnsequencedOperations(Expr *E);
10451
10452 /// \brief Perform semantic checks on a completed expression. This will either
10453 /// be a full-expression or a default argument expression.
10454 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10455 bool IsConstexpr = false);
10456
10457 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10458 Expr *Init);
10459
10460 /// Check if there is a field shadowing.
10461 void CheckShadowInheritedFields(const SourceLocation &Loc,
10462 DeclarationName FieldName,
10463 const CXXRecordDecl *RD);
10464
10465 /// \brief Check if the given expression contains 'break' or 'continue'
10466 /// statement that produces control flow different from GCC.
10467 void CheckBreakContinueBinding(Expr *E);
10468
10469 /// \brief Check whether receiver is mutable ObjC container which
10470 /// attempts to add itself into the container
10471 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10472
10473 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10474 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10475 bool DeleteWasArrayForm);
10476public:
10477 /// \brief Register a magic integral constant to be used as a type tag.
10478 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10479 uint64_t MagicValue, QualType Type,
10480 bool LayoutCompatible, bool MustBeNull);
10481
10482 struct TypeTagData {
10483 TypeTagData() {}
10484
10485 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10486 Type(Type), LayoutCompatible(LayoutCompatible),
10487 MustBeNull(MustBeNull)
10488 {}
10489
10490 QualType Type;
10491
10492 /// If true, \c Type should be compared with other expression's types for
10493 /// layout-compatibility.
10494 unsigned LayoutCompatible : 1;
10495 unsigned MustBeNull : 1;
10496 };
10497
10498 /// A pair of ArgumentKind identifier and magic value. This uniquely
10499 /// identifies the magic value.
10500 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10501
10502private:
10503 /// \brief A map from magic value to type information.
10504 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10505 TypeTagForDatatypeMagicValues;
10506
10507 /// \brief Peform checks on a call of a function with argument_with_type_tag
10508 /// or pointer_with_type_tag attributes.
10509 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10510 const ArrayRef<const Expr *> ExprArgs,
10511 SourceLocation CallSiteLoc);
10512
10513 /// \brief Check if we are taking the address of a packed field
10514 /// as this may be a problem if the pointer value is dereferenced.
10515 void CheckAddressOfPackedMember(Expr *rhs);
10516
10517 /// \brief The parser's current scope.
10518 ///
10519 /// The parser maintains this state here.
10520 Scope *CurScope;
10521
10522 mutable IdentifierInfo *Ident_super;
10523 mutable IdentifierInfo *Ident___float128;
10524
10525 /// Nullability type specifiers.
10526 IdentifierInfo *Ident__Nonnull = nullptr;
10527 IdentifierInfo *Ident__Nullable = nullptr;
10528 IdentifierInfo *Ident__Null_unspecified = nullptr;
10529
10530 IdentifierInfo *Ident_NSError = nullptr;
10531
10532 /// \brief The handler for the FileChanged preprocessor events.
10533 ///
10534 /// Used for diagnostics that implement custom semantic analysis for #include
10535 /// directives, like -Wpragma-pack.
10536 sema::SemaPPCallbacks *SemaPPCallbackHandler;
10537
10538protected:
10539 friend class Parser;
10540 friend class InitializationSequence;
10541 friend class ASTReader;
10542 friend class ASTDeclReader;
10543 friend class ASTWriter;
10544
10545public:
10546 /// Retrieve the keyword associated
10547 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10548
10549 /// The struct behind the CFErrorRef pointer.
10550 RecordDecl *CFError = nullptr;
10551
10552 /// Retrieve the identifier "NSError".
10553 IdentifierInfo *getNSErrorIdent();
10554
10555 /// \brief Retrieve the parser's current scope.
10556 ///
10557 /// This routine must only be used when it is certain that semantic analysis
10558 /// and the parser are in precisely the same context, which is not the case
10559 /// when, e.g., we are performing any kind of template instantiation.
10560 /// Therefore, the only safe places to use this scope are in the parser
10561 /// itself and in routines directly invoked from the parser and *never* from
10562 /// template substitution or instantiation.
10563 Scope *getCurScope() const { return CurScope; }
10564
10565 void incrementMSManglingNumber() const {
10566 return CurScope->incrementMSManglingNumber();
10567 }
10568
10569 IdentifierInfo *getSuperIdentifier() const;
10570 IdentifierInfo *getFloat128Identifier() const;
10571
10572 Decl *getObjCDeclContext() const;
10573
10574 DeclContext *getCurLexicalContext() const {
10575 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10576 }
10577
10578 const DeclContext *getCurObjCLexicalContext() const {
10579 const DeclContext *DC = getCurLexicalContext();
10580 // A category implicitly has the attribute of the interface.
10581 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10582 DC = CatD->getClassInterface();
10583 return DC;
10584 }
10585
10586 /// \brief To be used for checking whether the arguments being passed to
10587 /// function exceeds the number of parameters expected for it.
10588 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10589 bool PartialOverloading = false) {
10590 // We check whether we're just after a comma in code-completion.
10591 if (NumArgs > 0 && PartialOverloading)
10592 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10593 return NumArgs > NumParams;
10594 }
10595
10596 // Emitting members of dllexported classes is delayed until the class
10597 // (including field initializers) is fully parsed.
10598 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10599
10600private:
10601 class SavePendingParsedClassStateRAII {
10602 public:
10603 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
10604
10605 ~SavePendingParsedClassStateRAII() {
10606 assert(S.DelayedExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedExceptionSpecChecks.empty
() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 10607, __extension__ __PRETTY_FUNCTION__))
10607 "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedExceptionSpecChecks.empty
() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 10607, __extension__ __PRETTY_FUNCTION__))
;
10608 assert(S.DelayedDefaultedMemberExceptionSpecs.empty() &&(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 10610, __extension__ __PRETTY_FUNCTION__))
10609 "there shouldn't be any pending delayed defaulted member "(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 10610, __extension__ __PRETTY_FUNCTION__))
10610 "exception specs")(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 10610, __extension__ __PRETTY_FUNCTION__))
;
10611 assert(S.DelayedDllExportClasses.empty() &&(static_cast <bool> (S.DelayedDllExportClasses.empty() &&
"there shouldn't be any pending delayed DLL export classes")
? void (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 10612, __extension__ __PRETTY_FUNCTION__))
10612 "there shouldn't be any pending delayed DLL export classes")(static_cast <bool> (S.DelayedDllExportClasses.empty() &&
"there shouldn't be any pending delayed DLL export classes")
? void (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Sema/Sema.h"
, 10612, __extension__ __PRETTY_FUNCTION__))
;
10613 swapSavedState();
10614 }
10615
10616 private:
10617 Sema &S;
10618 decltype(DelayedExceptionSpecChecks) SavedExceptionSpecChecks;
10619 decltype(DelayedDefaultedMemberExceptionSpecs)
10620 SavedDefaultedMemberExceptionSpecs;
10621 decltype(DelayedDllExportClasses) SavedDllExportClasses;
10622
10623 void swapSavedState() {
10624 SavedExceptionSpecChecks.swap(S.DelayedExceptionSpecChecks);
10625 SavedDefaultedMemberExceptionSpecs.swap(
10626 S.DelayedDefaultedMemberExceptionSpecs);
10627 SavedDllExportClasses.swap(S.DelayedDllExportClasses);
10628 }
10629 };
10630
10631 /// \brief Helper class that collects misaligned member designations and
10632 /// their location info for delayed diagnostics.
10633 struct MisalignedMember {
10634 Expr *E;
10635 RecordDecl *RD;
10636 ValueDecl *MD;
10637 CharUnits Alignment;
10638
10639 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10640 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10641 CharUnits Alignment)
10642 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10643 explicit MisalignedMember(Expr *E)
10644 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10645
10646 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10647 };
10648 /// \brief Small set of gathered accesses to potentially misaligned members
10649 /// due to the packed attribute.
10650 SmallVector<MisalignedMember, 4> MisalignedMembers;
10651
10652 /// \brief Adds an expression to the set of gathered misaligned members.
10653 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10654 CharUnits Alignment);
10655
10656public:
10657 /// \brief Diagnoses the current set of gathered accesses. This typically
10658 /// happens at full expression level. The set is cleared after emitting the
10659 /// diagnostics.
10660 void DiagnoseMisalignedMembers();
10661
10662 /// \brief This function checks if the expression is in the sef of potentially
10663 /// misaligned members and it is converted to some pointer type T with lower
10664 /// or equal alignment requirements. If so it removes it. This is used when
10665 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10666 /// void*).
10667 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10668
10669 /// \brief This function calls Action when it determines that E designates a
10670 /// misaligned member due to the packed attribute. This is used to emit
10671 /// local diagnostics like in reference binding.
10672 void RefersToMemberWithReducedAlignment(
10673 Expr *E,
10674 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10675 Action);
10676};
10677
10678/// \brief RAII object that enters a new expression evaluation context.
10679class EnterExpressionEvaluationContext {
10680 Sema &Actions;
10681 bool Entered = true;
10682
10683public:
10684
10685 EnterExpressionEvaluationContext(Sema &Actions,
10686 Sema::ExpressionEvaluationContext NewContext,
10687 Decl *LambdaContextDecl = nullptr,
10688 bool IsDecltype = false,
10689 bool ShouldEnter = true)
10690 : Actions(Actions), Entered(ShouldEnter) {
10691 if (Entered)
10692 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10693 IsDecltype);
10694 }
10695 EnterExpressionEvaluationContext(Sema &Actions,
10696 Sema::ExpressionEvaluationContext NewContext,
10697 Sema::ReuseLambdaContextDecl_t,
10698 bool IsDecltype = false)
10699 : Actions(Actions) {
10700 Actions.PushExpressionEvaluationContext(NewContext,
10701 Sema::ReuseLambdaContextDecl,
10702 IsDecltype);
10703 }
10704
10705 enum InitListTag { InitList };
10706 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10707 bool ShouldEnter = true)
10708 : Actions(Actions), Entered(false) {
10709 // In C++11 onwards, narrowing checks are performed on the contents of
10710 // braced-init-lists, even when they occur within unevaluated operands.
10711 // Therefore we still need to instantiate constexpr functions used in such
10712 // a context.
10713 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10714 Actions.getLangOpts().CPlusPlus11) {
10715 Actions.PushExpressionEvaluationContext(
10716 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10717 Entered = true;
10718 }
10719 }
10720
10721 ~EnterExpressionEvaluationContext() {
10722 if (Entered)
10723 Actions.PopExpressionEvaluationContext();
10724 }
10725};
10726
10727DeductionFailureInfo
10728MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10729 sema::TemplateDeductionInfo &Info);
10730
10731/// \brief Contains a late templated function.
10732/// Will be parsed at the end of the translation unit, used by Sema & Parser.
10733struct LateParsedTemplate {
10734 CachedTokens Toks;
10735 /// \brief The template function declaration to be late parsed.
10736 Decl *D;
10737};
10738
10739} // end namespace clang
10740
10741namespace llvm {
10742// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10743// SourceLocation.
10744template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10745 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10746 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10747
10748 static FunctionDeclAndLoc getEmptyKey() {
10749 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10750 }
10751
10752 static FunctionDeclAndLoc getTombstoneKey() {
10753 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10754 }
10755
10756 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10757 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10758 FDL.Loc.getRawEncoding());
10759 }
10760
10761 static bool isEqual(const FunctionDeclAndLoc &LHS,
10762 const FunctionDeclAndLoc &RHS) {
10763 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10764 }
10765};
10766} // namespace llvm
10767
10768#endif

/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Basic/PartialDiagnostic.h

1//===--- PartialDiagnostic.h - Diagnostic "closures" ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief Implements a partial diagnostic that can be emitted anwyhere
12/// in a DiagnosticBuilder stream.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H
17#define LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H
18
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/SourceLocation.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Support/DataTypes.h"
24#include <cassert>
25
26namespace clang {
27
28class PartialDiagnostic {
29public:
30 enum {
31 // The MaxArguments and MaxFixItHints member enum values from
32 // DiagnosticsEngine are private but DiagnosticsEngine declares
33 // PartialDiagnostic a friend. These enum values are redeclared
34 // here so that the nested Storage class below can access them.
35 MaxArguments = DiagnosticsEngine::MaxArguments
36 };
37
38 struct Storage {
39 Storage() : NumDiagArgs(0) { }
40
41 enum {
42 /// \brief The maximum number of arguments we can hold. We
43 /// currently only support up to 10 arguments (%0-%9).
44 ///
45 /// A single diagnostic with more than that almost certainly has to
46 /// be simplified anyway.
47 MaxArguments = PartialDiagnostic::MaxArguments
48 };
49
50 /// \brief The number of entries in Arguments.
51 unsigned char NumDiagArgs;
52
53 /// \brief Specifies for each argument whether it is in DiagArgumentsStr
54 /// or in DiagArguments.
55 unsigned char DiagArgumentsKind[MaxArguments];
56
57 /// \brief The values for the various substitution positions.
58 ///
59 /// This is used when the argument is not an std::string. The specific value
60 /// is mangled into an intptr_t and the interpretation depends on exactly
61 /// what sort of argument kind it is.
62 intptr_t DiagArgumentsVal[MaxArguments];
63
64 /// \brief The values for the various substitution positions that have
65 /// string arguments.
66 std::string DiagArgumentsStr[MaxArguments];
67
68 /// \brief The list of ranges added to this diagnostic.
69 SmallVector<CharSourceRange, 8> DiagRanges;
70
71 /// \brief If valid, provides a hint with some code to insert, remove, or
72 /// modify at a particular position.
73 SmallVector<FixItHint, 6> FixItHints;
74 };
75
76 /// \brief An allocator for Storage objects, which uses a small cache to
77 /// objects, used to reduce malloc()/free() traffic for partial diagnostics.
78 class StorageAllocator {
79 static const unsigned NumCached = 16;
80 Storage Cached[NumCached];
81 Storage *FreeList[NumCached];
82 unsigned NumFreeListEntries;
83
84 public:
85 StorageAllocator();
86 ~StorageAllocator();
87
88 /// \brief Allocate new storage.
89 Storage *Allocate() {
90 if (NumFreeListEntries == 0)
91 return new Storage;
92
93 Storage *Result = FreeList[--NumFreeListEntries];
94 Result->NumDiagArgs = 0;
95 Result->DiagRanges.clear();
96 Result->FixItHints.clear();
97 return Result;
98 }
99
100 /// \brief Free the given storage object.
101 void Deallocate(Storage *S) {
102 if (S >= Cached && S <= Cached + NumCached) {
103 FreeList[NumFreeListEntries++] = S;
104 return;
105 }
106
107 delete S;
108 }
109 };
110
111private:
112 // NOTE: Sema assumes that PartialDiagnostic is location-invariant
113 // in the sense that its bits can be safely memcpy'ed and destructed
114 // in the new location.
115
116 /// \brief The diagnostic ID.
117 mutable unsigned DiagID;
118
119 /// \brief Storage for args and ranges.
120 mutable Storage *DiagStorage;
121
122 /// \brief Allocator used to allocate storage for this diagnostic.
123 StorageAllocator *Allocator;
124
125 /// \brief Retrieve storage for this particular diagnostic.
126 Storage *getStorage() const {
127 if (DiagStorage)
14
Taking false branch
128 return DiagStorage;
129
130 if (Allocator)
15
Assuming the condition is false
16
Taking false branch
131 DiagStorage = Allocator->Allocate();
132 else {
133 assert(Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))(static_cast <bool> (Allocator != reinterpret_cast<StorageAllocator
*>(~uintptr_t(0))) ? void (0) : __assert_fail ("Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0))"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 133, __extension__ __PRETTY_FUNCTION__))
;
134 DiagStorage = new Storage;
17
Memory is allocated
135 }
136 return DiagStorage;
137 }
138
139 void freeStorage() {
140 if (!DiagStorage)
141 return;
142
143 // The hot path for PartialDiagnostic is when we just used it to wrap an ID
144 // (typically so we have the flexibility of passing a more complex
145 // diagnostic into the callee, but that does not commonly occur).
146 //
147 // Split this out into a slow function for silly compilers (*cough*) which
148 // can't do decent partial inlining.
149 freeStorageSlow();
150 }
151
152 void freeStorageSlow() {
153 if (Allocator)
154 Allocator->Deallocate(DiagStorage);
155 else if (Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))
156 delete DiagStorage;
157 DiagStorage = nullptr;
158 }
159
160 void AddSourceRange(const CharSourceRange &R) const {
161 if (!DiagStorage)
162 DiagStorage = getStorage();
163
164 DiagStorage->DiagRanges.push_back(R);
165 }
166
167 void AddFixItHint(const FixItHint &Hint) const {
168 if (Hint.isNull())
169 return;
170
171 if (!DiagStorage)
172 DiagStorage = getStorage();
173
174 DiagStorage->FixItHints.push_back(Hint);
175 }
176
177public:
178 struct NullDiagnostic {};
179 /// \brief Create a null partial diagnostic, which cannot carry a payload,
180 /// and only exists to be swapped with a real partial diagnostic.
181 PartialDiagnostic(NullDiagnostic)
182 : DiagID(0), DiagStorage(nullptr), Allocator(nullptr) { }
183
184 PartialDiagnostic(unsigned DiagID, StorageAllocator &Allocator)
185 : DiagID(DiagID), DiagStorage(nullptr), Allocator(&Allocator) { }
186
187 PartialDiagnostic(const PartialDiagnostic &Other)
188 : DiagID(Other.DiagID), DiagStorage(nullptr), Allocator(Other.Allocator)
189 {
190 if (Other.DiagStorage) {
191 DiagStorage = getStorage();
192 *DiagStorage = *Other.DiagStorage;
193 }
194 }
195
196 PartialDiagnostic(PartialDiagnostic &&Other)
197 : DiagID(Other.DiagID), DiagStorage(Other.DiagStorage),
198 Allocator(Other.Allocator) {
199 Other.DiagStorage = nullptr;
200 }
201
202 PartialDiagnostic(const PartialDiagnostic &Other, Storage *DiagStorage)
203 : DiagID(Other.DiagID), DiagStorage(DiagStorage),
204 Allocator(reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))
205 {
206 if (Other.DiagStorage)
207 *this->DiagStorage = *Other.DiagStorage;
208 }
209
210 PartialDiagnostic(const Diagnostic &Other, StorageAllocator &Allocator)
211 : DiagID(Other.getID()), DiagStorage(nullptr), Allocator(&Allocator)
212 {
213 // Copy arguments.
214 for (unsigned I = 0, N = Other.getNumArgs(); I != N; ++I) {
215 if (Other.getArgKind(I) == DiagnosticsEngine::ak_std_string)
216 AddString(Other.getArgStdStr(I));
217 else
218 AddTaggedVal(Other.getRawArg(I), Other.getArgKind(I));
219 }
220
221 // Copy source ranges.
222 for (unsigned I = 0, N = Other.getNumRanges(); I != N; ++I)
223 AddSourceRange(Other.getRange(I));
224
225 // Copy fix-its.
226 for (unsigned I = 0, N = Other.getNumFixItHints(); I != N; ++I)
227 AddFixItHint(Other.getFixItHint(I));
228 }
229
230 PartialDiagnostic &operator=(const PartialDiagnostic &Other) {
231 DiagID = Other.DiagID;
232 if (Other.DiagStorage) {
233 if (!DiagStorage)
234 DiagStorage = getStorage();
235
236 *DiagStorage = *Other.DiagStorage;
237 } else {
238 freeStorage();
239 }
240
241 return *this;
242 }
243
244 PartialDiagnostic &operator=(PartialDiagnostic &&Other) {
245 freeStorage();
246
247 DiagID = Other.DiagID;
248 DiagStorage = Other.DiagStorage;
249 Allocator = Other.Allocator;
250
251 Other.DiagStorage = nullptr;
252 return *this;
253 }
254
255 ~PartialDiagnostic() {
256 freeStorage();
257 }
258
259 void swap(PartialDiagnostic &PD) {
260 std::swap(DiagID, PD.DiagID);
261 std::swap(DiagStorage, PD.DiagStorage);
262 std::swap(Allocator, PD.Allocator);
263 }
264
265 unsigned getDiagID() const { return DiagID; }
266
267 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
268 if (!DiagStorage)
11
Assuming the condition is true
12
Taking true branch
269 DiagStorage = getStorage();
13
Calling 'PartialDiagnostic::getStorage'
18
Returned allocated memory
270
271 assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 272, __extension__ __PRETTY_FUNCTION__))
272 "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 272, __extension__ __PRETTY_FUNCTION__))
;
273 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
274 DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
275 }
276
277 void AddString(StringRef V) const {
278 if (!DiagStorage)
279 DiagStorage = getStorage();
280
281 assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 282, __extension__ __PRETTY_FUNCTION__))
282 "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 282, __extension__ __PRETTY_FUNCTION__))
;
283 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs]
284 = DiagnosticsEngine::ak_std_string;
285 DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = V;
286 }
287
288 void Emit(const DiagnosticBuilder &DB) const {
289 if (!DiagStorage)
290 return;
291
292 // Add all arguments.
293 for (unsigned i = 0, e = DiagStorage->NumDiagArgs; i != e; ++i) {
294 if ((DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i]
295 == DiagnosticsEngine::ak_std_string)
296 DB.AddString(DiagStorage->DiagArgumentsStr[i]);
297 else
298 DB.AddTaggedVal(DiagStorage->DiagArgumentsVal[i],
299 (DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i]);
300 }
301
302 // Add all ranges.
303 for (const CharSourceRange &Range : DiagStorage->DiagRanges)
304 DB.AddSourceRange(Range);
305
306 // Add all fix-its.
307 for (const FixItHint &Fix : DiagStorage->FixItHints)
308 DB.AddFixItHint(Fix);
309 }
310
311 void EmitToString(DiagnosticsEngine &Diags,
312 SmallVectorImpl<char> &Buf) const {
313 // FIXME: It should be possible to render a diagnostic to a string without
314 // messing with the state of the diagnostics engine.
315 DiagnosticBuilder DB(Diags.Report(getDiagID()));
316 Emit(DB);
317 DB.FlushCounts();
318 Diagnostic(&Diags).FormatDiagnostic(Buf);
319 DB.Clear();
320 Diags.Clear();
321 }
322
323 /// \brief Clear out this partial diagnostic, giving it a new diagnostic ID
324 /// and removing all of its arguments, ranges, and fix-it hints.
325 void Reset(unsigned DiagID = 0) {
326 this->DiagID = DiagID;
327 freeStorage();
328 }
329
330 bool hasStorage() const { return DiagStorage != nullptr; }
331
332 /// Retrieve the string argument at the given index.
333 StringRef getStringArg(unsigned I) {
334 assert(DiagStorage && "No diagnostic storage?")(static_cast <bool> (DiagStorage && "No diagnostic storage?"
) ? void (0) : __assert_fail ("DiagStorage && \"No diagnostic storage?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 334, __extension__ __PRETTY_FUNCTION__))
;
335 assert(I < DiagStorage->NumDiagArgs && "Not enough diagnostic args")(static_cast <bool> (I < DiagStorage->NumDiagArgs
&& "Not enough diagnostic args") ? void (0) : __assert_fail
("I < DiagStorage->NumDiagArgs && \"Not enough diagnostic args\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 335, __extension__ __PRETTY_FUNCTION__))
;
336 assert(DiagStorage->DiagArgumentsKind[I](static_cast <bool> (DiagStorage->DiagArgumentsKind[
I] == DiagnosticsEngine::ak_std_string && "Not a string arg"
) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 337, __extension__ __PRETTY_FUNCTION__))
337 == DiagnosticsEngine::ak_std_string && "Not a string arg")(static_cast <bool> (DiagStorage->DiagArgumentsKind[
I] == DiagnosticsEngine::ak_std_string && "Not a string arg"
) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 337, __extension__ __PRETTY_FUNCTION__))
;
338 return DiagStorage->DiagArgumentsStr[I];
339 }
340
341 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
342 unsigned I) {
343 PD.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
344 return PD;
345 }
346
347 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
348 int I) {
349 PD.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
10
Calling 'PartialDiagnostic::AddTaggedVal'
19
Returned allocated memory
350 return PD;
351 }
352
353 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
354 const char *S) {
355 PD.AddTaggedVal(reinterpret_cast<intptr_t>(S),
356 DiagnosticsEngine::ak_c_string);
357 return PD;
358 }
359
360 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
361 StringRef S) {
362
363 PD.AddString(S);
364 return PD;
365 }
366
367 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
368 const IdentifierInfo *II) {
369 PD.AddTaggedVal(reinterpret_cast<intptr_t>(II),
370 DiagnosticsEngine::ak_identifierinfo);
371 return PD;
372 }
373
374 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
375 // so that we only match those arguments that are (statically) DeclContexts;
376 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
377 // match.
378 template<typename T>
379 friend inline
380 typename std::enable_if<std::is_same<T, DeclContext>::value,
381 const PartialDiagnostic &>::type
382 operator<<(const PartialDiagnostic &PD, T *DC) {
383 PD.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
384 DiagnosticsEngine::ak_declcontext);
385 return PD;
386 }
387
388 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
389 SourceRange R) {
390 PD.AddSourceRange(CharSourceRange::getTokenRange(R));
391 return PD;
392 }
393
394 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
395 const CharSourceRange &R) {
396 PD.AddSourceRange(R);
397 return PD;
398 }
399
400 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
401 const FixItHint &Hint) {
402 PD.AddFixItHint(Hint);
403 return PD;
404 }
405
406};
407
408inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
409 const PartialDiagnostic &PD) {
410 PD.Emit(DB);
411 return DB;
412}
413
414/// \brief A partial diagnostic along with the source location where this
415/// diagnostic occurs.
416typedef std::pair<SourceLocation, PartialDiagnostic> PartialDiagnosticAt;
417
418} // end namespace clang
419#endif