blob: cb6b030b7127597e0960f6666f99d7e3659317f2 [file] [log] [blame]
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001//===--- 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
David Majnemer929025d2016-01-26 19:30:26 +000014#include "clang/AST/ASTConsumer.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000015#include "clang/AST/ASTContext.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "clang/AST/ASTMutationListener.h"
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +000017#include "clang/AST/CXXInheritance.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar56fdb6a2008-08-11 06:23:49 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/DeclTemplate.h"
Daniel Dunbar56fdb6a2008-08-11 06:23:49 +000021#include "clang/AST/Expr.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000022#include "clang/AST/ExprCXX.h"
Rafael Espindoladb77c4a2013-02-26 19:13:56 +000023#include "clang/AST/Mangle.h"
Erik Pilkington5cd57172016-08-16 17:44:11 +000024#include "clang/AST/RecursiveASTVisitor.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000025#include "clang/Basic/CharInfo.h"
John McCall31168b02011-06-15 23:02:42 +000026#include "clang/Basic/SourceManager.h"
Chris Lattneracbc2d22008-06-27 22:18:37 +000027#include "clang/Basic/TargetInfo.h"
Benjamin Kramer6ee15622013-09-13 15:35:43 +000028#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000029#include "clang/Sema/DeclSpec.h"
John McCallb45a1e72010-08-26 02:13:20 +000030#include "clang/Sema/DelayedDiagnostic.h"
Artem Belevichbcec9da2016-06-06 22:54:57 +000031#include "clang/Sema/Initialization.h"
John McCallf1e8b342011-09-29 07:17:38 +000032#include "clang/Sema/Lookup.h"
Richard Smithe233fbf2013-01-28 22:42:45 +000033#include "clang/Sema/Scope.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000034#include "clang/Sema/SemaInternal.h"
George Burgess IV177399e2017-01-09 04:12:14 +000035#include "llvm/ADT/STLExtras.h"
Chris Lattner30ba6742009-08-10 19:03:04 +000036#include "llvm/ADT/StringExtras.h"
Hal Finkelee90a222014-09-26 05:04:30 +000037#include "llvm/Support/MathExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000038
Chris Lattner2c6fcf52008-06-26 18:38:35 +000039using namespace clang;
John McCallb45a1e72010-08-26 02:13:20 +000040using namespace sema;
Chris Lattner2c6fcf52008-06-26 18:38:35 +000041
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000042namespace AttributeLangSupport {
NAKAMURA Takumi01d27f92013-11-25 00:52:29 +000043 enum LANG {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000044 C,
45 Cpp,
46 ObjC
47 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000048} // end namespace AttributeLangSupport
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000049
Chris Lattner58418ff2008-06-29 00:16:31 +000050//===----------------------------------------------------------------------===//
51// Helper functions
52//===----------------------------------------------------------------------===//
53
Ted Kremenek527042b2009-08-14 20:49:40 +000054/// isFunctionOrMethod - Return true if the given decl has function
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000055/// type (function or function-typed variable) or an Objective-C
56/// method.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000057static bool isFunctionOrMethod(const Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +000058 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
Fariborz Jahanian4447e172009-05-15 23:15:03 +000059}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000060
David Majnemer06864812015-04-07 06:01:53 +000061/// \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}
Fariborz Jahanian4447e172009-05-15 23:15:03 +000066
John McCall3882ace2011-01-05 12:14:39 +000067/// Return true if the given decl has a declarator that should have
68/// been processed by Sema::GetTypeForDeclarator.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000069static bool hasDeclarator(const Decl *D) {
John McCall31168b02011-06-15 23:02:42 +000070 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000071 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
72 isa<ObjCPropertyDecl>(D);
John McCall3882ace2011-01-05 12:14:39 +000073}
74
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000075/// hasFunctionProto - Return true if the given decl has a argument
76/// information. This decl should have already passed
Fariborz Jahanian4447e172009-05-15 23:15:03 +000077/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000078static bool hasFunctionProto(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000079 if (const FunctionType *FnTy = D->getFunctionType())
Douglas Gregordeaad8c2009-02-26 23:50:07 +000080 return isa<FunctionProtoType>(FnTy);
Aaron Ballman12b9f652014-01-16 13:55:42 +000081 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000082}
83
Alp Toker601b22c2014-01-21 23:35:24 +000084/// getFunctionOrMethodNumParams - Return number of function or method
85/// parameters. It is an error to call this on a K&R function (use
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000086/// hasFunctionProto first).
Alp Toker601b22c2014-01-21 23:35:24 +000087static unsigned getFunctionOrMethodNumParams(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000088 if (const FunctionType *FnTy = D->getFunctionType())
Alp Toker9cacbab2014-01-20 20:26:09 +000089 return cast<FunctionProtoType>(FnTy)->getNumParams();
Chandler Carruthff4c4f02011-07-01 23:49:12 +000090 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
Fariborz Jahanian960910a2009-05-19 17:08:59 +000091 return BD->getNumParams();
Chandler Carruthff4c4f02011-07-01 23:49:12 +000092 return cast<ObjCMethodDecl>(D)->param_size();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +000093}
94
Alp Toker601b22c2014-01-21 23:35:24 +000095static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000096 if (const FunctionType *FnTy = D->getFunctionType())
Alp Toker9cacbab2014-01-20 20:26:09 +000097 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
Chandler Carruthff4c4f02011-07-01 23:49:12 +000098 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
Fariborz Jahanian960910a2009-05-19 17:08:59 +000099 return BD->getParamDecl(Idx)->getType();
Mike Stumpd3bb5572009-07-24 19:02:52 +0000100
Alp Toker03376dc2014-07-07 09:02:20 +0000101 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000102}
103
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000104static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
105 if (const auto *FD = dyn_cast<FunctionDecl>(D))
106 return FD->getParamDecl(Idx)->getSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000107 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000108 return MD->parameters()[Idx]->getSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000109 if (const auto *BD = dyn_cast<BlockDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000110 return BD->getParamDecl(Idx)->getSourceRange();
111 return SourceRange();
112}
113
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000114static QualType getFunctionOrMethodResultType(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +0000115 if (const FunctionType *FnTy = D->getFunctionType())
Aaron Ballman6288d062014-07-11 16:31:29 +0000116 return cast<FunctionType>(FnTy)->getReturnType();
Alp Toker314cc812014-01-25 16:55:45 +0000117 return cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanianf1c25022009-05-20 17:41:43 +0000118}
119
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000120static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
121 if (const auto *FD = dyn_cast<FunctionDecl>(D))
122 return FD->getReturnTypeSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000123 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000124 return MD->getReturnTypeSourceRange();
125 return SourceRange();
126}
127
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000128static bool isFunctionOrMethodVariadic(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +0000129 if (const FunctionType *FnTy = D->getFunctionType()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000130 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000131 return proto->isVariadic();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000132 }
Aaron Ballmane13d0092014-08-01 17:02:34 +0000133 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
134 return BD->isVariadic();
135
136 return cast<ObjCMethodDecl>(D)->isVariadic();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000137}
138
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000139static bool isInstanceMethod(const Decl *D) {
140 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
Chandler Carruth743682b2010-11-16 08:35:43 +0000141 return MethodDecl->isInstance();
142 return false;
143}
144
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000145static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
John McCall9dd450b2009-09-21 23:43:11 +0000146 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
Chris Lattner574dee62008-07-26 22:17:49 +0000147 if (!PT)
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000148 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000149
John McCall96fa4842010-05-17 21:00:27 +0000150 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
151 if (!Cls)
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000152 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000153
John McCall96fa4842010-05-17 21:00:27 +0000154 IdentifierInfo* ClsName = Cls->getIdentifier();
Mike Stumpd3bb5572009-07-24 19:02:52 +0000155
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000156 // FIXME: Should we walk the chain of classes?
157 return ClsName == &Ctx.Idents.get("NSString") ||
158 ClsName == &Ctx.Idents.get("NSMutableString");
159}
160
Daniel Dunbar980c6692008-09-26 03:32:58 +0000161static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000162 const PointerType *PT = T->getAs<PointerType>();
Daniel Dunbar980c6692008-09-26 03:32:58 +0000163 if (!PT)
164 return false;
165
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000166 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
Daniel Dunbar980c6692008-09-26 03:32:58 +0000167 if (!RT)
168 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000169
Daniel Dunbar980c6692008-09-26 03:32:58 +0000170 const RecordDecl *RD = RT->getDecl();
Abramo Bagnara6150c882010-05-11 21:36:43 +0000171 if (RD->getTagKind() != TTK_Struct)
Daniel Dunbar980c6692008-09-26 03:32:58 +0000172 return false;
173
174 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
175}
176
Richard Smithb87c4652013-10-31 21:23:20 +0000177static unsigned getNumAttributeArgs(const AttributeList &Attr) {
178 // FIXME: Include the type in the argument list.
179 return Attr.getNumArgs() + Attr.hasParsedType();
180}
181
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000182template <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;
Chandler Carruthfcc48d92011-07-11 23:30:35 +0000188 return false;
189 }
190
191 return true;
192}
193
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000194/// \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
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000203/// \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,
Richard Smithb87c4652013-10-31 21:23:20 +0000206 unsigned Num) {
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000207 return checkAttributeNumArgsImpl(S, Attr, Num,
208 diag::err_attribute_too_few_arguments,
209 std::less<unsigned>());
210}
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000211
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000212/// \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>());
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000219}
220
Erich Keane623efd82017-03-30 21:48:55 +0000221/// \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}
Benjamin Kramer674d5792017-05-26 20:08:24 +0000241static const IdentifierInfo *getAttrName(const clang::AttributeList &Attr) {
Erich Keane623efd82017-03-30 21:48:55 +0000242 return Attr.getName();
243}
244
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000245/// \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.
Erich Keane623efd82017-03-30 21:48:55 +0000247template<typename AttrInfo>
248static bool checkUInt32Argument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
249 uint32_t &Val, unsigned Idx = UINT_MAX) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000250 llvm::APSInt I(32);
251 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
252 !Expr->isIntegerConstantExpr(I, S.Context)) {
253 if (Idx != UINT_MAX)
Erich Keane623efd82017-03-30 21:48:55 +0000254 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
255 << getAttrName(Attr) << Idx << AANT_ArgumentIntegerConstant
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000256 << Expr->getSourceRange();
257 else
Erich Keane623efd82017-03-30 21:48:55 +0000258 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_type)
259 << getAttrName(Attr) << AANT_ArgumentIntegerConstant
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000260 << Expr->getSourceRange();
261 return false;
262 }
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000263
264 if (!I.isIntN(32)) {
Aaron Ballman31f42312014-07-24 14:51:23 +0000265 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
266 << I.toString(10, false) << 32 << /* Unsigned */ 1;
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000267 return false;
268 }
269
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000270 Val = (uint32_t)I.getZExtValue();
271 return true;
272}
273
George Burgess IVe3763372016-12-22 02:50:20 +0000274/// \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.
Erich Keane623efd82017-03-30 21:48:55 +0000277template<typename AttrInfo>
278static bool checkPositiveIntArgument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
279 int &Val, unsigned Idx = UINT_MAX) {
George Burgess IVe3763372016-12-22 02:50:20 +0000280 uint32_t UVal;
281 if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx))
282 return false;
283
George Burgess IVa8049572016-12-22 19:00:31 +0000284 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
George Burgess IVe3763372016-12-22 02:50:20 +0000285 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
Aaron Ballmanfb763042013-12-02 18:05:46 +0000296/// \brief Diagnose mutually exclusive attributes when present on a given
297/// declaration. Returns true if diagnosed.
298template <typename AttrTy>
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000299static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
300 IdentifierInfo *Ident) {
Aaron Ballman2cfbc002014-01-03 16:23:46 +0000301 if (AttrTy *A = D->getAttr<AttrTy>()) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000302 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
303 << A;
304 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
Aaron Ballmanfb763042013-12-02 18:05:46 +0000305 return true;
306 }
307 return false;
308}
309
Alp Toker601b22c2014-01-21 23:35:24 +0000310/// \brief Check if IdxExpr is a valid parameter index for a function or
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000311/// instance method D. May output an error.
312///
313/// \returns true if IdxExpr is a valid index.
Erich Keane623efd82017-03-30 21:48:55 +0000314template <typename AttrInfo>
315static bool checkFunctionOrMethodParameterIndex(
Dean Michael Berris7456a282017-06-16 03:22:09 +0000316 Sema &S, const Decl *D, const AttrInfo &Attr, unsigned AttrArgNum,
317 const Expr *IdxExpr, uint64_t &Idx, bool AllowImplicitThis = false) {
David Majnemer06864812015-04-07 06:01:53 +0000318 assert(isFunctionOrMethodOrBlock(D));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000319
320 // In C++ the implicit 'this' function parameter also counts.
321 // Parameters are counted from one.
Aaron Ballmanbe50eb82013-07-30 00:48:57 +0000322 bool HP = hasFunctionProto(D);
323 bool HasImplicitThisParam = isInstanceMethod(D);
324 bool IV = HP && isFunctionOrMethodVariadic(D);
Alp Toker601b22c2014-01-21 23:35:24 +0000325 unsigned NumParams =
326 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000327
328 llvm::APSInt IdxInt;
329 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
330 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
Erich Keane623efd82017-03-30 21:48:55 +0000331 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
332 << getAttrName(Attr) << AttrArgNum << AANT_ArgumentIntegerConstant
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000333 << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000334 return false;
335 }
336
337 Idx = IdxInt.getLimitedValue();
Alp Toker601b22c2014-01-21 23:35:24 +0000338 if (Idx < 1 || (!IV && Idx > NumParams)) {
Erich Keane623efd82017-03-30 21:48:55 +0000339 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_out_of_bounds)
340 << getAttrName(Attr) << AttrArgNum << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000341 return false;
342 }
343 Idx--; // Convert to zero-based.
Dean Michael Berris7456a282017-06-16 03:22:09 +0000344 if (HasImplicitThisParam && !AllowImplicitThis) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000345 if (Idx == 0) {
Erich Keane623efd82017-03-30 21:48:55 +0000346 S.Diag(getAttrLoc(Attr),
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000347 diag::err_attribute_invalid_implicit_this_argument)
Erich Keane623efd82017-03-30 21:48:55 +0000348 << getAttrName(Attr) << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000349 return false;
350 }
351 --Idx;
352 }
353
354 return true;
355}
356
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000357/// \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.
Tim Northover6a6b63b2013-10-01 14:34:18 +0000361bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
362 unsigned ArgNum, StringRef &Str,
Tim Northovera484bc02013-10-01 14:34:25 +0000363 SourceLocation *ArgLocation) {
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000364 // 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);
Tim Northover6a6b63b2013-10-01 14:34:18 +0000367 Diag(Loc->Loc, diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000368 << Attr.getName() << AANT_ArgumentString
369 << FixItHint::CreateInsertion(Loc->Loc, "\"")
Craig Topper07fa1762015-11-15 02:31:46 +0000370 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000371 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()) {
Tim Northover6a6b63b2013-10-01 14:34:18 +0000384 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000385 << Attr.getName() << AANT_ArgumentString;
386 return false;
387 }
388
389 Str = Literal->getString();
390 return true;
391}
392
Aaron Ballman6f9165a2013-11-27 15:24:06 +0000393/// \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
Justin Lebar3eaaf862016-01-13 01:07:35 +0000402template <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
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000421/// \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
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000427
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*.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000430static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
Richard Smithcf4bdde2015-02-21 02:45:19 +0000431 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
432 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
David Blaikieff7d47a2012-12-19 00:45:41 +0000433 if (Res1.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000434 return false;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000435
Richard Smithcf4bdde2015-02-21 02:45:19 +0000436 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
437 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
David Blaikieff7d47a2012-12-19 00:45:41 +0000438 if (Res2.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000439 return false;
440
441 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000442}
443
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000444/// \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
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000447static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
448 const AttributeList &Attr) {
Aaron Ballman553e6812013-12-26 14:54:11 +0000449 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())
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000459 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000460
Aaron Ballman553e6812013-12-26 14:54:11 +0000461 if (threadSafetyCheckIsSmartPointer(S, RT))
462 return true;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000463 }
Aaron Ballman553e6812013-12-26 14:54:11 +0000464
465 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
Aaron Ballman68289452013-12-26 15:06:01 +0000466 << Attr.getName() << QT;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000467 return false;
468}
469
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000470/// \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.
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000472static const RecordType *getRecordType(QualType QT) {
473 if (const RecordType *RT = QT->getAs<RecordType>())
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000474 return RT;
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000475
476 // Now check if we point to record type.
477 if (const PointerType *PT = QT->getAs<PointerType>())
478 return PT->getPointeeType()->getAs<RecordType>();
479
Craig Topperc3ec1492014-05-26 06:22:03 +0000480 return nullptr;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000481}
482
Josh Gao55afa752017-08-11 07:54:35 +0000483static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
DeLesley Hutchins481d5ab2012-04-06 20:02:30 +0000484 const RecordType *RT = getRecordType(Ty);
Michael Hana9171bc2012-08-03 17:40:43 +0000485
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000486 if (!RT)
487 return false;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000488
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000489 // Don't check for the capability if the class hasn't been defined yet.
DeLesley Hutchins3509f292012-02-16 17:15:51 +0000490 if (RT->isIncompleteType())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000491 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000492
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000493 // Allow smart pointers to be used as capability objects.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000494 // FIXME -- Check the type that the smart pointer points to.
495 if (threadSafetyCheckIsSmartPointer(S, RT))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000496 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000497
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000498 // Check if the record itself has a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000499 RecordDecl *RD = RT->getDecl();
Josh Gao55afa752017-08-11 07:54:35 +0000500 if (RD->hasAttr<CapabilityAttr>())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000501 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000502
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000503 // Else check if any base classes have a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000504 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
505 CXXBasePaths BPaths(false, false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000506 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
507 const auto *Type = BS->getType()->getAs<RecordType>();
Josh Gao55afa752017-08-11 07:54:35 +0000508 return Type->getDecl()->hasAttr<CapabilityAttr>();
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000509 }, BPaths))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000510 return true;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000511 }
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000512 return false;
513}
514
Josh Gao55afa752017-08-11 07:54:35 +0000515static bool checkTypedefTypeForCapability(QualType Ty) {
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000516 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
Josh Gao55afa752017-08-11 07:54:35 +0000524 return TN->hasAttr<CapabilityAttr>();
Aaron Ballman76050722014-04-04 15:13:57 +0000525}
526
Josh Gaob40c1772017-08-08 19:44:35 +0000527static bool typeHasCapability(Sema &S, QualType Ty) {
Josh Gao55afa752017-08-11 07:54:35 +0000528 if (checkTypedefTypeForCapability(Ty))
529 return true;
Josh Gaob40c1772017-08-08 19:44:35 +0000530
Josh Gao55afa752017-08-11 07:54:35 +0000531 if (checkRecordTypeForCapability(S, Ty))
532 return true;
533
534 return false;
Josh Gaob40c1772017-08-08 19:44:35 +0000535}
536
Aaron Ballman76050722014-04-04 15:13:57 +0000537static 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
Yi Kong2d58d192017-12-14 22:24:45 +0000543 if (const auto *E = dyn_cast<CastExpr>(Ex))
Aaron Ballman76050722014-04-04 15:13:57 +0000544 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)) {
Yi Kong2d58d192017-12-14 22:24:45 +0000548 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
549 E->getOpcode() == UO_Deref)
Aaron Ballman76050722014-04-04 15:13:57 +0000550 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
Yi Kong2d58d192017-12-14 22:24:45 +0000559 return typeHasCapability(S, Ex->getType());
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000560}
561
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000562/// \brief Checks that all attribute arguments, starting from Sidx, resolve to
563/// a capability object.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000564/// \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.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000567static 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) {
Aaron Ballman00e99962013-08-31 01:11:41 +0000573 Expr *ArgExp = Attr.getArgAsExpr(Idx);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000574
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000575 if (ArgExp->isTypeDependent()) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000576 // FIXME -- need to check this again on template instantiation
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000577 Args.push_back(ArgExp);
578 continue;
579 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000580
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000581 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000582 if (StrLit->getLength() == 0 ||
Benjamin Kramerca9fe142013-09-13 16:30:12 +0000583 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000584 // Pass empty strings to the analyzer without warnings.
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000585 // Treat "*" as the universal lock.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000586 Args.push_back(ArgExp);
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000587 continue;
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000588 }
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000589
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000590 // 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();
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000594 Args.push_back(ArgExp);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000595 continue;
596 }
597
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000598 QualType ArgTy = ArgExp->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000599
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000600 // 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
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000608 // First see if we can just cast to record type, or pointer to record type.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000609 const RecordType *RT = getRecordType(ArgTy);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000610
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000611 // Now check if we index into a record type function param.
Josh Gao55afa752017-08-11 07:54:35 +0000612 if(!RT && ParamIdxOk) {
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000613 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000614 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
Josh Gao55afa752017-08-11 07:54:35 +0000615 if(FD && IL) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000616 unsigned int NumParams = FD->getNumParams();
617 llvm::APInt ArgValue = IL->getValue();
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000618 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
619 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
Josh Gao55afa752017-08-11 07:54:35 +0000620 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000621 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
622 << Attr.getName() << Idx + 1 << NumParams;
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000623 continue;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000624 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000625 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000626 }
627 }
628
Aaron Ballman76050722014-04-04 15:13:57 +0000629 // 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;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000636
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000637 Args.push_back(ArgExp);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000638 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000639}
640
Chris Lattner58418ff2008-06-29 00:16:31 +0000641//===----------------------------------------------------------------------===//
Chris Lattner58418ff2008-06-29 00:16:31 +0000642// Attribute Implementations
643//===----------------------------------------------------------------------===//
644
Michael Hana9171bc2012-08-03 17:40:43 +0000645static void handlePtGuardedVarAttr(Sema &S, Decl *D,
Michael Han99315932013-01-24 16:46:58 +0000646 const AttributeList &Attr) {
Michael Han3be3b442012-07-23 18:48:41 +0000647 if (!threadSafetyCheckIsPointer(S, D, Attr))
648 return;
649
Michael Han99315932013-01-24 16:46:58 +0000650 D->addAttr(::new (S.Context)
651 PtGuardedVarAttr(Attr.getRange(), S.Context,
652 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000653}
654
Michael Hana9171bc2012-08-03 17:40:43 +0000655static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
656 const AttributeList &Attr,
Michael Han3be3b442012-07-23 18:48:41 +0000657 Expr* &Arg) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000658 SmallVector<Expr*, 1> Args;
659 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000660 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000661 unsigned Size = Args.size();
662 if (Size != 1)
Michael Han3be3b442012-07-23 18:48:41 +0000663 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000664
Michael Han3be3b442012-07-23 18:48:41 +0000665 Arg = Args[0];
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000666
Michael Han3be3b442012-07-23 18:48:41 +0000667 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000668}
669
Michael Han3be3b442012-07-23 18:48:41 +0000670static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000671 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000672 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
673 return;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000674
Aaron Ballman36a53502014-01-16 13:03:14 +0000675 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
676 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000677}
678
Michael Hana9171bc2012-08-03 17:40:43 +0000679static void handlePtGuardedByAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000680 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000681 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000682 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(),
Aaron Ballman36a53502014-01-16 13:03:14 +0000689 S.Context, Arg,
690 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000691}
692
Michael Hana9171bc2012-08-03 17:40:43 +0000693static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
694 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000695 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000696 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000697 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000698
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000699 // Check that this attribute only applies to lockable types.
Aaron Ballmane61b8b82013-12-02 15:02:49 +0000700 QualType QT = cast<ValueDecl>(D)->getType();
DeLesley Hutchins2b504dc2015-09-29 16:24:18 +0000701 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
702 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
703 << Attr.getName();
704 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000705 }
706
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000707 // Check that all arguments are lockable objects.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000708 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000709 if (Args.empty())
Michael Han3be3b442012-07-23 18:48:41 +0000710 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000711
Michael Han3be3b442012-07-23 18:48:41 +0000712 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000713}
714
Michael Hana9171bc2012-08-03 17:40:43 +0000715static void handleAcquiredAfterAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000716 const AttributeList &Attr) {
717 SmallVector<Expr*, 1> Args;
718 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
719 return;
720
721 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000722 D->addAttr(::new (S.Context)
723 AcquiredAfterAttr(Attr.getRange(), S.Context,
724 StartArg, Args.size(),
725 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000726}
727
Michael Hana9171bc2012-08-03 17:40:43 +0000728static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000729 const AttributeList &Attr) {
730 SmallVector<Expr*, 1> Args;
731 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
732 return;
733
734 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000735 D->addAttr(::new (S.Context)
736 AcquiredBeforeAttr(Attr.getRange(), S.Context,
737 StartArg, Args.size(),
738 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000739}
740
Michael Hana9171bc2012-08-03 17:40:43 +0000741static bool checkLockFunAttrCommon(Sema &S, Decl *D,
742 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000743 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000744 // zero or more arguments ok
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000745 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000746 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000747
Michael Han3be3b442012-07-23 18:48:41 +0000748 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000749}
750
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000751static 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();
Craig Topperc3ec1492014-05-26 06:22:03 +0000758 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000759 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();
Craig Topperc3ec1492014-05-26 06:22:03 +0000771 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000772 D->addAttr(::new (S.Context)
773 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
774 StartArg, Size,
775 Attr.getAttributeSpellingListIndex()));
776}
777
Erich Keane623efd82017-03-30 21:48:55 +0000778/// \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
George Burgess IVe3763372016-12-22 02:50:20 +0000780/// 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.
Erich Keane623efd82017-03-30 21:48:55 +0000784template <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.
George Burgess IVe3763372016-12-22 02:50:20 +0000811static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
812 const AttributeList &Attr,
Erich Keane623efd82017-03-30 21:48:55 +0000813 unsigned FuncParamNo, unsigned AttrArgNo,
814 bool AllowDependentType = false) {
George Burgess IVe3763372016-12-22 02:50:20 +0000815 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument");
Erich Keane623efd82017-03-30 21:48:55 +0000816 return checkParamIsIntegerType(S, FD, Attr, Attr.getArgAsExpr(AttrArgNo),
817 FuncParamNo, AttrArgNo, AllowDependentType);
George Burgess IVe3763372016-12-22 02:50:20 +0000818}
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;
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000834 // Parameter indices are 1-indexed, hence Index=1
George Burgess IVe3763372016-12-22 02:50:20 +0000835 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);
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000845 // Parameter indices are 1-based, hence Index=2
George Burgess IVe3763372016-12-22 02:50:20 +0000846 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}
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000858
Michael Hana9171bc2012-08-03 17:40:43 +0000859static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
860 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000861 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000862 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000863 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000864
Aaron Ballman00e99962013-08-31 01:11:41 +0000865 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
Aaron Ballman29982272013-07-23 14:03:57 +0000866 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +0000867 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
Michael Han3be3b442012-07-23 18:48:41 +0000868 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000869 }
870
871 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000872 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000873
Michael Han3be3b442012-07-23 18:48:41 +0000874 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000875}
876
Michael Hana9171bc2012-08-03 17:40:43 +0000877static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000878 const AttributeList &Attr) {
879 SmallVector<Expr*, 2> Args;
880 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
881 return;
882
Michael Han99315932013-01-24 16:46:58 +0000883 D->addAttr(::new (S.Context)
884 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
Aaron Ballman00e99962013-08-31 01:11:41 +0000885 Attr.getArgAsExpr(0),
886 Args.data(), Args.size(),
Michael Han99315932013-01-24 16:46:58 +0000887 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000888}
889
Michael Hana9171bc2012-08-03 17:40:43 +0000890static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000891 const AttributeList &Attr) {
892 SmallVector<Expr*, 2> Args;
893 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
894 return;
895
Nico Weber462fd1e2015-01-07 23:50:05 +0000896 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
897 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
898 Args.size(), Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000899}
900
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000901static void handleLockReturnedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000902 const AttributeList &Attr) {
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000903 // check that the argument is lockable object
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000904 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000905 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000906 unsigned Size = Args.size();
907 if (Size == 0)
908 return;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000909
Michael Han99315932013-01-24 16:46:58 +0000910 D->addAttr(::new (S.Context)
911 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
912 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000913}
914
915static void handleLocksExcludedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000916 const AttributeList &Attr) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000917 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000918 return;
919
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000920 // check that all arguments are lockable objects
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000921 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000922 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000923 unsigned Size = Args.size();
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000924 if (Size == 0)
925 return;
926 Expr **StartArg = &Args[0];
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000927
Michael Han99315932013-01-24 16:46:58 +0000928 D->addAttr(::new (S.Context)
929 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
930 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000931}
932
George Burgess IV177399e2017-01-09 04:12:14 +0000933static bool checkFunctionConditionAttr(Sema &S, Decl *D,
934 const AttributeList &Attr,
935 Expr *&Cond, StringRef &Msg) {
936 Cond = Attr.getArgAsExpr(0);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000937 if (!Cond->isTypeDependent()) {
938 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
939 if (Converted.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000940 return false;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000941 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000942 }
943
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000944 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
George Burgess IV177399e2017-01-09 04:12:14 +0000945 return false;
946
947 if (Msg.empty())
948 Msg = "<no message provided>";
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000949
950 SmallVector<PartialDiagnosticAt, 8> Diags;
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +0000951 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000952 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
953 Diags)) {
George Burgess IV177399e2017-01-09 04:12:14 +0000954 S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr)
955 << Attr.getName();
George Burgess IV0d546532016-11-10 21:47:12 +0000956 for (const PartialDiagnosticAt &PDiag : Diags)
957 S.Diag(PDiag.first, PDiag.second);
George Burgess IV177399e2017-01-09 04:12:14 +0000958 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 &&
1004 "`this` doesn't refer to the enclosing class?");
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);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001036 return;
1037 }
1038
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001039 bool ArgDependent = false;
Argyrios Kyrtzidis5f0c0aa2017-05-24 18:35:01 +00001040 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001041 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
George Burgess IV177399e2017-01-09 04:12:14 +00001042 D->addAttr(::new (S.Context) DiagnoseIfAttr(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001043 Attr.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D),
George Burgess IV177399e2017-01-09 04:12:14 +00001044 Attr.getAttributeSpellingListIndex()));
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001045}
1046
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001047static 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
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001084static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
David Blaikie16f76d22013-09-06 01:28:43 +00001085 ConsumableAttr::ConsumedState DefaultState;
1086
1087 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +00001088 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;
David Blaikie16f76d22013-09-06 01:28:43 +00001093 return;
1094 }
David Blaikie16f76d22013-09-06 01:28:43 +00001095 } else {
1096 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1097 << Attr.getName() << AANT_ArgumentIdentifier;
1098 return;
1099 }
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001100
1101 D->addAttr(::new (S.Context)
David Blaikie16f76d22013-09-06 01:28:43 +00001102 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001103 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
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001123static void handleCallableWhenAttr(Sema &S, Decl *D,
1124 const AttributeList &Attr) {
Aaron Ballmandbd586f2013-10-14 23:26:04 +00001125 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1126 return;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001127
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001128 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1129 return;
1130
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001131 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1132 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1133 CallableWhenAttr::ConsumedState CallableState;
1134
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001135 StringRef StateString;
1136 SourceLocation Loc;
Aaron Ballman55ef1512014-12-19 16:42:04 +00001137 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 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001145
1146 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
DeLesley Hutchins69391772013-10-17 23:23:53 +00001147 CallableState)) {
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001148 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1149 << Attr.getName() << StateString;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001150 return;
1151 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001152
1153 States.push_back(CallableState);
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001154 }
1155
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001156 D->addAttr(::new (S.Context)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001157 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1158 States.size(), Attr.getAttributeSpellingListIndex()));
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001159}
1160
DeLesley Hutchins69391772013-10-17 23:23:53 +00001161static void handleParamTypestateAttr(Sema &S, Decl *D,
1162 const AttributeList &Attr) {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001163 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
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001198static void handleReturnTypestateAttr(Sema &S, Decl *D,
1199 const AttributeList &Attr) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001200 ReturnTypestateAttr::ConsumedState ReturnState;
1201
1202 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +00001203 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;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001208 return;
1209 }
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001210 } else {
1211 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1212 Attr.getName() << AANT_ArgumentIdentifier;
1213 return;
1214 }
1215
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001216 // 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 //
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001221 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1222 // ReturnType = Param->getType();
1223 //
1224 //} else if (const CXXConstructorDecl *Constructor =
1225 // dyn_cast<CXXConstructorDecl>(D)) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001226 // 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
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001246static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001247 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1248 return;
1249
1250 SetTypestateAttr::ConsumedState NewState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001251 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001252 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;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001257 return;
1258 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001259 } 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
Chris Wailes9385f9f2013-10-29 20:28:41 +00001270static void handleTestTypestateAttr(Sema &S, Decl *D,
1271 const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001272 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1273 return;
1274
Chris Wailes9385f9f2013-10-29 20:28:41 +00001275 TestTypestateAttr::ConsumedState TestState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001276 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001277 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1278 StringRef Param = Ident->Ident->getName();
Chris Wailes9385f9f2013-10-29 20:28:41 +00001279 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001280 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1281 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001282 return;
1283 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001284 } 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)
Chris Wailes9385f9f2013-10-29 20:28:41 +00001291 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001292 Attr.getAttributeSpellingListIndex()));
1293}
1294
Chandler Carruthedc2c642011-07-02 00:01:44 +00001295static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1296 const AttributeList &Attr) {
Richard Smith1f5a4322013-01-13 02:11:23 +00001297 // Remember this typedef decl, we will need it later for diagnostics.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00001298 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001299}
1300
Chandler Carruthedc2c642011-07-02 00:01:44 +00001301static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001302 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Aaron Ballman36a53502014-01-16 13:03:14 +00001303 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1304 Attr.getAttributeSpellingListIndex()));
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001305 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Aaron Ballmanb6fd7262017-08-08 18:07:17 +00001306 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1307 !FD->getType()->isIncompleteType() &&
1308 FD->isBitField() &&
1309 S.Context.getTypeAlign(FD->getType()) <= 8);
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001310
Aaron Ballmanb6fd7262017-08-08 18:07:17 +00001311 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
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001328 } else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001329 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001330}
1331
Ted Kremenek7fd17232011-09-29 07:02:25 +00001332static 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>()) {
Ted Kremenek5d6044e2011-11-01 18:08:35 +00001338 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001339 << 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>()) {
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001345 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001346 << 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 }
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001354
Ted Kremenek7fd17232011-09-29 07:02:25 +00001355 return true;
1356}
1357
Chandler Carruthedc2c642011-07-02 00:01:44 +00001358static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
Ted Kremenek7fd17232011-09-29 07:02:25 +00001359 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek1f672822010-02-18 03:08:58 +00001360 return;
Ted Kremenek1f672822010-02-18 03:08:58 +00001361
Michael Han99315932013-01-24 16:46:58 +00001362 D->addAttr(::new (S.Context)
1363 IBOutletAttr(Attr.getRange(), S.Context,
1364 Attr.getAttributeSpellingListIndex()));
Ted Kremenek8e3704d2008-07-15 22:26:48 +00001365}
1366
Chandler Carruthedc2c642011-07-02 00:01:44 +00001367static void handleIBOutletCollection(Sema &S, Decl *D,
1368 const AttributeList &Attr) {
Ted Kremenek26bde772010-05-19 17:38:06 +00001369
1370 // The iboutletcollection attribute can have zero or one arguments.
Aaron Ballman00e99962013-08-31 01:11:41 +00001371 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001372 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1373 << Attr.getName() << 1;
Ted Kremenek26bde772010-05-19 17:38:06 +00001374 return;
1375 }
1376
Ted Kremenek7fd17232011-09-29 07:02:25 +00001377 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek26bde772010-05-19 17:38:06 +00001378 return;
Ted Kremenek7fd17232011-09-29 07:02:25 +00001379
Richard Smithb1f9a282013-10-31 01:56:18 +00001380 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 }
Aaron Ballman00e99962013-08-31 01:11:41 +00001391 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001392
Craig Topperc3ec1492014-05-26 06:22:03 +00001393 TypeSourceInfo *QTLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00001394 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1395 if (!QTLoc)
1396 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
Richard Smithb1f9a282013-10-31 01:56:18 +00001397
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001398 // 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())).
Fariborz Jahanian2f31b332011-10-18 19:54:31 +00001402 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
Richard Smithb1f9a282013-10-31 01:56:18 +00001403 S.Diag(Attr.getLoc(),
1404 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1405 : diag::err_iboutletcollection_type) << QT;
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001406 return;
1407 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001408
Michael Han99315932013-01-24 16:46:58 +00001409 D->addAttr(::new (S.Context)
Richard Smithb87c4652013-10-31 21:23:20 +00001410 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
Michael Han99315932013-01-24 16:46:58 +00001411 Attr.getAttributeSpellingListIndex()));
Ted Kremenek26bde772010-05-19 17:38:06 +00001412}
1413
Hal Finkelee90a222014-09-26 05:04:30 +00001414bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1415 if (RefOkay) {
1416 if (T->isReferenceType())
1417 return true;
1418 } else {
1419 T = T.getNonReferenceType();
1420 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001421
Hal Finkelee90a222014-09-26 05:04:30 +00001422 // The nonnull attribute, and other similar attributes, can be applied to a
1423 // transparent union that contains a pointer type.
Richard Smith588bd9b2014-08-27 04:59:42 +00001424 if (const RecordType *UT = T->getAsUnionType()) {
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001425 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1426 RecordDecl *UD = UT->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001427 for (const auto *I : UD->fields()) {
1428 QualType QT = I->getType();
Richard Smith588bd9b2014-08-27 04:59:42 +00001429 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1430 return true;
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001431 }
1432 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001433 }
1434
1435 return T->isAnyPointerType() || T->isBlockPointerType();
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001436}
1437
Ted Kremenek9aedc152014-01-17 06:24:56 +00001438static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001439 SourceRange AttrParmRange,
Hal Finkelee90a222014-09-26 05:04:30 +00001440 SourceRange TypeRange,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001441 bool isReturnValue = false) {
Hal Finkelee90a222014-09-26 05:04:30 +00001442 if (!S.isValidPointerAttrType(T)) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001443 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;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001449 return false;
1450 }
1451 return true;
1452}
1453
Chandler Carruthedc2c642011-07-02 00:01:44 +00001454static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001455 SmallVector<unsigned, 8> NonNullArgs;
Richard Smith588bd9b2014-08-27 04:59:42 +00001456 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1457 Expr *Ex = Attr.getArgAsExpr(I);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001458 uint64_t Idx;
Richard Smith588bd9b2014-08-27 04:59:42 +00001459 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001460 return;
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001461
1462 // Is the function argument a pointer type?
Richard Smith588bd9b2014-08-27 04:59:42 +00001463 if (Idx < getFunctionOrMethodNumParams(D) &&
1464 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001465 Ex->getSourceRange(),
1466 getFunctionOrMethodParamRange(D, Idx)))
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001467 continue;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001468
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001469 NonNullArgs.push_back(Idx);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001470 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001471
1472 // If no arguments were specified to __attribute__((nonnull)) then all pointer
Richard Smith588bd9b2014-08-27 04:59:42 +00001473 // 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() &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001477 !S.inTemplateInstantiation()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001478 bool AnyPointers = isFunctionOrMethodVariadic(D);
1479 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1480 I != E && !AnyPointers; ++I) {
1481 QualType T = getFunctionOrMethodParamType(D, I);
Hal Finkelee90a222014-09-26 05:04:30 +00001482 if (T->isDependentType() || S.isValidPointerAttrType(T))
Richard Smith588bd9b2014-08-27 04:59:42 +00001483 AnyPointers = true;
Ted Kremenek5fa50522008-11-18 06:52:58 +00001484 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001485
Richard Smith588bd9b2014-08-27 04:59:42 +00001486 if (!AnyPointers)
1487 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001488 }
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001489
Richard Smith588bd9b2014-08-27 04:59:42 +00001490 unsigned *Start = NonNullArgs.data();
1491 unsigned Size = NonNullArgs.size();
1492 llvm::array_pod_sort(Start, Start + Size);
Michael Han99315932013-01-24 16:46:58 +00001493 D->addAttr(::new (S.Context)
Richard Smith588bd9b2014-08-27 04:59:42 +00001494 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
Michael Han99315932013-01-24 16:46:58 +00001495 Attr.getAttributeSpellingListIndex()));
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001496}
1497
Jordan Rosec9399072014-02-11 17:27:59 +00001498static 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?
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001511 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1512 D->getSourceRange()))
Jordan Rosec9399072014-02-11 17:27:59 +00001513 return;
1514
1515 D->addAttr(::new (S.Context)
Craig Topperc3ec1492014-05-26 06:22:03 +00001516 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
Jordan Rosec9399072014-02-11 17:27:59 +00001517 Attr.getAttributeSpellingListIndex()));
1518}
1519
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001520static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1521 const AttributeList &Attr) {
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00001522 QualType ResultType = getFunctionOrMethodResultType(D);
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001523 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1524 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001525 /* isReturnValue */ true))
1526 return;
1527
1528 D->addAttr(::new (S.Context)
1529 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1530 Attr.getAttributeSpellingListIndex()));
1531}
1532
Akira Hatanaka98a49332017-09-22 00:41:05 +00001533static 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
Hal Finkelee90a222014-09-26 05:04:30 +00001549static 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
Erich Keane623efd82017-03-30 21:48:55 +00001557static void handleAllocAlignAttr(Sema &S, Decl *D,
1558 const AttributeList &Attr) {
1559 S.AddAllocAlignAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
1560 Attr.getAttributeSpellingListIndex());
1561}
1562
Hal Finkelee90a222014-09-26 05:04:30 +00001563void 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
Erich Keane623efd82017-03-30 21:48:55 +00001614void 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
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001652/// Normalize the attribute, __foo__ becomes foo.
1653/// Returns true if normalization was applied.
1654static bool normalizeName(StringRef &AttrName) {
Aaron Ballman62692362015-10-09 13:53:24 +00001655 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1656 AttrName.endswith("__")) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001657 AttrName = AttrName.drop_front(2).drop_back(2);
1658 return true;
1659 }
1660 return false;
1661}
1662
Chandler Carruthedc2c642011-07-02 00:01:44 +00001663static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001664 // 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.
Ted Kremenekd21139a2010-07-31 01:52:11 +00001668 // The difference between Holds and Takes is that a pointer may still be used
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001669 // after being held. free() should be __attribute((ownership_takes)), whereas
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001670 // a list append function may well be __attribute((ownership_holds)).
Ted Kremenekd21139a2010-07-31 01:52:11 +00001671
Aaron Ballman00e99962013-08-31 01:11:41 +00001672 if (!AL.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00001673 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001674 << AL.getName() << 1 << AANT_ArgumentIdentifier;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001675 return;
1676 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001677
Richard Smith852e9ce2013-11-27 01:46:48 +00001678 // Figure out our Kind.
1679 OwnershipAttr::OwnershipKind K =
Craig Topperc3ec1492014-05-26 06:22:03 +00001680 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
Richard Smith852e9ce2013-11-27 01:46:48 +00001681 AL.getAttributeSpellingListIndex()).getOwnKind();
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001682
Richard Smith852e9ce2013-11-27 01:46:48 +00001683 // Check arguments.
1684 switch (K) {
1685 case OwnershipAttr::Takes:
1686 case OwnershipAttr::Holds:
1687 if (AL.getNumArgs() < 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001688 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1689 << AL.getName() << 2;
Richard Smith852e9ce2013-11-27 01:46:48 +00001690 return;
1691 }
1692 break;
1693 case OwnershipAttr::Returns:
Aaron Ballman00e99962013-08-31 01:11:41 +00001694 if (AL.getNumArgs() > 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001695 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1696 << AL.getName() << 1;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001697 return;
1698 }
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001699 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001700 }
1701
Richard Smith852e9ce2013-11-27 01:46:48 +00001702 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001703
Richard Smith852e9ce2013-11-27 01:46:48 +00001704 StringRef ModuleName = Module->getName();
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001705 if (normalizeName(ModuleName)) {
Richard Smith852e9ce2013-11-27 01:46:48 +00001706 Module = &S.PP.getIdentifierTable().get(ModuleName);
1707 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001708
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001709 SmallVector<unsigned, 8> OwnershipArgs;
Aaron Ballman00e99962013-08-31 01:11:41 +00001710 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1711 Expr *Ex = AL.getArgAsExpr(i);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001712 uint64_t Idx;
Alp Toker601b22c2014-01-21 23:35:24 +00001713 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001714 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00001715
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001716 // Is the function argument a pointer type?
Alp Toker601b22c2014-01-21 23:35:24 +00001717 QualType T = getFunctionOrMethodParamType(D, Idx);
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001718 int Err = -1; // No error
Ted Kremenekd21139a2010-07-31 01:52:11 +00001719 switch (K) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001720 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;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001729 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001730 if (-1 != Err) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00001731 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001732 << Ex->getSourceRange();
1733 return;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001734 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001735
1736 // Check we don't have a conflict with another ownership attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001737 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001738 // Cannot have two ownership attributes of different kinds for the same
1739 // index.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001740 if (I->getOwnKind() != K && I->args_end() !=
1741 std::find(I->args_begin(), I->args_end(), Idx)) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001742 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001743 << AL.getName() << I;
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001744 return;
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001745 } 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 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001758 }
1759 }
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001760 OwnershipArgs.push_back(Idx);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001761 }
1762
1763 unsigned* start = OwnershipArgs.data();
1764 unsigned size = OwnershipArgs.size();
1765 llvm::array_pod_sort(start, start + size);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001766
Michael Han99315932013-01-24 16:46:58 +00001767 D->addAttr(::new (S.Context)
Richard Smith852e9ce2013-11-27 01:46:48 +00001768 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
Michael Han99315932013-01-24 16:46:58 +00001769 AL.getAttributeSpellingListIndex()));
Ted Kremenekd21139a2010-07-31 01:52:11 +00001770}
1771
Chandler Carruthedc2c642011-07-02 00:01:44 +00001772static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Rafael Espindolac18086a2010-02-23 22:00:30 +00001773 // Check the attribute arguments.
1774 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001775 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1776 << Attr.getName() << 1;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001777 return;
1778 }
1779
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001780 NamedDecl *nd = cast<NamedDecl>(D);
John McCall7a198ce2011-02-08 22:35:49 +00001781
Rafael Espindolac18086a2010-02-23 22:00:30 +00001782 // 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
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001792 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
Sebastian Redl50c68252010-08-31 00:36:30 +00001793 if (!Ctx->isFileContext()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00001794 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1795 << nd;
Sebastian Redl50c68252010-08-31 00:36:30 +00001796 return;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001797 }
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
Rafael Espindolac18086a2010-02-23 22:00:30 +00001817 // GCC rejects
1818 // static ((alias ("y"), weakref)).
1819 // Should we? How to check that weakref is before or after alias?
1820
Aaron Ballmanfebff0c2013-09-09 23:40:31 +00001821 // 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.
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001824 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001825 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Rafael Espindolac18086a2010-02-23 22:00:30 +00001826 // GCC will accept anything as the argument of weakref. Should we
1827 // check for an existing decl?
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001828 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1829 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001830
Michael Han99315932013-01-24 16:46:58 +00001831 D->addAttr(::new (S.Context)
1832 WeakRefAttr(Attr.getRange(), S.Context,
1833 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001834}
1835
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001836static 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 }
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001847
1848 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1849 Attr.getAttributeSpellingListIndex()));
1850}
1851
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001852static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1853 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001854 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001855 return;
1856
Douglas Gregore8bbc122011-09-02 00:18:52 +00001857 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001858 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1859 return;
1860 }
Justin Lebara8f0254b2016-01-23 21:28:10 +00001861 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1862 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1863 }
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001864
David Majnemer2dc81462015-01-19 09:00:28 +00001865 // Aliases should be on declarations, not definitions.
1866 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1867 if (FD->isThisDeclarationADefinition()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001868 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001869 return;
1870 }
1871 } else {
1872 const auto *VD = cast<VarDecl>(D);
1873 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001874 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001875 return;
1876 }
1877 }
1878
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001879 // FIXME: check if target symbol exists in current file
Mike Stumpd3bb5572009-07-24 19:02:52 +00001880
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001881 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00001882 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001883}
1884
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001885static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001886 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001887 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001888
Michael Han99315932013-01-24 16:46:58 +00001889 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1890 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001891}
1892
1893static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001894 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001895 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001896
Michael Han99315932013-01-24 16:46:58 +00001897 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1898 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001899}
1900
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001901static void handleTLSModelAttr(Sema &S, Decl *D,
1902 const AttributeList &Attr) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001903 StringRef Model;
1904 SourceLocation LiteralLoc;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001905 // Check that it is a string.
Tim Northover6a6b63b2013-10-01 14:34:18 +00001906 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001907 return;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001908
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001909 // Check that the value.
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001910 if (Model != "global-dynamic" && Model != "local-dynamic"
1911 && Model != "initial-exec" && Model != "local-exec") {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001912 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001913 return;
1914 }
1915
Michael Han99315932013-01-24 16:46:58 +00001916 D->addAttr(::new (S.Context)
1917 TLSModelAttr(Attr.getRange(), S.Context, Model,
1918 Attr.getAttributeSpellingListIndex()));
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001919}
1920
David Majnemer631a90b2015-02-04 07:23:21 +00001921static 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;
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001927 }
1928
David Majnemer631a90b2015-02-04 07:23:21 +00001929 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1930 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001931}
1932
Chandler Carruthedc2c642011-07-02 00:01:44 +00001933static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001934 if (S.LangOpts.CPlusPlus) {
Aaron Ballman3db89662013-11-24 21:48:06 +00001935 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001936 << Attr.getName() << AttributeLangSupport::Cpp;
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001937 return;
1938 }
1939
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001940 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1941 Attr.getAttributeSpellingListIndex()))
1942 D->addAttr(CA);
Eric Christopher8a2ee392010-12-02 02:45:55 +00001943}
1944
Charles Davis0e379112016-08-08 21:19:08 +00001945static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1946 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1947 Attr.getName()))
1948 return;
1949
Saleem Abdulrasoolb51bcaf2017-04-07 15:13:47 +00001950 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
Charles Davis0e379112016-08-08 21:19:08 +00001961 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1962 Attr.getAttributeSpellingListIndex()));
1963}
1964
Erich Keaneb11ebc52017-09-27 03:20:13 +00001965static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &Attrs) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001966 if (hasDeclarator(D)) return;
John McCall3882ace2011-01-05 12:14:39 +00001967
Erich Keaneb11ebc52017-09-27 03:20:13 +00001968 if (S.CheckNoReturnAttr(Attrs))
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001969 return;
John McCall3882ace2011-01-05 12:14:39 +00001970
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001971 if (!isa<ObjCMethodDecl>(D)) {
Erich Keaneb11ebc52017-09-27 03:20:13 +00001972 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
1973 << Attrs.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00001974 return;
1975 }
1976
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001977 D->addAttr(::new (S.Context) NoReturnAttr(
Erich Keaneb11ebc52017-09-27 03:20:13 +00001978 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001979}
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()));
John McCall3882ace2011-01-05 12:14:39 +00001988}
1989
Erich Keaneb11ebc52017-09-27 03:20:13 +00001990bool Sema::CheckNoReturnAttr(const AttributeList &Attrs) {
1991 if (!checkAttributeNumArgs(*this, Attrs, 0)) {
1992 Attrs.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00001993 return true;
1994 }
1995
1996 return false;
Ted Kremenek40f4ee72009-04-10 00:01:14 +00001997}
1998
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001999bool 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
Chandler Carruthedc2c642011-07-02 00:01:44 +00002015static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
2016 const AttributeList &Attr) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00002017
2018 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2019 // because 'analyzer_noreturn' does not impact the type.
David Majnemer06864812015-04-07 06:01:53 +00002020 if (!isFunctionOrMethodOrBlock(D)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002021 ValueDecl *VD = dyn_cast<ValueDecl>(D);
Craig Topperc3ec1492014-05-26 06:22:03 +00002022 if (!VD || (!VD->getType()->isBlockPointerType() &&
2023 !VD->getType()->isFunctionPointerType())) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00002024 S.Diag(Attr.getLoc(),
Richard Smith89645bc2013-01-02 12:01:23 +00002025 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002026 : diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002027 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Ted Kremenek5295ce82010-08-19 00:51:58 +00002028 return;
2029 }
2030 }
2031
Michael Han99315932013-01-24 16:46:58 +00002032 D->addAttr(::new (S.Context)
2033 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
2034 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002035}
2036
John Thompsoncdb847ba2010-08-09 21:53:52 +00002037// PS3 PPU-specific.
Chandler Carruthedc2c642011-07-02 00:01:44 +00002038static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John Thompsoncdb847ba2010-08-09 21:53:52 +00002039/*
2040 Returning a Vector Class in Registers
2041
Eric Christopherbc638a82010-12-01 22:13:54 +00002042 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.
John Thompsoncdb847ba2010-08-09 21:53:52 +00002047
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*/
Aaron Ballman3e424b52013-12-26 18:30:57 +00002062 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2063 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
John Thompsoncdb847ba2010-08-09 21:53:52 +00002064 return;
2065 }
2066
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002067 RecordDecl *record = cast<RecordDecl>(D);
John Thompson9a587aaa2010-09-18 01:12:07 +00002068 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
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002080 for (const auto *I : record->fields()) {
2081 if ((count == 1) || !I->getType()->isVectorType()) {
John Thompson9a587aaa2010-09-18 01:12:07 +00002082 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2083 return;
2084 }
2085 count++;
2086 }
2087
Michael Han99315932013-01-24 16:46:58 +00002088 D->addAttr(::new (S.Context)
2089 VecReturnAttr(Attr.getRange(), S.Context,
2090 Attr.getAttributeSpellingListIndex()));
John Thompsoncdb847ba2010-08-09 21:53:52 +00002091}
2092
Richard Smithe233fbf2013-01-28 22:42:45 +00002093static 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 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00002103 }
Richard Smithe233fbf2013-01-28 22:42:45 +00002104
2105 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2106 Attr.getRange(), S.Context,
2107 Attr.getAttributeSpellingListIndex()));
Alexis Hunt96d5c762009-11-21 08:43:09 +00002108}
2109
Akira Hatanakac8667622015-11-06 23:56:15 +00002110static void handleNotTailCalledAttr(Sema &S, Decl *D,
2111 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00002112 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
2113 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00002114 return;
2115
2116 D->addAttr(::new (S.Context) NotTailCalledAttr(
2117 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2118}
2119
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00002120static 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
Chandler Carruthedc2c642011-07-02 00:01:44 +00002130static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002131 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola87198cd2013-08-16 23:18:50 +00002132 if (VD->hasLocalStorage()) {
Aaron Ballman88fe3222013-12-26 17:30:44 +00002133 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002134 return;
2135 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002136 } else if (!isFunctionOrMethod(D)) {
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002137 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002138 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002139 return;
2140 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002141
Michael Han99315932013-01-24 16:46:58 +00002142 D->addAttr(::new (S.Context)
2143 UsedAttr(Attr.getRange(), S.Context,
2144 Attr.getAttributeSpellingListIndex()));
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002145}
2146
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00002147static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002148 bool IsCXX17Attr = Attr.isCXX11Attribute() && !Attr.getScopeName();
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00002149
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002150 if (IsCXX17Attr && isa<VarDecl>(D)) {
2151 // The C++17 spelling of this attribute cannot be applied to a static data
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00002152 // 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
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002160 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00002161 // about using it as an extension.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002162 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
Richard Smithb115e5d2017-08-13 23:37:29 +00002163 S.Diag(Attr.getLoc(), diag::ext_cxx17_attr) << Attr.getName();
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00002164
2165 D->addAttr(::new (S.Context) UnusedAttr(
2166 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2167}
2168
Chandler Carruthedc2c642011-07-02 00:01:44 +00002169static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002170 uint32_t priority = ConstructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002171 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002172 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2173 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002174
Michael Han99315932013-01-24 16:46:58 +00002175 D->addAttr(::new (S.Context)
2176 ConstructorAttr(Attr.getRange(), S.Context, priority,
2177 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00002178}
2179
Chandler Carruthedc2c642011-07-02 00:01:44 +00002180static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf28e4992014-01-20 15:22:57 +00002181 uint32_t priority = DestructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002182 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002183 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2184 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002185
Michael Han99315932013-01-24 16:46:58 +00002186 D->addAttr(::new (S.Context)
2187 DestructorAttr(Attr.getRange(), S.Context, priority,
2188 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00002189}
2190
Benjamin Kramerf435ab42012-05-16 12:19:08 +00002191template <typename AttrTy>
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00002192static void handleAttrWithMessage(Sema &S, Decl *D,
2193 const AttributeList &Attr) {
Benjamin Kramerf435ab42012-05-16 12:19:08 +00002194 // Handle the case where the attribute has a text message.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002195 StringRef Str;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002196 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002197 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002198
Michael Han99315932013-01-24 16:46:58 +00002199 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2200 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian1470e932008-12-17 01:07:27 +00002201}
2202
Ted Kremenek438f8db2014-02-22 01:06:05 +00002203static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
Ted Kremenek28eace62013-11-23 01:01:34 +00002204 const AttributeList &Attr) {
Ted Kremenek438f8db2014-02-22 01:06:05 +00002205 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
Ted Kremenek27cfe102014-02-21 22:49:04 +00002206 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2207 << Attr.getName() << Attr.getRange();
2208 return;
2209 }
2210
Ted Kremenek28eace62013-11-23 01:01:34 +00002211 D->addAttr(::new (S.Context)
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00002212 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
2213 Attr.getAttributeSpellingListIndex()));
Ted Kremenek28eace62013-11-23 01:01:34 +00002214}
2215
Jordy Rose740b0c22012-05-08 03:27:22 +00002216static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2217 IdentifierInfo *Platform,
2218 VersionTuple Introduced,
2219 VersionTuple Deprecated,
2220 VersionTuple Obsoleted) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002221 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
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002255/// \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
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002273AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002274 IdentifierInfo *Platform,
Manman Ren719a8642016-05-06 21:04:01 +00002275 bool Implicit,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002276 VersionTuple Introduced,
2277 VersionTuple Deprecated,
2278 VersionTuple Obsoleted,
2279 bool IsUnavailable,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002280 StringRef Message,
Manman Rend8039df2016-02-22 04:47:24 +00002281 bool IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002282 StringRef Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002283 AvailabilityMergeKind AMK,
Michael Han99315932013-01-24 16:46:58 +00002284 unsigned AttrSpellingListIndex) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00002285 VersionTuple MergedIntroduced = Introduced;
2286 VersionTuple MergedDeprecated = Deprecated;
2287 VersionTuple MergedObsoleted = Obsoleted;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002288 bool FoundAny = false;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002289 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 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002301
Rafael Espindolac67f2232012-05-10 02:50:16 +00002302 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 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002310
Rafael Espindolac67f2232012-05-10 02:50:16 +00002311 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2312 if (OldPlatform != Platform) {
2313 ++i;
2314 continue;
2315 }
2316
Tim Northover7a73cc72015-10-30 16:30:49 +00002317 // 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.
Manman Ren719a8642016-05-06 21:04:01 +00002320 if (!OldAA->isImplicit() && Implicit) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002321 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.
Manman Ren719a8642016-05-06 21:04:01 +00002327 if (!Implicit && OldAA->isImplicit()) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002328 Attrs.erase(Attrs.begin() + i);
2329 --e;
2330 continue;
2331 }
2332
Rafael Espindolac67f2232012-05-10 02:50:16 +00002333 FoundAny = true;
2334 VersionTuple OldIntroduced = OldAA->getIntroduced();
2335 VersionTuple OldDeprecated = OldAA->getDeprecated();
2336 VersionTuple OldObsoleted = OldAA->getObsoleted();
2337 bool OldIsUnavailable = OldAA->getUnavailable();
Rafael Espindolac67f2232012-05-10 02:50:16 +00002338
Douglas Gregord2a713e2015-09-30 21:27:42 +00002339 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2340 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2341 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002342 !(OldIsUnavailable == IsUnavailable ||
Douglas Gregord2a713e2015-09-30 21:27:42 +00002343 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2344 if (OverrideOrImpl) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002345 int Which = -1;
2346 VersionTuple FirstVersion;
2347 VersionTuple SecondVersion;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002348 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002349 Which = 0;
2350 FirstVersion = OldIntroduced;
2351 SecondVersion = Introduced;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002352 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002353 Which = 1;
2354 FirstVersion = Deprecated;
2355 SecondVersion = OldDeprecated;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002356 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002357 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)
Douglas Gregord2a713e2015-09-30 21:27:42 +00002365 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2366 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002367 } else {
2368 Diag(OldAA->getLocation(),
2369 diag::warn_mismatched_availability_override)
2370 << Which
2371 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
Douglas Gregord2a713e2015-09-30 21:27:42 +00002372 << FirstVersion.getAsString() << SecondVersion.getAsString()
2373 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002374 }
Douglas Gregord2a713e2015-09-30 21:27:42 +00002375 if (AMK == AMK_Override)
2376 Diag(Range.getBegin(), diag::note_overridden_method);
2377 else
2378 Diag(Range.getBegin(), diag::note_protocol_method);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002379 } else {
2380 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2381 Diag(Range.getBegin(), diag::note_previous_attribute);
2382 }
2383
Rafael Espindolac67f2232012-05-10 02:50:16 +00002384 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;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002412 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002413 }
2414
2415 if (FoundAny &&
2416 MergedIntroduced == Introduced &&
2417 MergedDeprecated == Deprecated &&
2418 MergedObsoleted == Obsoleted)
Craig Topperc3ec1492014-05-26 06:22:03 +00002419 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002420
Douglas Gregord2a713e2015-09-30 21:27:42 +00002421 // Only create a new attribute if !OverrideOrImpl, but we want to do
Ted Kremenekb5445722013-04-06 00:34:27 +00002422 // the checking.
Rafael Espindolac67f2232012-05-10 02:50:16 +00002423 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
Ted Kremenekb5445722013-04-06 00:34:27 +00002424 MergedDeprecated, MergedObsoleted) &&
Douglas Gregord2a713e2015-09-30 21:27:42 +00002425 !OverrideOrImpl) {
Manman Ren719a8642016-05-06 21:04:01 +00002426 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002427 Introduced, Deprecated,
Michael Han99315932013-01-24 16:46:58 +00002428 Obsoleted, IsUnavailable, Message,
Manman Ren75bc6762016-03-21 17:30:55 +00002429 IsStrict, Replacement,
2430 AttrSpellingListIndex);
Manman Ren719a8642016-05-06 21:04:01 +00002431 Avail->setImplicit(Implicit);
2432 return Avail;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002433 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002434 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002435}
2436
Chandler Carruthedc2c642011-07-02 00:01:44 +00002437static void handleAvailabilityAttr(Sema &S, Decl *D,
2438 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002439 if (!checkAttributeNumArgs(S, Attr, 1))
2440 return;
2441 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
Michael Han99315932013-01-24 16:46:58 +00002442 unsigned Index = Attr.getAttributeSpellingListIndex();
2443
Aaron Ballman00e99962013-08-31 01:11:41 +00002444 IdentifierInfo *II = Platform->Ident;
2445 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2446 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2447 << Platform->Ident;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002448
Rafael Espindolac231fab2013-01-08 21:30:32 +00002449 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Alex Lorenz472cc792017-04-20 09:35:02 +00002450 if (!ND) // We warned about this already, so just return.
Rafael Espindolac231fab2013-01-08 21:30:32 +00002451 return;
Rafael Espindolac231fab2013-01-08 21:30:32 +00002452
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002453 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2454 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2455 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
Douglas Gregor7ab142b2011-03-26 03:35:55 +00002456 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
Manman Rend8039df2016-02-22 04:47:24 +00002457 bool IsStrict = Attr.getStrictLoc().isValid();
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002458 StringRef Str;
Benjamin Kramera9dfa922013-09-13 17:31:48 +00002459 if (const StringLiteral *SE =
2460 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002461 Str = SE->getString();
Manman Ren75bc6762016-03-21 17:30:55 +00002462 StringRef Replacement;
2463 if (const StringLiteral *SE =
2464 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2465 Replacement = SE->getString();
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002466
Aaron Ballman00e99962013-08-31 01:11:41 +00002467 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
Manman Ren719a8642016-05-06 21:04:01 +00002468 false/*Implicit*/,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002469 Introduced.Version,
2470 Deprecated.Version,
2471 Obsoleted.Version,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002472 IsUnavailable, Str,
Manman Ren75bc6762016-03-21 17:30:55 +00002473 IsStrict, Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002474 Sema::AMK_None,
Michael Han99315932013-01-24 16:46:58 +00002475 Index);
Rafael Espindola19de5612013-01-12 06:42:30 +00002476 if (NewAttr)
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002477 D->addAttr(NewAttr);
Tim Northover7a73cc72015-10-30 16:30:49 +00002478
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,
Manman Ren719a8642016-05-06 21:04:01 +00002512 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002513 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002514 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002515 NewIntroduced,
2516 NewDeprecated,
2517 NewObsoleted,
2518 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002519 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002520 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002521 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,
Manman Ren719a8642016-05-06 21:04:01 +00002537 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002538 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002539 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002540 Introduced.Version,
2541 Deprecated.Version,
2542 Obsoleted.Version,
2543 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002544 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002545 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002546 Sema::AMK_None,
2547 Index);
2548 if (NewAttr)
2549 D->addAttr(NewAttr);
2550 }
2551 }
Rafael Espindolac67f2232012-05-10 02:50:16 +00002552}
2553
Alex Lorenzd5d27e12017-03-01 18:06:25 +00002554static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2555 const AttributeList &Attr) {
2556 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2557 return;
2558 assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&
2559 "Invalid number of arguments in an external_source_symbol attribute");
2560
Alex Lorenzd5d27e12017-03-01 18:06:25 +00002561 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
John McCalld041a9b2013-02-20 01:54:26 +00002574template <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)
Craig Topperc3ec1492014-05-26 06:22:03 +00002582 return nullptr;
John McCalld041a9b2013-02-20 01:54:26 +00002583 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
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002590VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002591 VisibilityAttr::VisibilityType Vis,
2592 unsigned AttrSpellingListIndex) {
John McCalld041a9b2013-02-20 01:54:26 +00002593 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2594 AttrSpellingListIndex);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002595}
2596
John McCalld041a9b2013-02-20 01:54:26 +00002597TypeVisibilityAttr *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
Benjamin Kramer70370212013-09-09 15:08:57 +00002623 // Check that the argument is a string literal.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002624 StringRef TypeStr;
2625 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002626 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002627 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002628
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002629 VisibilityAttr::VisibilityType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002630 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002631 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
Aaron Ballman682ee422013-09-11 19:47:58 +00002632 << Attr.getName() << TypeStr;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002633 return;
2634 }
Aaron Ballman682ee422013-09-11 19:47:58 +00002635
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 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002643
Michael Han99315932013-01-24 16:46:58 +00002644 unsigned Index = Attr.getAttributeSpellingListIndex();
John McCalld041a9b2013-02-20 01:54:26 +00002645 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);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002655}
2656
Chandler Carruthedc2c642011-07-02 00:01:44 +00002657static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2658 const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002659 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
Aaron Ballman00e99962013-08-31 01:11:41 +00002660 if (!Attr.isArgIdent(0)) {
2661 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2662 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
John McCall86bc21f2011-03-02 11:33:24 +00002663 return;
2664 }
Aaron Ballman00e99962013-08-31 01:11:41 +00002665
Aaron Ballman682ee422013-09-11 19:47:58 +00002666 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;
John McCall86bc21f2011-03-02 11:33:24 +00002671 return;
2672 }
2673
Alp Toker314cc812014-01-25 16:55:45 +00002674 if (F == ObjCMethodFamilyAttr::OMF_init &&
2675 !method->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002676 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
Alp Toker314cc812014-01-25 16:55:45 +00002677 << method->getReturnType();
John McCall31168b02011-06-15 23:02:42 +00002678 // Ignore the attribute.
2679 return;
2680 }
2681
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00002682 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +00002683 S.Context, F,
2684 Attr.getAttributeSpellingListIndex()));
John McCall86bc21f2011-03-02 11:33:24 +00002685}
2686
Chandler Carruthedc2c642011-07-02 00:01:44 +00002687static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
Richard Smithdda56e42011-04-15 14:24:37 +00002688 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002689 QualType T = TD->getUnderlyingType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002690 if (!T->isCARCBridgableType()) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002691 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2692 return;
2693 }
2694 }
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002695 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2696 QualType T = PD->getType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002697 if (!T->isCARCBridgableType()) {
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002698 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2699 return;
2700 }
2701 }
2702 else {
Ted Kremenek05e916b2012-03-01 01:40:32 +00002703 // 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.
Fariborz Jahaniana45495a2011-11-29 01:48:40 +00002709 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
Ted Kremenek05e916b2012-03-01 01:40:32 +00002710 }
Michael Han99315932013-01-24 16:46:58 +00002711 D->addAttr(::new (S.Context)
2712 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2713 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002714}
2715
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00002716static 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
Chandler Carruthedc2c642011-07-02 00:01:44 +00002732static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002733 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002734 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00002735 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Steve Naroff3405a732008-09-18 16:44:58 +00002736 return;
2737 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002738
Aaron Ballman00e99962013-08-31 01:11:41 +00002739 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002740 BlocksAttr::BlockType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002741 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2742 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2743 << Attr.getName() << II;
Steve Naroff3405a732008-09-18 16:44:58 +00002744 return;
2745 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002746
Michael Han99315932013-01-24 16:46:58 +00002747 D->addAttr(::new (S.Context)
2748 BlocksAttr(Attr.getRange(), S.Context, type,
2749 Attr.getAttributeSpellingListIndex()));
Steve Naroff3405a732008-09-18 16:44:58 +00002750}
2751
Chandler Carruthedc2c642011-07-02 00:01:44 +00002752static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00002753 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
Anders Carlssonc181b012008-10-05 18:05:59 +00002754 if (Attr.getNumArgs() > 0) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002755 Expr *E = Attr.getArgAsExpr(0);
Anders Carlssonc181b012008-10-05 18:05:59 +00002756 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002757 if (E->isTypeDependent() || E->isValueDependent() ||
2758 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002759 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002760 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002761 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002762 return;
2763 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002764
John McCallb46f2872011-09-09 07:56:05 +00002765 if (Idx.isSigned() && Idx.isNegative()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002766 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2767 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002768 return;
2769 }
John McCallb46f2872011-09-09 07:56:05 +00002770
2771 sentinel = Idx.getZExtValue();
Anders Carlssonc181b012008-10-05 18:05:59 +00002772 }
2773
Aaron Ballman18a78382013-11-21 00:28:23 +00002774 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
Anders Carlssonc181b012008-10-05 18:05:59 +00002775 if (Attr.getNumArgs() > 1) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002776 Expr *E = Attr.getArgAsExpr(1);
Anders Carlssonc181b012008-10-05 18:05:59 +00002777 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002778 if (E->isTypeDependent() || E->isValueDependent() ||
2779 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002780 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002781 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002782 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002783 return;
2784 }
2785 nullPos = Idx.getZExtValue();
Mike Stumpd3bb5572009-07-24 19:02:52 +00002786
John McCallb46f2872011-09-09 07:56:05 +00002787 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002788 // FIXME: This error message could be improved, it would be nice
2789 // to say what the bounds actually are.
Chris Lattner3b054132008-11-19 05:08:23 +00002790 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2791 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002792 return;
2793 }
2794 }
2795
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002796 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +00002797 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
Chris Lattner9363e312009-03-17 23:03:47 +00002798 if (isa<FunctionNoProtoType>(FT)) {
2799 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2800 return;
2801 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002802
Chris Lattner9363e312009-03-17 23:03:47 +00002803 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002804 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002805 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002806 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002807 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002808 if (!MD->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002809 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002810 return;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002811 }
Eli Friedman5c5e3b72012-01-06 01:23:10 +00002812 } 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 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002817 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002818 QualType Ty = V->getType();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002819 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Aaron Ballman12b9f652014-01-16 13:55:42 +00002820 const FunctionType *FT = Ty->isFunctionPointerType()
2821 ? D->getFunctionType()
Eric Christopherbc638a82010-12-01 22:13:54 +00002822 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002823 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002824 int m = Ty->isFunctionPointerType() ? 0 : 1;
2825 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002826 return;
2827 }
Mike Stump12b8ce12009-08-04 21:02:39 +00002828 } else {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002829 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002830 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002831 return;
2832 }
Anders Carlssonc181b012008-10-05 18:05:59 +00002833 } else {
Chris Lattner3b054132008-11-19 05:08:23 +00002834 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002835 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Anders Carlssonc181b012008-10-05 18:05:59 +00002836 return;
2837 }
Michael Han99315932013-01-24 16:46:58 +00002838 D->addAttr(::new (S.Context)
2839 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2840 Attr.getAttributeSpellingListIndex()));
Anders Carlssonc181b012008-10-05 18:05:59 +00002841}
2842
Chandler Carruthedc2c642011-07-02 00:01:44 +00002843static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
Alp Toker314cc812014-01-25 16:55:45 +00002844 if (D->getFunctionType() &&
2845 D->getFunctionType()->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002846 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2847 << Attr.getName() << 0;
Nuno Lopes56abcbd2009-12-22 23:59:52 +00002848 return;
2849 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002850 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00002851 if (MD->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002852 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2853 << Attr.getName() << 1;
2854 return;
2855 }
2856
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002857 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
Aaron Ballmane7964782016-03-07 22:44:55 +00002858 // about using it as an extension.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002859 if (!S.getLangOpts().CPlusPlus17 && Attr.isCXX11Attribute() &&
Aaron Ballmane7964782016-03-07 22:44:55 +00002860 !Attr.getScopeName())
Richard Smithb115e5d2017-08-13 23:37:29 +00002861 S.Diag(Attr.getLoc(), diag::ext_cxx17_attr) << Attr.getName();
Aaron Ballmane7964782016-03-07 22:44:55 +00002862
Michael Han99315932013-01-24 16:46:58 +00002863 D->addAttr(::new (S.Context)
2864 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2865 Attr.getAttributeSpellingListIndex()));
Chris Lattner237f2752009-02-14 07:37:35 +00002866}
2867
Chandler Carruthedc2c642011-07-02 00:01:44 +00002868static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002869 // weak_import only applies to variable & function declarations.
2870 bool isDef = false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002871 if (!D->canBeWeakImported(isDef)) {
2872 if (isDef)
Reid Kleckner52d598e2013-05-20 21:53:29 +00002873 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2874 << "weak_import";
Douglas Gregord71149a2011-03-23 13:27:51 +00002875 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
Douglas Gregore8bbc122011-09-02 00:18:52 +00002876 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
Fariborz Jahanian3249a1e2011-10-26 23:59:12 +00002877 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
Douglas Gregord71149a2011-03-23 13:27:51 +00002878 // Nothing to warn about here.
2879 } else
Fariborz Jahanianea70a172010-04-13 20:22:35 +00002880 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002881 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002882
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002883 return;
2884 }
2885
Michael Han99315932013-01-24 16:46:58 +00002886 D->addAttr(::new (S.Context)
2887 WeakImportAttr(Attr.getRange(), S.Context,
2888 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002889}
2890
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002891// Handles reqd_work_group_size and work_group_size_hint.
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002892template <typename WorkGroupAttr>
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002893static void handleWorkGroupSize(Sema &S, Decl *D,
Nick Lewyckyb9e4a3a2012-07-24 01:31:55 +00002894 const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002895 uint32_t WGSize[3];
Joey Goulyb1d23a82014-05-19 14:41:38 +00002896 for (unsigned i = 0; i < 3; ++i) {
2897 const Expr *E = Attr.getArgAsExpr(i);
2898 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
Nate Begemanf2758702009-06-26 06:32:41 +00002899 return;
Joey Goulyb1d23a82014-05-19 14:41:38 +00002900 if (WGSize[i] == 0) {
2901 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2902 << Attr.getName() << E->getSourceRange();
2903 return;
2904 }
2905 }
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002906
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002907 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();
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002912
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002913 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2914 WGSize[0], WGSize[1], WGSize[2],
Michael Han99315932013-01-24 16:46:58 +00002915 Attr.getAttributeSpellingListIndex()));
Nate Begemanf2758702009-06-26 06:32:41 +00002916}
2917
Xiuli Panbe6da4b2017-05-04 07:31:20 +00002918// 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
Joey Goulyaba589c2013-03-08 09:42:32 +00002940static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002941 if (!Attr.hasParsedType()) {
2942 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2943 << Attr.getName() << 1;
2944 return;
2945 }
2946
Craig Topperc3ec1492014-05-26 06:22:03 +00002947 TypeSourceInfo *ParmTSI = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00002948 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2949 assert(ParmTSI && "no type source info for attribute argument");
Joey Goulyaba589c2013-03-08 09:42:32 +00002950
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
Aaron Ballmana9e05402013-12-02 22:16:55 +00002959 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
Richard Smithb87c4652013-10-31 21:23:20 +00002960 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
Joey Goulyaba589c2013-03-08 09:42:32 +00002961 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,
Aaron Ballman36a53502014-01-16 13:03:14 +00002967 ParmTSI,
2968 Attr.getAttributeSpellingListIndex()));
Joey Goulyaba589c2013-03-08 09:42:32 +00002969}
2970
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002971SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002972 StringRef Name,
2973 unsigned AttrSpellingListIndex) {
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002974 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2975 if (ExistingAttr->getName() == Name)
Craig Topperc3ec1492014-05-26 06:22:03 +00002976 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002977 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2978 Diag(Range.getBegin(), diag::note_previous_attribute);
Craig Topperc3ec1492014-05-26 06:22:03 +00002979 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002980 }
Michael Han99315932013-01-24 16:46:58 +00002981 return ::new (Context) SectionAttr(Range, Context, Name,
2982 AttrSpellingListIndex);
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002983}
2984
Reid Kleckner2a133222015-03-04 23:39:17 +00002985bool 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
Chandler Carruthedc2c642011-07-02 00:01:44 +00002994static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar648bf782009-02-12 17:28:23 +00002995 // Make sure that there is a string literal as the sections's single
2996 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002997 StringRef Str;
2998 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002999 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
Daniel Dunbar648bf782009-02-12 17:28:23 +00003000 return;
Mike Stump11289f42009-09-09 15:08:12 +00003001
Reid Kleckner2a133222015-03-04 23:39:17 +00003002 if (!S.checkSectionName(LiteralLoc, Str))
3003 return;
3004
Chris Lattner30ba6742009-08-10 19:03:04 +00003005 // If the target wants to validate the section specifier, make it happen.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003006 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
Chris Lattner20aee9b2010-01-12 20:58:53 +00003007 if (!Error.empty()) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003008 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
Chris Lattner20aee9b2010-01-12 20:58:53 +00003009 << Error;
Chris Lattner30ba6742009-08-10 19:03:04 +00003010 return;
3011 }
Mike Stump11289f42009-09-09 15:08:12 +00003012
Michael Han99315932013-01-24 16:46:58 +00003013 unsigned Index = Attr.getAttributeSpellingListIndex();
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003014 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00003015 if (NewAttr)
3016 D->addAttr(NewAttr);
Daniel Dunbar648bf782009-02-12 17:28:23 +00003017}
3018
Erich Keane57e15cd2017-07-19 22:06:33 +00003019// 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 };
Eric Christopher789a7ad2015-06-12 01:36:05 +00003024 for (auto Str : {"tune=", "fpmath="})
3025 if (AttrStr.find(Str) != StringRef::npos)
Erich Keane57e15cd2017-07-19 22:06:33 +00003026 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;
Eric Christopher789a7ad2015-06-12 01:36:05 +00003048}
3049
Eric Christopher11acf732015-06-12 01:35:52 +00003050static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eric Christopher11acf732015-06-12 01:35:52 +00003051 StringRef Str;
3052 SourceLocation LiteralLoc;
Erich Keane57e15cd2017-07-19 22:06:33 +00003053 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc) ||
3054 !S.checkTargetAttr(LiteralLoc, Str))
Eric Christopher11acf732015-06-12 01:35:52 +00003055 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
Chandler Carruthedc2c642011-07-02 00:01:44 +00003062static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003063 Expr *E = Attr.getArgAsExpr(0);
3064 SourceLocation Loc = E->getExprLoc();
Craig Topperc3ec1492014-05-26 06:22:03 +00003065 FunctionDecl *FD = nullptr;
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003066 DeclarationNameInfo NI;
Aaron Ballman00e99962013-08-31 01:11:41 +00003067
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003068 // 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);
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003083 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3084 NI = ULE->getNameInfo();
Alp Toker67b47ac2013-10-20 18:48:56 +00003085 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 }
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003092 } else {
3093 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
Anders Carlssond277d792009-01-31 01:16:18 +00003094 return;
3095 }
3096
Anders Carlssond277d792009-01-31 01:16:18 +00003097 if (FD->getNumParams() != 1) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003098 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3099 << NI.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00003100 return;
3101 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003102
Anders Carlsson723f55d2009-02-07 23:16:50 +00003103 // 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.
Aaron Ballman3b70e752017-12-01 16:53:49 +00003105 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
Anders Carlsson723f55d2009-02-07 23:16:50 +00003106 QualType ParamTy = FD->getParamDecl(0)->getType();
Douglas Gregorc03a1082011-01-28 02:26:04 +00003107 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3108 ParamTy, Ty) != Sema::Compatible) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003109 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3110 << NI.getName() << ParamTy << Ty;
Anders Carlsson723f55d2009-02-07 23:16:50 +00003111 return;
3112 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003113
Michael Han99315932013-01-24 16:46:58 +00003114 D->addAttr(::new (S.Context)
3115 CleanupAttr(Attr.getRange(), S.Context, FD,
3116 Attr.getAttributeSpellingListIndex()));
Anders Carlssond277d792009-01-31 01:16:18 +00003117}
3118
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003119static 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
Mike Stumpd3bb5572009-07-24 19:02:52 +00003141/// Handle __attribute__((format_arg((idx)))) attribute based on
Bill Wendling44426052012-12-20 19:22:21 +00003142/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003143static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00003144 Expr *IdxExpr = Attr.getArgAsExpr(0);
Alp Toker601b22c2014-01-21 23:35:24 +00003145 uint64_t Idx;
3146 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003147 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00003148
Eric Christopherb64963e2015-08-13 21:34:35 +00003149 // Make sure the format string is really a string.
Alp Toker601b22c2014-01-21 23:35:24 +00003150 QualType Ty = getFunctionOrMethodParamType(D, Idx);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003151
Eric Christopherb64963e2015-08-13 21:34:35 +00003152 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3153 if (NotNSStringTy &&
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003154 !isCFStringType(Ty, S.Context) &&
3155 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003156 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003157 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00003158 << "a string type" << IdxExpr->getSourceRange()
3159 << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003160 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003161 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003162 Ty = getFunctionOrMethodResultType(D);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003163 if (!isNSStringType(Ty, S.Context) &&
3164 !isCFStringType(Ty, S.Context) &&
3165 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003166 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003167 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00003168 << (NotNSStringTy ? "string type" : "NSString")
Aaron Ballman2f9e88b2014-08-04 15:17:29 +00003169 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003170 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003171 }
3172
Alp Toker601b22c2014-01-21 23:35:24 +00003173 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00003174 // 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
Michael Han99315932013-01-24 16:46:58 +00003179 D->addAttr(::new (S.Context)
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00003180 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
Michael Han99315932013-01-24 16:46:58 +00003181 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003182}
3183
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003184enum FormatAttrKind {
3185 CFStringFormat,
3186 NSStringFormat,
3187 StrftimeFormat,
3188 SupportedFormat,
Chris Lattner12161d32010-03-22 21:08:50 +00003189 IgnoredFormat,
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003190 InvalidFormat
3191};
3192
3193/// getFormatAttrKind - Map from format attribute names to supported format
3194/// types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003195static FormatAttrKind getFormatAttrKind(StringRef Format) {
Benjamin Kramer96a44b62012-05-16 12:44:25 +00003196 return llvm::StringSwitch<FormatAttrKind>(Format)
Mehdi Amini06d367c2016-10-24 20:39:34 +00003197 // Check for formats that get handled specially.
3198 .Case("NSString", NSStringFormat)
3199 .Case("CFString", CFStringFormat)
3200 .Case("strftime", StrftimeFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003201
Mehdi Amini06d367c2016-10-24 20:39:34 +00003202 // 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)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003209
Mehdi Amini06d367c2016-10-24 20:39:34 +00003210 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3211 .Default(InvalidFormat);
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003212}
3213
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003214/// Handle __attribute__((init_priority(priority))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00003215/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003216static void handleInitPriorityAttr(Sema &S, Decl *D,
3217 const AttributeList &Attr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003218 if (!S.getLangOpts().CPlusPlus) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003219 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3220 return;
3221 }
3222
Aaron Ballman4a611152013-11-27 16:34:09 +00003223 if (S.getCurFunctionOrMethodDecl()) {
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00003224 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3225 Attr.setInvalid();
3226 return;
3227 }
Aaron Ballman4a611152013-11-27 16:34:09 +00003228 QualType T = cast<VarDecl>(D)->getType();
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00003229 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 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003236
3237 Expr *E = Attr.getArgAsExpr(0);
3238 uint32_t prioritynum;
3239 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003240 Attr.setInvalid();
3241 return;
3242 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003243
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003244 if (prioritynum < 101 || prioritynum > 65535) {
3245 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003246 << E->getSourceRange() << Attr.getName() << 101 << 65535;
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003247 Attr.setInvalid();
3248 return;
3249 }
Michael Han99315932013-01-24 16:46:58 +00003250 D->addAttr(::new (S.Context)
3251 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3252 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003253}
3254
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003255FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3256 IdentifierInfo *Format, int FormatIdx,
3257 int FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003258 unsigned AttrSpellingListIndex) {
Rafael Espindola92d49452012-05-11 00:36:07 +00003259 // Check whether we already have an equivalent format attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003260 for (auto *F : D->specific_attrs<FormatAttr>()) {
3261 if (F->getType() == Format &&
3262 F->getFormatIdx() == FormatIdx &&
3263 F->getFirstArg() == FirstArg) {
Rafael Espindola92d49452012-05-11 00:36:07 +00003264 // If we don't have a valid location for this attribute, adopt the
3265 // location.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003266 if (F->getLocation().isInvalid())
3267 F->setRange(Range);
Craig Topperc3ec1492014-05-26 06:22:03 +00003268 return nullptr;
Rafael Espindola92d49452012-05-11 00:36:07 +00003269 }
3270 }
3271
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003272 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3273 FirstArg, AttrSpellingListIndex);
Rafael Espindola92d49452012-05-11 00:36:07 +00003274}
3275
Mike Stumpd3bb5572009-07-24 19:02:52 +00003276/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00003277/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003278static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00003279 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00003280 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00003281 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003282 return;
3283 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003284
Chandler Carruth743682b2010-11-16 08:35:43 +00003285 // In C++ the implicit 'this' function parameter also counts, and they are
3286 // counted from one.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003287 bool HasImplicitThisParam = isInstanceMethod(D);
Alp Toker601b22c2014-01-21 23:35:24 +00003288 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003289
Aaron Ballman00e99962013-08-31 01:11:41 +00003290 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3291 StringRef Format = II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003292
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00003293 if (normalizeName(Format)) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003294 // If we've modified the string name, we need a new identifier for it.
3295 II = &S.Context.Idents.get(Format);
3296 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003297
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003298 // Check for supported formats.
3299 FormatAttrKind Kind = getFormatAttrKind(Format);
Chris Lattner12161d32010-03-22 21:08:50 +00003300
3301 if (Kind == IgnoredFormat)
3302 return;
3303
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003304 if (Kind == InvalidFormat) {
Chris Lattner3b054132008-11-19 05:08:23 +00003305 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
Aaron Ballman190bad42013-12-26 16:13:50 +00003306 << Attr.getName() << II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003307 return;
3308 }
3309
3310 // checks for the 2nd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00003311 Expr *IdxExpr = Attr.getArgAsExpr(1);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003312 uint32_t Idx;
3313 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003314 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003315
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003316 if (Idx < 1 || Idx > NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00003317 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00003318 << Attr.getName() << 2 << IdxExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003319 return;
3320 }
3321
3322 // FIXME: Do we need to bounds check?
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003323 unsigned ArgIdx = Idx - 1;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003324
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003325 if (HasImplicitThisParam) {
3326 if (ArgIdx == 0) {
Chandler Carruth743682b2010-11-16 08:35:43 +00003327 S.Diag(Attr.getLoc(),
3328 diag::err_format_attribute_implicit_this_format_string)
3329 << IdxExpr->getSourceRange();
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003330 return;
3331 }
3332 ArgIdx--;
3333 }
Mike Stump11289f42009-09-09 15:08:12 +00003334
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003335 // make sure the format string is really a string
Alp Toker601b22c2014-01-21 23:35:24 +00003336 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003337
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003338 if (Kind == CFStringFormat) {
Daniel Dunbar980c6692008-09-26 03:32:58 +00003339 if (!isCFStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00003340 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003341 << "a CFString" << IdxExpr->getSourceRange()
3342 << getFunctionOrMethodParamRange(D, ArgIdx);
Daniel Dunbar980c6692008-09-26 03:32:58 +00003343 return;
3344 }
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003345 } else if (Kind == NSStringFormat) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003346 // FIXME: do we need to check if the type is NSString*? What are the
3347 // semantics?
Chris Lattnerb632a6e2008-06-29 00:43:07 +00003348 if (!isNSStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00003349 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003350 << "an NSString" << IdxExpr->getSourceRange()
3351 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003352 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003353 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003354 } else if (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003355 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003356 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003357 << "a string type" << IdxExpr->getSourceRange()
3358 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003359 return;
3360 }
3361
3362 // check the 3rd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00003363 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003364 uint32_t FirstArg;
3365 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003366 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003367
3368 // check if the function is variadic if the 3rd argument non-zero
3369 if (FirstArg != 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003370 if (isFunctionOrMethodVariadic(D)) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003371 ++NumArgs; // +1 for ...
3372 } else {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003373 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003374 return;
3375 }
3376 }
3377
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003378 // 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.
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003380 if (Kind == StrftimeFormat) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003381 if (FirstArg != 0) {
Chris Lattner3b054132008-11-19 05:08:23 +00003382 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3383 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003384 return;
3385 }
3386 // if 0 it disables parameter checking (to use with e.g. va_list)
3387 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00003388 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00003389 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003390 return;
3391 }
3392
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003393 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003394 Idx, FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003395 Attr.getAttributeSpellingListIndex());
Rafael Espindolae200f1c2012-05-13 03:25:18 +00003396 if (NewAttr)
3397 D->addAttr(NewAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003398}
3399
Chandler Carruthedc2c642011-07-02 00:01:44 +00003400static void handleTransparentUnionAttr(Sema &S, Decl *D,
3401 const AttributeList &Attr) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003402 // Try to find the underlying union declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00003403 RecordDecl *RD = nullptr;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003404 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003405 if (TD && TD->getUnderlyingType()->isUnionType())
3406 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3407 else
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003408 RD = dyn_cast<RecordDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003409
3410 if (!RD || !RD->isUnion()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003411 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00003412 << Attr.getName() << ExpectedUnion;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003413 return;
3414 }
3415
John McCallf937c022011-10-07 06:10:15 +00003416 if (!RD->isCompleteDefinition()) {
Erich Keane2fe684b2017-02-28 20:44:39 +00003417 if (!RD->isBeingDefined())
3418 S.Diag(Attr.getLoc(),
3419 diag::warn_transparent_union_attribute_not_definition);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003420 return;
3421 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003422
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003423 RecordDecl::field_iterator Field = RD->field_begin(),
3424 FieldEnd = RD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003425 if (Field == FieldEnd) {
3426 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3427 return;
3428 }
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003429
David Blaikie40ed2972012-06-06 20:45:41 +00003430 FieldDecl *FirstField = *Field;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003431 QualType FirstType = FirstField->getType();
Douglas Gregor21872662010-06-30 17:24:13 +00003432 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
Mike Stumpd3bb5572009-07-24 19:02:52 +00003433 S.Diag(FirstField->getLocation(),
Douglas Gregor21872662010-06-30 17:24:13 +00003434 diag::warn_transparent_union_attribute_floating)
3435 << FirstType->isVectorType() << FirstType;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003436 return;
3437 }
3438
Alex Lorenz6f4bc4f2016-10-06 09:47:29 +00003439 if (FirstType->isIncompleteType())
3440 return;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003441 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();
Alex Lorenz6f4bc4f2016-10-06 09:47:29 +00003445 if (FieldType->isIncompleteType())
3446 return;
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003447 // 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).
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003452 if (S.Context.getTypeSize(FieldType) != FirstSize ||
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003453 S.Context.getTypeAlign(FieldType) > FirstAlign) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003454 // Warn if we drop the attribute.
3455 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003456 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003457 : S.Context.getTypeAlign(FieldType);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003458 S.Diag(Field->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003459 diag::warn_transparent_union_attribute_field_size_align)
3460 << isSize << Field->getDeclName() << FieldBits;
3461 unsigned FirstBits = isSize? FirstSize : FirstAlign;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003462 S.Diag(FirstField->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003463 diag::note_transparent_union_first_field_size_align)
3464 << isSize << FirstBits;
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003465 return;
3466 }
3467 }
3468
Michael Han99315932013-01-24 16:46:58 +00003469 RD->addAttr(::new (S.Context)
3470 TransparentUnionAttr(Attr.getRange(), S.Context,
3471 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003472}
3473
Chandler Carruthedc2c642011-07-02 00:01:44 +00003474static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003475 // Make sure that there is a string literal as the annotation's single
3476 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003477 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003478 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003479 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003480
3481 // Don't duplicate annotations that are already set.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003482 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3483 if (I->getAnnotation() == Str)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003484 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003485 }
Michael Han99315932013-01-24 16:46:58 +00003486
3487 D->addAttr(::new (S.Context)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003488 AnnotateAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00003489 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003490}
3491
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003492static 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");
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()) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003519 llvm::APSInt Alignment;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003520 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));
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003541}
3542
Chandler Carruthedc2c642011-07-02 00:01:44 +00003543static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003544 // check the attribute arguments.
Chris Lattner4a927cb2008-06-28 23:36:30 +00003545 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00003546 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3547 << Attr.getName() << 1;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003548 return;
3549 }
Aaron Ballman478faed2012-06-19 22:09:27 +00003550
Richard Smith848e1f12013-02-01 08:12:08 +00003551 if (Attr.getNumArgs() == 0) {
3552 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00003553 true, nullptr, Attr.getAttributeSpellingListIndex()));
Richard Smith848e1f12013-02-01 08:12:08 +00003554 return;
3555 }
3556
Aaron Ballman00e99962013-08-31 01:11:41 +00003557 Expr *E = Attr.getArgAsExpr(0);
Richard Smith44c247f2013-02-22 08:32:16 +00003558 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
David Majnemer26a1e0e2015-04-07 02:37:09 +00003567 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
Richard Smith44c247f2013-02-22 08:32:16 +00003577 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3578 Attr.isPackExpansion());
Richard Smith848e1f12013-02-01 08:12:08 +00003579}
3580
3581void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
Richard Smith44c247f2013-02-22 08:32:16 +00003582 unsigned SpellingListIndex, bool IsPackExpansion) {
Richard Smith848e1f12013-02-01 08:12:08 +00003583 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3584 SourceLocation AttrLoc = AttrRange.getBegin();
3585
Richard Smith1dba27c2013-01-29 09:02:09 +00003586 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
Richard Smith848e1f12013-02-01 08:12:08 +00003587 if (TmpAttr.isAlignas()) {
Richard Smith1dba27c2013-01-29 09:02:09 +00003588 // 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)) {
Aaron Ballman3d216a52014-01-02 23:39:11 +00003611 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
Richard Smith9eaab4b2013-02-01 08:25:07 +00003612 << (TmpAttr.isC11() ? ExpectedVariableOrField
3613 : ExpectedVariableFieldOrTag);
Richard Smith1dba27c2013-01-29 09:02:09 +00003614 return;
3615 }
3616 if (DiagKind != -1) {
Richard Smith848e1f12013-02-01 08:12:08 +00003617 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
Aaron Ballman3d216a52014-01-02 23:39:11 +00003618 << &TmpAttr << DiagKind;
Richard Smith1dba27c2013-01-29 09:02:09 +00003619 return;
3620 }
3621 }
3622
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003623 if (E->isTypeDependent() || E->isValueDependent()) {
3624 // Save dependent expressions in the AST to be instantiated.
Richard Smith44c247f2013-02-22 08:32:16 +00003625 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3626 AA->setPackExpansion(IsPackExpansion);
3627 D->addAttr(AA);
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003628 return;
3629 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003630
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003631 // FIXME: Cache the number on the Attr object?
David Majnemer0be6bd02015-07-26 09:02:21 +00003632 llvm::APSInt Alignment;
Douglas Gregore2b37442012-05-04 22:38:52 +00003633 ExprResult ICE
3634 = VerifyIntegerConstantExpression(E, &Alignment,
3635 diag::err_aligned_attribute_argument_not_int,
3636 /*AllowFold*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00003637 if (ICE.isInvalid())
Chris Lattner4627b742008-06-28 23:50:44 +00003638 return;
Richard Smith848e1f12013-02-01 08:12:08 +00003639
David Majnemer0be6bd02015-07-26 09:02:21 +00003640 uint64_t AlignVal = Alignment.getZExtValue();
3641
Richard Smith848e1f12013-02-01 08:12:08 +00003642 // 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.
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003647 if (!(TmpAttr.isAlignas() && !Alignment)) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003648 if (!llvm::isPowerOf2_64(AlignVal)) {
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003649 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3650 << E->getSourceRange();
3651 return;
3652 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003653 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003654
David Majnemerabecae72014-02-12 20:36:10 +00003655 // Alignment calculations can wrap around if it's greater than 2**28.
David Majnemer29c69db2015-07-26 01:48:59 +00003656 unsigned MaxValidAlignment =
3657 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3658 : 268435456;
David Majnemer0be6bd02015-07-26 09:02:21 +00003659 if (AlignVal > MaxValidAlignment) {
David Majnemerabecae72014-02-12 20:36:10 +00003660 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3661 << E->getSourceRange();
3662 return;
Aaron Ballman478faed2012-06-19 22:09:27 +00003663 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003664
David Majnemer0be6bd02015-07-26 09:02:21 +00003665 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
Richard Smith44c247f2013-02-22 08:32:16 +00003678 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003679 ICE.get(), SpellingListIndex);
Richard Smith44c247f2013-02-22 08:32:16 +00003680 AA->setPackExpansion(IsPackExpansion);
3681 D->addAttr(AA);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003682}
3683
Michael Hanaf02bbe2013-02-01 01:19:17 +00003684void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
Richard Smith44c247f2013-02-22 08:32:16 +00003685 unsigned SpellingListIndex, bool IsPackExpansion) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003686 // FIXME: Cache the number on the Attr object if non-dependent?
3687 // FIXME: Perform checking of type validity
Richard Smith44c247f2013-02-22 08:32:16 +00003688 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3689 SpellingListIndex);
3690 AA->setPackExpansion(IsPackExpansion);
3691 D->addAttr(AA);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003692}
Chris Lattneracbc2d22008-06-27 22:18:37 +00003693
Richard Smith848e1f12013-02-01 08:12:08 +00003694void Sema::CheckAlignasUnderalignment(Decl *D) {
3695 assert(D->hasAttrs() && "no attributes on decl");
3696
David Majnemer475b25e2015-01-21 10:54:38 +00003697 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())
Richard Smith848e1f12013-02-01 08:12:08 +00003706 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.
Craig Topperc3ec1492014-05-26 06:22:03 +00003712 AlignedAttr *AlignasAttr = nullptr;
Richard Smith848e1f12013-02-01 08:12:08 +00003713 unsigned Align = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003714 for (auto *I : D->specific_attrs<AlignedAttr>()) {
Richard Smith848e1f12013-02-01 08:12:08 +00003715 if (I->isAlignmentDependent())
3716 return;
3717 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003718 AlignasAttr = I;
Richard Smith848e1f12013-02-01 08:12:08 +00003719 Align = std::max(Align, I->getAlignment(Context));
3720 }
3721
3722 if (AlignasAttr && Align) {
3723 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
David Majnemer475b25e2015-01-21 10:54:38 +00003724 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
Richard Smith848e1f12013-02-01 08:12:08 +00003725 if (NaturalAlign > RequestedAlign)
3726 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
David Majnemer475b25e2015-01-21 10:54:38 +00003727 << DiagTy << (unsigned)NaturalAlign.getQuantity();
Richard Smith848e1f12013-02-01 08:12:08 +00003728 }
3729}
3730
David Majnemer2c4e00a2014-01-29 22:07:36 +00003731bool Sema::checkMSInheritanceAttrOnDefinition(
David Majnemer4bb09802014-02-10 19:50:15 +00003732 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00003733 MSInheritanceAttr::Spelling SemanticSpelling) {
3734 assert(RD->hasDefinition() && "RD has no definition!");
3735
David Majnemer98c9ee22014-02-07 00:43:07 +00003736 // 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;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003740
David Majnemer98c9ee22014-02-07 00:43:07 +00003741 // The unspecified model never matches what a definition could need.
3742 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3743 return false;
3744
David Majnemer4bb09802014-02-10 19:50:15 +00003745 if (BestCase) {
3746 if (RD->calculateInheritanceModel() == SemanticSpelling)
3747 return false;
3748 } else {
3749 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3750 return false;
3751 }
David Majnemer98c9ee22014-02-07 00:43:07 +00003752
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;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003758}
3759
Alexey Bataevf278eb12015-11-19 10:13:11 +00003760/// 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) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003764 IntegerMode = true;
3765 ComplexMode = false;
Daniel Dunbarafff4342009-10-18 02:09:24 +00003766 switch (Str.size()) {
Chris Lattneracbc2d22008-06-27 22:18:37 +00003767 case 2:
Eli Friedman4735374e2009-03-03 06:41:03 +00003768 switch (Str[0]) {
Alexey Bataevf278eb12015-11-19 10:13:11 +00003769 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;
Eli Friedman4735374e2009-03-03 06:41:03 +00003787 }
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 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003796 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.
Daniel Dunbarafff4342009-10-18 02:09:24 +00003800 if (Str == "word")
Reid Klecknerf27e7522016-02-01 18:58:24 +00003801 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
Daniel Dunbarafff4342009-10-18 02:09:24 +00003802 else if (Str == "byte")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003803 DestWidth = S.Context.getTargetInfo().getCharWidth();
Chris Lattneracbc2d22008-06-27 22:18:37 +00003804 break;
3805 case 7:
Daniel Dunbarafff4342009-10-18 02:09:24 +00003806 if (Str == "pointer")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003807 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
Chris Lattneracbc2d22008-06-27 22:18:37 +00003808 break;
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003809 case 11:
3810 if (Str == "unwind_word")
Rafael Espindola03705972013-01-07 20:01:57 +00003811 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003812 break;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003813 }
Alexey Bataevf278eb12015-11-19 10:13:11 +00003814}
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;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003832
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003833 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();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003839 normalizeName(Str);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003840 SourceLocation AttrLoc = AttrRange.getBegin();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003841
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()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003856 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
Alexey Bataevf278eb12015-11-19 10:13:11 +00003857 IntegerMode, ComplexMode);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003858 // Avoid duplicate warning from template instantiation.
3859 if (!InInstantiation)
3860 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003861 } else {
3862 VectorSize = 0;
3863 }
3864 }
3865
3866 if (!VectorSize)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003867 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 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003877
3878 QualType OldTy;
Richard Smithdda56e42011-04-15 14:24:37 +00003879 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
Chris Lattneracbc2d22008-06-27 22:18:37 +00003880 OldTy = TD->getUnderlyingType();
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003881 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
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003888 OldTy = cast<ValueDecl>(D)->getType();
Eli Friedman4735374e2009-03-03 06:41:03 +00003889
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003890 if (OldTy->isDependentType()) {
3891 D->addAttr(::new (Context)
3892 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3893 return;
3894 }
3895
Alexey Bataev326057d2015-06-19 07:46:21 +00003896 // 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
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003902 // 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);
Eli Friedman4735374e2009-03-03 06:41:03 +00003916 else if (IntegerMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003917 if (!IntegralOrAnyEnumType)
3918 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003919 } else if (ComplexMode) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003920 if (!OldElemTy->isComplexType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003921 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003922 } else {
Alexey Bataev326057d2015-06-19 07:46:21 +00003923 if (!OldElemTy->isFloatingType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003924 Diag(AttrLoc, diag::err_mode_wrong_type);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003925 }
3926
Alexey Bataev326057d2015-06-19 07:46:21 +00003927 QualType NewElemTy;
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003928
3929 if (IntegerMode)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003930 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3931 OldElemTy->isSignedIntegerType());
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003932 else
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003933 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003934
Alexey Bataev326057d2015-06-19 07:46:21 +00003935 if (NewElemTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003936 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003937 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003938 }
3939
Eli Friedman4735374e2009-03-03 06:41:03 +00003940 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003941 NewElemTy = Context.getComplexType(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003942 }
3943
3944 QualType NewTy = NewElemTy;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003945 if (VectorSize.getBoolValue()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003946 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3947 VectorType::GenericVector);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003948 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003949 // Complex machine mode does not support base vector types.
3950 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003951 Diag(AttrLoc, diag::err_complex_mode_vector_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003952 return;
3953 }
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003954 unsigned NumElements = Context.getTypeSize(OldElemTy) *
Alexey Bataev326057d2015-06-19 07:46:21 +00003955 OldVT->getNumElements() /
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003956 Context.getTypeSize(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003957 NewTy =
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003958 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
Alexey Bataev326057d2015-06-19 07:46:21 +00003959 }
3960
3961 if (NewTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003962 Diag(AttrLoc, diag::err_mode_wrong_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003963 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003964 }
3965
3966 // Install the new type.
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003967 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3968 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003969 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3970 ED->setIntegerType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003971 else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003972 cast<ValueDecl>(D)->setType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003973
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003974 D->addAttr(::new (Context)
3975 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
Chris Lattneracbc2d22008-06-27 22:18:37 +00003976}
Chris Lattner9e2aafe2008-06-29 00:23:49 +00003977
Chandler Carruthedc2c642011-07-02 00:01:44 +00003978static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Michael Han99315932013-01-24 16:46:58 +00003979 D->addAttr(::new (S.Context)
3980 NoDebugAttr(Attr.getRange(), S.Context,
3981 Attr.getAttributeSpellingListIndex()));
Anders Carlsson76187b42009-02-13 06:46:13 +00003982}
3983
Paul Robinson30e41fb2014-12-15 18:57:28 +00003984AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
Paul Robinson080b1f32015-01-13 18:34:56 +00003985 IdentifierInfo *Ident,
Paul Robinson30e41fb2014-12-15 18:57:28 +00003986 unsigned AttrSpellingListIndex) {
3987 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
Paul Robinson080b1f32015-01-13 18:34:56 +00003988 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
Paul Robinson30e41fb2014-12-15 18:57:28 +00003989 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
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004000CommonAttr *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
Paul Robinson30e41fb2014-12-15 18:57:28 +00004036MinSizeAttr *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
Paul Robinsonf0674352014-03-31 22:29:15 +00004070static void handleAlwaysInlineAttr(Sema &S, Decl *D,
4071 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004072 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
Charles Davis0e379112016-08-08 21:19:08 +00004073 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00004074 return;
4075
Paul Robinson080b1f32015-01-13 18:34:56 +00004076 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4077 D, Attr.getRange(), Attr.getName(),
4078 Attr.getAttributeSpellingListIndex()))
4079 D->addAttr(Inline);
Paul Robinsonf0674352014-03-31 22:29:15 +00004080}
4081
Paul Robinson080b1f32015-01-13 18:34:56 +00004082static 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);
Paul Robinsonaae2fba2014-12-10 23:34:36 +00004086}
4087
Paul Robinsonf0674352014-03-31 22:29:15 +00004088static void handleOptimizeNoneAttr(Sema &S, Decl *D,
4089 const AttributeList &Attr) {
Paul Robinson080b1f32015-01-13 18:34:56 +00004090 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4091 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4092 D->addAttr(Optnone);
Paul Robinsonf0674352014-03-31 22:29:15 +00004093}
4094
Justin Lebare71b2fa2016-09-30 23:57:34 +00004095static 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
Justin Lebar10411012016-09-30 23:57:30 +00004108static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4109 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
4110 Attr.getName()))
4111 return;
4112 auto *VD = cast<VarDecl>(D);
Justin Lebar281ce2a2016-10-02 15:24:50 +00004113 // extern __shared__ is only allowed on arrays with no length (e.g.
4114 // "int x[]").
4115 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
Justin Lebar10411012016-09-30 23:57:30 +00004116 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
4117 return;
4118 }
Justin Lebaraa370bd2016-10-13 18:45:13 +00004119 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4120 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
4121 << S.CurrentCUDATarget())
4122 return;
Justin Lebar10411012016-09-30 23:57:30 +00004123 D->addAttr(::new (S.Context) CUDASharedAttr(
4124 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4125}
4126
Chandler Carruthedc2c642011-07-02 00:01:44 +00004127static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Justin Lebar3eaaf862016-01-13 01:07:35 +00004128 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
4129 Attr.getName()) ||
4130 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
4131 Attr.getName())) {
4132 return;
4133 }
Aaron Ballman3aff6332013-12-02 19:30:36 +00004134 FunctionDecl *FD = cast<FunctionDecl>(D);
Alp Toker314cc812014-01-25 16:55:45 +00004135 if (!FD->getReturnType()->isVoidType()) {
Alp Tokerf5b10792014-07-02 12:55:58 +00004136 SourceRange RTRange = FD->getReturnTypeSourceRange();
4137 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
Aaron Ballman3aff6332013-12-02 19:30:36 +00004138 << FD->getType()
Alp Tokerf5b10792014-07-02 12:55:58 +00004139 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4140 : FixItHint());
Aaron Ballman3aff6332013-12-02 19:30:36 +00004141 return;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004142 }
Justin Lebarc66a1062016-01-20 00:26:57 +00004143 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;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004154
Aaron Ballman3aff6332013-12-02 19:30:36 +00004155 D->addAttr(::new (S.Context)
4156 CUDAGlobalAttr(Attr.getRange(), S.Context,
Eli Bendersky83860042014-09-02 22:00:06 +00004157 Attr.getAttributeSpellingListIndex()));
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004158}
4159
Chandler Carruthedc2c642011-07-02 00:01:44 +00004160static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004161 FunctionDecl *Fn = cast<FunctionDecl>(D);
Douglas Gregor35b57532009-10-27 21:01:01 +00004162 if (!Fn->isInlineSpecified()) {
Chris Lattnerddf6ca02009-04-20 19:12:28 +00004163 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
Chris Lattner4225e232009-04-14 17:02:11 +00004164 return;
4165 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004166
Michael Han99315932013-01-24 16:46:58 +00004167 D->addAttr(::new (S.Context)
4168 GNUInlineAttr(Attr.getRange(), S.Context,
4169 Attr.getAttributeSpellingListIndex()));
Chris Lattnereaad6b72009-04-14 16:30:50 +00004170}
4171
Chandler Carruthedc2c642011-07-02 00:01:44 +00004172static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004173 if (hasDeclarator(D)) return;
Abramo Bagnara50099372010-04-30 13:10:51 +00004174
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004175 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
John McCall3882ace2011-01-05 12:14:39 +00004176 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4177 CallingConv CC;
Richard Smitheec7cb12015-05-28 23:38:53 +00004178 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
John McCall3882ace2011-01-05 12:14:39 +00004179 return;
4180
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004181 if (!isa<ObjCMethodDecl>(D)) {
4182 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4183 << Attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00004184 return;
4185 }
4186
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004187 switch (Attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004188 case AttributeList::AT_FastCall:
Michael Han99315932013-01-24 16:46:58 +00004189 D->addAttr(::new (S.Context)
4190 FastCallAttr(Attr.getRange(), S.Context,
4191 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004192 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004193 case AttributeList::AT_StdCall:
Michael Han99315932013-01-24 16:46:58 +00004194 D->addAttr(::new (S.Context)
4195 StdCallAttr(Attr.getRange(), S.Context,
4196 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004197 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004198 case AttributeList::AT_ThisCall:
Michael Han99315932013-01-24 16:46:58 +00004199 D->addAttr(::new (S.Context)
4200 ThisCallAttr(Attr.getRange(), S.Context,
4201 Attr.getAttributeSpellingListIndex()));
Douglas Gregor4d13d102010-08-30 23:30:49 +00004202 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004203 case AttributeList::AT_CDecl:
Michael Han99315932013-01-24 16:46:58 +00004204 D->addAttr(::new (S.Context)
4205 CDeclAttr(Attr.getRange(), S.Context,
4206 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004207 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004208 case AttributeList::AT_Pascal:
Michael Han99315932013-01-24 16:46:58 +00004209 D->addAttr(::new (S.Context)
4210 PascalAttr(Attr.getRange(), S.Context,
4211 Attr.getAttributeSpellingListIndex()));
Dawn Perchik335e16b2010-09-03 01:29:35 +00004212 return;
John McCall477f2bb2016-03-03 06:39:32 +00004213 case AttributeList::AT_SwiftCall:
4214 D->addAttr(::new (S.Context)
4215 SwiftCallAttr(Attr.getRange(), S.Context,
4216 Attr.getAttributeSpellingListIndex()));
4217 return;
Reid Klecknerd7857f02014-10-24 17:42:17 +00004218 case AttributeList::AT_VectorCall:
4219 D->addAttr(::new (S.Context)
4220 VectorCallAttr(Attr.getRange(), S.Context,
4221 Attr.getAttributeSpellingListIndex()));
4222 return;
Charles Davisb5a214e2013-08-30 04:39:01 +00004223 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;
Erich Keane757d3172016-11-02 18:29:35 +00004233 case AttributeList::AT_RegCall:
4234 D->addAttr(::new (S.Context) RegCallAttr(
4235 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4236 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004237 case AttributeList::AT_Pcs: {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004238 PcsAttr::PCSType PCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004239 switch (CC) {
4240 case CC_AAPCS:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004241 PCS = PcsAttr::AAPCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004242 break;
4243 case CC_AAPCS_VFP:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004244 PCS = PcsAttr::AAPCS_VFP;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004245 break;
4246 default:
4247 llvm_unreachable("unexpected calling convention in pcs attribute");
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004248 }
4249
Michael Han99315932013-01-24 16:46:58 +00004250 D->addAttr(::new (S.Context)
4251 PcsAttr(Attr.getRange(), S.Context, PCS,
4252 Attr.getAttributeSpellingListIndex()));
Derek Schuffa2020962012-10-16 22:30:41 +00004253 return;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004254 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00004255 case AttributeList::AT_IntelOclBicc:
Michael Han99315932013-01-24 16:46:58 +00004256 D->addAttr(::new (S.Context)
4257 IntelOclBiccAttr(Attr.getRange(), S.Context,
4258 Attr.getAttributeSpellingListIndex()));
Guy Benyeif0a014b2012-12-25 08:53:55 +00004259 return;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00004260 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;
Abramo Bagnara50099372010-04-30 13:10:51 +00004268 default:
4269 llvm_unreachable("unexpected attribute kind");
Abramo Bagnara50099372010-04-30 13:10:51 +00004270 }
4271}
4272
Matthias Gehre01a63382017-03-27 19:45:24 +00004273static 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
Erich Keaneb11ebc52017-09-27 03:20:13 +00004293bool Sema::CheckCallingConvAttr(const AttributeList &Attrs, CallingConv &CC,
Aaron Ballman02df2e02012-12-09 17:45:41 +00004294 const FunctionDecl *FD) {
Erich Keaneb11ebc52017-09-27 03:20:13 +00004295 if (Attrs.isInvalid())
John McCall3882ace2011-01-05 12:14:39 +00004296 return true;
4297
Erich Keaneb11ebc52017-09-27 03:20:13 +00004298 if (Attrs.hasProcessingCache()) {
4299 CC = (CallingConv) Attrs.getProcessingCache();
John McCall3b5a8f52016-03-03 00:10:03 +00004300 return false;
4301 }
4302
Erich Keaneb11ebc52017-09-27 03:20:13 +00004303 unsigned ReqArgs = Attrs.getKind() == AttributeList::AT_Pcs ? 1 : 0;
4304 if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4305 Attrs.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004306 return true;
4307 }
4308
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004309 // TODO: diagnose uses of these conventions on the wrong target.
Erich Keaneb11ebc52017-09-27 03:20:13 +00004310 switch (Attrs.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004311 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;
John McCall477f2bb2016-03-03 06:39:32 +00004316 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +00004317 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
Erich Keane757d3172016-11-02 18:29:35 +00004318 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
Charles Davisb5a214e2013-08-30 04:39:01 +00004319 case AttributeList::AT_MSABI:
4320 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
Martin Storsjo022e7822017-07-17 20:49:45 +00004321 CC_Win64;
Charles Davisb5a214e2013-08-30 04:39:01 +00004322 break;
4323 case AttributeList::AT_SysVABI:
4324 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4325 CC_C;
4326 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004327 case AttributeList::AT_Pcs: {
Aaron Ballmand6600a52013-09-13 17:48:25 +00004328 StringRef StrRef;
Erich Keaneb11ebc52017-09-27 03:20:13 +00004329 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4330 Attrs.setInvalid();
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004331 return true;
4332 }
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004333 if (StrRef == "aapcs") {
4334 CC = CC_AAPCS;
4335 break;
4336 } else if (StrRef == "aapcs-vfp") {
4337 CC = CC_AAPCS_VFP;
4338 break;
4339 }
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00004340
Erich Keaneb11ebc52017-09-27 03:20:13 +00004341 Attrs.setInvalid();
4342 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00004343 return true;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004344 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00004345 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00004346 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4347 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
David Blaikie8a40f702012-01-17 06:56:22 +00004348 default: llvm_unreachable("unexpected attribute kind");
John McCall3882ace2011-01-05 12:14:39 +00004349 }
4350
Aaron Ballmane91c6be2012-10-02 14:26:08 +00004351 const TargetInfo &TI = Context.getTargetInfo();
4352 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
Reid Kleckner9fde2e02015-02-26 19:43:46 +00004353 if (A != TargetInfo::CCCR_OK) {
4354 if (A == TargetInfo::CCCR_Warning)
Erich Keaneb11ebc52017-09-27 03:20:13 +00004355 Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs.getName();
Aaron Ballman02df2e02012-12-09 17:45:41 +00004356
Reid Kleckner9fde2e02015-02-26 19:43:46 +00004357 // This convention is not valid for the target. Use the default function or
4358 // method calling convention.
Alexey Bataeva7547182016-05-18 09:06:38 +00004359 bool IsCXXMethod = false, IsVariadic = false;
4360 if (FD) {
4361 IsCXXMethod = FD->isCXXInstanceMember();
4362 IsVariadic = FD->isVariadic();
4363 }
4364 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
Aaron Ballmane91c6be2012-10-02 14:26:08 +00004365 }
4366
Erich Keaneb11ebc52017-09-27 03:20:13 +00004367 Attrs.setProcessingCache((unsigned) CC);
John McCall3882ace2011-01-05 12:14:39 +00004368 return false;
4369}
4370
John McCall477f2bb2016-03-03 06:39:32 +00004371/// Pointer-like types in the default address space.
4372static bool isValidSwiftContextType(QualType type) {
4373 if (!type->hasPointerRepresentation())
4374 return type->isDependentType();
Alexander Richardson6d989432017-10-15 18:48:14 +00004375 return type->getPointeeType().getAddressSpace() == LangAS::Default;
John McCall477f2bb2016-03-03 06:39:32 +00004376}
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 }
Alexander Richardson6d989432017-10-15 18:48:14 +00004387 return type.getAddressSpace() == LangAS::Default;
John McCall477f2bb2016-03-03 06:39:32 +00004388}
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
Erich Keaneb11ebc52017-09-27 03:20:13 +00004404static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &Attrs,
4405 ParameterABI Abi) {
4406 S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
4407 Attrs.getAttributeSpellingListIndex());
John McCall477f2bb2016-03-03 06:39:32 +00004408}
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?");
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");
4459}
4460
John McCall3882ace2011-01-05 12:14:39 +00004461/// Checks a regparm attribute, returning true if it is ill-formed and
4462/// otherwise setting numParams to the appropriate value.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004463bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4464 if (Attr.isInvalid())
John McCall3882ace2011-01-05 12:14:39 +00004465 return true;
4466
Aaron Ballmanc2cbc662013-07-18 18:01:48 +00004467 if (!checkAttributeNumArgs(*this, Attr, 1)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004468 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004469 return true;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004470 }
Eli Friedman7044b762009-03-27 21:06:47 +00004471
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004472 uint32_t NP;
Aaron Ballman00e99962013-08-31 01:11:41 +00004473 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004474 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004475 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004476 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004477 }
4478
Douglas Gregore8bbc122011-09-02 00:18:52 +00004479 if (Context.getTargetInfo().getRegParmMax() == 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004480 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
Eli Friedman7044b762009-03-27 21:06:47 +00004481 << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004482 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004483 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004484 }
4485
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004486 numParams = NP;
Douglas Gregore8bbc122011-09-02 00:18:52 +00004487 if (numParams > Context.getTargetInfo().getRegParmMax()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004488 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
Douglas Gregore8bbc122011-09-02 00:18:52 +00004489 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004490 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004491 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004492 }
4493
John McCall3882ace2011-01-05 12:14:39 +00004494 return false;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004495}
4496
Artem Belevichbcec9da2016-06-06 22:54:57 +00004497// 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) {
Artem Belevich7093e402015-04-21 22:55:54 +00004504 if (S.DiagnoseUnexpandedParameterPack(E))
Artem Belevichbcec9da2016-06-06 22:54:57 +00004505 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004506
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())
Artem Belevichbcec9da2016-06-06 22:54:57 +00004510 return E;
Artem Belevich7093e402015-04-21 22:55:54 +00004511
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();
Artem Belevichbcec9da2016-06-06 22:54:57 +00004516 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004517 }
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;
Artem Belevichbcec9da2016-06-06 22:54:57 +00004522 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004523 }
4524 if (I < 0)
4525 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4526 << &Attr << Idx << E->getSourceRange();
4527
Artem Belevichbcec9da2016-06-06 22:54:57 +00004528 // 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() &&
4533 "Unexpected PerformCopyInitialization() failure.");
4534
4535 return ValArg.getAs<Expr>();
Artem Belevich7093e402015-04-21 22:55:54 +00004536}
4537
4538void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4539 Expr *MinBlocks, unsigned SpellingListIndex) {
4540 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4541 SpellingListIndex);
Artem Belevichbcec9da2016-06-06 22:54:57 +00004542 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4543 if (MaxThreads == nullptr)
Aaron Ballman3aff6332013-12-02 19:30:36 +00004544 return;
4545
Artem Belevichbcec9da2016-06-06 22:54:57 +00004546 if (MinBlocks) {
4547 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4548 if (MinBlocks == nullptr)
4549 return;
4550 }
Artem Belevich7093e402015-04-21 22:55:54 +00004551
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());
Peter Collingbourne827301e2010-12-12 23:03:07 +00004565}
4566
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004567static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4568 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004569 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004570 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004571 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004572 return;
4573 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004574
4575 if (!checkAttributeNumArgs(S, Attr, 3))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004576 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004577
Aaron Ballman00e99962013-08-31 01:11:41 +00004578 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004579
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;
Alp Toker601b22c2014-01-21 23:35:24 +00004587 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4588 ArgumentIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004589 return;
4590
4591 uint64_t TypeTagIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004592 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4593 TypeTagIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004594 return;
4595
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00004596 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004597 if (IsPointer) {
4598 // Ensure that buffer has a pointer type.
Alp Toker601b22c2014-01-21 23:35:24 +00004599 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004600 if (!BufferTy->isPointerType()) {
4601 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004602 << Attr.getName() << 0;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004603 }
4604 }
4605
Michael Han99315932013-01-24 16:46:58 +00004606 D->addAttr(::new (S.Context)
4607 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4608 ArgumentIdx, TypeTagIdx, IsPointer,
4609 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004610}
4611
4612static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4613 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004614 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004615 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004616 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004617 return;
4618 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004619
4620 if (!checkAttributeNumArgs(S, Attr, 1))
4621 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004622
Aaron Ballman90f8c6f2013-11-25 18:50:49 +00004623 if (!isa<VarDecl>(D)) {
4624 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4625 << Attr.getName() << ExpectedVariable;
4626 return;
4627 }
4628
Aaron Ballman00e99962013-08-31 01:11:41 +00004629 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
Craig Topperc3ec1492014-05-26 06:22:03 +00004630 TypeSourceInfo *MatchingCTypeLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00004631 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4632 assert(MatchingCTypeLoc && "no type source info for attribute argument");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004633
Michael Han99315932013-01-24 16:46:58 +00004634 D->addAttr(::new (S.Context)
4635 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
Richard Smithb87c4652013-10-31 21:23:20 +00004636 MatchingCTypeLoc,
Michael Han99315932013-01-24 16:46:58 +00004637 Attr.getLayoutCompatible(),
4638 Attr.getMustBeNull(),
4639 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004640}
4641
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004642static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4643 const AttributeList &Attr) {
4644 uint64_t ArgCount;
Dean Michael Berris7456a282017-06-16 03:22:09 +00004645
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004646 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
Dean Michael Berris7456a282017-06-16 03:22:09 +00004647 ArgCount,
4648 true /* AllowImplicitThis*/))
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004649 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)
Dean Michael Berris7456a282017-06-16 03:22:09 +00004653 XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4654 Attr.getAttributeSpellingListIndex()));
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004655}
4656
Chris Lattner9e2aafe2008-06-29 00:23:49 +00004657//===----------------------------------------------------------------------===//
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004658// Checker-specific attribute handlers.
4659//===----------------------------------------------------------------------===//
4660
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004661static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004662 return type->isDependentType() ||
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004663 type->isObjCRetainableType();
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004664}
4665
John McCalled433932011-01-25 03:31:58 +00004666static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004667 return type->isDependentType() ||
4668 type->isObjCObjectPointerType() ||
4669 S.Context.isObjCNSObjectType(type);
John McCalled433932011-01-25 03:31:58 +00004670}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004671
John McCalled433932011-01-25 03:31:58 +00004672static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004673 return type->isDependentType() ||
4674 type->isPointerType() ||
4675 isValidSubjectOfNSAttribute(S, type);
John McCalled433932011-01-25 03:31:58 +00004676}
4677
Chandler Carruthedc2c642011-07-02 00:01:44 +00004678static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John McCall3b5a8f52016-03-03 00:10:03 +00004679 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4680 Attr.getKind() == AttributeList::AT_NSConsumed,
4681 /*template instantiation*/ false);
4682}
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004683
John McCall3b5a8f52016-03-03 00:10:03 +00004684void 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());
John McCalled433932011-01-25 03:31:58 +00004692 } else {
John McCall3b5a8f52016-03-03 00:10:03 +00004693 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004694 }
4695
4696 if (!typeOK) {
John McCall3b5a8f52016-03-03 00:10:03 +00004697 // 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);
John McCalled433932011-01-25 03:31:58 +00004709 return;
4710 }
4711
John McCall3b5a8f52016-03-03 00:10:03 +00004712 if (isNSConsumed)
4713 param->addAttr(::new (Context)
4714 NSConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004715 else
John McCall3b5a8f52016-03-03 00:10:03 +00004716 param->addAttr(::new (Context)
4717 CFConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004718}
4719
John McCall12251882017-07-15 11:06:46 +00004720bool 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
Chandler Carruthedc2c642011-07-02 00:01:44 +00004730static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4731 const AttributeList &Attr) {
John McCalled433932011-01-25 03:31:58 +00004732 QualType returnType;
Mike Stumpd3bb5572009-07-24 19:02:52 +00004733
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004734 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004735 returnType = MD->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004736 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004737 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
John McCall31168b02011-06-15 23:02:42 +00004738 return; // ignore: was handled as a type attribute
Fariborz Jahanian272b7dc2012-08-28 22:26:21 +00004739 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4740 returnType = PD->getType();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004741 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004742 returnType = FD->getReturnType();
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004743 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 }
John McCall12251882017-07-15 11:06:46 +00004751 } else if (Attr.isUsedAsTypeAttr()) {
4752 return;
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004753 } else {
4754 AttributeDeclKind ExpectedDeclKind;
4755 switch (Attr.getKind()) {
4756 default: llvm_unreachable("invalid ownership attribute");
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 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004768 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004769 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004770 return;
4771 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004772
John McCalled433932011-01-25 03:31:58 +00004773 bool typeOK;
4774 bool cf;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004775 switch (Attr.getKind()) {
David Blaikie8a40f702012-01-17 06:56:22 +00004776 default: llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004777 case AttributeList::AT_NSReturnsRetained:
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004778 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004779 cf = false;
4780 break;
4781
4782 case AttributeList::AT_NSReturnsAutoreleased:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004783 case AttributeList::AT_NSReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004784 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4785 cf = false;
4786 break;
4787
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004788 case AttributeList::AT_CFReturnsRetained:
4789 case AttributeList::AT_CFReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004790 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4791 cf = true;
4792 break;
4793 }
4794
4795 if (!typeOK) {
John McCall12251882017-07-15 11:06:46 +00004796 if (Attr.isUsedAsTypeAttr())
4797 return;
4798
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004799 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 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004818 return;
Ted Kremenek3b204e42009-05-13 21:07:32 +00004819 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004820
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004821 switch (Attr.getKind()) {
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004822 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004823 llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004824 case AttributeList::AT_NSReturnsAutoreleased:
Nico Weber462fd1e2015-01-07 23:50:05 +00004825 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4826 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
John McCalled433932011-01-25 03:31:58 +00004827 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004828 case AttributeList::AT_CFReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004829 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4830 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004831 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004832 case AttributeList::AT_NSReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004833 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4834 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004835 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004836 case AttributeList::AT_CFReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004837 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4838 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004839 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004840 case AttributeList::AT_NSReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004841 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4842 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004843 return;
4844 };
4845}
4846
John McCallcf166702011-07-22 08:53:00 +00004847static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
Erich Keaneb11ebc52017-09-27 03:20:13 +00004848 const AttributeList &Attrs) {
Fariborz Jahanian8bf05562013-09-19 17:52:50 +00004849 const int EP_ObjCMethod = 1;
4850 const int EP_ObjCProperty = 2;
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004851
Erich Keaneb11ebc52017-09-27 03:20:13 +00004852 SourceLocation loc = Attrs.getLoc();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004853 QualType resultType;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004854 if (isa<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004855 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004856 else
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004857 resultType = cast<ObjCPropertyDecl>(D)->getType();
John McCallcf166702011-07-22 08:53:00 +00004858
Fariborz Jahanian044a5be2011-09-30 20:50:23 +00004859 if (!resultType->isReferenceType() &&
4860 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004861 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
John McCallcf166702011-07-22 08:53:00 +00004862 << SourceRange(loc)
Erich Keaneb11ebc52017-09-27 03:20:13 +00004863 << Attrs.getName()
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004864 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004865 << /*non-retainable pointer*/ 2;
John McCallcf166702011-07-22 08:53:00 +00004866
4867 // Drop the attribute.
4868 return;
4869 }
4870
Nico Weber462fd1e2015-01-07 23:50:05 +00004871 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
Erich Keaneb11ebc52017-09-27 03:20:13 +00004872 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
John McCallcf166702011-07-22 08:53:00 +00004873}
4874
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004875static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
Erich Keaneb11ebc52017-09-27 03:20:13 +00004876 const AttributeList &Attrs) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004877 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004878
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004879 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)
Erich Keaneb11ebc52017-09-27 03:20:13 +00004882 << Attrs.getName() << 0;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004883 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)
Erich Keaneb11ebc52017-09-27 03:20:13 +00004888 << Attrs.getName() << 1;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004889 return;
4890 }
4891
Michael Han99315932013-01-24 16:46:58 +00004892 method->addAttr(::new (S.Context)
Erich Keaneb11ebc52017-09-27 03:20:13 +00004893 ObjCRequiresSuperAttr(Attrs.getRange(), S.Context,
4894 Attrs.getAttributeSpellingListIndex()));
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004895}
4896
Aaron Ballmanfb763042013-12-02 18:05:46 +00004897static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4898 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004899 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4900 Attr.getName()))
John McCall32f5fe12011-09-30 05:12:12 +00004901 return;
John McCall32f5fe12011-09-30 05:12:12 +00004902
Aaron Ballmanfb763042013-12-02 18:05:46 +00004903 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) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004910 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4911 Attr.getName()))
Aaron Ballmanfb763042013-12-02 18:05:46 +00004912 return;
4913
4914 D->addAttr(::new (S.Context)
4915 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4916 Attr.getAttributeSpellingListIndex()));
John McCall32f5fe12011-09-30 05:12:12 +00004917}
4918
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004919static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4920 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004921 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004922
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004923 if (!Parm) {
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004924 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004925 return;
4926 }
John McCall28592582015-02-01 22:34:06 +00004927
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 }
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004943
4944 D->addAttr(::new (S.Context)
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004945 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004946 Attr.getAttributeSpellingListIndex()));
4947}
4948
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004949static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4950 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004951 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4952
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004953 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
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004963static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4964 const AttributeList &Attr) {
4965 IdentifierInfo *RelatedClass =
Craig Topperc3ec1492014-05-26 06:22:03 +00004966 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004967 if (!RelatedClass) {
4968 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4969 return;
4970 }
4971 IdentifierInfo *ClassMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004972 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004973 IdentifierInfo *InstanceMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004974 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004975 D->addAttr(::new (S.Context)
4976 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4977 ClassMethod, InstanceMethod,
4978 Attr.getAttributeSpellingListIndex()));
4979}
4980
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004981static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4982 const AttributeList &Attr) {
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004983 ObjCInterfaceDecl *IFace;
Nico Weber462fd1e2015-01-07 23:50:05 +00004984 if (ObjCCategoryDecl *CatDecl =
4985 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004986 IFace = CatDecl->getClassInterface();
4987 else
4988 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00004989
4990 if (!IFace)
4991 return;
4992
Argyrios Kyrtzidis9ed9e5f2013-12-03 21:11:30 +00004993 IFace->setHasDesignatedInitializers();
Argyrios Kyrtzidise8186812013-12-07 06:08:04 +00004994 D->addAttr(::new (S.Context)
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004995 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4996 Attr.getAttributeSpellingListIndex()));
4997}
4998
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004999static void handleObjCRuntimeName(Sema &S, Decl *D,
5000 const AttributeList &Attr) {
Fariborz Jahaniana2e5deb2014-07-16 19:44:34 +00005001 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()));
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005008}
5009
Nico Webera6916892016-06-10 18:53:04 +00005010// 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:
Alex Denisovfde64952015-06-26 05:28:36 +00005013// 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
Chandler Carruthedc2c642011-07-02 00:01:44 +00005037static void handleObjCOwnershipAttr(Sema &S, Decl *D,
5038 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005039 if (hasDeclarator(D)) return;
John McCall31168b02011-06-15 23:02:42 +00005040
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005041 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
Douglas Gregor5c3cc422012-03-14 16:55:17 +00005042 << Attr.getRange() << Attr.getName() << ExpectedVariable;
John McCall31168b02011-06-15 23:02:42 +00005043}
5044
Chandler Carruthedc2c642011-07-02 00:01:44 +00005045static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5046 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005047 ValueDecl *vd = cast<ValueDecl>(D);
John McCall31168b02011-06-15 23:02:42 +00005048 QualType type = vd->getType();
5049
5050 if (!type->isDependentType() &&
5051 !type->isObjCLifetimeType()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005052 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
John McCall31168b02011-06-15 23:02:42 +00005053 << 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() &&
5067 "didn't infer lifetime for non-dependent type?");
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:
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005076 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
John McCall31168b02011-06-15 23:02:42 +00005077 << (lifetime == Qualifiers::OCL_Autoreleasing);
5078 break;
5079 }
5080
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005081 D->addAttr(::new (S.Context)
Michael Han99315932013-01-24 16:46:58 +00005082 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
5083 Attr.getAttributeSpellingListIndex()));
John McCall31168b02011-06-15 23:02:42 +00005084}
5085
Francois Picheta83957a2010-12-19 06:50:37 +00005086//===----------------------------------------------------------------------===//
5087// Microsoft specific attribute handlers.
5088//===----------------------------------------------------------------------===//
5089
Nico Weber88f5ed92016-09-13 18:55:26 +00005090UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
5091 unsigned AttrSpellingListIndex, StringRef Uuid) {
5092 if (const auto *UA = D->getAttr<UuidAttr>()) {
Nico Weberd58c2602016-09-14 01:16:54 +00005093 if (UA->getGuid().equals_lower(Uuid))
Nico Weber88f5ed92016-09-13 18:55:26 +00005094 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
Chandler Carruthedc2c642011-07-02 00:01:44 +00005103static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +00005104 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
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005110 StringRef StrRef;
5111 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00005112 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
Reid Kleckner140c4a72013-05-17 14:04:52 +00005113 return;
Francois Pichet7da11662010-12-20 01:41:49 +00005114
David Majnemer89085342013-08-09 08:56:20 +00005115 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5116 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
David Majnemer89085342013-08-09 08:56:20 +00005117 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5118 StrRef = StrRef.drop_front().drop_back();
Francois Pichet7da11662010-12-20 01:41:49 +00005119
Reid Kleckner140c4a72013-05-17 14:04:52 +00005120 // Validate GUID length.
David Majnemer89085342013-08-09 08:56:20 +00005121 if (StrRef.size() != 36) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005122 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00005123 return;
5124 }
Anders Carlsson19588aa2011-01-23 21:07:30 +00005125
David Majnemer89085342013-08-09 08:56:20 +00005126 for (unsigned i = 0; i < 36; ++i) {
Reid Kleckner140c4a72013-05-17 14:04:52 +00005127 if (i == 8 || i == 13 || i == 18 || i == 23) {
David Majnemer89085342013-08-09 08:56:20 +00005128 if (StrRef[i] != '-') {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005129 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Francois Pichet7da11662010-12-20 01:41:49 +00005130 return;
5131 }
David Majnemer89085342013-08-09 08:56:20 +00005132 } else if (!isHexDigit(StrRef[i])) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005133 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00005134 return;
Francois Pichet7da11662010-12-20 01:41:49 +00005135 }
Reid Kleckner140c4a72013-05-17 14:04:52 +00005136 }
Francois Picheta83957a2010-12-19 06:50:37 +00005137
Nico Weber469891e2017-05-05 17:05:56 +00005138 // 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.
Nico Weber0a234042017-05-05 17:15:08 +00005142 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
Nico Weber469891e2017-05-05 17:05:56 +00005143 // on cfe-dev.
5144 if (Attr.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5145 S.Diag(Attr.getLoc(), diag::warn_atl_uuid_deprecated);
5146
Nico Weber88f5ed92016-09-13 18:55:26 +00005147 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
5148 Attr.getAttributeSpellingListIndex(), StrRef);
5149 if (UA)
5150 D->addAttr(UA);
Charles Davis163855f2010-02-16 18:27:26 +00005151}
5152
David Majnemer2c4e00a2014-01-29 22:07:36 +00005153static 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(
David Majnemer4bb09802014-02-10 19:50:15 +00005160 D, Attr.getRange(), /*BestCase=*/true,
5161 Attr.getAttributeSpellingListIndex(),
David Majnemer2c4e00a2014-01-29 22:07:36 +00005162 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
David Majnemer929025d2016-01-26 19:30:26 +00005163 if (IA) {
David Majnemer2c4e00a2014-01-29 22:07:36 +00005164 D->addAttr(IA);
David Majnemer929025d2016-01-26 19:30:26 +00005165 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5166 }
David Majnemer2c4e00a2014-01-29 22:07:36 +00005167}
5168
Reid Kleckner7d6d2702014-05-01 03:16:47 +00005169static 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
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005188static 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()));
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005218}
5219
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005220static 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
Aaron Ballman36a53502014-01-16 13:03:14 +00005279 D->addAttr(::new (S.Context)
5280 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5281 Attr.getAttributeSpellingListIndex()));
5282 D->addAttr(UsedAttr::CreateImplicit(S.Context));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005283}
5284
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005285static 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
Alexey Bataevd51e9932016-01-15 04:06:31 +00005344static 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
Dylan McKaye8232d72017-02-08 05:09:26 +00005410static 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
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005436static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5437 // Dispatch the interrupt attribute based on the current target.
Alexey Bataevd51e9932016-01-15 04:06:31 +00005438 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5439 case llvm::Triple::msp430:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005440 handleMSP430InterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005441 break;
5442 case llvm::Triple::mipsel:
5443 case llvm::Triple::mips:
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005444 handleMipsInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005445 break;
5446 case llvm::Triple::x86:
5447 case llvm::Triple::x86_64:
5448 handleAnyX86InterruptAttr(S, D, Attr);
5449 break;
Dylan McKaye8232d72017-02-08 05:09:26 +00005450 case llvm::Triple::avr:
5451 handleAVRInterruptAttr(S, D, Attr);
5452 break;
Alexey Bataevd51e9932016-01-15 04:06:31 +00005453 default:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005454 handleARMInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005455 break;
5456 }
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005457}
5458
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005459static 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))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005464 return;
5465
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005466 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
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005482 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005483 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()));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005515}
5516
5517static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5518 const AttributeList &Attr) {
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005519 uint32_t NumSGPR = 0;
5520 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5521 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005522 return;
5523
5524 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005525 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,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005538 Attr.getAttributeSpellingListIndex()));
5539}
5540
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005541static 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)
Hongbin Zheng702ffea2018-01-19 03:07:00 +00005557 << Attr.getName() << ExpectedFunction;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005558 return;
5559 }
5560
Aaron Ballman36a53502014-01-16 13:03:14 +00005561 D->addAttr(::new (S.Context)
5562 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5563 Attr.getAttributeSpellingListIndex()));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005564}
5565
David Majnemercd3ebfe2016-05-23 17:16:12 +00005566static 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
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005584DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5585 unsigned AttrSpellingListIndex) {
5586 if (D->hasAttr<DLLExportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005587 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
Craig Topperc3ec1492014-05-26 06:22:03 +00005588 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005589 }
5590
5591 if (D->hasAttr<DLLImportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005592 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005593
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005594 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005595}
5596
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005597DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5598 unsigned AttrSpellingListIndex) {
5599 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005600 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005601 D->dropAttr<DLLImportAttr>();
5602 }
5603
5604 if (D->hasAttr<DLLExportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005605 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005606
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005607 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005608}
5609
Hans Wennborge82f19c2014-06-24 23:57:05 +00005610static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
Hans Wennborg5e645282014-06-24 23:57:13 +00005611 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
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005618 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
Hans Wennborg5869ec42015-09-15 21:05:30 +00005628 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
Hans Wennborge82f19c2014-06-24 23:57:05 +00005636 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);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005640 if (NewAttr)
5641 D->addAttr(NewAttr);
5642}
5643
David Majnemer2c4e00a2014-01-29 22:07:36 +00005644MSInheritanceAttr *
David Majnemer4bb09802014-02-10 19:50:15 +00005645Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00005646 unsigned AttrSpellingListIndex,
5647 MSInheritanceAttr::Spelling SemanticSpelling) {
5648 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5649 if (IA->getSemanticSpelling() == SemanticSpelling)
Craig Topperc3ec1492014-05-26 06:22:03 +00005650 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005651 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()) {
David Majnemer4bb09802014-02-10 19:50:15 +00005659 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5660 SemanticSpelling)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005661 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005662 }
5663 } else {
5664 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5665 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5666 << 1 /*partial specialization*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005667 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005668 }
5669 if (RD->getDescribedClassTemplate()) {
5670 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5671 << 0 /*primary template*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005672 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005673 }
5674 }
5675
5676 return ::new (Context)
David Majnemer4bb09802014-02-10 19:50:15 +00005677 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
David Majnemer2c4e00a2014-01-29 22:07:36 +00005678}
5679
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005680static 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.
Aaron Ballman6c810072014-03-05 21:47:13 +00005686 //
Alp Toker958027b2014-07-14 19:42:55 +00005687 // For backward compatibility, any capability which has no specified string
Aaron Ballman6c810072014-03-05 21:47:13 +00005688 // literal will be considered a "mutex."
5689 StringRef N("mutex");
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005690 SourceLocation LiteralLoc;
5691 if (Attr.getKind() == AttributeList::AT_Capability &&
5692 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5693 return;
5694
Aaron Ballman6c810072014-03-05 21:47:13 +00005695 // 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
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005700 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5701 Attr.getAttributeSpellingListIndex()));
5702}
5703
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005704static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5705 const AttributeList &Attr) {
Josh Gaoec1369e2017-08-08 19:44:34 +00005706 SmallVector<Expr*, 1> Args;
5707 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5708 return;
5709
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005710 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
Josh Gaoec1369e2017-08-08 19:44:34 +00005711 Args.data(), Args.size(),
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005712 Attr.getAttributeSpellingListIndex()));
5713}
5714
5715static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5716 const AttributeList &Attr) {
5717 SmallVector<Expr*, 1> Args;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005718 if (!checkLockFunAttrCommon(S, D, Attr, Args))
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005719 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) {
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005743 // Check that all arguments are lockable objects.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005744 SmallVector<Expr *, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005745 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005746
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005747 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5748 Attr.getRange(), S.Context, Args.data(), Args.size(),
5749 Attr.getAttributeSpellingListIndex()));
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005750}
5751
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005752static 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;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005759 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005760 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
Aaron Ballman43f40102014-11-14 22:34:56 +00005770static 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 }
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005780
Manman Renc7890fe2016-03-16 18:50:49 +00005781 // 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
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005794 if (!S.getLangOpts().CPlusPlus14)
5795 if (Attr.isCXX11Attribute() &&
5796 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
Richard Smith4f902c72016-03-08 00:32:55 +00005797 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005798
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005799 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;
Aaron Ballman43f40102014-11-14 22:34:56 +00005808}
5809
Peter Collingbourne915df992015-05-15 18:33:32 +00005810static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5811 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5812 return;
5813
Benjamin Kramer1b582012016-02-13 18:11:49 +00005814 std::vector<StringRef> Sanitizers;
Peter Collingbourne915df992015-05-15 18:33:32 +00005815
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;
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005825 else if (isGlobalVar(D) && SanitizerName != "address")
5826 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5827 << Attr.getName() << ExpectedFunctionOrMethod;
Peter Collingbourne915df992015-05-15 18:33:32 +00005828 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) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00005838 StringRef AttrName = Attr.getName()->getName();
5839 normalizeName(AttrName);
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005840 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;
Peter Collingbourne915df992015-05-15 18:33:32 +00005848 D->addAttr(::new (S.Context)
5849 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5850 Attr.getAttributeSpellingListIndex()));
5851}
5852
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00005853static 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
Anastasia Stulovac4bb5df2016-03-31 11:07:22 +00005861static 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
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005870/// 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
Alex Lorenz24952fb2017-04-19 15:52:11 +00005876 // those are opted out of the common argument checks.
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005877 //
5878 // We also bail on unknown and ignored attributes because those are handled
5879 // as part of the target-specific handling logic.
Alex Lorenz24952fb2017-04-19 15:52:11 +00005880 if (Attr.getKind() == AttributeList::UnknownAttribute)
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005881 return false;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005882 // Check whether the attribute requires specific language extensions to be
5883 // enabled.
5884 if (!Attr.diagnoseLangOpts(S))
5885 return true;
Alex Lorenz24952fb2017-04-19 15:52:11 +00005886 // 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;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005891
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00005892 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 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00005906
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005907 return false;
5908}
5909
Xiuli Pan11e13f62016-02-26 03:13:03 +00005910static 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
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00005944//===----------------------------------------------------------------------===//
Chris Lattner9e2aafe2008-06-29 00:23:49 +00005945// Top Level Sema Entry Points
5946//===----------------------------------------------------------------------===//
5947
Richard Smithf8a75c32013-08-29 00:47:48 +00005948/// 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) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005954 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
Richard Smithf8a75c32013-08-29 00:47:48 +00005955 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00005956
Richard Smithf8a75c32013-08-29 00:47:48 +00005957 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5958 // instead.
5959 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5960 return;
5961
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005962 // 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 ||
Bob Wilson7c730832015-07-20 22:57:31 +00005966 !Attr.existsInTarget(S.Context.getTargetInfo())) {
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005967 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5968 ? diag::warn_unhandled_ms_attribute_ignored
5969 : diag::warn_unknown_attribute_ignored)
5970 << Attr.getName();
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005971 return;
5972 }
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005973
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005974 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5975 return;
5976
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005977 switch (Attr.getKind()) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005978 default:
Richard Smith4f902c72016-03-08 00:32:55 +00005979 if (!Attr.isStmtAttr()) {
5980 // Type attributes are handled elsewhere; silently move on.
5981 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5982 break;
5983 }
5984 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5985 << Attr.getName() << D->getLocation();
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005986 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005987 case AttributeList::AT_Interrupt:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005988 handleInterruptAttr(S, D, Attr);
5989 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005990 case AttributeList::AT_X86ForceAlignArgPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005991 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5992 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005993 case AttributeList::AT_DLLExport:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005994 case AttributeList::AT_DLLImport:
Hans Wennborge82f19c2014-06-24 23:57:05 +00005995 handleDLLAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005996 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005997 case AttributeList::AT_Mips16:
Simon Atanasyan2c87f532017-05-22 12:47:43 +00005998 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
5999 MipsInterruptAttr>(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006000 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006001 case AttributeList::AT_NoMips16:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006002 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
6003 break;
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006004 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;
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006010 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;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006018 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
6019 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
6020 break;
6021 case AttributeList::AT_AMDGPUWavesPerEU:
6022 handleAMDGPUWavesPerEUAttr(S, D, Attr);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006023 break;
6024 case AttributeList::AT_AMDGPUNumSGPR:
6025 handleAMDGPUNumSGPRAttr(S, D, Attr);
6026 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006027 case AttributeList::AT_AMDGPUNumVGPR:
6028 handleAMDGPUNumVGPRAttr(S, D, Attr);
6029 break;
Dylan McKaye8232d72017-02-08 05:09:26 +00006030 case AttributeList::AT_AVRSignal:
6031 handleAVRSignalAttr(S, D, Attr);
6032 break;
Aaron Ballman9beb5172013-12-02 15:13:14 +00006033 case AttributeList::AT_IBAction:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006034 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
6035 break;
6036 case AttributeList::AT_IBOutlet:
6037 handleIBOutlet(S, D, Attr);
6038 break;
Richard Smith10876ef2013-01-17 01:30:42 +00006039 case AttributeList::AT_IBOutletCollection:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006040 handleIBOutletCollection(S, D, Attr);
6041 break;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00006042 case AttributeList::AT_IFunc:
6043 handleIFuncAttr(S, D, Attr);
6044 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006045 case AttributeList::AT_Alias:
6046 handleAliasAttr(S, D, Attr);
6047 break;
6048 case AttributeList::AT_Aligned:
6049 handleAlignedAttr(S, D, Attr);
6050 break;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00006051 case AttributeList::AT_AlignValue:
6052 handleAlignValueAttr(S, D, Attr);
6053 break;
George Burgess IVe3763372016-12-22 02:50:20 +00006054 case AttributeList::AT_AllocSize:
6055 handleAllocSizeAttr(S, D, Attr);
6056 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006057 case AttributeList::AT_AlwaysInline:
Paul Robinsonf0674352014-03-31 22:29:15 +00006058 handleAlwaysInlineAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006059 break;
Erich Keane293a0552018-02-14 00:14:07 +00006060 case AttributeList::AT_Artificial:
6061 handleSimpleAttribute<ArtificialAttr>(S, D, Attr);
6062 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006063 case AttributeList::AT_AnalyzerNoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006064 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;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006075 case AttributeList::AT_CarriesDependency:
Richard Smithe233fbf2013-01-28 22:42:45 +00006076 handleDependencyAttr(S, scope, D, Attr);
6077 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006078 case AttributeList::AT_Common:
6079 handleCommonAttr(S, D, Attr);
6080 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006081 case AttributeList::AT_CUDAConstant:
Justin Lebare71b2fa2016-09-30 23:57:34 +00006082 handleConstantAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006083 break;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006084 case AttributeList::AT_PassObjectSize:
6085 handlePassObjectSizeAttr(S, D, Attr);
6086 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006087 case AttributeList::AT_Constructor:
6088 handleConstructorAttr(S, D, Attr);
6089 break;
Richard Smith10876ef2013-01-17 01:30:42 +00006090 case AttributeList::AT_CXX11NoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006091 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
6092 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006093 case AttributeList::AT_Deprecated:
Aaron Ballman43f40102014-11-14 22:34:56 +00006094 handleDeprecatedAttr(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00006095 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006096 case AttributeList::AT_Destructor:
6097 handleDestructorAttr(S, D, Attr);
6098 break;
6099 case AttributeList::AT_EnableIf:
6100 handleEnableIfAttr(S, D, Attr);
6101 break;
George Burgess IV177399e2017-01-09 04:12:14 +00006102 case AttributeList::AT_DiagnoseIf:
6103 handleDiagnoseIfAttr(S, D, Attr);
6104 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006105 case AttributeList::AT_ExtVectorType:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006106 handleExtVectorTypeAttr(S, scope, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006107 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +00006108 case AttributeList::AT_ExternalSourceSymbol:
6109 handleExternalSourceSymbolAttr(S, D, Attr);
6110 break;
Quentin Colombet4e172062012-11-01 23:55:47 +00006111 case AttributeList::AT_MinSize:
Paul Robinsonaae2fba2014-12-10 23:34:36 +00006112 handleMinSizeAttr(S, D, Attr);
Quentin Colombet4e172062012-11-01 23:55:47 +00006113 break;
Paul Robinsonf0674352014-03-31 22:29:15 +00006114 case AttributeList::AT_OptimizeNone:
6115 handleOptimizeNoneAttr(S, D, Attr);
6116 break;
Alexis Hunt724f14e2014-11-28 00:53:20 +00006117 case AttributeList::AT_FlagEnum:
6118 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
6119 break;
Akira Hatanaka3c268af2017-03-21 02:23:00 +00006120 case AttributeList::AT_EnumExtensibility:
6121 handleEnumExtensibilityAttr(S, D, Attr);
6122 break;
Peter Collingbourne41af7c22014-05-20 17:12:51 +00006123 case AttributeList::AT_Flatten:
6124 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
6125 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006126 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;
Aaron Ballmanf79ee272013-12-02 21:09:08 +00006135 case AttributeList::AT_CUDADevice:
Justin Lebar3eaaf862016-01-13 01:07:35 +00006136 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6137 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006138 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006139 case AttributeList::AT_CUDAHost:
Justin Lebar3eaaf862016-01-13 01:07:35 +00006140 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
6141 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006142 break;
6143 case AttributeList::AT_GNUInline:
6144 handleGNUInlineAttr(S, D, Attr);
6145 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006146 case AttributeList::AT_CUDALaunchBounds:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006147 handleLaunchBoundsAttr(S, D, Attr);
Peter Collingbourne827301e2010-12-12 23:03:07 +00006148 break;
David Majnemer631a90b2015-02-04 07:23:21 +00006149 case AttributeList::AT_Restrict:
6150 handleRestrictAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006151 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006152 case AttributeList::AT_MayAlias:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006153 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
6154 break;
6155 case AttributeList::AT_Mode:
6156 handleModeAttr(S, D, Attr);
6157 break;
David Majnemer1bf0f8e2015-07-20 22:51:52 +00006158 case AttributeList::AT_NoAlias:
6159 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
6160 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006161 case AttributeList::AT_NoCommon:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006162 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
6163 break;
Peter Collingbourneb4728c12014-05-19 22:14:34 +00006164 case AttributeList::AT_NoSplitStack:
6165 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
6166 break;
Ted Kremenek9aedc152014-01-17 06:24:56 +00006167 case AttributeList::AT_NonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006168 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
6169 handleNonNullAttrParameter(S, PVD, Attr);
6170 else
6171 handleNonNullAttr(S, D, Attr);
6172 break;
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00006173 case AttributeList::AT_ReturnsNonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006174 handleReturnsNonNullAttr(S, D, Attr);
6175 break;
Akira Hatanaka98a49332017-09-22 00:41:05 +00006176 case AttributeList::AT_NoEscape:
6177 handleNoEscapeAttr(S, D, Attr);
6178 break;
Hal Finkelee90a222014-09-26 05:04:30 +00006179 case AttributeList::AT_AssumeAligned:
6180 handleAssumeAlignedAttr(S, D, Attr);
6181 break;
Erich Keane623efd82017-03-30 21:48:55 +00006182 case AttributeList::AT_AllocAlign:
6183 handleAllocAlignAttr(S, D, Attr);
6184 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006185 case AttributeList::AT_Overloadable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006186 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;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006197 case AttributeList::AT_Naked:
Charles Davis0e379112016-08-08 21:19:08 +00006198 handleNakedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006199 break;
6200 case AttributeList::AT_NoReturn:
6201 handleNoReturnAttr(S, D, Attr);
6202 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00006203 case AttributeList::AT_NoThrow:
Reid Klecknera3fe27f2017-10-02 17:16:14 +00006204 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006205 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006206 case AttributeList::AT_CUDAShared:
Justin Lebar10411012016-09-30 23:57:30 +00006207 handleSharedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006208 break;
6209 case AttributeList::AT_VecReturn:
6210 handleVecReturnAttr(S, D, Attr);
6211 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006212 case AttributeList::AT_ObjCOwnership:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006213 handleObjCOwnershipAttr(S, D, Attr);
6214 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006215 case AttributeList::AT_ObjCPreciseLifetime:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006216 handleObjCPreciseLifetimeAttr(S, D, Attr);
6217 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006218 case AttributeList::AT_ObjCReturnsInnerPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006219 handleObjCReturnsInnerPointerAttr(S, D, Attr);
6220 break;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00006221 case AttributeList::AT_ObjCRequiresSuper:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006222 handleObjCRequiresSuperAttr(S, D, Attr);
6223 break;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00006224 case AttributeList::AT_ObjCBridge:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006225 handleObjCBridgeAttr(S, scope, D, Attr);
6226 break;
Fariborz Jahanian87c77912013-11-21 20:50:32 +00006227 case AttributeList::AT_ObjCBridgeMutable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006228 handleObjCBridgeMutableAttr(S, scope, D, Attr);
6229 break;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00006230 case AttributeList::AT_ObjCBridgeRelated:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006231 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
6232 break;
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00006233 case AttributeList::AT_ObjCDesignatedInitializer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006234 handleObjCDesignatedInitializer(S, D, Attr);
6235 break;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006236 case AttributeList::AT_ObjCRuntimeName:
6237 handleObjCRuntimeName(S, D, Attr);
6238 break;
Douglas Gregor24ae22c2016-04-01 23:23:52 +00006239 case AttributeList::AT_ObjCRuntimeVisible:
6240 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
6241 break;
Alex Denisovfde64952015-06-26 05:28:36 +00006242 case AttributeList::AT_ObjCBoxable:
6243 handleObjCBoxable(S, D, Attr);
6244 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006245 case AttributeList::AT_CFAuditedTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006246 handleCFAuditedTransferAttr(S, D, Attr);
6247 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006248 case AttributeList::AT_CFUnknownTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006249 handleCFUnknownTransferAttr(S, D, Attr);
6250 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006251 case AttributeList::AT_CFConsumed:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006252 case AttributeList::AT_NSConsumed:
6253 handleNSConsumedAttr(S, D, Attr);
6254 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006255 case AttributeList::AT_NSConsumesSelf:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006256 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
6257 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006258 case AttributeList::AT_NSReturnsAutoreleased:
6259 case AttributeList::AT_NSReturnsNotRetained:
6260 case AttributeList::AT_CFReturnsNotRetained:
6261 case AttributeList::AT_NSReturnsRetained:
6262 case AttributeList::AT_CFReturnsRetained:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006263 handleNSReturnsRetainedAttr(S, D, Attr);
6264 break;
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00006265 case AttributeList::AT_WorkGroupSizeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006266 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
6267 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006268 case AttributeList::AT_ReqdWorkGroupSize:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006269 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
6270 break;
Xiuli Panbe6da4b2017-05-04 07:31:20 +00006271 case AttributeList::AT_OpenCLIntelReqdSubGroupSize:
6272 handleSubGroupSize(S, D, Attr);
6273 break;
Joey Goulyaba589c2013-03-08 09:42:32 +00006274 case AttributeList::AT_VecTypeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006275 handleVecTypeHint(S, D, Attr);
6276 break;
Eric Fiselier341e8252016-09-02 18:53:31 +00006277 case AttributeList::AT_RequireConstantInit:
6278 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
6279 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006280 case AttributeList::AT_InitPriority:
6281 handleInitPriorityAttr(S, D, Attr);
6282 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006283 case AttributeList::AT_Packed:
6284 handlePackedAttr(S, D, Attr);
6285 break;
6286 case AttributeList::AT_Section:
6287 handleSectionAttr(S, D, Attr);
6288 break;
Eric Christopher11acf732015-06-12 01:35:52 +00006289 case AttributeList::AT_Target:
6290 handleTargetAttr(S, D, Attr);
6291 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006292 case AttributeList::AT_Unavailable:
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00006293 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00006294 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006295 case AttributeList::AT_ArcWeakrefUnavailable:
6296 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
6297 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006298 case AttributeList::AT_ObjCRootClass:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006299 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
6300 break;
Alex Lorenza8c44ba2016-10-28 10:25:10 +00006301 case AttributeList::AT_ObjCSubclassingRestricted:
6302 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
6303 break;
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00006304 case AttributeList::AT_ObjCExplicitProtocolImpl:
Ted Kremenek438f8db2014-02-22 01:06:05 +00006305 handleObjCSuppresProtocolAttr(S, D, Attr);
Ted Kremenek28eace62013-11-23 01:01:34 +00006306 break;
6307 case AttributeList::AT_ObjCRequiresPropertyDefs:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006308 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
6309 break;
Aaron Ballman12b9f652014-01-16 13:55:42 +00006310 case AttributeList::AT_Unused:
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00006311 handleUnusedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006312 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006313 case AttributeList::AT_ReturnsTwice:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006314 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
6315 break;
Akira Hatanakac8667622015-11-06 23:56:15 +00006316 case AttributeList::AT_NotTailCalled:
6317 handleNotTailCalledAttr(S, D, Attr);
6318 break;
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00006319 case AttributeList::AT_DisableTailCalls:
6320 handleDisableTailCallsAttr(S, D, Attr);
6321 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006322 case AttributeList::AT_Used:
6323 handleUsedAttr(S, D, Attr);
6324 break;
John McCalld041a9b2013-02-20 01:54:26 +00006325 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;
Lubos Lunakedc13882013-07-20 15:05:36 +00006331 case AttributeList::AT_WarnUnused:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006332 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
6333 break;
6334 case AttributeList::AT_WarnUnusedResult:
6335 handleWarnUnusedResult(S, D, Attr);
Chris Lattner237f2752009-02-14 07:37:35 +00006336 break;
Aaron Ballman604dfec2013-12-02 17:07:07 +00006337 case AttributeList::AT_Weak:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006338 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;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006346 case AttributeList::AT_TransparentUnion:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006347 handleTransparentUnionAttr(S, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006348 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006349 case AttributeList::AT_ObjCException:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006350 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6351 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006352 case AttributeList::AT_ObjCMethodFamily:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006353 handleObjCMethodFamilyAttr(S, D, Attr);
John McCall86bc21f2011-03-02 11:33:24 +00006354 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006355 case AttributeList::AT_ObjCNSObject:
6356 handleObjCNSObject(S, D, Attr);
6357 break;
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00006358 case AttributeList::AT_ObjCIndependentClass:
6359 handleObjCIndependentClass(S, D, Attr);
6360 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006361 case AttributeList::AT_Blocks:
6362 handleBlocksAttr(S, D, Attr);
6363 break;
6364 case AttributeList::AT_Sentinel:
6365 handleSentinelAttr(S, D, Attr);
6366 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00006367 case AttributeList::AT_Const:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006368 handleSimpleAttribute<ConstAttr>(S, D, Attr);
6369 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006370 case AttributeList::AT_Pure:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006371 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;
Aaron Ballman7c19ab12014-02-22 16:59:24 +00006379 case AttributeList::AT_NoDuplicate:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006380 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6381 break;
Yaxun Liu7d07ae72016-11-01 18:45:32 +00006382 case AttributeList::AT_Convergent:
6383 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6384 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006385 case AttributeList::AT_NoInline:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006386 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6387 break;
6388 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6389 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6390 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006391 case AttributeList::AT_StdCall:
6392 case AttributeList::AT_CDecl:
6393 case AttributeList::AT_FastCall:
6394 case AttributeList::AT_ThisCall:
6395 case AttributeList::AT_Pascal:
Erich Keane757d3172016-11-02 18:29:35 +00006396 case AttributeList::AT_RegCall:
John McCall477f2bb2016-03-03 06:39:32 +00006397 case AttributeList::AT_SwiftCall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00006398 case AttributeList::AT_VectorCall:
Charles Davisb5a214e2013-08-30 04:39:01 +00006399 case AttributeList::AT_MSABI:
6400 case AttributeList::AT_SysVABI:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006401 case AttributeList::AT_Pcs:
Guy Benyeif0a014b2012-12-25 08:53:55 +00006402 case AttributeList::AT_IntelOclBicc:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00006403 case AttributeList::AT_PreserveMost:
6404 case AttributeList::AT_PreserveAll:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006405 handleCallConvAttr(S, D, Attr);
John McCallab26cfa2010-02-05 21:31:56 +00006406 break;
Matthias Gehre01a63382017-03-27 19:45:24 +00006407 case AttributeList::AT_Suppress:
6408 handleSuppressAttr(S, D, Attr);
6409 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006410 case AttributeList::AT_OpenCLKernel:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006411 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6412 break;
Xiuli Pan11e13f62016-02-26 03:13:03 +00006413 case AttributeList::AT_OpenCLAccess:
6414 handleOpenCLAccessAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006415 break;
Anastasia Stulovafde76222016-04-01 16:05:09 +00006416 case AttributeList::AT_OpenCLNoSVM:
6417 handleOpenCLNoSVMAttr(S, D, Attr);
6418 break;
John McCall477f2bb2016-03-03 06:39:32 +00006419 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;
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00006428 case AttributeList::AT_InternalLinkage:
6429 handleInternalLinkageAttr(S, D, Attr);
6430 break;
Peter Collingbourne3afb2662016-04-28 17:09:37 +00006431 case AttributeList::AT_LTOVisibilityPublic:
6432 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6433 break;
John McCall8d32c052012-05-22 21:28:12 +00006434
6435 // Microsoft attributes:
David Majnemercd3ebfe2016-05-23 17:16:12 +00006436 case AttributeList::AT_EmptyBases:
6437 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6438 break;
6439 case AttributeList::AT_LayoutVersion:
6440 handleLayoutVersion(S, D, Attr);
6441 break;
Akira Hatanaka02914dc2018-02-05 20:23:22 +00006442 case AttributeList::AT_TrivialABI:
6443 handleSimpleAttribute<TrivialABIAttr>(S, D, Attr);
6444 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00006445 case AttributeList::AT_MSNoVTable:
6446 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
David Majnemer129f4172015-02-02 10:22:20 +00006447 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00006448 case AttributeList::AT_MSStruct:
6449 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
John McCall8d32c052012-05-22 21:28:12 +00006450 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006451 case AttributeList::AT_Uuid:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006452 handleUuidAttr(S, D, Attr);
Francois Picheta83957a2010-12-19 06:50:37 +00006453 break;
Aaron Ballman8edb5c22013-12-18 23:44:18 +00006454 case AttributeList::AT_MSInheritance:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006455 handleMSInheritanceAttr(S, D, Attr);
6456 break;
Reid Klecknerb144d362013-05-20 14:02:37 +00006457 case AttributeList::AT_SelectAny:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006458 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6459 break;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00006460 case AttributeList::AT_Thread:
6461 handleDeclspecThreadAttr(S, D, Attr);
6462 break;
David Majnemercd3ebfe2016-05-23 17:16:12 +00006463
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00006464 case AttributeList::AT_AbiTag:
6465 handleAbiTagAttr(S, D, Attr);
6466 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006467
6468 // Thread safety attributes:
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00006469 case AttributeList::AT_AssertExclusiveLock:
6470 handleAssertExclusiveLockAttr(S, D, Attr);
6471 break;
6472 case AttributeList::AT_AssertSharedLock:
6473 handleAssertSharedLockAttr(S, D, Attr);
6474 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006475 case AttributeList::AT_GuardedVar:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006476 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6477 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006478 case AttributeList::AT_PtGuardedVar:
Michael Han3be3b442012-07-23 18:48:41 +00006479 handlePtGuardedVarAttr(S, D, Attr);
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006480 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006481 case AttributeList::AT_ScopedLockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006482 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6483 break;
Peter Collingbourne915df992015-05-15 18:33:32 +00006484 case AttributeList::AT_NoSanitize:
6485 handleNoSanitizeAttr(S, D, Attr);
6486 break;
6487 case AttributeList::AT_NoSanitizeSpecific:
6488 handleNoSanitizeSpecificAttr(S, D, Attr);
Kostya Serebryany588d6ab2012-01-24 19:25:38 +00006489 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006490 case AttributeList::AT_NoThreadSafetyAnalysis:
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006491 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00006492 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006493 case AttributeList::AT_GuardedBy:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006494 handleGuardedByAttr(S, D, Attr);
6495 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006496 case AttributeList::AT_PtGuardedBy:
Michael Han3be3b442012-07-23 18:48:41 +00006497 handlePtGuardedByAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006498 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006499 case AttributeList::AT_ExclusiveTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00006500 handleExclusiveTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006501 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006502 case AttributeList::AT_LockReturned:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006503 handleLockReturnedAttr(S, D, Attr);
6504 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006505 case AttributeList::AT_LocksExcluded:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006506 handleLocksExcludedAttr(S, D, Attr);
6507 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006508 case AttributeList::AT_SharedTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00006509 handleSharedTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006510 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006511 case AttributeList::AT_AcquiredBefore:
Michael Han3be3b442012-07-23 18:48:41 +00006512 handleAcquiredBeforeAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006513 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006514 case AttributeList::AT_AcquiredAfter:
Michael Han3be3b442012-07-23 18:48:41 +00006515 handleAcquiredAfterAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006516 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006517
Aaron Ballmanefe348e2014-02-18 17:36:50 +00006518 // Capability analysis attributes.
6519 case AttributeList::AT_Capability:
6520 case AttributeList::AT_Lockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006521 handleCapabilityAttr(S, D, Attr);
6522 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006523 case AttributeList::AT_RequiresCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006524 handleRequiresCapabilityAttr(S, D, Attr);
6525 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006526
6527 case AttributeList::AT_AssertCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006528 handleAssertCapabilityAttr(S, D, Attr);
6529 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006530 case AttributeList::AT_AcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006531 handleAcquireCapabilityAttr(S, D, Attr);
6532 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006533 case AttributeList::AT_ReleaseCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006534 handleReleaseCapabilityAttr(S, D, Attr);
6535 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006536 case AttributeList::AT_TryAcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006537 handleTryAcquireCapabilityAttr(S, D, Attr);
6538 break;
Aaron Ballmanefe348e2014-02-18 17:36:50 +00006539
DeLesley Hutchins8d41d992013-10-11 22:30:48 +00006540 // Consumed analysis attributes.
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00006541 case AttributeList::AT_Consumable:
6542 handleConsumableAttr(S, D, Attr);
6543 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00006544 case AttributeList::AT_ConsumableAutoCast:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006545 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6546 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00006547 case AttributeList::AT_ConsumableSetOnRead:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006548 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6549 break;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00006550 case AttributeList::AT_CallableWhen:
6551 handleCallableWhenAttr(S, D, Attr);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00006552 break;
DeLesley Hutchins69391772013-10-17 23:23:53 +00006553 case AttributeList::AT_ParamTypestate:
6554 handleParamTypestateAttr(S, D, Attr);
6555 break;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00006556 case AttributeList::AT_ReturnTypestate:
6557 handleReturnTypestateAttr(S, D, Attr);
6558 break;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00006559 case AttributeList::AT_SetTypestate:
6560 handleSetTypestateAttr(S, D, Attr);
6561 break;
Chris Wailes9385f9f2013-10-29 20:28:41 +00006562 case AttributeList::AT_TestTypestate:
6563 handleTestTypestateAttr(S, D, Attr);
DeLesley Hutchins33a29342013-10-11 23:03:26 +00006564 break;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00006565
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00006566 // 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;
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006573 case AttributeList::AT_AnyX86NoCallerSavedRegisters:
6574 handleNoCallerSavedRegsAttr(S, D, Attr);
6575 break;
Pirama Arumuga Nainare5d2d712016-06-10 21:51:18 +00006576 case AttributeList::AT_RenderScriptKernel:
6577 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
Pirama Arumuga Nainar8b788d02016-06-09 23:34:20 +00006578 break;
Aaron Ballman7d2aecb2016-07-13 22:32:15 +00006579 // XRay attributes.
6580 case AttributeList::AT_XRayInstrument:
6581 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6582 break;
Dean Michael Berris418da3f2017-03-06 07:08:21 +00006583 case AttributeList::AT_XRayLogArgs:
6584 handleXRayLogArgsAttr(S, D, Attr);
6585 break;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006586 }
6587}
6588
6589/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6590/// attribute list to the specified decl, ignoring any type attributes.
Eric Christopherbc638a82010-12-01 22:13:54 +00006591void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
Peter Collingbourneb331b262011-01-21 02:08:45 +00006592 const AttributeList *AttrList,
Richard Smith10876ef2013-01-17 01:30:42 +00006593 bool IncludeCXX11Attributes) {
6594 for (const AttributeList* l = AttrList; l; l = l->getNext())
Richard Smithf8a75c32013-08-29 00:47:48 +00006595 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
Rafael Espindolac18086a2010-02-23 22:00:30 +00006596
Joey Gouly2cd9db12013-12-13 16:15:28 +00006597 // FIXME: We should be able to handle these cases in TableGen.
Rafael Espindolac18086a2010-02-23 22:00:30 +00006598 // GCC accepts
6599 // static int a9 __attribute__((weakref));
6600 // but that looks really pointless. We reject it.
Richard Smithf8a75c32013-08-29 00:47:48 +00006601 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00006602 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6603 << cast<NamedDecl>(D);
Rafael Espindolab3069002013-01-16 23:49:06 +00006604 D->dropAttr<WeakRefAttr>();
Rafael Espindolac18086a2010-02-23 22:00:30 +00006605 return;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006606 }
Joey Gouly2cd9db12013-12-13 16:15:28 +00006607
Aaron Ballmanbe243a72014-12-04 22:45:31 +00006608 // 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.
Joey Gouly2cd9db12013-12-13 16:15:28 +00006612 if (!D->hasAttr<OpenCLKernelAttr>()) {
6613 // These attributes cannot be applied to a non-kernel function.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006614 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006615 // FIXME: This emits a different error message than
6616 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006617 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006618 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006619 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006620 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006621 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006622 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006623 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006624 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006625 } 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>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006630 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();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006637 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6638 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6639 << A << ExpectedKernelFunction;
6640 D->setInvalidDecl();
Xiuli Panbe6da4b2017-05-04 07:31:20 +00006641 } else if (Attr *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
6642 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6643 D->setInvalidDecl();
Joey Gouly2cd9db12013-12-13 16:15:28 +00006644 }
6645 }
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006646}
6647
Hiroshi Inoue939d9322017-06-30 05:40:31 +00006648// Helper for delayed processing TransparentUnion attribute.
Erich Keane2fe684b2017-02-28 20:44:39 +00006649void 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
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006657// 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()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006662 if (l->getKind() == AttributeList::AT_Annotate) {
David Majnemer706f3152014-12-14 01:05:01 +00006663 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006664 } else {
6665 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6666 return true;
6667 }
6668 }
6669
6670 return false;
6671}
6672
John McCall42856de2011-10-01 05:17:03 +00006673/// 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.
Richard Smith810ad3e2013-01-29 10:02:16 +00006678 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
John McCall42856de2011-10-01 05:17:03 +00006679 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
Ryan Flynn7d470f32009-07-30 03:15:39 +00006701/// DeclClonePragmaWeak - clone existing decl (maybe definition),
James Dennett634962f2012-06-14 21:40:34 +00006702/// \#pragma weak needs a non-definition decl and source may not have one.
Eli Friedmance3e2c82011-09-07 04:05:06 +00006703NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6704 SourceLocation Loc) {
Ryan Flynnd963a492009-07-31 02:52:19 +00006705 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
Craig Topperc3ec1492014-05-26 06:22:03 +00006706 NamedDecl *NewD = nullptr;
Ryan Flynn7d470f32009-07-30 03:15:39 +00006707 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Alexander Kornienko061900f2015-12-03 11:37:28 +00006708 FunctionDecl *NewFD;
6709 // FIXME: Missing call to CheckFunctionDeclaration().
Eli Friedmance3e2c82011-09-07 04:05:06 +00006710 // FIXME: Mangling?
6711 // FIXME: Is the qualifier info correct?
6712 // FIXME: Is the DeclContext correct?
Alexander Kornienko061900f2015-12-03 11:37:28 +00006713 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*/);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006719 NewD = NewFD;
6720
6721 if (FD->getQualifier())
Douglas Gregor14454802011-02-25 02:25:35 +00006722 NewFD->setQualifierInfo(FD->getQualifierLoc());
Eli Friedmance3e2c82011-09-07 04:05:06 +00006723
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;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006729 for (const auto &AI : FT->param_types()) {
6730 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006731 Param->setScopeInfo(0, Params.size());
6732 Params.push_back(Param);
6733 }
David Blaikie9c70e042011-09-21 18:16:56 +00006734 NewFD->setParams(Params);
John McCall3e11ebe2010-03-15 10:12:16 +00006735 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006736 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6737 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00006738 VD->getInnerLocStart(), VD->getLocation(), II,
John McCallbcd03502009-12-07 02:54:59 +00006739 VD->getType(), VD->getTypeSourceInfo(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006740 VD->getStorageClass());
John McCall3e11ebe2010-03-15 10:12:16 +00006741 if (VD->getQualifier()) {
6742 VarDecl *NewVD = cast<VarDecl>(NewD);
Douglas Gregor14454802011-02-25 02:25:35 +00006743 NewVD->setQualifierInfo(VD->getQualifierLoc());
John McCall3e11ebe2010-03-15 10:12:16 +00006744 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006745 }
6746 return NewD;
6747}
6748
James Dennett634962f2012-06-14 21:40:34 +00006749/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
Ryan Flynn7d470f32009-07-30 03:15:39 +00006750/// applied to it, possibly with an alias.
Ryan Flynnd963a492009-07-31 02:52:19 +00006751void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
Chris Lattnere6eab982009-09-08 18:10:11 +00006752 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();
Eli Friedmance3e2c82011-09-07 04:05:06 +00006756 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
Aaron Ballman36a53502014-01-16 13:03:14 +00006757 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6758 W.getLocation()));
6759 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Chris Lattnere6eab982009-09-08 18:10:11 +00006760 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();
Argyrios Kyrtzidis0098a4b2014-03-09 05:15:28 +00006765 NewD->setDeclContext(CurContext);
6766 NewD->setLexicalDeclContext(CurContext);
Chris Lattnere6eab982009-09-08 18:10:11 +00006767 PushOnScopeChains(NewD, S);
6768 CurContext = SavedContext;
6769 } else { // just add weak to existing
Aaron Ballman36a53502014-01-16 13:03:14 +00006770 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Ryan Flynn7d470f32009-07-30 03:15:39 +00006771 }
6772}
6773
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006774void 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()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006779 NamedDecl *ND = nullptr;
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006780 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()) {
Chandler Carruthf85d9822015-03-26 08:32:49 +00006788 auto I = WeakUndeclaredIdentifiers.find(Id);
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006789 if (I != WeakUndeclaredIdentifiers.end()) {
6790 WeakInfo W = I->second;
6791 DeclApplyPragmaWeak(S, ND, W);
6792 WeakUndeclaredIdentifiers[Id] = W;
6793 }
6794 }
6795 }
6796 }
6797}
6798
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006799/// 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.
Richard Smithf8a75c32013-08-29 00:47:48 +00006802void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006803 // Apply decl attributes from the DeclSpec if present.
John McCall53fa7142010-12-24 02:08:15 +00006804 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
Richard Smithf8a75c32013-08-29 00:47:48 +00006805 ProcessDeclAttributeList(S, D, Attrs);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006806
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006807 // 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())
Richard Smithf8a75c32013-08-29 00:47:48 +00006813 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006814
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006815 // Finally, apply any attributes on the decl itself.
6816 if (const AttributeList *Attrs = PD.getAttributes())
Richard Smithf8a75c32013-08-29 00:47:48 +00006817 ProcessDeclAttributeList(S, D, Attrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00006818
6819 // Apply additional attributes specified by '#pragma clang attribute'.
6820 AddPragmaAttributes(S, D);
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006821}
John McCall28a6aea2009-11-04 02:18:39 +00006822
John McCall31168b02011-06-15 23:02:42 +00006823/// Is the given declaration allowed to use a forbidden type?
John McCallb61e14e2015-10-27 04:54:50 +00006824/// 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,
John McCallc6af8c62015-10-28 05:03:19 +00006828 UnavailableAttr::ImplicitReason &reason) {
John McCall31168b02011-06-15 23:02:42 +00006829 // 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.
Fariborz Jahanian6d5d6a22011-09-26 21:23:35 +00006832 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6833 !isa<FunctionDecl>(decl))
John McCall31168b02011-06-15 23:02:42 +00006834 return false;
6835
John McCallc6af8c62015-10-28 05:03:19 +00006836 // 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 }
John McCallb61e14e2015-10-27 04:54:50 +00006847 }
6848
John McCallc6af8c62015-10-28 05:03:19 +00006849 // 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;
John McCallb61e14e2015-10-27 04:54:50 +00006855 }
6856
6857 return false;
John McCall31168b02011-06-15 23:02:42 +00006858}
6859
6860/// Handle a delayed forbidden-type diagnostic.
6861static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6862 Decl *decl) {
John McCallc6af8c62015-10-28 05:03:19 +00006863 auto reason = UnavailableAttr::IR_None;
6864 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6865 assert(reason && "didn't set reason?");
6866 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6867 diag.Loc));
John McCall31168b02011-06-15 23:02:42 +00006868 return;
6869 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00006870 if (S.getLangOpts().ObjCAutoRefCount)
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006871 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
Benjamin Kramer474261a2012-06-02 10:20:41 +00006872 // FIXME: we may want to suppress diagnostics for all
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006873 // 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 }
John McCall31168b02011-06-15 23:02:42 +00006881
6882 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6883 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6884 diag.Triggered = true;
6885}
6886
Manman Ren45b1ab12016-05-06 19:57:16 +00006887static 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
Erik Pilkington9f866a72017-07-18 20:32:07 +00006915/// 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
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00006959/// \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!");
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
Alex Lorenzc9a369f2017-06-22 17:02:24 +00007024static 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
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007050static 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
Alex Lorenz727c21e2017-07-26 13:58:02 +00007065namespace {
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
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007108/// 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.
Erik Pilkington796a3e22016-08-05 22:59:03 +00007118static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007119 Decl *Ctx, const NamedDecl *ReferringDecl,
7120 const NamedDecl *OffendingDecl,
Aaron Ballmanfb237522014-10-15 15:37:51 +00007121 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;
John McCallb61e14e2015-10-27 04:54:50 +00007127 unsigned diag_available_here = diag::note_availability_specified_here;
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007128 SourceLocation NoteLocation = OffendingDecl->getLocation();
Aaron Ballmanfb237522014-10-15 15:37:51 +00007129
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
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007136 VersionTuple DeclVersion;
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007137 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl))
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007138 DeclVersion = AA->getIntroduced();
7139
7140 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
7141 return;
7142
Erik Pilkington8b352c42017-08-14 19:49:12 +00007143 // 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
Aaron Ballmanfb237522014-10-15 15:37:51 +00007160 switch (K) {
Erik Pilkington8b352c42017-08-14 19:49:12 +00007161 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 }
Erik Pilkington796a3e22016-08-05 22:59:03 +00007220 case AR_Deprecated:
Aaron Ballmanfb237522014-10-15 15:37:51 +00007221 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;
Erich Keaneb11ebc52017-09-27 03:20:13 +00007227 if (const auto *Attr = OffendingDecl->getAttr<DeprecatedAttr>())
7228 NoteLocation = Attr->getLocation();
Aaron Ballmanfb237522014-10-15 15:37:51 +00007229 break;
7230
Erik Pilkington796a3e22016-08-05 22:59:03 +00007231 case AR_Unavailable:
Aaron Ballmanfb237522014-10-15 15:37:51 +00007232 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;
John McCallb61e14e2015-10-27 04:54:50 +00007238
Erich Keaneb11ebc52017-09-27 03:20:13 +00007239 if (auto Attr = OffendingDecl->getAttr<UnavailableAttr>()) {
7240 if (Attr->isImplicit() && Attr->getImplicitReason()) {
John McCallc6af8c62015-10-28 05:03:19 +00007241 // 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 &&
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007245 S.getSourceManager().isInSystemHeader(
7246 OffendingDecl->getLocation()))
John McCallc6af8c62015-10-28 05:03:19 +00007247 diag = diag::err_unavailable_in_arc;
7248 };
7249
Erich Keaneb11ebc52017-09-27 03:20:13 +00007250 switch (Attr->getImplicitReason()) {
John McCallc6af8c62015-10-28 05:03:19 +00007251 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 }
John McCallb61e14e2015-10-27 04:54:50 +00007281 }
Aaron Ballmanfb237522014-10-15 15:37:51 +00007282 break;
7283
Erik Pilkington796a3e22016-08-05 22:59:03 +00007284 case AR_Available:
7285 llvm_unreachable("Warning for availability of available declaration?");
Aaron Ballmanfb237522014-10-15 15:37:51 +00007286 }
7287
Manman Renc7890fe2016-03-16 18:50:49 +00007288 CharSourceRange UseRange;
7289 StringRef Replacement;
Erik Pilkington796a3e22016-08-05 22:59:03 +00007290 if (K == AR_Deprecated) {
Erich Keaneb11ebc52017-09-27 03:20:13 +00007291 if (auto Attr = OffendingDecl->getAttr<DeprecatedAttr>())
7292 Replacement = Attr->getReplacement();
7293 if (auto Attr = getAttrForPlatform(S.Context, OffendingDecl))
7294 Replacement = Attr->getReplacement();
Manman Renc7890fe2016-03-16 18:50:49 +00007295
7296 if (!Replacement.empty())
7297 UseRange =
7298 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
7299 }
7300
Aaron Ballmanfb237522014-10-15 15:37:51 +00007301 if (!Message.empty()) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007302 S.Diag(Loc, diag_message) << ReferringDecl << Message
Manman Renc7890fe2016-03-16 18:50:49 +00007303 << (UseRange.isValid() ?
7304 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00007305 if (ObjCProperty)
7306 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7307 << ObjCProperty->getDeclName() << property_note_select;
7308 } else if (!UnknownObjCClass) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007309 S.Diag(Loc, diag) << ReferringDecl
Manman Renc7890fe2016-03-16 18:50:49 +00007310 << (UseRange.isValid() ?
7311 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00007312 if (ObjCProperty)
7313 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7314 << ObjCProperty->getDeclName() << property_note_select;
7315 } else {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007316 S.Diag(Loc, diag_fwdclass_message) << ReferringDecl
Manman Renc7890fe2016-03-16 18:50:49 +00007317 << (UseRange.isValid() ?
7318 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00007319 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
7320 }
7321
Erik Pilkington8b352c42017-08-14 19:49:12 +00007322 S.Diag(NoteLocation, diag_available_here)
7323 << OffendingDecl << available_here_select_kind;
Aaron Ballmanfb237522014-10-15 15:37:51 +00007324}
7325
7326static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
7327 Decl *Ctx) {
Erik Pilkingtona8003972016-10-28 21:39:27 +00007328 assert(DD.Kind == DelayedDiagnostic::Availability &&
7329 "Expected an availability diagnostic here");
7330
Aaron Ballmanfb237522014-10-15 15:37:51 +00007331 DD.Triggered = true;
Nico Weber0055a192015-03-19 19:18:22 +00007332 DoEmitAvailabilityWarning(
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007333 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(),
7334 DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(), DD.Loc,
7335 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
Aaron Ballmanfb237522014-10-15 15:37:51 +00007336}
7337
John McCall2ec85372012-05-07 06:16:41 +00007338void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7339 assert(DelayedDiagnostics.getCurrentPool());
John McCall6347b682012-05-07 06:16:58 +00007340 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
John McCall2ec85372012-05-07 06:16:41 +00007341 DelayedDiagnostics.popWithoutEmitting(state);
John McCallc1465822011-02-14 07:13:47 +00007342
John McCall2ec85372012-05-07 06:16:41 +00007343 // 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;
John McCallc1465822011-02-14 07:13:47 +00007347
John McCall2ec85372012-05-07 06:16:41 +00007348 // 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.
John McCall6347b682012-05-07 06:16:58 +00007355 const DelayedDiagnosticPool *pool = &poppedPool;
John McCall2ec85372012-05-07 06:16:41 +00007356 do {
John McCall6347b682012-05-07 06:16:58 +00007357 for (DelayedDiagnosticPool::pool_iterator
John McCall2ec85372012-05-07 06:16:41 +00007358 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);
John McCallc1465822011-02-14 07:13:47 +00007361 if (diag.Triggered)
John McCall86121512010-01-27 03:50:35 +00007362 continue;
7363
John McCallc1465822011-02-14 07:13:47 +00007364 switch (diag.Kind) {
Erik Pilkingtona8003972016-10-28 21:39:27 +00007365 case DelayedDiagnostic::Availability:
Ted Kremenekb79ee572013-12-18 23:30:06 +00007366 // Don't bother giving deprecation/unavailable diagnostics if
7367 // the decl is invalid.
John McCall18a962b2012-01-26 20:04:03 +00007368 if (!decl->isInvalidDecl())
Aaron Ballmanfb237522014-10-15 15:37:51 +00007369 handleDelayedAvailabilityCheck(*this, diag, decl);
John McCall86121512010-01-27 03:50:35 +00007370 break;
7371
7372 case DelayedDiagnostic::Access:
John McCall2ec85372012-05-07 06:16:41 +00007373 HandleDelayedAccessCheck(diag, decl);
John McCall86121512010-01-27 03:50:35 +00007374 break;
John McCall31168b02011-06-15 23:02:42 +00007375
7376 case DelayedDiagnostic::ForbiddenType:
John McCall2ec85372012-05-07 06:16:41 +00007377 handleDelayedForbiddenType(*this, diag, decl);
John McCall31168b02011-06-15 23:02:42 +00007378 break;
John McCall86121512010-01-27 03:50:35 +00007379 }
7380 }
John McCall2ec85372012-05-07 06:16:41 +00007381 } while ((pool = pool->getParent()));
John McCall28a6aea2009-11-04 02:18:39 +00007382}
7383
John McCall6347b682012-05-07 06:16:58 +00007384/// 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");
7390 curPool->steal(pool);
7391}
7392
Erik Pilkington9f866a72017-07-18 20:32:07 +00007393static 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) {
John McCall28a6aea2009-11-04 02:18:39 +00007400 // Delay if we're currently parsing a declaration.
Erik Pilkington9f866a72017-07-18 20:32:07 +00007401 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7402 S.DelayedDiagnostics.add(
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007403 DelayedDiagnostic::makeAvailability(
7404 AR, Loc, ReferringDecl, OffendingDecl, UnknownObjCClass,
7405 ObjCProperty, Message, ObjCPropertyAccess));
John McCall28a6aea2009-11-04 02:18:39 +00007406 return;
7407 }
7408
Erik Pilkington9f866a72017-07-18 20:32:07 +00007409 Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
7410 DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007411 Message, Loc, UnknownObjCClass, ObjCProperty,
7412 ObjCPropertyAccess);
John McCall28a6aea2009-11-04 02:18:39 +00007413}
Erik Pilkington48c7cc92016-07-29 17:37:38 +00007414
Erik Pilkington5cd57172016-08-16 17:44:11 +00007415namespace {
7416
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007417/// 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
Erik Pilkington5cd57172016-08-16 17:44:11 +00007480/// \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;
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007491 Decl *Ctx;
Erik Pilkington5cd57172016-08-16 17:44:11 +00007492
7493 /// Stack of potentially nested 'if (@available(...))'s.
7494 SmallVector<VersionTuple, 8> AvailabilityStack;
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007495 SmallVector<const Stmt *, 16> StmtStack;
Erik Pilkington5cd57172016-08-16 17:44:11 +00007496
7497 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
7498
7499public:
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007500 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
7501 : SemaRef(SemaRef), Ctx(Ctx) {
7502 AvailabilityStack.push_back(
7503 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
Erik Pilkington5cd57172016-08-16 17:44:11 +00007504 }
7505
Alex Lorenz6f911122017-05-16 13:58:53 +00007506 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
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007513 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
Erik Pilkington5cd57172016-08-16 17:44:11 +00007522 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
7523
7524 bool TraverseIfStmt(IfStmt *If);
7525
Alex Lorenz6f911122017-05-16 13:58:53 +00007526 bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
7527
Erik Pilkingtonba87c622017-08-18 20:20:56 +00007528 // 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
Erik Pilkington6ac77a62017-05-22 15:41:12 +00007532 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
7533 if (PRE->isClassReceiver())
7534 DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
7535 return true;
7536 }
7537
Erik Pilkington5cd57172016-08-16 17:44:11 +00007538 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
Alex Lorenz0a484ba2017-05-24 15:15:29 +00007557 bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
7558 SemaRef.Diag(E->getLocStart(), diag::warn_at_available_unchecked_use)
7559 << (!SemaRef.getLangOpts().ObjC1);
7560 return true;
7561 }
7562
Erik Pilkington5cd57172016-08-16 17:44:11 +00007563 bool VisitTypeLoc(TypeLoc Ty);
7564};
7565
7566void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
7567 NamedDecl *D, SourceRange Range) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007568 AvailabilityResult Result;
7569 const NamedDecl *OffendingDecl;
7570 std::tie(Result, OffendingDecl) =
Erik Pilkington9f866a72017-07-18 20:32:07 +00007571 ShouldDiagnoseAvailabilityOfDecl(D, nullptr);
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007572 if (Result != AR_Available) {
Erik Pilkington5cd57172016-08-16 17:44:11 +00007573 // All other diagnostic kinds have already been handled in
7574 // DiagnoseAvailabilityOfDecl.
7575 if (Result != AR_NotYetIntroduced)
7576 return;
7577
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007578 const AvailabilityAttr *AA =
7579 getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
Erik Pilkington5cd57172016-08-16 17:44:11 +00007580 VersionTuple Introduced = AA->getIntroduced();
7581
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007582 if (AvailabilityStack.back() >= Introduced)
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007583 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
Alex Lorenzc9a369f2017-06-22 17:02:24 +00007590 // 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)
Erik Pilkington5cd57172016-08-16 17:44:11 +00007602 << Range << D
7603 << AvailabilityAttr::getPrettyPlatformName(
7604 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7605 << Introduced.getAsString();
7606
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007607 SemaRef.Diag(OffendingDecl->getLocation(),
7608 diag::note_availability_specified_here)
7609 << OffendingDecl << /* partial */ 3;
Erik Pilkington5cd57172016-08-16 17:44:11 +00007610
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007611 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")
Alex Lorenze1fb64e2017-05-09 15:34:46 +00007661 << "("
7662 << AvailabilityAttr::getPlatformNameSourceSpelling(
7663 SemaRef.getASTContext().getTargetInfo().getPlatformName())
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007664 << " " << 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());
Erik Pilkington5cd57172016-08-16 17:44:11 +00007680 }
7681}
7682
7683bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
7684 const Type *TyPtr = Ty.getTypePtr();
7685 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
7686
Erik Pilkington6ac77a62017-05-22 15:41:12 +00007687 if (Range.isInvalid())
7688 return true;
7689
Erik Pilkington5cd57172016-08-16 17:44:11 +00007690 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())
Alex Lorenz98f9fcd2017-08-17 14:22:27 +00007714 return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
Erik Pilkington5cd57172016-08-16 17:44:11 +00007715 } 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();
Alex Lorenz28559ce2017-04-26 14:20:02 +00007741 else if (auto *BD = dyn_cast<BlockDecl>(D))
7742 Body = BD->getBody();
Erik Pilkington5cd57172016-08-16 17:44:11 +00007743
7744 assert(Body && "Need a body here!");
7745
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007746 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
Erik Pilkington5cd57172016-08-16 17:44:11 +00007747}
Erik Pilkington9f866a72017-07-18 20:32:07 +00007748
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}