blob: 18065cb52d83b13ce4aede9067d48d817944da52 [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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
David Majnemer929025d2016-01-26 19:30:26 +000015#include "clang/AST/ASTConsumer.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000016#include "clang/AST/ASTContext.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"
Alex Denisovfde64952015-06-26 05:28:36 +000024#include "clang/AST/ASTMutationListener.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"
John McCallf1e8b342011-09-29 07:17:38 +000031#include "clang/Sema/Lookup.h"
Richard Smithe233fbf2013-01-28 22:42:45 +000032#include "clang/Sema/Scope.h"
Chris Lattner30ba6742009-08-10 19:03:04 +000033#include "llvm/ADT/StringExtras.h"
Hal Finkelee90a222014-09-26 05:04:30 +000034#include "llvm/Support/MathExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000035
Chris Lattner2c6fcf52008-06-26 18:38:35 +000036using namespace clang;
John McCallb45a1e72010-08-26 02:13:20 +000037using namespace sema;
Chris Lattner2c6fcf52008-06-26 18:38:35 +000038
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000039namespace AttributeLangSupport {
NAKAMURA Takumi01d27f92013-11-25 00:52:29 +000040 enum LANG {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000041 C,
42 Cpp,
43 ObjC
44 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000045} // end namespace AttributeLangSupport
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000046
Chris Lattner58418ff2008-06-29 00:16:31 +000047//===----------------------------------------------------------------------===//
48// Helper functions
49//===----------------------------------------------------------------------===//
50
Ted Kremenek527042b2009-08-14 20:49:40 +000051/// isFunctionOrMethod - Return true if the given decl has function
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000052/// type (function or function-typed variable) or an Objective-C
53/// method.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000054static bool isFunctionOrMethod(const Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +000055 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
Fariborz Jahanian4447e172009-05-15 23:15:03 +000056}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000057
David Majnemer06864812015-04-07 06:01:53 +000058/// \brief Return true if the given decl has function type (function or
59/// function-typed variable) or an Objective-C method or a block.
60static bool isFunctionOrMethodOrBlock(const Decl *D) {
61 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
62}
Fariborz Jahanian4447e172009-05-15 23:15:03 +000063
John McCall3882ace2011-01-05 12:14:39 +000064/// Return true if the given decl has a declarator that should have
65/// been processed by Sema::GetTypeForDeclarator.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000066static bool hasDeclarator(const Decl *D) {
John McCall31168b02011-06-15 23:02:42 +000067 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000068 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
69 isa<ObjCPropertyDecl>(D);
John McCall3882ace2011-01-05 12:14:39 +000070}
71
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000072/// hasFunctionProto - Return true if the given decl has a argument
73/// information. This decl should have already passed
Fariborz Jahanian4447e172009-05-15 23:15:03 +000074/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000075static bool hasFunctionProto(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000076 if (const FunctionType *FnTy = D->getFunctionType())
Douglas Gregordeaad8c2009-02-26 23:50:07 +000077 return isa<FunctionProtoType>(FnTy);
Aaron Ballman12b9f652014-01-16 13:55:42 +000078 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000079}
80
Alp Toker601b22c2014-01-21 23:35:24 +000081/// getFunctionOrMethodNumParams - Return number of function or method
82/// parameters. It is an error to call this on a K&R function (use
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000083/// hasFunctionProto first).
Alp Toker601b22c2014-01-21 23:35:24 +000084static unsigned getFunctionOrMethodNumParams(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000085 if (const FunctionType *FnTy = D->getFunctionType())
Alp Toker9cacbab2014-01-20 20:26:09 +000086 return cast<FunctionProtoType>(FnTy)->getNumParams();
Chandler Carruthff4c4f02011-07-01 23:49:12 +000087 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
Fariborz Jahanian960910a2009-05-19 17:08:59 +000088 return BD->getNumParams();
Chandler Carruthff4c4f02011-07-01 23:49:12 +000089 return cast<ObjCMethodDecl>(D)->param_size();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +000090}
91
Alp Toker601b22c2014-01-21 23:35:24 +000092static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000093 if (const FunctionType *FnTy = D->getFunctionType())
Alp Toker9cacbab2014-01-20 20:26:09 +000094 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
Chandler Carruthff4c4f02011-07-01 23:49:12 +000095 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
Fariborz Jahanian960910a2009-05-19 17:08:59 +000096 return BD->getParamDecl(Idx)->getType();
Mike Stumpd3bb5572009-07-24 19:02:52 +000097
Alp Toker03376dc2014-07-07 09:02:20 +000098 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +000099}
100
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000101static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
102 if (const auto *FD = dyn_cast<FunctionDecl>(D))
103 return FD->getParamDecl(Idx)->getSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000104 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000105 return MD->parameters()[Idx]->getSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000106 if (const auto *BD = dyn_cast<BlockDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000107 return BD->getParamDecl(Idx)->getSourceRange();
108 return SourceRange();
109}
110
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000111static QualType getFunctionOrMethodResultType(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +0000112 if (const FunctionType *FnTy = D->getFunctionType())
Aaron Ballman6288d062014-07-11 16:31:29 +0000113 return cast<FunctionType>(FnTy)->getReturnType();
Alp Toker314cc812014-01-25 16:55:45 +0000114 return cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanianf1c25022009-05-20 17:41:43 +0000115}
116
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000117static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
118 if (const auto *FD = dyn_cast<FunctionDecl>(D))
119 return FD->getReturnTypeSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000120 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000121 return MD->getReturnTypeSourceRange();
122 return SourceRange();
123}
124
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000125static bool isFunctionOrMethodVariadic(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +0000126 if (const FunctionType *FnTy = D->getFunctionType()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000127 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000128 return proto->isVariadic();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000129 }
Aaron Ballmane13d0092014-08-01 17:02:34 +0000130 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
131 return BD->isVariadic();
132
133 return cast<ObjCMethodDecl>(D)->isVariadic();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000134}
135
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000136static bool isInstanceMethod(const Decl *D) {
137 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
Chandler Carruth743682b2010-11-16 08:35:43 +0000138 return MethodDecl->isInstance();
139 return false;
140}
141
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000142static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
John McCall9dd450b2009-09-21 23:43:11 +0000143 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
Chris Lattner574dee62008-07-26 22:17:49 +0000144 if (!PT)
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000145 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000146
John McCall96fa4842010-05-17 21:00:27 +0000147 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
148 if (!Cls)
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000149 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000150
John McCall96fa4842010-05-17 21:00:27 +0000151 IdentifierInfo* ClsName = Cls->getIdentifier();
Mike Stumpd3bb5572009-07-24 19:02:52 +0000152
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000153 // FIXME: Should we walk the chain of classes?
154 return ClsName == &Ctx.Idents.get("NSString") ||
155 ClsName == &Ctx.Idents.get("NSMutableString");
156}
157
Daniel Dunbar980c6692008-09-26 03:32:58 +0000158static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000159 const PointerType *PT = T->getAs<PointerType>();
Daniel Dunbar980c6692008-09-26 03:32:58 +0000160 if (!PT)
161 return false;
162
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000163 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
Daniel Dunbar980c6692008-09-26 03:32:58 +0000164 if (!RT)
165 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000166
Daniel Dunbar980c6692008-09-26 03:32:58 +0000167 const RecordDecl *RD = RT->getDecl();
Abramo Bagnara6150c882010-05-11 21:36:43 +0000168 if (RD->getTagKind() != TTK_Struct)
Daniel Dunbar980c6692008-09-26 03:32:58 +0000169 return false;
170
171 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
172}
173
Richard Smithb87c4652013-10-31 21:23:20 +0000174static unsigned getNumAttributeArgs(const AttributeList &Attr) {
175 // FIXME: Include the type in the argument list.
176 return Attr.getNumArgs() + Attr.hasParsedType();
177}
178
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000179template <typename Compare>
180static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
181 unsigned Num, unsigned Diag,
182 Compare Comp) {
183 if (Comp(getNumAttributeArgs(Attr), Num)) {
184 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
Chandler Carruthfcc48d92011-07-11 23:30:35 +0000185 return false;
186 }
187
188 return true;
189}
190
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000191/// \brief Check if the attribute has exactly as many args as Num. May
192/// output an error.
193static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
194 unsigned Num) {
195 return checkAttributeNumArgsImpl(S, Attr, Num,
196 diag::err_attribute_wrong_number_arguments,
197 std::not_equal_to<unsigned>());
198}
199
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000200/// \brief Check if the attribute has at least as many args as Num. May
201/// output an error.
202static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
Richard Smithb87c4652013-10-31 21:23:20 +0000203 unsigned Num) {
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000204 return checkAttributeNumArgsImpl(S, Attr, Num,
205 diag::err_attribute_too_few_arguments,
206 std::less<unsigned>());
207}
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000208
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000209/// \brief Check if the attribute has at most as many args as Num. May
210/// output an error.
211static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
212 unsigned Num) {
213 return checkAttributeNumArgsImpl(S, Attr, Num,
214 diag::err_attribute_too_many_arguments,
215 std::greater<unsigned>());
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000216}
217
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000218/// \brief If Expr is a valid integer constant, get the value of the integer
219/// expression and return success or failure. May output an error.
220static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
221 const Expr *Expr, uint32_t &Val,
222 unsigned Idx = UINT_MAX) {
223 llvm::APSInt I(32);
224 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
225 !Expr->isIntegerConstantExpr(I, S.Context)) {
226 if (Idx != UINT_MAX)
227 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
228 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
229 << Expr->getSourceRange();
230 else
231 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
232 << Attr.getName() << AANT_ArgumentIntegerConstant
233 << Expr->getSourceRange();
234 return false;
235 }
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000236
237 if (!I.isIntN(32)) {
Aaron Ballman31f42312014-07-24 14:51:23 +0000238 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
239 << I.toString(10, false) << 32 << /* Unsigned */ 1;
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000240 return false;
241 }
242
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000243 Val = (uint32_t)I.getZExtValue();
244 return true;
245}
246
Aaron Ballmanfb763042013-12-02 18:05:46 +0000247/// \brief Diagnose mutually exclusive attributes when present on a given
248/// declaration. Returns true if diagnosed.
249template <typename AttrTy>
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000250static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
251 IdentifierInfo *Ident) {
Aaron Ballman2cfbc002014-01-03 16:23:46 +0000252 if (AttrTy *A = D->getAttr<AttrTy>()) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000253 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
254 << A;
255 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
Aaron Ballmanfb763042013-12-02 18:05:46 +0000256 return true;
257 }
258 return false;
259}
260
Alp Toker601b22c2014-01-21 23:35:24 +0000261/// \brief Check if IdxExpr is a valid parameter index for a function or
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000262/// instance method D. May output an error.
263///
264/// \returns true if IdxExpr is a valid index.
Alp Toker601b22c2014-01-21 23:35:24 +0000265static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
266 const AttributeList &Attr,
267 unsigned AttrArgNum,
268 const Expr *IdxExpr,
269 uint64_t &Idx) {
David Majnemer06864812015-04-07 06:01:53 +0000270 assert(isFunctionOrMethodOrBlock(D));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000271
272 // In C++ the implicit 'this' function parameter also counts.
273 // Parameters are counted from one.
Aaron Ballmanbe50eb82013-07-30 00:48:57 +0000274 bool HP = hasFunctionProto(D);
275 bool HasImplicitThisParam = isInstanceMethod(D);
276 bool IV = HP && isFunctionOrMethodVariadic(D);
Alp Toker601b22c2014-01-21 23:35:24 +0000277 unsigned NumParams =
278 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000279
280 llvm::APSInt IdxInt;
281 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
282 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000283 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
284 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
285 << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000286 return false;
287 }
288
289 Idx = IdxInt.getLimitedValue();
Alp Toker601b22c2014-01-21 23:35:24 +0000290 if (Idx < 1 || (!IV && Idx > NumParams)) {
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000291 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
292 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000293 return false;
294 }
295 Idx--; // Convert to zero-based.
296 if (HasImplicitThisParam) {
297 if (Idx == 0) {
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000298 S.Diag(Attr.getLoc(),
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000299 diag::err_attribute_invalid_implicit_this_argument)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000300 << Attr.getName() << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000301 return false;
302 }
303 --Idx;
304 }
305
306 return true;
307}
308
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000309/// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
310/// If not emit an error and return false. If the argument is an identifier it
311/// will emit an error with a fixit hint and treat it as if it was a string
312/// literal.
Tim Northover6a6b63b2013-10-01 14:34:18 +0000313bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
314 unsigned ArgNum, StringRef &Str,
Tim Northovera484bc02013-10-01 14:34:25 +0000315 SourceLocation *ArgLocation) {
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000316 // Look for identifiers. If we have one emit a hint to fix it to a literal.
317 if (Attr.isArgIdent(ArgNum)) {
318 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
Tim Northover6a6b63b2013-10-01 14:34:18 +0000319 Diag(Loc->Loc, diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000320 << Attr.getName() << AANT_ArgumentString
321 << FixItHint::CreateInsertion(Loc->Loc, "\"")
Craig Topper07fa1762015-11-15 02:31:46 +0000322 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000323 Str = Loc->Ident->getName();
324 if (ArgLocation)
325 *ArgLocation = Loc->Loc;
326 return true;
327 }
328
329 // Now check for an actual string literal.
330 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
331 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
332 if (ArgLocation)
333 *ArgLocation = ArgExpr->getLocStart();
334
335 if (!Literal || !Literal->isAscii()) {
Tim Northover6a6b63b2013-10-01 14:34:18 +0000336 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000337 << Attr.getName() << AANT_ArgumentString;
338 return false;
339 }
340
341 Str = Literal->getString();
342 return true;
343}
344
Aaron Ballman6f9165a2013-11-27 15:24:06 +0000345/// \brief Applies the given attribute to the Decl without performing any
346/// additional semantic checking.
347template <typename AttrType>
348static void handleSimpleAttribute(Sema &S, Decl *D,
349 const AttributeList &Attr) {
350 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
351 Attr.getAttributeSpellingListIndex()));
352}
353
Justin Lebar3eaaf862016-01-13 01:07:35 +0000354template <typename AttrType>
355static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
356 const AttributeList &Attr) {
357 handleSimpleAttribute<AttrType>(S, D, Attr);
358}
359
360/// \brief Applies the given attribute to the Decl so long as the Decl doesn't
361/// already have one of the given incompatible attributes.
362template <typename AttrType, typename IncompatibleAttrType,
363 typename... IncompatibleAttrTypes>
364static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
365 const AttributeList &Attr) {
366 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
367 Attr.getName()))
368 return;
369 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
370 Attr);
371}
372
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000373/// \brief Check if the passed-in expression is of type int or bool.
374static bool isIntOrBool(Expr *Exp) {
375 QualType QT = Exp->getType();
376 return QT->isBooleanType() || QT->isIntegerType();
377}
378
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000379
380// Check to see if the type is a smart pointer of some kind. We assume
381// it's a smart pointer if it defines both operator-> and operator*.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000382static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
Richard Smithcf4bdde2015-02-21 02:45:19 +0000383 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
384 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
David Blaikieff7d47a2012-12-19 00:45:41 +0000385 if (Res1.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000386 return false;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000387
Richard Smithcf4bdde2015-02-21 02:45:19 +0000388 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
389 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
David Blaikieff7d47a2012-12-19 00:45:41 +0000390 if (Res2.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000391 return false;
392
393 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000394}
395
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000396/// \brief Check if passed in Decl is a pointer type.
397/// Note that this function may produce an error message.
398/// \return true if the Decl is a pointer type; false otherwise
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000399static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
400 const AttributeList &Attr) {
Aaron Ballman553e6812013-12-26 14:54:11 +0000401 const ValueDecl *vd = cast<ValueDecl>(D);
402 QualType QT = vd->getType();
403 if (QT->isAnyPointerType())
404 return true;
405
406 if (const RecordType *RT = QT->getAs<RecordType>()) {
407 // If it's an incomplete type, it could be a smart pointer; skip it.
408 // (We don't want to force template instantiation if we can avoid it,
409 // since that would alter the order in which templates are instantiated.)
410 if (RT->isIncompleteType())
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000411 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000412
Aaron Ballman553e6812013-12-26 14:54:11 +0000413 if (threadSafetyCheckIsSmartPointer(S, RT))
414 return true;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000415 }
Aaron Ballman553e6812013-12-26 14:54:11 +0000416
417 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
Aaron Ballman68289452013-12-26 15:06:01 +0000418 << Attr.getName() << QT;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000419 return false;
420}
421
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000422/// \brief Checks that the passed in QualType either is of RecordType or points
423/// to RecordType. Returns the relevant RecordType, null if it does not exit.
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000424static const RecordType *getRecordType(QualType QT) {
425 if (const RecordType *RT = QT->getAs<RecordType>())
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000426 return RT;
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000427
428 // Now check if we point to record type.
429 if (const PointerType *PT = QT->getAs<PointerType>())
430 return PT->getPointeeType()->getAs<RecordType>();
431
Craig Topperc3ec1492014-05-26 06:22:03 +0000432 return nullptr;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000433}
434
Aaron Ballman76050722014-04-04 15:13:57 +0000435static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
DeLesley Hutchins481d5ab2012-04-06 20:02:30 +0000436 const RecordType *RT = getRecordType(Ty);
Michael Hana9171bc2012-08-03 17:40:43 +0000437
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000438 if (!RT)
439 return false;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000440
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000441 // Don't check for the capability if the class hasn't been defined yet.
DeLesley Hutchins3509f292012-02-16 17:15:51 +0000442 if (RT->isIncompleteType())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000443 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000444
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000445 // Allow smart pointers to be used as capability objects.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000446 // FIXME -- Check the type that the smart pointer points to.
447 if (threadSafetyCheckIsSmartPointer(S, RT))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000448 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000449
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000450 // Check if the record itself has a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000451 RecordDecl *RD = RT->getDecl();
Aaron Ballmanefe348e2014-02-18 17:36:50 +0000452 if (RD->hasAttr<CapabilityAttr>())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000453 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000454
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000455 // Else check if any base classes have a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000456 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
457 CXXBasePaths BPaths(false, false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000458 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
459 const auto *Type = BS->getType()->getAs<RecordType>();
460 return Type->getDecl()->hasAttr<CapabilityAttr>();
461 }, BPaths))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000462 return true;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000463 }
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000464 return false;
465}
466
Aaron Ballman76050722014-04-04 15:13:57 +0000467static bool checkTypedefTypeForCapability(QualType Ty) {
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000468 const auto *TD = Ty->getAs<TypedefType>();
469 if (!TD)
470 return false;
471
472 TypedefNameDecl *TN = TD->getDecl();
473 if (!TN)
474 return false;
475
476 return TN->hasAttr<CapabilityAttr>();
477}
478
Aaron Ballman76050722014-04-04 15:13:57 +0000479static bool typeHasCapability(Sema &S, QualType Ty) {
480 if (checkTypedefTypeForCapability(Ty))
481 return true;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000482
Aaron Ballman76050722014-04-04 15:13:57 +0000483 if (checkRecordTypeForCapability(S, Ty))
484 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000485
Aaron Ballman76050722014-04-04 15:13:57 +0000486 return false;
487}
488
489static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
490 // Capability expressions are simple expressions involving the boolean logic
491 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
492 // a DeclRefExpr is found, its type should be checked to determine whether it
493 // is a capability or not.
494
495 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
496 return typeHasCapability(S, E->getType());
497 else if (const auto *E = dyn_cast<CastExpr>(Ex))
498 return isCapabilityExpr(S, E->getSubExpr());
499 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
500 return isCapabilityExpr(S, E->getSubExpr());
501 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
502 if (E->getOpcode() == UO_LNot)
503 return isCapabilityExpr(S, E->getSubExpr());
504 return false;
505 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
506 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
507 return isCapabilityExpr(S, E->getLHS()) &&
508 isCapabilityExpr(S, E->getRHS());
509 return false;
510 }
511
512 return false;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000513}
514
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000515/// \brief Checks that all attribute arguments, starting from Sidx, resolve to
516/// a capability object.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000517/// \param Sidx The attribute argument index to start checking with.
518/// \param ParamIdxOk Whether an argument can be indexing into a function
519/// parameter list.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000520static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
521 const AttributeList &Attr,
522 SmallVectorImpl<Expr *> &Args,
523 int Sidx = 0,
524 bool ParamIdxOk = false) {
525 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
Aaron Ballman00e99962013-08-31 01:11:41 +0000526 Expr *ArgExp = Attr.getArgAsExpr(Idx);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000527
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000528 if (ArgExp->isTypeDependent()) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000529 // FIXME -- need to check this again on template instantiation
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000530 Args.push_back(ArgExp);
531 continue;
532 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000533
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000534 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000535 if (StrLit->getLength() == 0 ||
Benjamin Kramerca9fe142013-09-13 16:30:12 +0000536 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000537 // Pass empty strings to the analyzer without warnings.
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000538 // Treat "*" as the universal lock.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000539 Args.push_back(ArgExp);
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000540 continue;
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000541 }
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000542
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000543 // We allow constant strings to be used as a placeholder for expressions
544 // that are not valid C++ syntax, but warn that they are ignored.
545 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
546 Attr.getName();
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000547 Args.push_back(ArgExp);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000548 continue;
549 }
550
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000551 QualType ArgTy = ArgExp->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000552
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000553 // A pointer to member expression of the form &MyClass::mu is treated
554 // specially -- we need to look at the type of the member.
555 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
556 if (UOp->getOpcode() == UO_AddrOf)
557 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
558 if (DRE->getDecl()->isCXXInstanceMember())
559 ArgTy = DRE->getDecl()->getType();
560
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000561 // First see if we can just cast to record type, or pointer to record type.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000562 const RecordType *RT = getRecordType(ArgTy);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000563
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000564 // Now check if we index into a record type function param.
565 if(!RT && ParamIdxOk) {
566 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000567 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
568 if(FD && IL) {
569 unsigned int NumParams = FD->getNumParams();
570 llvm::APInt ArgValue = IL->getValue();
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000571 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
572 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
573 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000574 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
575 << Attr.getName() << Idx + 1 << NumParams;
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000576 continue;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000577 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000578 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000579 }
580 }
581
Aaron Ballman76050722014-04-04 15:13:57 +0000582 // If the type does not have a capability, see if the components of the
583 // expression have capabilities. This allows for writing C code where the
584 // capability may be on the type, and the expression is a capability
585 // boolean logic expression. Eg) requires_capability(A || B && !C)
586 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
587 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
588 << Attr.getName() << ArgTy;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000589
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000590 Args.push_back(ArgExp);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000591 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000592}
593
Chris Lattner58418ff2008-06-29 00:16:31 +0000594//===----------------------------------------------------------------------===//
Chris Lattner58418ff2008-06-29 00:16:31 +0000595// Attribute Implementations
596//===----------------------------------------------------------------------===//
597
Michael Hana9171bc2012-08-03 17:40:43 +0000598static void handlePtGuardedVarAttr(Sema &S, Decl *D,
Michael Han99315932013-01-24 16:46:58 +0000599 const AttributeList &Attr) {
Michael Han3be3b442012-07-23 18:48:41 +0000600 if (!threadSafetyCheckIsPointer(S, D, Attr))
601 return;
602
Michael Han99315932013-01-24 16:46:58 +0000603 D->addAttr(::new (S.Context)
604 PtGuardedVarAttr(Attr.getRange(), S.Context,
605 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000606}
607
Michael Hana9171bc2012-08-03 17:40:43 +0000608static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
609 const AttributeList &Attr,
Michael Han3be3b442012-07-23 18:48:41 +0000610 Expr* &Arg) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000611 SmallVector<Expr*, 1> Args;
612 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000613 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000614 unsigned Size = Args.size();
615 if (Size != 1)
Michael Han3be3b442012-07-23 18:48:41 +0000616 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000617
Michael Han3be3b442012-07-23 18:48:41 +0000618 Arg = Args[0];
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000619
Michael Han3be3b442012-07-23 18:48:41 +0000620 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000621}
622
Michael Han3be3b442012-07-23 18:48:41 +0000623static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000624 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000625 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
626 return;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000627
Aaron Ballman36a53502014-01-16 13:03:14 +0000628 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
629 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000630}
631
Michael Hana9171bc2012-08-03 17:40:43 +0000632static void handlePtGuardedByAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000633 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000634 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000635 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
636 return;
637
638 if (!threadSafetyCheckIsPointer(S, D, Attr))
639 return;
640
641 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +0000642 S.Context, Arg,
643 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000644}
645
Michael Hana9171bc2012-08-03 17:40:43 +0000646static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
647 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000648 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000649 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000650 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000651
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000652 // Check that this attribute only applies to lockable types.
Aaron Ballmane61b8b82013-12-02 15:02:49 +0000653 QualType QT = cast<ValueDecl>(D)->getType();
DeLesley Hutchins2b504dc2015-09-29 16:24:18 +0000654 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
655 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
656 << Attr.getName();
657 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000658 }
659
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000660 // Check that all arguments are lockable objects.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000661 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000662 if (Args.empty())
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 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000666}
667
Michael Hana9171bc2012-08-03 17:40:43 +0000668static void handleAcquiredAfterAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000669 const AttributeList &Attr) {
670 SmallVector<Expr*, 1> Args;
671 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
672 return;
673
674 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000675 D->addAttr(::new (S.Context)
676 AcquiredAfterAttr(Attr.getRange(), S.Context,
677 StartArg, Args.size(),
678 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000679}
680
Michael Hana9171bc2012-08-03 17:40:43 +0000681static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000682 const AttributeList &Attr) {
683 SmallVector<Expr*, 1> Args;
684 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
685 return;
686
687 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000688 D->addAttr(::new (S.Context)
689 AcquiredBeforeAttr(Attr.getRange(), S.Context,
690 StartArg, Args.size(),
691 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000692}
693
Michael Hana9171bc2012-08-03 17:40:43 +0000694static bool checkLockFunAttrCommon(Sema &S, Decl *D,
695 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000696 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000697 // zero or more arguments ok
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000698 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000699 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000700
Michael Han3be3b442012-07-23 18:48:41 +0000701 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000702}
703
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000704static void handleAssertSharedLockAttr(Sema &S, Decl *D,
705 const AttributeList &Attr) {
706 SmallVector<Expr*, 1> Args;
707 if (!checkLockFunAttrCommon(S, D, Attr, Args))
708 return;
709
710 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000711 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000712 D->addAttr(::new (S.Context)
713 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
714 Attr.getAttributeSpellingListIndex()));
715}
716
717static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
718 const AttributeList &Attr) {
719 SmallVector<Expr*, 1> Args;
720 if (!checkLockFunAttrCommon(S, D, Attr, Args))
721 return;
722
723 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000724 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000725 D->addAttr(::new (S.Context)
726 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
727 StartArg, Size,
728 Attr.getAttributeSpellingListIndex()));
729}
730
731
Michael Hana9171bc2012-08-03 17:40:43 +0000732static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
733 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000734 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000735 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000736 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000737
Aaron Ballman00e99962013-08-31 01:11:41 +0000738 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
Aaron Ballman29982272013-07-23 14:03:57 +0000739 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +0000740 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
Michael Han3be3b442012-07-23 18:48:41 +0000741 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000742 }
743
744 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000745 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000746
Michael Han3be3b442012-07-23 18:48:41 +0000747 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000748}
749
Michael Hana9171bc2012-08-03 17:40:43 +0000750static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000751 const AttributeList &Attr) {
752 SmallVector<Expr*, 2> Args;
753 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
754 return;
755
Michael Han99315932013-01-24 16:46:58 +0000756 D->addAttr(::new (S.Context)
757 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
Aaron Ballman00e99962013-08-31 01:11:41 +0000758 Attr.getArgAsExpr(0),
759 Args.data(), Args.size(),
Michael Han99315932013-01-24 16:46:58 +0000760 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000761}
762
Michael Hana9171bc2012-08-03 17:40:43 +0000763static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000764 const AttributeList &Attr) {
765 SmallVector<Expr*, 2> Args;
766 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
767 return;
768
Nico Weber462fd1e2015-01-07 23:50:05 +0000769 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
770 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
771 Args.size(), Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000772}
773
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000774static void handleLockReturnedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000775 const AttributeList &Attr) {
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000776 // check that the argument is lockable object
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000777 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000778 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000779 unsigned Size = Args.size();
780 if (Size == 0)
781 return;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000782
Michael Han99315932013-01-24 16:46:58 +0000783 D->addAttr(::new (S.Context)
784 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
785 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000786}
787
788static void handleLocksExcludedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000789 const AttributeList &Attr) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000790 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000791 return;
792
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000793 // check that all arguments are lockable objects
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000794 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000795 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000796 unsigned Size = Args.size();
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000797 if (Size == 0)
798 return;
799 Expr **StartArg = &Args[0];
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000800
Michael Han99315932013-01-24 16:46:58 +0000801 D->addAttr(::new (S.Context)
802 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
803 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000804}
805
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000806static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Saleem Abdulrasool046ba5b2016-02-18 06:49:31 +0000807 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
808
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000809 Expr *Cond = Attr.getArgAsExpr(0);
810 if (!Cond->isTypeDependent()) {
811 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
812 if (Converted.isInvalid())
813 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000814 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000815 }
816
817 StringRef Msg;
818 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
819 return;
820
821 SmallVector<PartialDiagnosticAt, 8> Diags;
822 if (!Cond->isValueDependent() &&
823 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
824 Diags)) {
825 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
826 for (int I = 0, N = Diags.size(); I != N; ++I)
827 S.Diag(Diags[I].first, Diags[I].second);
828 return;
829 }
830
831 D->addAttr(::new (S.Context)
832 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
833 Attr.getAttributeSpellingListIndex()));
834}
835
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000836static void handlePassObjectSizeAttr(Sema &S, Decl *D,
837 const AttributeList &Attr) {
838 if (D->hasAttr<PassObjectSizeAttr>()) {
839 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
840 << Attr.getName();
841 return;
842 }
843
844 Expr *E = Attr.getArgAsExpr(0);
845 uint32_t Type;
846 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
847 return;
848
849 // pass_object_size's argument is passed in as the second argument of
850 // __builtin_object_size. So, it has the same constraints as that second
851 // argument; namely, it must be in the range [0, 3].
852 if (Type > 3) {
853 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
854 << Attr.getName() << 0 << 3 << E->getSourceRange();
855 return;
856 }
857
858 // pass_object_size is only supported on constant pointer parameters; as a
859 // kindness to users, we allow the parameter to be non-const for declarations.
860 // At this point, we have no clue if `D` belongs to a function declaration or
861 // definition, so we defer the constness check until later.
862 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
863 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
864 << Attr.getName() << 1;
865 return;
866 }
867
868 D->addAttr(::new (S.Context)
869 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
870 Attr.getAttributeSpellingListIndex()));
871}
872
DeLesley Hutchins5a715c42013-08-30 22:56:34 +0000873static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
David Blaikie16f76d22013-09-06 01:28:43 +0000874 ConsumableAttr::ConsumedState DefaultState;
875
876 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +0000877 IdentifierLoc *IL = Attr.getArgAsIdent(0);
878 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
879 DefaultState)) {
880 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
881 << Attr.getName() << IL->Ident;
David Blaikie16f76d22013-09-06 01:28:43 +0000882 return;
883 }
David Blaikie16f76d22013-09-06 01:28:43 +0000884 } else {
885 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
886 << Attr.getName() << AANT_ArgumentIdentifier;
887 return;
888 }
DeLesley Hutchins48a31762013-08-12 21:20:55 +0000889
890 D->addAttr(::new (S.Context)
David Blaikie16f76d22013-09-06 01:28:43 +0000891 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
DeLesley Hutchins5a715c42013-08-30 22:56:34 +0000892 Attr.getAttributeSpellingListIndex()));
893}
894
895static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
896 const AttributeList &Attr) {
897 ASTContext &CurrContext = S.getASTContext();
898 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
899
900 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
901 if (!RD->hasAttr<ConsumableAttr>()) {
902 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
903 RD->getNameAsString();
904
905 return false;
906 }
907 }
908
909 return true;
910}
911
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000912static void handleCallableWhenAttr(Sema &S, Decl *D,
913 const AttributeList &Attr) {
Aaron Ballmandbd586f2013-10-14 23:26:04 +0000914 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
915 return;
DeLesley Hutchins48a31762013-08-12 21:20:55 +0000916
DeLesley Hutchins5a715c42013-08-30 22:56:34 +0000917 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
918 return;
919
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000920 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
921 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
922 CallableWhenAttr::ConsumedState CallableState;
923
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +0000924 StringRef StateString;
925 SourceLocation Loc;
Aaron Ballman55ef1512014-12-19 16:42:04 +0000926 if (Attr.isArgIdent(ArgIndex)) {
927 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
928 StateString = Ident->Ident->getName();
929 Loc = Ident->Loc;
930 } else {
931 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
932 return;
933 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +0000934
935 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
DeLesley Hutchins69391772013-10-17 23:23:53 +0000936 CallableState)) {
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +0000937 S.Diag(Loc, diag::warn_attribute_type_not_supported)
938 << Attr.getName() << StateString;
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000939 return;
940 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +0000941
942 States.push_back(CallableState);
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000943 }
944
DeLesley Hutchins48a31762013-08-12 21:20:55 +0000945 D->addAttr(::new (S.Context)
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000946 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
947 States.size(), Attr.getAttributeSpellingListIndex()));
DeLesley Hutchins48a31762013-08-12 21:20:55 +0000948}
949
DeLesley Hutchins69391772013-10-17 23:23:53 +0000950static void handleParamTypestateAttr(Sema &S, Decl *D,
951 const AttributeList &Attr) {
DeLesley Hutchins69391772013-10-17 23:23:53 +0000952 ParamTypestateAttr::ConsumedState ParamState;
953
954 if (Attr.isArgIdent(0)) {
955 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
956 StringRef StateString = Ident->Ident->getName();
957
958 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
959 ParamState)) {
960 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
961 << Attr.getName() << StateString;
962 return;
963 }
964 } else {
965 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
966 Attr.getName() << AANT_ArgumentIdentifier;
967 return;
968 }
969
970 // FIXME: This check is currently being done in the analysis. It can be
971 // enabled here only after the parser propagates attributes at
972 // template specialization definition, not declaration.
973 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
974 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
975 //
976 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
977 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
978 // ReturnType.getAsString();
979 // return;
980 //}
981
982 D->addAttr(::new (S.Context)
983 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
984 Attr.getAttributeSpellingListIndex()));
985}
986
DeLesley Hutchinsfc368252013-09-03 20:11:38 +0000987static void handleReturnTypestateAttr(Sema &S, Decl *D,
988 const AttributeList &Attr) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +0000989 ReturnTypestateAttr::ConsumedState ReturnState;
990
991 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +0000992 IdentifierLoc *IL = Attr.getArgAsIdent(0);
993 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
994 ReturnState)) {
995 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
996 << Attr.getName() << IL->Ident;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +0000997 return;
998 }
DeLesley Hutchinsfc368252013-09-03 20:11:38 +0000999 } else {
1000 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1001 Attr.getName() << AANT_ArgumentIdentifier;
1002 return;
1003 }
1004
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001005 // FIXME: This check is currently being done in the analysis. It can be
1006 // enabled here only after the parser propagates attributes at
1007 // template specialization definition, not declaration.
1008 //QualType ReturnType;
1009 //
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001010 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1011 // ReturnType = Param->getType();
1012 //
1013 //} else if (const CXXConstructorDecl *Constructor =
1014 // dyn_cast<CXXConstructorDecl>(D)) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001015 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1016 //
1017 //} else {
1018 //
1019 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1020 //}
1021 //
1022 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1023 //
1024 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1025 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1026 // ReturnType.getAsString();
1027 // return;
1028 //}
1029
1030 D->addAttr(::new (S.Context)
1031 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1032 Attr.getAttributeSpellingListIndex()));
1033}
1034
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001035static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001036 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1037 return;
1038
1039 SetTypestateAttr::ConsumedState NewState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001040 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001041 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1042 StringRef Param = Ident->Ident->getName();
1043 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1044 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1045 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001046 return;
1047 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001048 } else {
1049 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1050 Attr.getName() << AANT_ArgumentIdentifier;
1051 return;
1052 }
1053
1054 D->addAttr(::new (S.Context)
1055 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1056 Attr.getAttributeSpellingListIndex()));
1057}
1058
Chris Wailes9385f9f2013-10-29 20:28:41 +00001059static void handleTestTypestateAttr(Sema &S, Decl *D,
1060 const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001061 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1062 return;
1063
Chris Wailes9385f9f2013-10-29 20:28:41 +00001064 TestTypestateAttr::ConsumedState TestState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001065 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001066 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1067 StringRef Param = Ident->Ident->getName();
Chris Wailes9385f9f2013-10-29 20:28:41 +00001068 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001069 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1070 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001071 return;
1072 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001073 } else {
1074 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1075 Attr.getName() << AANT_ArgumentIdentifier;
1076 return;
1077 }
1078
1079 D->addAttr(::new (S.Context)
Chris Wailes9385f9f2013-10-29 20:28:41 +00001080 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001081 Attr.getAttributeSpellingListIndex()));
1082}
1083
Chandler Carruthedc2c642011-07-02 00:01:44 +00001084static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1085 const AttributeList &Attr) {
Richard Smith1f5a4322013-01-13 02:11:23 +00001086 // Remember this typedef decl, we will need it later for diagnostics.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00001087 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001088}
1089
Chandler Carruthedc2c642011-07-02 00:01:44 +00001090static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001091 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Aaron Ballman36a53502014-01-16 13:03:14 +00001092 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1093 Attr.getAttributeSpellingListIndex()));
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001094 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001095 // Report warning about changed offset in the newer compiler versions.
Eli Friedmanc087c3f2012-11-07 00:35:20 +00001096 if (!FD->getType()->isDependentType() &&
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001097 !FD->getType()->isIncompleteType() && FD->isBitField() &&
Chris Lattnerb632a6e2008-06-29 00:43:07 +00001098 S.Context.getTypeAlign(FD->getType()) <= 8)
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001099 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1100
1101 FD->addAttr(::new (S.Context) PackedAttr(
1102 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001103 } else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001104 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001105}
1106
Ted Kremenek7fd17232011-09-29 07:02:25 +00001107static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1108 // The IBOutlet/IBOutletCollection attributes only apply to instance
1109 // variables or properties of Objective-C classes. The outlet must also
1110 // have an object reference type.
1111 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1112 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
Ted Kremenek5d6044e2011-11-01 18:08:35 +00001113 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001114 << Attr.getName() << VD->getType() << 0;
1115 return false;
1116 }
1117 }
1118 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1119 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001120 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001121 << Attr.getName() << PD->getType() << 1;
1122 return false;
1123 }
1124 }
1125 else {
1126 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1127 return false;
1128 }
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001129
Ted Kremenek7fd17232011-09-29 07:02:25 +00001130 return true;
1131}
1132
Chandler Carruthedc2c642011-07-02 00:01:44 +00001133static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
Ted Kremenek7fd17232011-09-29 07:02:25 +00001134 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek1f672822010-02-18 03:08:58 +00001135 return;
Ted Kremenek1f672822010-02-18 03:08:58 +00001136
Michael Han99315932013-01-24 16:46:58 +00001137 D->addAttr(::new (S.Context)
1138 IBOutletAttr(Attr.getRange(), S.Context,
1139 Attr.getAttributeSpellingListIndex()));
Ted Kremenek8e3704d2008-07-15 22:26:48 +00001140}
1141
Chandler Carruthedc2c642011-07-02 00:01:44 +00001142static void handleIBOutletCollection(Sema &S, Decl *D,
1143 const AttributeList &Attr) {
Ted Kremenek26bde772010-05-19 17:38:06 +00001144
1145 // The iboutletcollection attribute can have zero or one arguments.
Aaron Ballman00e99962013-08-31 01:11:41 +00001146 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001147 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1148 << Attr.getName() << 1;
Ted Kremenek26bde772010-05-19 17:38:06 +00001149 return;
1150 }
1151
Ted Kremenek7fd17232011-09-29 07:02:25 +00001152 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek26bde772010-05-19 17:38:06 +00001153 return;
Ted Kremenek7fd17232011-09-29 07:02:25 +00001154
Richard Smithb1f9a282013-10-31 01:56:18 +00001155 ParsedType PT;
1156
1157 if (Attr.hasParsedType())
1158 PT = Attr.getTypeArg();
1159 else {
1160 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1161 S.getScopeForContext(D->getDeclContext()->getParent()));
1162 if (!PT) {
1163 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1164 return;
1165 }
Aaron Ballman00e99962013-08-31 01:11:41 +00001166 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001167
Craig Topperc3ec1492014-05-26 06:22:03 +00001168 TypeSourceInfo *QTLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00001169 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1170 if (!QTLoc)
1171 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
Richard Smithb1f9a282013-10-31 01:56:18 +00001172
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001173 // Diagnose use of non-object type in iboutletcollection attribute.
1174 // FIXME. Gnu attribute extension ignores use of builtin types in
1175 // attributes. So, __attribute__((iboutletcollection(char))) will be
1176 // treated as __attribute__((iboutletcollection())).
Fariborz Jahanian2f31b332011-10-18 19:54:31 +00001177 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
Richard Smithb1f9a282013-10-31 01:56:18 +00001178 S.Diag(Attr.getLoc(),
1179 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1180 : diag::err_iboutletcollection_type) << QT;
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001181 return;
1182 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001183
Michael Han99315932013-01-24 16:46:58 +00001184 D->addAttr(::new (S.Context)
Richard Smithb87c4652013-10-31 21:23:20 +00001185 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
Michael Han99315932013-01-24 16:46:58 +00001186 Attr.getAttributeSpellingListIndex()));
Ted Kremenek26bde772010-05-19 17:38:06 +00001187}
1188
Hal Finkelee90a222014-09-26 05:04:30 +00001189bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1190 if (RefOkay) {
1191 if (T->isReferenceType())
1192 return true;
1193 } else {
1194 T = T.getNonReferenceType();
1195 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001196
Hal Finkelee90a222014-09-26 05:04:30 +00001197 // The nonnull attribute, and other similar attributes, can be applied to a
1198 // transparent union that contains a pointer type.
Richard Smith588bd9b2014-08-27 04:59:42 +00001199 if (const RecordType *UT = T->getAsUnionType()) {
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001200 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1201 RecordDecl *UD = UT->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001202 for (const auto *I : UD->fields()) {
1203 QualType QT = I->getType();
Richard Smith588bd9b2014-08-27 04:59:42 +00001204 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1205 return true;
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001206 }
1207 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001208 }
1209
1210 return T->isAnyPointerType() || T->isBlockPointerType();
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001211}
1212
Ted Kremenek9aedc152014-01-17 06:24:56 +00001213static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001214 SourceRange AttrParmRange,
Hal Finkelee90a222014-09-26 05:04:30 +00001215 SourceRange TypeRange,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001216 bool isReturnValue = false) {
Hal Finkelee90a222014-09-26 05:04:30 +00001217 if (!S.isValidPointerAttrType(T)) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001218 if (isReturnValue)
1219 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1220 << Attr.getName() << AttrParmRange << TypeRange;
1221 else
1222 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1223 << Attr.getName() << AttrParmRange << TypeRange << 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001224 return false;
1225 }
1226 return true;
1227}
1228
Chandler Carruthedc2c642011-07-02 00:01:44 +00001229static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001230 SmallVector<unsigned, 8> NonNullArgs;
Richard Smith588bd9b2014-08-27 04:59:42 +00001231 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1232 Expr *Ex = Attr.getArgAsExpr(I);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001233 uint64_t Idx;
Richard Smith588bd9b2014-08-27 04:59:42 +00001234 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001235 return;
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001236
1237 // Is the function argument a pointer type?
Richard Smith588bd9b2014-08-27 04:59:42 +00001238 if (Idx < getFunctionOrMethodNumParams(D) &&
1239 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001240 Ex->getSourceRange(),
1241 getFunctionOrMethodParamRange(D, Idx)))
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001242 continue;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001243
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001244 NonNullArgs.push_back(Idx);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001245 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001246
1247 // If no arguments were specified to __attribute__((nonnull)) then all pointer
Richard Smith588bd9b2014-08-27 04:59:42 +00001248 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1249 // check if the attribute came from a macro expansion or a template
1250 // instantiation.
1251 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1252 S.ActiveTemplateInstantiations.empty()) {
1253 bool AnyPointers = isFunctionOrMethodVariadic(D);
1254 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1255 I != E && !AnyPointers; ++I) {
1256 QualType T = getFunctionOrMethodParamType(D, I);
Hal Finkelee90a222014-09-26 05:04:30 +00001257 if (T->isDependentType() || S.isValidPointerAttrType(T))
Richard Smith588bd9b2014-08-27 04:59:42 +00001258 AnyPointers = true;
Ted Kremenek5fa50522008-11-18 06:52:58 +00001259 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001260
Richard Smith588bd9b2014-08-27 04:59:42 +00001261 if (!AnyPointers)
1262 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001263 }
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001264
Richard Smith588bd9b2014-08-27 04:59:42 +00001265 unsigned *Start = NonNullArgs.data();
1266 unsigned Size = NonNullArgs.size();
1267 llvm::array_pod_sort(Start, Start + Size);
Michael Han99315932013-01-24 16:46:58 +00001268 D->addAttr(::new (S.Context)
Richard Smith588bd9b2014-08-27 04:59:42 +00001269 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
Michael Han99315932013-01-24 16:46:58 +00001270 Attr.getAttributeSpellingListIndex()));
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001271}
1272
Jordan Rosec9399072014-02-11 17:27:59 +00001273static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1274 const AttributeList &Attr) {
1275 if (Attr.getNumArgs() > 0) {
1276 if (D->getFunctionType()) {
1277 handleNonNullAttr(S, D, Attr);
1278 } else {
1279 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1280 << D->getSourceRange();
1281 }
1282 return;
1283 }
1284
1285 // Is the argument a pointer type?
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001286 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1287 D->getSourceRange()))
Jordan Rosec9399072014-02-11 17:27:59 +00001288 return;
1289
1290 D->addAttr(::new (S.Context)
Craig Topperc3ec1492014-05-26 06:22:03 +00001291 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
Jordan Rosec9399072014-02-11 17:27:59 +00001292 Attr.getAttributeSpellingListIndex()));
1293}
1294
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001295static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1296 const AttributeList &Attr) {
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00001297 QualType ResultType = getFunctionOrMethodResultType(D);
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001298 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1299 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001300 /* isReturnValue */ true))
1301 return;
1302
1303 D->addAttr(::new (S.Context)
1304 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1305 Attr.getAttributeSpellingListIndex()));
1306}
1307
Hal Finkelee90a222014-09-26 05:04:30 +00001308static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1309 const AttributeList &Attr) {
1310 Expr *E = Attr.getArgAsExpr(0),
1311 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1312 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1313 Attr.getAttributeSpellingListIndex());
1314}
1315
1316void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1317 Expr *OE, unsigned SpellingListIndex) {
1318 QualType ResultType = getFunctionOrMethodResultType(D);
1319 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1320
1321 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1322 SourceLocation AttrLoc = AttrRange.getBegin();
1323
1324 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1325 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1326 << &TmpAttr << AttrRange << SR;
1327 return;
1328 }
1329
1330 if (!E->isValueDependent()) {
1331 llvm::APSInt I(64);
1332 if (!E->isIntegerConstantExpr(I, Context)) {
1333 if (OE)
1334 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1335 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1336 << E->getSourceRange();
1337 else
1338 Diag(AttrLoc, diag::err_attribute_argument_type)
1339 << &TmpAttr << AANT_ArgumentIntegerConstant
1340 << E->getSourceRange();
1341 return;
1342 }
1343
1344 if (!I.isPowerOf2()) {
1345 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1346 << E->getSourceRange();
1347 return;
1348 }
1349 }
1350
1351 if (OE) {
1352 if (!OE->isValueDependent()) {
1353 llvm::APSInt I(64);
1354 if (!OE->isIntegerConstantExpr(I, Context)) {
1355 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1356 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1357 << OE->getSourceRange();
1358 return;
1359 }
1360 }
1361 }
1362
1363 D->addAttr(::new (Context)
1364 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1365}
1366
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001367/// Normalize the attribute, __foo__ becomes foo.
1368/// Returns true if normalization was applied.
1369static bool normalizeName(StringRef &AttrName) {
Aaron Ballman62692362015-10-09 13:53:24 +00001370 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1371 AttrName.endswith("__")) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001372 AttrName = AttrName.drop_front(2).drop_back(2);
1373 return true;
1374 }
1375 return false;
1376}
1377
Chandler Carruthedc2c642011-07-02 00:01:44 +00001378static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001379 // This attribute must be applied to a function declaration. The first
1380 // argument to the attribute must be an identifier, the name of the resource,
1381 // for example: malloc. The following arguments must be argument indexes, the
1382 // arguments must be of integer type for Returns, otherwise of pointer type.
Ted Kremenekd21139a2010-07-31 01:52:11 +00001383 // The difference between Holds and Takes is that a pointer may still be used
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001384 // after being held. free() should be __attribute((ownership_takes)), whereas
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001385 // a list append function may well be __attribute((ownership_holds)).
Ted Kremenekd21139a2010-07-31 01:52:11 +00001386
Aaron Ballman00e99962013-08-31 01:11:41 +00001387 if (!AL.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00001388 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001389 << AL.getName() << 1 << AANT_ArgumentIdentifier;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001390 return;
1391 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001392
Richard Smith852e9ce2013-11-27 01:46:48 +00001393 // Figure out our Kind.
1394 OwnershipAttr::OwnershipKind K =
Craig Topperc3ec1492014-05-26 06:22:03 +00001395 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
Richard Smith852e9ce2013-11-27 01:46:48 +00001396 AL.getAttributeSpellingListIndex()).getOwnKind();
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001397
Richard Smith852e9ce2013-11-27 01:46:48 +00001398 // Check arguments.
1399 switch (K) {
1400 case OwnershipAttr::Takes:
1401 case OwnershipAttr::Holds:
1402 if (AL.getNumArgs() < 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001403 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1404 << AL.getName() << 2;
Richard Smith852e9ce2013-11-27 01:46:48 +00001405 return;
1406 }
1407 break;
1408 case OwnershipAttr::Returns:
Aaron Ballman00e99962013-08-31 01:11:41 +00001409 if (AL.getNumArgs() > 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001410 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1411 << AL.getName() << 1;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001412 return;
1413 }
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001414 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001415 }
1416
Richard Smith852e9ce2013-11-27 01:46:48 +00001417 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001418
Richard Smith852e9ce2013-11-27 01:46:48 +00001419 StringRef ModuleName = Module->getName();
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001420 if (normalizeName(ModuleName)) {
Richard Smith852e9ce2013-11-27 01:46:48 +00001421 Module = &S.PP.getIdentifierTable().get(ModuleName);
1422 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001423
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001424 SmallVector<unsigned, 8> OwnershipArgs;
Aaron Ballman00e99962013-08-31 01:11:41 +00001425 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1426 Expr *Ex = AL.getArgAsExpr(i);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001427 uint64_t Idx;
Alp Toker601b22c2014-01-21 23:35:24 +00001428 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001429 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00001430
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001431 // Is the function argument a pointer type?
Alp Toker601b22c2014-01-21 23:35:24 +00001432 QualType T = getFunctionOrMethodParamType(D, Idx);
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001433 int Err = -1; // No error
Ted Kremenekd21139a2010-07-31 01:52:11 +00001434 switch (K) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001435 case OwnershipAttr::Takes:
1436 case OwnershipAttr::Holds:
1437 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1438 Err = 0;
1439 break;
1440 case OwnershipAttr::Returns:
1441 if (!T->isIntegerType())
1442 Err = 1;
1443 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001444 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001445 if (-1 != Err) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00001446 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001447 << Ex->getSourceRange();
1448 return;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001449 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001450
1451 // Check we don't have a conflict with another ownership attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001452 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001453 // Cannot have two ownership attributes of different kinds for the same
1454 // index.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001455 if (I->getOwnKind() != K && I->args_end() !=
1456 std::find(I->args_begin(), I->args_end(), Idx)) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001457 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001458 << AL.getName() << I;
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001459 return;
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001460 } else if (K == OwnershipAttr::Returns &&
1461 I->getOwnKind() == OwnershipAttr::Returns) {
1462 // A returns attribute conflicts with any other returns attribute using
1463 // a different index. Note, diagnostic reporting is 1-based, but stored
1464 // argument indexes are 0-based.
1465 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1466 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1467 << *(I->args_begin()) + 1;
1468 if (I->args_size())
1469 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1470 << (unsigned)Idx + 1 << Ex->getSourceRange();
1471 return;
1472 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001473 }
1474 }
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001475 OwnershipArgs.push_back(Idx);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001476 }
1477
1478 unsigned* start = OwnershipArgs.data();
1479 unsigned size = OwnershipArgs.size();
1480 llvm::array_pod_sort(start, start + size);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001481
Michael Han99315932013-01-24 16:46:58 +00001482 D->addAttr(::new (S.Context)
Richard Smith852e9ce2013-11-27 01:46:48 +00001483 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
Michael Han99315932013-01-24 16:46:58 +00001484 AL.getAttributeSpellingListIndex()));
Ted Kremenekd21139a2010-07-31 01:52:11 +00001485}
1486
Chandler Carruthedc2c642011-07-02 00:01:44 +00001487static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Rafael Espindolac18086a2010-02-23 22:00:30 +00001488 // Check the attribute arguments.
1489 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001490 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1491 << Attr.getName() << 1;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001492 return;
1493 }
1494
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001495 NamedDecl *nd = cast<NamedDecl>(D);
John McCall7a198ce2011-02-08 22:35:49 +00001496
Rafael Espindolac18086a2010-02-23 22:00:30 +00001497 // gcc rejects
1498 // class c {
1499 // static int a __attribute__((weakref ("v2")));
1500 // static int b() __attribute__((weakref ("f3")));
1501 // };
1502 // and ignores the attributes of
1503 // void f(void) {
1504 // static int a __attribute__((weakref ("v2")));
1505 // }
1506 // we reject them
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001507 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
Sebastian Redl50c68252010-08-31 00:36:30 +00001508 if (!Ctx->isFileContext()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00001509 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1510 << nd;
Sebastian Redl50c68252010-08-31 00:36:30 +00001511 return;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001512 }
1513
1514 // The GCC manual says
1515 //
1516 // At present, a declaration to which `weakref' is attached can only
1517 // be `static'.
1518 //
1519 // It also says
1520 //
1521 // Without a TARGET,
1522 // given as an argument to `weakref' or to `alias', `weakref' is
1523 // equivalent to `weak'.
1524 //
1525 // gcc 4.4.1 will accept
1526 // int a7 __attribute__((weakref));
1527 // as
1528 // int a7 __attribute__((weak));
1529 // This looks like a bug in gcc. We reject that for now. We should revisit
1530 // it if this behaviour is actually used.
1531
Rafael Espindolac18086a2010-02-23 22:00:30 +00001532 // GCC rejects
1533 // static ((alias ("y"), weakref)).
1534 // Should we? How to check that weakref is before or after alias?
1535
Aaron Ballmanfebff0c2013-09-09 23:40:31 +00001536 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1537 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1538 // StringRef parameter it was given anyway.
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001539 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001540 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Rafael Espindolac18086a2010-02-23 22:00:30 +00001541 // GCC will accept anything as the argument of weakref. Should we
1542 // check for an existing decl?
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001543 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1544 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001545
Michael Han99315932013-01-24 16:46:58 +00001546 D->addAttr(::new (S.Context)
1547 WeakRefAttr(Attr.getRange(), S.Context,
1548 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001549}
1550
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001551static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1552 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001553 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001554 return;
1555
Douglas Gregore8bbc122011-09-02 00:18:52 +00001556 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001557 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1558 return;
1559 }
Justin Lebara8f0254b2016-01-23 21:28:10 +00001560 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1561 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1562 }
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001563
David Majnemer2dc81462015-01-19 09:00:28 +00001564 // Aliases should be on declarations, not definitions.
1565 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1566 if (FD->isThisDeclarationADefinition()) {
1567 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD;
1568 return;
1569 }
1570 } else {
1571 const auto *VD = cast<VarDecl>(D);
1572 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1573 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD;
1574 return;
1575 }
1576 }
1577
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001578 // FIXME: check if target symbol exists in current file
Mike Stumpd3bb5572009-07-24 19:02:52 +00001579
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001580 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00001581 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001582}
1583
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001584static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001585 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001586 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001587
Michael Han99315932013-01-24 16:46:58 +00001588 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1589 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001590}
1591
1592static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001593 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001594 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001595
Michael Han99315932013-01-24 16:46:58 +00001596 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1597 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001598}
1599
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001600static void handleTLSModelAttr(Sema &S, Decl *D,
1601 const AttributeList &Attr) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001602 StringRef Model;
1603 SourceLocation LiteralLoc;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001604 // Check that it is a string.
Tim Northover6a6b63b2013-10-01 14:34:18 +00001605 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001606 return;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001607
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001608 // Check that the value.
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001609 if (Model != "global-dynamic" && Model != "local-dynamic"
1610 && Model != "initial-exec" && Model != "local-exec") {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001611 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001612 return;
1613 }
1614
Michael Han99315932013-01-24 16:46:58 +00001615 D->addAttr(::new (S.Context)
1616 TLSModelAttr(Attr.getRange(), S.Context, Model,
1617 Attr.getAttributeSpellingListIndex()));
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001618}
1619
David Majnemer631a90b2015-02-04 07:23:21 +00001620static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1621 QualType ResultType = getFunctionOrMethodResultType(D);
1622 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1623 D->addAttr(::new (S.Context) RestrictAttr(
1624 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1625 return;
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001626 }
1627
David Majnemer631a90b2015-02-04 07:23:21 +00001628 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1629 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001630}
1631
Chandler Carruthedc2c642011-07-02 00:01:44 +00001632static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001633 if (S.LangOpts.CPlusPlus) {
Aaron Ballman3db89662013-11-24 21:48:06 +00001634 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001635 << Attr.getName() << AttributeLangSupport::Cpp;
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001636 return;
1637 }
1638
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001639 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1640 Attr.getAttributeSpellingListIndex()))
1641 D->addAttr(CA);
Eric Christopher8a2ee392010-12-02 02:45:55 +00001642}
1643
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001644static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1645 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1646 Attr.getName()))
1647 return;
1648
1649 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1650 Attr.getAttributeSpellingListIndex()));
1651}
1652
Chandler Carruthedc2c642011-07-02 00:01:44 +00001653static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001654 if (hasDeclarator(D)) return;
John McCall3882ace2011-01-05 12:14:39 +00001655
1656 if (S.CheckNoReturnAttr(attr)) return;
1657
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001658 if (!isa<ObjCMethodDecl>(D)) {
John McCall3882ace2011-01-05 12:14:39 +00001659 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001660 << attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00001661 return;
1662 }
1663
Michael Han99315932013-01-24 16:46:58 +00001664 D->addAttr(::new (S.Context)
1665 NoReturnAttr(attr.getRange(), S.Context,
1666 attr.getAttributeSpellingListIndex()));
John McCall3882ace2011-01-05 12:14:39 +00001667}
1668
1669bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00001670 if (!checkAttributeNumArgs(*this, attr, 0)) {
John McCall3882ace2011-01-05 12:14:39 +00001671 attr.setInvalid();
1672 return true;
1673 }
1674
1675 return false;
Ted Kremenek40f4ee72009-04-10 00:01:14 +00001676}
1677
Chandler Carruthedc2c642011-07-02 00:01:44 +00001678static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1679 const AttributeList &Attr) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00001680
1681 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1682 // because 'analyzer_noreturn' does not impact the type.
David Majnemer06864812015-04-07 06:01:53 +00001683 if (!isFunctionOrMethodOrBlock(D)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001684 ValueDecl *VD = dyn_cast<ValueDecl>(D);
Craig Topperc3ec1492014-05-26 06:22:03 +00001685 if (!VD || (!VD->getType()->isBlockPointerType() &&
1686 !VD->getType()->isFunctionPointerType())) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00001687 S.Diag(Attr.getLoc(),
Richard Smith89645bc2013-01-02 12:01:23 +00001688 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
Craig Topper8f7f3ea2015-11-17 05:40:05 +00001689 : diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001690 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Ted Kremenek5295ce82010-08-19 00:51:58 +00001691 return;
1692 }
1693 }
1694
Michael Han99315932013-01-24 16:46:58 +00001695 D->addAttr(::new (S.Context)
1696 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1697 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001698}
1699
John Thompsoncdb847ba2010-08-09 21:53:52 +00001700// PS3 PPU-specific.
Chandler Carruthedc2c642011-07-02 00:01:44 +00001701static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John Thompsoncdb847ba2010-08-09 21:53:52 +00001702/*
1703 Returning a Vector Class in Registers
1704
Eric Christopherbc638a82010-12-01 22:13:54 +00001705 According to the PPU ABI specifications, a class with a single member of
1706 vector type is returned in memory when used as the return value of a function.
1707 This results in inefficient code when implementing vector classes. To return
1708 the value in a single vector register, add the vecreturn attribute to the
1709 class definition. This attribute is also applicable to struct types.
John Thompsoncdb847ba2010-08-09 21:53:52 +00001710
1711 Example:
1712
1713 struct Vector
1714 {
1715 __vector float xyzw;
1716 } __attribute__((vecreturn));
1717
1718 Vector Add(Vector lhs, Vector rhs)
1719 {
1720 Vector result;
1721 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1722 return result; // This will be returned in a register
1723 }
1724*/
Aaron Ballman3e424b52013-12-26 18:30:57 +00001725 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1726 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
John Thompsoncdb847ba2010-08-09 21:53:52 +00001727 return;
1728 }
1729
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001730 RecordDecl *record = cast<RecordDecl>(D);
John Thompson9a587aaa2010-09-18 01:12:07 +00001731 int count = 0;
1732
1733 if (!isa<CXXRecordDecl>(record)) {
1734 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1735 return;
1736 }
1737
1738 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1739 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1740 return;
1741 }
1742
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001743 for (const auto *I : record->fields()) {
1744 if ((count == 1) || !I->getType()->isVectorType()) {
John Thompson9a587aaa2010-09-18 01:12:07 +00001745 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1746 return;
1747 }
1748 count++;
1749 }
1750
Michael Han99315932013-01-24 16:46:58 +00001751 D->addAttr(::new (S.Context)
1752 VecReturnAttr(Attr.getRange(), S.Context,
1753 Attr.getAttributeSpellingListIndex()));
John Thompsoncdb847ba2010-08-09 21:53:52 +00001754}
1755
Richard Smithe233fbf2013-01-28 22:42:45 +00001756static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1757 const AttributeList &Attr) {
1758 if (isa<ParmVarDecl>(D)) {
1759 // [[carries_dependency]] can only be applied to a parameter if it is a
1760 // parameter of a function declaration or lambda.
1761 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1762 S.Diag(Attr.getLoc(),
1763 diag::err_carries_dependency_param_not_function_decl);
1764 return;
1765 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00001766 }
Richard Smithe233fbf2013-01-28 22:42:45 +00001767
1768 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1769 Attr.getRange(), S.Context,
1770 Attr.getAttributeSpellingListIndex()));
Alexis Hunt96d5c762009-11-21 08:43:09 +00001771}
1772
Akira Hatanakac8667622015-11-06 23:56:15 +00001773static void handleNotTailCalledAttr(Sema &S, Decl *D,
1774 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001775 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
1776 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00001777 return;
1778
1779 D->addAttr(::new (S.Context) NotTailCalledAttr(
1780 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1781}
1782
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001783static void handleDisableTailCallsAttr(Sema &S, Decl *D,
1784 const AttributeList &Attr) {
1785 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
1786 Attr.getName()))
1787 return;
1788
1789 D->addAttr(::new (S.Context) DisableTailCallsAttr(
1790 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1791}
1792
Chandler Carruthedc2c642011-07-02 00:01:44 +00001793static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001794 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola87198cd2013-08-16 23:18:50 +00001795 if (VD->hasLocalStorage()) {
Aaron Ballman88fe3222013-12-26 17:30:44 +00001796 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001797 return;
1798 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001799 } else if (!isFunctionOrMethod(D)) {
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001800 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001801 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001802 return;
1803 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001804
Michael Han99315932013-01-24 16:46:58 +00001805 D->addAttr(::new (S.Context)
1806 UsedAttr(Attr.getRange(), S.Context,
1807 Attr.getAttributeSpellingListIndex()));
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001808}
1809
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00001810static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1811 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
1812
1813 if (IsCXX1zAttr && isa<VarDecl>(D)) {
1814 // The C++1z spelling of this attribute cannot be applied to a static data
1815 // member per [dcl.attr.unused]p2.
1816 if (cast<VarDecl>(D)->isStaticDataMember()) {
1817 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1818 << Attr.getName() << ExpectedForMaybeUnused;
1819 return;
1820 }
1821 }
1822
1823 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
1824 // about using it as an extension.
1825 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
1826 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
1827
1828 D->addAttr(::new (S.Context) UnusedAttr(
1829 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1830}
1831
Chandler Carruthedc2c642011-07-02 00:01:44 +00001832static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00001833 uint32_t priority = ConstructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00001834 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00001835 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1836 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001837
Michael Han99315932013-01-24 16:46:58 +00001838 D->addAttr(::new (S.Context)
1839 ConstructorAttr(Attr.getRange(), S.Context, priority,
1840 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00001841}
1842
Chandler Carruthedc2c642011-07-02 00:01:44 +00001843static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf28e4992014-01-20 15:22:57 +00001844 uint32_t priority = DestructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00001845 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00001846 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1847 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001848
Michael Han99315932013-01-24 16:46:58 +00001849 D->addAttr(::new (S.Context)
1850 DestructorAttr(Attr.getRange(), S.Context, priority,
1851 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00001852}
1853
Benjamin Kramerf435ab42012-05-16 12:19:08 +00001854template <typename AttrTy>
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00001855static void handleAttrWithMessage(Sema &S, Decl *D,
1856 const AttributeList &Attr) {
Benjamin Kramerf435ab42012-05-16 12:19:08 +00001857 // Handle the case where the attribute has a text message.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001858 StringRef Str;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00001859 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001860 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001861
Michael Han99315932013-01-24 16:46:58 +00001862 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1863 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001864}
1865
Ted Kremenek438f8db2014-02-22 01:06:05 +00001866static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
Ted Kremenek28eace62013-11-23 01:01:34 +00001867 const AttributeList &Attr) {
Ted Kremenek438f8db2014-02-22 01:06:05 +00001868 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
Ted Kremenek27cfe102014-02-21 22:49:04 +00001869 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1870 << Attr.getName() << Attr.getRange();
1871 return;
1872 }
1873
Ted Kremenek28eace62013-11-23 01:01:34 +00001874 D->addAttr(::new (S.Context)
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00001875 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1876 Attr.getAttributeSpellingListIndex()));
Ted Kremenek28eace62013-11-23 01:01:34 +00001877}
1878
Jordy Rose740b0c22012-05-08 03:27:22 +00001879static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1880 IdentifierInfo *Platform,
1881 VersionTuple Introduced,
1882 VersionTuple Deprecated,
1883 VersionTuple Obsoleted) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001884 StringRef PlatformName
1885 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1886 if (PlatformName.empty())
1887 PlatformName = Platform->getName();
1888
1889 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1890 // of these steps are needed).
1891 if (!Introduced.empty() && !Deprecated.empty() &&
1892 !(Introduced <= Deprecated)) {
1893 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1894 << 1 << PlatformName << Deprecated.getAsString()
1895 << 0 << Introduced.getAsString();
1896 return true;
1897 }
1898
1899 if (!Introduced.empty() && !Obsoleted.empty() &&
1900 !(Introduced <= Obsoleted)) {
1901 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1902 << 2 << PlatformName << Obsoleted.getAsString()
1903 << 0 << Introduced.getAsString();
1904 return true;
1905 }
1906
1907 if (!Deprecated.empty() && !Obsoleted.empty() &&
1908 !(Deprecated <= Obsoleted)) {
1909 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1910 << 2 << PlatformName << Obsoleted.getAsString()
1911 << 1 << Deprecated.getAsString();
1912 return true;
1913 }
1914
1915 return false;
1916}
1917
Douglas Gregor66a8ca02013-01-15 22:43:08 +00001918/// \brief Check whether the two versions match.
1919///
1920/// If either version tuple is empty, then they are assumed to match. If
1921/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
1922static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1923 bool BeforeIsOkay) {
1924 if (X.empty() || Y.empty())
1925 return true;
1926
1927 if (X == Y)
1928 return true;
1929
1930 if (BeforeIsOkay && X < Y)
1931 return true;
1932
1933 return false;
1934}
1935
Rafael Espindolaa3aea432013-01-08 22:04:34 +00001936AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001937 IdentifierInfo *Platform,
1938 VersionTuple Introduced,
1939 VersionTuple Deprecated,
1940 VersionTuple Obsoleted,
1941 bool IsUnavailable,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00001942 StringRef Message,
Manman Rend8039df2016-02-22 04:47:24 +00001943 bool IsStrict,
Douglas Gregord2a713e2015-09-30 21:27:42 +00001944 AvailabilityMergeKind AMK,
Michael Han99315932013-01-24 16:46:58 +00001945 unsigned AttrSpellingListIndex) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001946 VersionTuple MergedIntroduced = Introduced;
1947 VersionTuple MergedDeprecated = Deprecated;
1948 VersionTuple MergedObsoleted = Obsoleted;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001949 bool FoundAny = false;
Douglas Gregord2a713e2015-09-30 21:27:42 +00001950 bool OverrideOrImpl = false;
1951 switch (AMK) {
1952 case AMK_None:
1953 case AMK_Redeclaration:
1954 OverrideOrImpl = false;
1955 break;
1956
1957 case AMK_Override:
1958 case AMK_ProtocolImplementation:
1959 OverrideOrImpl = true;
1960 break;
1961 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001962
Rafael Espindolac67f2232012-05-10 02:50:16 +00001963 if (D->hasAttrs()) {
1964 AttrVec &Attrs = D->getAttrs();
1965 for (unsigned i = 0, e = Attrs.size(); i != e;) {
1966 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1967 if (!OldAA) {
1968 ++i;
1969 continue;
1970 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001971
Rafael Espindolac67f2232012-05-10 02:50:16 +00001972 IdentifierInfo *OldPlatform = OldAA->getPlatform();
1973 if (OldPlatform != Platform) {
1974 ++i;
1975 continue;
1976 }
1977
Tim Northover7a73cc72015-10-30 16:30:49 +00001978 // If there is an existing availability attribute for this platform that
1979 // is explicit and the new one is implicit use the explicit one and
1980 // discard the new implicit attribute.
1981 if (OldAA->getRange().isValid() && Range.isInvalid()) {
1982 return nullptr;
1983 }
1984
1985 // If there is an existing attribute for this platform that is implicit
1986 // and the new attribute is explicit then erase the old one and
1987 // continue processing the attributes.
1988 if (Range.isValid() && OldAA->getRange().isInvalid()) {
1989 Attrs.erase(Attrs.begin() + i);
1990 --e;
1991 continue;
1992 }
1993
Rafael Espindolac67f2232012-05-10 02:50:16 +00001994 FoundAny = true;
1995 VersionTuple OldIntroduced = OldAA->getIntroduced();
1996 VersionTuple OldDeprecated = OldAA->getDeprecated();
1997 VersionTuple OldObsoleted = OldAA->getObsoleted();
1998 bool OldIsUnavailable = OldAA->getUnavailable();
Rafael Espindolac67f2232012-05-10 02:50:16 +00001999
Douglas Gregord2a713e2015-09-30 21:27:42 +00002000 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2001 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2002 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002003 !(OldIsUnavailable == IsUnavailable ||
Douglas Gregord2a713e2015-09-30 21:27:42 +00002004 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2005 if (OverrideOrImpl) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002006 int Which = -1;
2007 VersionTuple FirstVersion;
2008 VersionTuple SecondVersion;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002009 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002010 Which = 0;
2011 FirstVersion = OldIntroduced;
2012 SecondVersion = Introduced;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002013 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002014 Which = 1;
2015 FirstVersion = Deprecated;
2016 SecondVersion = OldDeprecated;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002017 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002018 Which = 2;
2019 FirstVersion = Obsoleted;
2020 SecondVersion = OldObsoleted;
2021 }
2022
2023 if (Which == -1) {
2024 Diag(OldAA->getLocation(),
2025 diag::warn_mismatched_availability_override_unavail)
Douglas Gregord2a713e2015-09-30 21:27:42 +00002026 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2027 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002028 } else {
2029 Diag(OldAA->getLocation(),
2030 diag::warn_mismatched_availability_override)
2031 << Which
2032 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
Douglas Gregord2a713e2015-09-30 21:27:42 +00002033 << FirstVersion.getAsString() << SecondVersion.getAsString()
2034 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002035 }
Douglas Gregord2a713e2015-09-30 21:27:42 +00002036 if (AMK == AMK_Override)
2037 Diag(Range.getBegin(), diag::note_overridden_method);
2038 else
2039 Diag(Range.getBegin(), diag::note_protocol_method);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002040 } else {
2041 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2042 Diag(Range.getBegin(), diag::note_previous_attribute);
2043 }
2044
Rafael Espindolac67f2232012-05-10 02:50:16 +00002045 Attrs.erase(Attrs.begin() + i);
2046 --e;
2047 continue;
2048 }
2049
2050 VersionTuple MergedIntroduced2 = MergedIntroduced;
2051 VersionTuple MergedDeprecated2 = MergedDeprecated;
2052 VersionTuple MergedObsoleted2 = MergedObsoleted;
2053
2054 if (MergedIntroduced2.empty())
2055 MergedIntroduced2 = OldIntroduced;
2056 if (MergedDeprecated2.empty())
2057 MergedDeprecated2 = OldDeprecated;
2058 if (MergedObsoleted2.empty())
2059 MergedObsoleted2 = OldObsoleted;
2060
2061 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2062 MergedIntroduced2, MergedDeprecated2,
2063 MergedObsoleted2)) {
2064 Attrs.erase(Attrs.begin() + i);
2065 --e;
2066 continue;
2067 }
2068
2069 MergedIntroduced = MergedIntroduced2;
2070 MergedDeprecated = MergedDeprecated2;
2071 MergedObsoleted = MergedObsoleted2;
2072 ++i;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002073 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002074 }
2075
2076 if (FoundAny &&
2077 MergedIntroduced == Introduced &&
2078 MergedDeprecated == Deprecated &&
2079 MergedObsoleted == Obsoleted)
Craig Topperc3ec1492014-05-26 06:22:03 +00002080 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002081
Douglas Gregord2a713e2015-09-30 21:27:42 +00002082 // Only create a new attribute if !OverrideOrImpl, but we want to do
Ted Kremenekb5445722013-04-06 00:34:27 +00002083 // the checking.
Rafael Espindolac67f2232012-05-10 02:50:16 +00002084 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
Ted Kremenekb5445722013-04-06 00:34:27 +00002085 MergedDeprecated, MergedObsoleted) &&
Douglas Gregord2a713e2015-09-30 21:27:42 +00002086 !OverrideOrImpl) {
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002087 return ::new (Context) AvailabilityAttr(Range, Context, Platform,
2088 Introduced, Deprecated,
Michael Han99315932013-01-24 16:46:58 +00002089 Obsoleted, IsUnavailable, Message,
Manman Ren34888f82016-03-17 22:13:50 +00002090 IsStrict, AttrSpellingListIndex);
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002091 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002092 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002093}
2094
Chandler Carruthedc2c642011-07-02 00:01:44 +00002095static void handleAvailabilityAttr(Sema &S, Decl *D,
2096 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002097 if (!checkAttributeNumArgs(S, Attr, 1))
2098 return;
2099 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
Michael Han99315932013-01-24 16:46:58 +00002100 unsigned Index = Attr.getAttributeSpellingListIndex();
2101
Aaron Ballman00e99962013-08-31 01:11:41 +00002102 IdentifierInfo *II = Platform->Ident;
2103 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2104 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2105 << Platform->Ident;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002106
Rafael Espindolac231fab2013-01-08 21:30:32 +00002107 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2108 if (!ND) {
2109 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2110 return;
2111 }
2112
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002113 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2114 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2115 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
Douglas Gregor7ab142b2011-03-26 03:35:55 +00002116 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
Manman Rend8039df2016-02-22 04:47:24 +00002117 bool IsStrict = Attr.getStrictLoc().isValid();
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002118 StringRef Str;
Benjamin Kramera9dfa922013-09-13 17:31:48 +00002119 if (const StringLiteral *SE =
2120 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002121 Str = SE->getString();
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002122
Aaron Ballman00e99962013-08-31 01:11:41 +00002123 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002124 Introduced.Version,
2125 Deprecated.Version,
2126 Obsoleted.Version,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002127 IsUnavailable, Str,
Manman Ren34888f82016-03-17 22:13:50 +00002128 IsStrict,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002129 Sema::AMK_None,
Michael Han99315932013-01-24 16:46:58 +00002130 Index);
Rafael Espindola19de5612013-01-12 06:42:30 +00002131 if (NewAttr)
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002132 D->addAttr(NewAttr);
Tim Northover7a73cc72015-10-30 16:30:49 +00002133
2134 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2135 // matches before the start of the watchOS platform.
2136 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2137 IdentifierInfo *NewII = nullptr;
2138 if (II->getName() == "ios")
2139 NewII = &S.Context.Idents.get("watchos");
2140 else if (II->getName() == "ios_app_extension")
2141 NewII = &S.Context.Idents.get("watchos_app_extension");
2142
2143 if (NewII) {
2144 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2145 if (Version.empty())
2146 return Version;
2147 auto Major = Version.getMajor();
2148 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2149 if (NewMajor >= 2) {
2150 if (Version.getMinor().hasValue()) {
2151 if (Version.getSubminor().hasValue())
2152 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2153 Version.getSubminor().getValue());
2154 else
2155 return VersionTuple(NewMajor, Version.getMinor().getValue());
2156 }
2157 }
2158
2159 return VersionTuple(2, 0);
2160 };
2161
2162 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2163 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2164 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2165
2166 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2167 SourceRange(),
2168 NewII,
2169 NewIntroduced,
2170 NewDeprecated,
2171 NewObsoleted,
2172 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002173 IsStrict,
Tim Northover7a73cc72015-10-30 16:30:49 +00002174 Sema::AMK_None,
2175 Index);
2176 if (NewAttr)
2177 D->addAttr(NewAttr);
2178 }
2179 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2180 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2181 // matches before the start of the tvOS platform.
2182 IdentifierInfo *NewII = nullptr;
2183 if (II->getName() == "ios")
2184 NewII = &S.Context.Idents.get("tvos");
2185 else if (II->getName() == "ios_app_extension")
2186 NewII = &S.Context.Idents.get("tvos_app_extension");
2187
2188 if (NewII) {
2189 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2190 SourceRange(),
2191 NewII,
2192 Introduced.Version,
2193 Deprecated.Version,
2194 Obsoleted.Version,
2195 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002196 IsStrict,
Tim Northover7a73cc72015-10-30 16:30:49 +00002197 Sema::AMK_None,
2198 Index);
2199 if (NewAttr)
2200 D->addAttr(NewAttr);
2201 }
2202 }
Rafael Espindolac67f2232012-05-10 02:50:16 +00002203}
2204
John McCalld041a9b2013-02-20 01:54:26 +00002205template <class T>
2206static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2207 typename T::VisibilityType value,
2208 unsigned attrSpellingListIndex) {
2209 T *existingAttr = D->getAttr<T>();
2210 if (existingAttr) {
2211 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2212 if (existingValue == value)
Craig Topperc3ec1492014-05-26 06:22:03 +00002213 return nullptr;
John McCalld041a9b2013-02-20 01:54:26 +00002214 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2215 S.Diag(range.getBegin(), diag::note_previous_attribute);
2216 D->dropAttr<T>();
2217 }
2218 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2219}
2220
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002221VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002222 VisibilityAttr::VisibilityType Vis,
2223 unsigned AttrSpellingListIndex) {
John McCalld041a9b2013-02-20 01:54:26 +00002224 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2225 AttrSpellingListIndex);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002226}
2227
John McCalld041a9b2013-02-20 01:54:26 +00002228TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2229 TypeVisibilityAttr::VisibilityType Vis,
2230 unsigned AttrSpellingListIndex) {
2231 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2232 AttrSpellingListIndex);
2233}
2234
2235static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2236 bool isTypeVisibility) {
2237 // Visibility attributes don't mean anything on a typedef.
2238 if (isa<TypedefNameDecl>(D)) {
2239 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2240 << Attr.getName();
2241 return;
2242 }
2243
2244 // 'type_visibility' can only go on a type or namespace.
2245 if (isTypeVisibility &&
2246 !(isa<TagDecl>(D) ||
2247 isa<ObjCInterfaceDecl>(D) ||
2248 isa<NamespaceDecl>(D))) {
2249 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2250 << Attr.getName() << ExpectedTypeOrNamespace;
2251 return;
2252 }
2253
Benjamin Kramer70370212013-09-09 15:08:57 +00002254 // Check that the argument is a string literal.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002255 StringRef TypeStr;
2256 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002257 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002258 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002259
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002260 VisibilityAttr::VisibilityType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002261 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002262 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
Aaron Ballman682ee422013-09-11 19:47:58 +00002263 << Attr.getName() << TypeStr;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002264 return;
2265 }
Aaron Ballman682ee422013-09-11 19:47:58 +00002266
2267 // Complain about attempts to use protected visibility on targets
2268 // (like Darwin) that don't support it.
2269 if (type == VisibilityAttr::Protected &&
2270 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2271 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2272 type = VisibilityAttr::Default;
2273 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002274
Michael Han99315932013-01-24 16:46:58 +00002275 unsigned Index = Attr.getAttributeSpellingListIndex();
John McCalld041a9b2013-02-20 01:54:26 +00002276 clang::Attr *newAttr;
2277 if (isTypeVisibility) {
2278 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2279 (TypeVisibilityAttr::VisibilityType) type,
2280 Index);
2281 } else {
2282 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2283 }
2284 if (newAttr)
2285 D->addAttr(newAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002286}
2287
Chandler Carruthedc2c642011-07-02 00:01:44 +00002288static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2289 const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002290 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
Aaron Ballman00e99962013-08-31 01:11:41 +00002291 if (!Attr.isArgIdent(0)) {
2292 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2293 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
John McCall86bc21f2011-03-02 11:33:24 +00002294 return;
2295 }
Aaron Ballman00e99962013-08-31 01:11:41 +00002296
Aaron Ballman682ee422013-09-11 19:47:58 +00002297 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2298 ObjCMethodFamilyAttr::FamilyKind F;
2299 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2300 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2301 << IL->Ident;
John McCall86bc21f2011-03-02 11:33:24 +00002302 return;
2303 }
2304
Alp Toker314cc812014-01-25 16:55:45 +00002305 if (F == ObjCMethodFamilyAttr::OMF_init &&
2306 !method->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002307 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
Alp Toker314cc812014-01-25 16:55:45 +00002308 << method->getReturnType();
John McCall31168b02011-06-15 23:02:42 +00002309 // Ignore the attribute.
2310 return;
2311 }
2312
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00002313 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +00002314 S.Context, F,
2315 Attr.getAttributeSpellingListIndex()));
John McCall86bc21f2011-03-02 11:33:24 +00002316}
2317
Chandler Carruthedc2c642011-07-02 00:01:44 +00002318static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
Richard Smithdda56e42011-04-15 14:24:37 +00002319 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002320 QualType T = TD->getUnderlyingType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002321 if (!T->isCARCBridgableType()) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002322 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2323 return;
2324 }
2325 }
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002326 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2327 QualType T = PD->getType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002328 if (!T->isCARCBridgableType()) {
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002329 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2330 return;
2331 }
2332 }
2333 else {
Ted Kremenek05e916b2012-03-01 01:40:32 +00002334 // It is okay to include this attribute on properties, e.g.:
2335 //
2336 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2337 //
2338 // In this case it follows tradition and suppresses an error in the above
2339 // case.
Fariborz Jahaniana45495a2011-11-29 01:48:40 +00002340 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
Ted Kremenek05e916b2012-03-01 01:40:32 +00002341 }
Michael Han99315932013-01-24 16:46:58 +00002342 D->addAttr(::new (S.Context)
2343 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2344 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002345}
2346
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00002347static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2348 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2349 QualType T = TD->getUnderlyingType();
2350 if (!T->isObjCObjectPointerType()) {
2351 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2352 return;
2353 }
2354 } else {
2355 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2356 return;
2357 }
2358 D->addAttr(::new (S.Context)
2359 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2360 Attr.getAttributeSpellingListIndex()));
2361}
2362
Chandler Carruthedc2c642011-07-02 00:01:44 +00002363static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002364 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002365 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00002366 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Steve Naroff3405a732008-09-18 16:44:58 +00002367 return;
2368 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002369
Aaron Ballman00e99962013-08-31 01:11:41 +00002370 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002371 BlocksAttr::BlockType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002372 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2373 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2374 << Attr.getName() << II;
Steve Naroff3405a732008-09-18 16:44:58 +00002375 return;
2376 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002377
Michael Han99315932013-01-24 16:46:58 +00002378 D->addAttr(::new (S.Context)
2379 BlocksAttr(Attr.getRange(), S.Context, type,
2380 Attr.getAttributeSpellingListIndex()));
Steve Naroff3405a732008-09-18 16:44:58 +00002381}
2382
Chandler Carruthedc2c642011-07-02 00:01:44 +00002383static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00002384 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
Anders Carlssonc181b012008-10-05 18:05:59 +00002385 if (Attr.getNumArgs() > 0) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002386 Expr *E = Attr.getArgAsExpr(0);
Anders Carlssonc181b012008-10-05 18:05:59 +00002387 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002388 if (E->isTypeDependent() || E->isValueDependent() ||
2389 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002390 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002391 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002392 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002393 return;
2394 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002395
John McCallb46f2872011-09-09 07:56:05 +00002396 if (Idx.isSigned() && Idx.isNegative()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002397 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2398 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002399 return;
2400 }
John McCallb46f2872011-09-09 07:56:05 +00002401
2402 sentinel = Idx.getZExtValue();
Anders Carlssonc181b012008-10-05 18:05:59 +00002403 }
2404
Aaron Ballman18a78382013-11-21 00:28:23 +00002405 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
Anders Carlssonc181b012008-10-05 18:05:59 +00002406 if (Attr.getNumArgs() > 1) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002407 Expr *E = Attr.getArgAsExpr(1);
Anders Carlssonc181b012008-10-05 18:05:59 +00002408 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002409 if (E->isTypeDependent() || E->isValueDependent() ||
2410 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002411 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002412 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002413 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002414 return;
2415 }
2416 nullPos = Idx.getZExtValue();
Mike Stumpd3bb5572009-07-24 19:02:52 +00002417
John McCallb46f2872011-09-09 07:56:05 +00002418 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002419 // FIXME: This error message could be improved, it would be nice
2420 // to say what the bounds actually are.
Chris Lattner3b054132008-11-19 05:08:23 +00002421 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2422 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002423 return;
2424 }
2425 }
2426
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002427 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +00002428 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
Chris Lattner9363e312009-03-17 23:03:47 +00002429 if (isa<FunctionNoProtoType>(FT)) {
2430 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2431 return;
2432 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002433
Chris Lattner9363e312009-03-17 23:03:47 +00002434 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002435 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002436 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002437 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002438 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002439 if (!MD->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002440 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002441 return;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002442 }
Eli Friedman5c5e3b72012-01-06 01:23:10 +00002443 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2444 if (!BD->isVariadic()) {
2445 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2446 return;
2447 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002448 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002449 QualType Ty = V->getType();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002450 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Aaron Ballman12b9f652014-01-16 13:55:42 +00002451 const FunctionType *FT = Ty->isFunctionPointerType()
2452 ? D->getFunctionType()
Eric Christopherbc638a82010-12-01 22:13:54 +00002453 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002454 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002455 int m = Ty->isFunctionPointerType() ? 0 : 1;
2456 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002457 return;
2458 }
Mike Stump12b8ce12009-08-04 21:02:39 +00002459 } else {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002460 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002461 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002462 return;
2463 }
Anders Carlssonc181b012008-10-05 18:05:59 +00002464 } else {
Chris Lattner3b054132008-11-19 05:08:23 +00002465 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002466 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Anders Carlssonc181b012008-10-05 18:05:59 +00002467 return;
2468 }
Michael Han99315932013-01-24 16:46:58 +00002469 D->addAttr(::new (S.Context)
2470 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2471 Attr.getAttributeSpellingListIndex()));
Anders Carlssonc181b012008-10-05 18:05:59 +00002472}
2473
Chandler Carruthedc2c642011-07-02 00:01:44 +00002474static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
Alp Toker314cc812014-01-25 16:55:45 +00002475 if (D->getFunctionType() &&
2476 D->getFunctionType()->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002477 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2478 << Attr.getName() << 0;
Nuno Lopes56abcbd2009-12-22 23:59:52 +00002479 return;
2480 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002481 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00002482 if (MD->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002483 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2484 << Attr.getName() << 1;
2485 return;
2486 }
2487
Aaron Ballmane7964782016-03-07 22:44:55 +00002488 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2489 // about using it as an extension.
2490 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2491 !Attr.getScopeName())
Richard Smith4f902c72016-03-08 00:32:55 +00002492 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
Aaron Ballmane7964782016-03-07 22:44:55 +00002493
Michael Han99315932013-01-24 16:46:58 +00002494 D->addAttr(::new (S.Context)
2495 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2496 Attr.getAttributeSpellingListIndex()));
Chris Lattner237f2752009-02-14 07:37:35 +00002497}
2498
Chandler Carruthedc2c642011-07-02 00:01:44 +00002499static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002500 // weak_import only applies to variable & function declarations.
2501 bool isDef = false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002502 if (!D->canBeWeakImported(isDef)) {
2503 if (isDef)
Reid Kleckner52d598e2013-05-20 21:53:29 +00002504 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2505 << "weak_import";
Douglas Gregord71149a2011-03-23 13:27:51 +00002506 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
Douglas Gregore8bbc122011-09-02 00:18:52 +00002507 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
Fariborz Jahanian3249a1e2011-10-26 23:59:12 +00002508 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
Douglas Gregord71149a2011-03-23 13:27:51 +00002509 // Nothing to warn about here.
2510 } else
Fariborz Jahanianea70a172010-04-13 20:22:35 +00002511 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002512 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002513
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002514 return;
2515 }
2516
Michael Han99315932013-01-24 16:46:58 +00002517 D->addAttr(::new (S.Context)
2518 WeakImportAttr(Attr.getRange(), S.Context,
2519 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002520}
2521
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002522// Handles reqd_work_group_size and work_group_size_hint.
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002523template <typename WorkGroupAttr>
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002524static void handleWorkGroupSize(Sema &S, Decl *D,
Nick Lewyckyb9e4a3a2012-07-24 01:31:55 +00002525 const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002526 uint32_t WGSize[3];
Joey Goulyb1d23a82014-05-19 14:41:38 +00002527 for (unsigned i = 0; i < 3; ++i) {
2528 const Expr *E = Attr.getArgAsExpr(i);
2529 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
Nate Begemanf2758702009-06-26 06:32:41 +00002530 return;
Joey Goulyb1d23a82014-05-19 14:41:38 +00002531 if (WGSize[i] == 0) {
2532 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2533 << Attr.getName() << E->getSourceRange();
2534 return;
2535 }
2536 }
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002537
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002538 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2539 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2540 Existing->getYDim() == WGSize[1] &&
2541 Existing->getZDim() == WGSize[2]))
2542 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002543
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002544 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2545 WGSize[0], WGSize[1], WGSize[2],
Michael Han99315932013-01-24 16:46:58 +00002546 Attr.getAttributeSpellingListIndex()));
Nate Begemanf2758702009-06-26 06:32:41 +00002547}
2548
Joey Goulyaba589c2013-03-08 09:42:32 +00002549static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002550 if (!Attr.hasParsedType()) {
2551 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2552 << Attr.getName() << 1;
2553 return;
2554 }
2555
Craig Topperc3ec1492014-05-26 06:22:03 +00002556 TypeSourceInfo *ParmTSI = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00002557 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2558 assert(ParmTSI && "no type source info for attribute argument");
Joey Goulyaba589c2013-03-08 09:42:32 +00002559
2560 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2561 (ParmType->isBooleanType() ||
2562 !ParmType->isIntegralType(S.getASTContext()))) {
2563 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2564 << ParmType;
2565 return;
2566 }
2567
Aaron Ballmana9e05402013-12-02 22:16:55 +00002568 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
Richard Smithb87c4652013-10-31 21:23:20 +00002569 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
Joey Goulyaba589c2013-03-08 09:42:32 +00002570 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2571 return;
2572 }
2573 }
2574
2575 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00002576 ParmTSI,
2577 Attr.getAttributeSpellingListIndex()));
Joey Goulyaba589c2013-03-08 09:42:32 +00002578}
2579
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002580SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002581 StringRef Name,
2582 unsigned AttrSpellingListIndex) {
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002583 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2584 if (ExistingAttr->getName() == Name)
Craig Topperc3ec1492014-05-26 06:22:03 +00002585 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002586 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2587 Diag(Range.getBegin(), diag::note_previous_attribute);
Craig Topperc3ec1492014-05-26 06:22:03 +00002588 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002589 }
Michael Han99315932013-01-24 16:46:58 +00002590 return ::new (Context) SectionAttr(Range, Context, Name,
2591 AttrSpellingListIndex);
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002592}
2593
Reid Kleckner2a133222015-03-04 23:39:17 +00002594bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2595 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2596 if (!Error.empty()) {
2597 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2598 return false;
2599 }
2600 return true;
2601}
2602
Chandler Carruthedc2c642011-07-02 00:01:44 +00002603static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar648bf782009-02-12 17:28:23 +00002604 // Make sure that there is a string literal as the sections's single
2605 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002606 StringRef Str;
2607 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002608 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
Daniel Dunbar648bf782009-02-12 17:28:23 +00002609 return;
Mike Stump11289f42009-09-09 15:08:12 +00002610
Reid Kleckner2a133222015-03-04 23:39:17 +00002611 if (!S.checkSectionName(LiteralLoc, Str))
2612 return;
2613
Chris Lattner30ba6742009-08-10 19:03:04 +00002614 // If the target wants to validate the section specifier, make it happen.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002615 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
Chris Lattner20aee9b2010-01-12 20:58:53 +00002616 if (!Error.empty()) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002617 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
Chris Lattner20aee9b2010-01-12 20:58:53 +00002618 << Error;
Chris Lattner30ba6742009-08-10 19:03:04 +00002619 return;
2620 }
Mike Stump11289f42009-09-09 15:08:12 +00002621
Michael Han99315932013-01-24 16:46:58 +00002622 unsigned Index = Attr.getAttributeSpellingListIndex();
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002623 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002624 if (NewAttr)
2625 D->addAttr(NewAttr);
Daniel Dunbar648bf782009-02-12 17:28:23 +00002626}
2627
Eric Christopher789a7ad2015-06-12 01:36:05 +00002628// Check for things we'd like to warn about, no errors or validation for now.
2629// TODO: Validation should use a backend target library that specifies
2630// the allowable subtarget features and cpus. We could use something like a
2631// TargetCodeGenInfo hook here to do validation.
2632void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2633 for (auto Str : {"tune=", "fpmath="})
2634 if (AttrStr.find(Str) != StringRef::npos)
2635 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2636}
2637
Eric Christopher11acf732015-06-12 01:35:52 +00002638static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eric Christopher11acf732015-06-12 01:35:52 +00002639 StringRef Str;
2640 SourceLocation LiteralLoc;
2641 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2642 return;
Eric Christopher789a7ad2015-06-12 01:36:05 +00002643 S.checkTargetAttr(LiteralLoc, Str);
Eric Christopher11acf732015-06-12 01:35:52 +00002644 unsigned Index = Attr.getAttributeSpellingListIndex();
2645 TargetAttr *NewAttr =
2646 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2647 D->addAttr(NewAttr);
2648}
2649
Chandler Carruthedc2c642011-07-02 00:01:44 +00002650static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002651 VarDecl *VD = cast<VarDecl>(D);
2652 if (!VD->hasLocalStorage()) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002653 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00002654 return;
2655 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002656
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002657 Expr *E = Attr.getArgAsExpr(0);
2658 SourceLocation Loc = E->getExprLoc();
Craig Topperc3ec1492014-05-26 06:22:03 +00002659 FunctionDecl *FD = nullptr;
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002660 DeclarationNameInfo NI;
Aaron Ballman00e99962013-08-31 01:11:41 +00002661
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002662 // gcc only allows for simple identifiers. Since we support more than gcc, we
2663 // will warn the user.
2664 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2665 if (DRE->hasQualifier())
2666 S.Diag(Loc, diag::warn_cleanup_ext);
2667 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2668 NI = DRE->getNameInfo();
2669 if (!FD) {
2670 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2671 << NI.getName();
2672 return;
2673 }
2674 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2675 if (ULE->hasExplicitTemplateArgs())
2676 S.Diag(Loc, diag::warn_cleanup_ext);
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002677 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2678 NI = ULE->getNameInfo();
Alp Toker67b47ac2013-10-20 18:48:56 +00002679 if (!FD) {
2680 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2681 << NI.getName();
2682 if (ULE->getType() == S.Context.OverloadTy)
2683 S.NoteAllOverloadCandidates(ULE);
2684 return;
2685 }
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002686 } else {
2687 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
Anders Carlssond277d792009-01-31 01:16:18 +00002688 return;
2689 }
2690
Anders Carlssond277d792009-01-31 01:16:18 +00002691 if (FD->getNumParams() != 1) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002692 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2693 << NI.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00002694 return;
2695 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002696
Anders Carlsson723f55d2009-02-07 23:16:50 +00002697 // We're currently more strict than GCC about what function types we accept.
2698 // If this ever proves to be a problem it should be easy to fix.
2699 QualType Ty = S.Context.getPointerType(VD->getType());
2700 QualType ParamTy = FD->getParamDecl(0)->getType();
Douglas Gregorc03a1082011-01-28 02:26:04 +00002701 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2702 ParamTy, Ty) != Sema::Compatible) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002703 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2704 << NI.getName() << ParamTy << Ty;
Anders Carlsson723f55d2009-02-07 23:16:50 +00002705 return;
2706 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002707
Michael Han99315932013-01-24 16:46:58 +00002708 D->addAttr(::new (S.Context)
2709 CleanupAttr(Attr.getRange(), S.Context, FD,
2710 Attr.getAttributeSpellingListIndex()));
Anders Carlssond277d792009-01-31 01:16:18 +00002711}
2712
Mike Stumpd3bb5572009-07-24 19:02:52 +00002713/// Handle __attribute__((format_arg((idx)))) attribute based on
Bill Wendling44426052012-12-20 19:22:21 +00002714/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00002715static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002716 Expr *IdxExpr = Attr.getArgAsExpr(0);
Alp Toker601b22c2014-01-21 23:35:24 +00002717 uint64_t Idx;
2718 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002719 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00002720
Eric Christopherb64963e2015-08-13 21:34:35 +00002721 // Make sure the format string is really a string.
Alp Toker601b22c2014-01-21 23:35:24 +00002722 QualType Ty = getFunctionOrMethodParamType(D, Idx);
Mike Stumpd3bb5572009-07-24 19:02:52 +00002723
Eric Christopherb64963e2015-08-13 21:34:35 +00002724 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
2725 if (NotNSStringTy &&
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002726 !isCFStringType(Ty, S.Context) &&
2727 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002728 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002729 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00002730 << "a string type" << IdxExpr->getSourceRange()
2731 << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002732 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002733 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002734 Ty = getFunctionOrMethodResultType(D);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002735 if (!isNSStringType(Ty, S.Context) &&
2736 !isCFStringType(Ty, S.Context) &&
2737 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002738 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002739 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00002740 << (NotNSStringTy ? "string type" : "NSString")
Aaron Ballman2f9e88b2014-08-04 15:17:29 +00002741 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002742 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002743 }
2744
Alp Toker601b22c2014-01-21 23:35:24 +00002745 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00002746 // because that has corrected for the implicit this parameter, and is zero-
2747 // based. The attribute expects what the user wrote explicitly.
2748 llvm::APSInt Val;
2749 IdxExpr->EvaluateAsInt(Val, S.Context);
2750
Michael Han99315932013-01-24 16:46:58 +00002751 D->addAttr(::new (S.Context)
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00002752 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
Michael Han99315932013-01-24 16:46:58 +00002753 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002754}
2755
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002756enum FormatAttrKind {
2757 CFStringFormat,
2758 NSStringFormat,
2759 StrftimeFormat,
2760 SupportedFormat,
Chris Lattner12161d32010-03-22 21:08:50 +00002761 IgnoredFormat,
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002762 InvalidFormat
2763};
2764
2765/// getFormatAttrKind - Map from format attribute names to supported format
2766/// types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002767static FormatAttrKind getFormatAttrKind(StringRef Format) {
Benjamin Kramer96a44b62012-05-16 12:44:25 +00002768 return llvm::StringSwitch<FormatAttrKind>(Format)
2769 // Check for formats that get handled specially.
2770 .Case("NSString", NSStringFormat)
2771 .Case("CFString", CFStringFormat)
2772 .Case("strftime", StrftimeFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002773
Benjamin Kramer96a44b62012-05-16 12:44:25 +00002774 // Otherwise, check for supported formats.
2775 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2776 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2777 .Case("kprintf", SupportedFormat) // OpenBSD.
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002778 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002779 .Case("os_trace", SupportedFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002780
Benjamin Kramer96a44b62012-05-16 12:44:25 +00002781 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2782 .Default(InvalidFormat);
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002783}
2784
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002785/// Handle __attribute__((init_priority(priority))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00002786/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00002787static void handleInitPriorityAttr(Sema &S, Decl *D,
2788 const AttributeList &Attr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002789 if (!S.getLangOpts().CPlusPlus) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002790 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2791 return;
2792 }
2793
Aaron Ballman4a611152013-11-27 16:34:09 +00002794 if (S.getCurFunctionOrMethodDecl()) {
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00002795 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2796 Attr.setInvalid();
2797 return;
2798 }
Aaron Ballman4a611152013-11-27 16:34:09 +00002799 QualType T = cast<VarDecl>(D)->getType();
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00002800 if (S.Context.getAsArrayType(T))
2801 T = S.Context.getBaseElementType(T);
2802 if (!T->getAs<RecordType>()) {
2803 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2804 Attr.setInvalid();
2805 return;
2806 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002807
2808 Expr *E = Attr.getArgAsExpr(0);
2809 uint32_t prioritynum;
2810 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002811 Attr.setInvalid();
2812 return;
2813 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002814
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002815 if (prioritynum < 101 || prioritynum > 65535) {
2816 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002817 << E->getSourceRange() << Attr.getName() << 101 << 65535;
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002818 Attr.setInvalid();
2819 return;
2820 }
Michael Han99315932013-01-24 16:46:58 +00002821 D->addAttr(::new (S.Context)
2822 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2823 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002824}
2825
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002826FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2827 IdentifierInfo *Format, int FormatIdx,
2828 int FirstArg,
Michael Han99315932013-01-24 16:46:58 +00002829 unsigned AttrSpellingListIndex) {
Rafael Espindola92d49452012-05-11 00:36:07 +00002830 // Check whether we already have an equivalent format attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002831 for (auto *F : D->specific_attrs<FormatAttr>()) {
2832 if (F->getType() == Format &&
2833 F->getFormatIdx() == FormatIdx &&
2834 F->getFirstArg() == FirstArg) {
Rafael Espindola92d49452012-05-11 00:36:07 +00002835 // If we don't have a valid location for this attribute, adopt the
2836 // location.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002837 if (F->getLocation().isInvalid())
2838 F->setRange(Range);
Craig Topperc3ec1492014-05-26 06:22:03 +00002839 return nullptr;
Rafael Espindola92d49452012-05-11 00:36:07 +00002840 }
2841 }
2842
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002843 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2844 FirstArg, AttrSpellingListIndex);
Rafael Espindola92d49452012-05-11 00:36:07 +00002845}
2846
Mike Stumpd3bb5572009-07-24 19:02:52 +00002847/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00002848/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00002849static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002850 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002851 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00002852 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002853 return;
2854 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002855
Chandler Carruth743682b2010-11-16 08:35:43 +00002856 // In C++ the implicit 'this' function parameter also counts, and they are
2857 // counted from one.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002858 bool HasImplicitThisParam = isInstanceMethod(D);
Alp Toker601b22c2014-01-21 23:35:24 +00002859 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002860
Aaron Ballman00e99962013-08-31 01:11:41 +00002861 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2862 StringRef Format = II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002863
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00002864 if (normalizeName(Format)) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002865 // If we've modified the string name, we need a new identifier for it.
2866 II = &S.Context.Idents.get(Format);
2867 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002868
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002869 // Check for supported formats.
2870 FormatAttrKind Kind = getFormatAttrKind(Format);
Chris Lattner12161d32010-03-22 21:08:50 +00002871
2872 if (Kind == IgnoredFormat)
2873 return;
2874
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002875 if (Kind == InvalidFormat) {
Chris Lattner3b054132008-11-19 05:08:23 +00002876 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
Aaron Ballman190bad42013-12-26 16:13:50 +00002877 << Attr.getName() << II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002878 return;
2879 }
2880
2881 // checks for the 2nd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00002882 Expr *IdxExpr = Attr.getArgAsExpr(1);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002883 uint32_t Idx;
2884 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002885 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002886
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002887 if (Idx < 1 || Idx > NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00002888 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00002889 << Attr.getName() << 2 << IdxExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002890 return;
2891 }
2892
2893 // FIXME: Do we need to bounds check?
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002894 unsigned ArgIdx = Idx - 1;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002895
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002896 if (HasImplicitThisParam) {
2897 if (ArgIdx == 0) {
Chandler Carruth743682b2010-11-16 08:35:43 +00002898 S.Diag(Attr.getLoc(),
2899 diag::err_format_attribute_implicit_this_format_string)
2900 << IdxExpr->getSourceRange();
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002901 return;
2902 }
2903 ArgIdx--;
2904 }
Mike Stump11289f42009-09-09 15:08:12 +00002905
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002906 // make sure the format string is really a string
Alp Toker601b22c2014-01-21 23:35:24 +00002907 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002908
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002909 if (Kind == CFStringFormat) {
Daniel Dunbar980c6692008-09-26 03:32:58 +00002910 if (!isCFStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00002911 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00002912 << "a CFString" << IdxExpr->getSourceRange()
2913 << getFunctionOrMethodParamRange(D, ArgIdx);
Daniel Dunbar980c6692008-09-26 03:32:58 +00002914 return;
2915 }
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002916 } else if (Kind == NSStringFormat) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002917 // FIXME: do we need to check if the type is NSString*? What are the
2918 // semantics?
Chris Lattnerb632a6e2008-06-29 00:43:07 +00002919 if (!isNSStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00002920 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00002921 << "an NSString" << IdxExpr->getSourceRange()
2922 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002923 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002924 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002925 } else if (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002926 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002927 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00002928 << "a string type" << IdxExpr->getSourceRange()
2929 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002930 return;
2931 }
2932
2933 // check the 3rd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00002934 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002935 uint32_t FirstArg;
2936 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002937 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002938
2939 // check if the function is variadic if the 3rd argument non-zero
2940 if (FirstArg != 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002941 if (isFunctionOrMethodVariadic(D)) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002942 ++NumArgs; // +1 for ...
2943 } else {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002944 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002945 return;
2946 }
2947 }
2948
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002949 // strftime requires FirstArg to be 0 because it doesn't read from any
2950 // variable the input is just the current time + the format string.
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002951 if (Kind == StrftimeFormat) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002952 if (FirstArg != 0) {
Chris Lattner3b054132008-11-19 05:08:23 +00002953 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2954 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002955 return;
2956 }
2957 // if 0 it disables parameter checking (to use with e.g. va_list)
2958 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00002959 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00002960 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002961 return;
2962 }
2963
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002964 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002965 Idx, FirstArg,
Michael Han99315932013-01-24 16:46:58 +00002966 Attr.getAttributeSpellingListIndex());
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002967 if (NewAttr)
2968 D->addAttr(NewAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002969}
2970
Chandler Carruthedc2c642011-07-02 00:01:44 +00002971static void handleTransparentUnionAttr(Sema &S, Decl *D,
2972 const AttributeList &Attr) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002973 // Try to find the underlying union declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00002974 RecordDecl *RD = nullptr;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002975 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002976 if (TD && TD->getUnderlyingType()->isUnionType())
2977 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2978 else
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002979 RD = dyn_cast<RecordDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002980
2981 if (!RD || !RD->isUnion()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002982 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002983 << Attr.getName() << ExpectedUnion;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002984 return;
2985 }
2986
John McCallf937c022011-10-07 06:10:15 +00002987 if (!RD->isCompleteDefinition()) {
Mike Stumpd3bb5572009-07-24 19:02:52 +00002988 S.Diag(Attr.getLoc(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002989 diag::warn_transparent_union_attribute_not_definition);
2990 return;
2991 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002992
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002993 RecordDecl::field_iterator Field = RD->field_begin(),
2994 FieldEnd = RD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002995 if (Field == FieldEnd) {
2996 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
2997 return;
2998 }
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00002999
David Blaikie40ed2972012-06-06 20:45:41 +00003000 FieldDecl *FirstField = *Field;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003001 QualType FirstType = FirstField->getType();
Douglas Gregor21872662010-06-30 17:24:13 +00003002 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
Mike Stumpd3bb5572009-07-24 19:02:52 +00003003 S.Diag(FirstField->getLocation(),
Douglas Gregor21872662010-06-30 17:24:13 +00003004 diag::warn_transparent_union_attribute_floating)
3005 << FirstType->isVectorType() << FirstType;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003006 return;
3007 }
3008
3009 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3010 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3011 for (; Field != FieldEnd; ++Field) {
3012 QualType FieldType = Field->getType();
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003013 // FIXME: this isn't fully correct; we also need to test whether the
3014 // members of the union would all have the same calling convention as the
3015 // first member of the union. Checking just the size and alignment isn't
3016 // sufficient (consider structs passed on the stack instead of in registers
3017 // as an example).
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003018 if (S.Context.getTypeSize(FieldType) != FirstSize ||
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003019 S.Context.getTypeAlign(FieldType) > FirstAlign) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003020 // Warn if we drop the attribute.
3021 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003022 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003023 : S.Context.getTypeAlign(FieldType);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003024 S.Diag(Field->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003025 diag::warn_transparent_union_attribute_field_size_align)
3026 << isSize << Field->getDeclName() << FieldBits;
3027 unsigned FirstBits = isSize? FirstSize : FirstAlign;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003028 S.Diag(FirstField->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003029 diag::note_transparent_union_first_field_size_align)
3030 << isSize << FirstBits;
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003031 return;
3032 }
3033 }
3034
Michael Han99315932013-01-24 16:46:58 +00003035 RD->addAttr(::new (S.Context)
3036 TransparentUnionAttr(Attr.getRange(), S.Context,
3037 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003038}
3039
Chandler Carruthedc2c642011-07-02 00:01:44 +00003040static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003041 // Make sure that there is a string literal as the annotation's single
3042 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003043 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003044 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003045 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003046
3047 // Don't duplicate annotations that are already set.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003048 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3049 if (I->getAnnotation() == Str)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003050 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003051 }
Michael Han99315932013-01-24 16:46:58 +00003052
3053 D->addAttr(::new (S.Context)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003054 AnnotateAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00003055 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003056}
3057
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003058static void handleAlignValueAttr(Sema &S, Decl *D,
3059 const AttributeList &Attr) {
3060 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3061 Attr.getAttributeSpellingListIndex());
3062}
3063
3064void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3065 unsigned SpellingListIndex) {
3066 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3067 SourceLocation AttrLoc = AttrRange.getBegin();
3068
3069 QualType T;
3070 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3071 T = TD->getUnderlyingType();
3072 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3073 T = VD->getType();
3074 else
3075 llvm_unreachable("Unknown decl type for align_value");
3076
3077 if (!T->isDependentType() && !T->isAnyPointerType() &&
3078 !T->isReferenceType() && !T->isMemberPointerType()) {
3079 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3080 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3081 return;
3082 }
3083
3084 if (!E->isValueDependent()) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003085 llvm::APSInt Alignment;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003086 ExprResult ICE
3087 = VerifyIntegerConstantExpression(E, &Alignment,
3088 diag::err_align_value_attribute_argument_not_int,
3089 /*AllowFold*/ false);
3090 if (ICE.isInvalid())
3091 return;
3092
3093 if (!Alignment.isPowerOf2()) {
3094 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3095 << E->getSourceRange();
3096 return;
3097 }
3098
3099 D->addAttr(::new (Context)
3100 AlignValueAttr(AttrRange, Context, ICE.get(),
3101 SpellingListIndex));
3102 return;
3103 }
3104
3105 // Save dependent expressions in the AST to be instantiated.
3106 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003107}
3108
Chandler Carruthedc2c642011-07-02 00:01:44 +00003109static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003110 // check the attribute arguments.
Chris Lattner4a927cb2008-06-28 23:36:30 +00003111 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00003112 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3113 << Attr.getName() << 1;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003114 return;
3115 }
Aaron Ballman478faed2012-06-19 22:09:27 +00003116
Richard Smith848e1f12013-02-01 08:12:08 +00003117 if (Attr.getNumArgs() == 0) {
3118 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00003119 true, nullptr, Attr.getAttributeSpellingListIndex()));
Richard Smith848e1f12013-02-01 08:12:08 +00003120 return;
3121 }
3122
Aaron Ballman00e99962013-08-31 01:11:41 +00003123 Expr *E = Attr.getArgAsExpr(0);
Richard Smith44c247f2013-02-22 08:32:16 +00003124 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3125 S.Diag(Attr.getEllipsisLoc(),
3126 diag::err_pack_expansion_without_parameter_packs);
3127 return;
3128 }
3129
3130 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3131 return;
3132
David Majnemer26a1e0e2015-04-07 02:37:09 +00003133 if (E->isValueDependent()) {
3134 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3135 if (!TND->getUnderlyingType()->isDependentType()) {
3136 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3137 << E->getSourceRange();
3138 return;
3139 }
3140 }
3141 }
3142
Richard Smith44c247f2013-02-22 08:32:16 +00003143 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3144 Attr.isPackExpansion());
Richard Smith848e1f12013-02-01 08:12:08 +00003145}
3146
3147void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
Richard Smith44c247f2013-02-22 08:32:16 +00003148 unsigned SpellingListIndex, bool IsPackExpansion) {
Richard Smith848e1f12013-02-01 08:12:08 +00003149 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3150 SourceLocation AttrLoc = AttrRange.getBegin();
3151
Richard Smith1dba27c2013-01-29 09:02:09 +00003152 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
Richard Smith848e1f12013-02-01 08:12:08 +00003153 if (TmpAttr.isAlignas()) {
Richard Smith1dba27c2013-01-29 09:02:09 +00003154 // C++11 [dcl.align]p1:
3155 // An alignment-specifier may be applied to a variable or to a class
3156 // data member, but it shall not be applied to a bit-field, a function
3157 // parameter, the formal parameter of a catch clause, or a variable
3158 // declared with the register storage class specifier. An
3159 // alignment-specifier may also be applied to the declaration of a class
3160 // or enumeration type.
3161 // C11 6.7.5/2:
3162 // An alignment attribute shall not be specified in a declaration of
3163 // a typedef, or a bit-field, or a function, or a parameter, or an
3164 // object declared with the register storage-class specifier.
3165 int DiagKind = -1;
3166 if (isa<ParmVarDecl>(D)) {
3167 DiagKind = 0;
3168 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3169 if (VD->getStorageClass() == SC_Register)
3170 DiagKind = 1;
3171 if (VD->isExceptionVariable())
3172 DiagKind = 2;
3173 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3174 if (FD->isBitField())
3175 DiagKind = 3;
3176 } else if (!isa<TagDecl>(D)) {
Aaron Ballman3d216a52014-01-02 23:39:11 +00003177 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
Richard Smith9eaab4b2013-02-01 08:25:07 +00003178 << (TmpAttr.isC11() ? ExpectedVariableOrField
3179 : ExpectedVariableFieldOrTag);
Richard Smith1dba27c2013-01-29 09:02:09 +00003180 return;
3181 }
3182 if (DiagKind != -1) {
Richard Smith848e1f12013-02-01 08:12:08 +00003183 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
Aaron Ballman3d216a52014-01-02 23:39:11 +00003184 << &TmpAttr << DiagKind;
Richard Smith1dba27c2013-01-29 09:02:09 +00003185 return;
3186 }
3187 }
3188
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003189 if (E->isTypeDependent() || E->isValueDependent()) {
3190 // Save dependent expressions in the AST to be instantiated.
Richard Smith44c247f2013-02-22 08:32:16 +00003191 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3192 AA->setPackExpansion(IsPackExpansion);
3193 D->addAttr(AA);
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003194 return;
3195 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003196
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003197 // FIXME: Cache the number on the Attr object?
David Majnemer0be6bd02015-07-26 09:02:21 +00003198 llvm::APSInt Alignment;
Douglas Gregore2b37442012-05-04 22:38:52 +00003199 ExprResult ICE
3200 = VerifyIntegerConstantExpression(E, &Alignment,
3201 diag::err_aligned_attribute_argument_not_int,
3202 /*AllowFold*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00003203 if (ICE.isInvalid())
Chris Lattner4627b742008-06-28 23:50:44 +00003204 return;
Richard Smith848e1f12013-02-01 08:12:08 +00003205
David Majnemer0be6bd02015-07-26 09:02:21 +00003206 uint64_t AlignVal = Alignment.getZExtValue();
3207
Richard Smith848e1f12013-02-01 08:12:08 +00003208 // C++11 [dcl.align]p2:
3209 // -- if the constant expression evaluates to zero, the alignment
3210 // specifier shall have no effect
3211 // C11 6.7.5p6:
3212 // An alignment specification of zero has no effect.
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003213 if (!(TmpAttr.isAlignas() && !Alignment)) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003214 if (!llvm::isPowerOf2_64(AlignVal)) {
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003215 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3216 << E->getSourceRange();
3217 return;
3218 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003219 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003220
David Majnemerabecae72014-02-12 20:36:10 +00003221 // Alignment calculations can wrap around if it's greater than 2**28.
David Majnemer29c69db2015-07-26 01:48:59 +00003222 unsigned MaxValidAlignment =
3223 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3224 : 268435456;
David Majnemer0be6bd02015-07-26 09:02:21 +00003225 if (AlignVal > MaxValidAlignment) {
David Majnemerabecae72014-02-12 20:36:10 +00003226 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3227 << E->getSourceRange();
3228 return;
Aaron Ballman478faed2012-06-19 22:09:27 +00003229 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003230
David Majnemer0be6bd02015-07-26 09:02:21 +00003231 if (Context.getTargetInfo().isTLSSupported()) {
3232 unsigned MaxTLSAlign =
3233 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3234 .getQuantity();
3235 auto *VD = dyn_cast<VarDecl>(D);
3236 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3237 VD->getTLSKind() != VarDecl::TLS_None) {
3238 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3239 << (unsigned)AlignVal << VD << MaxTLSAlign;
3240 return;
3241 }
3242 }
3243
Richard Smith44c247f2013-02-22 08:32:16 +00003244 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003245 ICE.get(), SpellingListIndex);
Richard Smith44c247f2013-02-22 08:32:16 +00003246 AA->setPackExpansion(IsPackExpansion);
3247 D->addAttr(AA);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003248}
3249
Michael Hanaf02bbe2013-02-01 01:19:17 +00003250void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
Richard Smith44c247f2013-02-22 08:32:16 +00003251 unsigned SpellingListIndex, bool IsPackExpansion) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003252 // FIXME: Cache the number on the Attr object if non-dependent?
3253 // FIXME: Perform checking of type validity
Richard Smith44c247f2013-02-22 08:32:16 +00003254 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3255 SpellingListIndex);
3256 AA->setPackExpansion(IsPackExpansion);
3257 D->addAttr(AA);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003258}
Chris Lattneracbc2d22008-06-27 22:18:37 +00003259
Richard Smith848e1f12013-02-01 08:12:08 +00003260void Sema::CheckAlignasUnderalignment(Decl *D) {
3261 assert(D->hasAttrs() && "no attributes on decl");
3262
David Majnemer475b25e2015-01-21 10:54:38 +00003263 QualType UnderlyingTy, DiagTy;
3264 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3265 UnderlyingTy = DiagTy = VD->getType();
3266 } else {
3267 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3268 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3269 UnderlyingTy = ED->getIntegerType();
3270 }
3271 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
Richard Smith848e1f12013-02-01 08:12:08 +00003272 return;
3273
3274 // C++11 [dcl.align]p5, C11 6.7.5/4:
3275 // The combined effect of all alignment attributes in a declaration shall
3276 // not specify an alignment that is less strict than the alignment that
3277 // would otherwise be required for the entity being declared.
Craig Topperc3ec1492014-05-26 06:22:03 +00003278 AlignedAttr *AlignasAttr = nullptr;
Richard Smith848e1f12013-02-01 08:12:08 +00003279 unsigned Align = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003280 for (auto *I : D->specific_attrs<AlignedAttr>()) {
Richard Smith848e1f12013-02-01 08:12:08 +00003281 if (I->isAlignmentDependent())
3282 return;
3283 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003284 AlignasAttr = I;
Richard Smith848e1f12013-02-01 08:12:08 +00003285 Align = std::max(Align, I->getAlignment(Context));
3286 }
3287
3288 if (AlignasAttr && Align) {
3289 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
David Majnemer475b25e2015-01-21 10:54:38 +00003290 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
Richard Smith848e1f12013-02-01 08:12:08 +00003291 if (NaturalAlign > RequestedAlign)
3292 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
David Majnemer475b25e2015-01-21 10:54:38 +00003293 << DiagTy << (unsigned)NaturalAlign.getQuantity();
Richard Smith848e1f12013-02-01 08:12:08 +00003294 }
3295}
3296
David Majnemer2c4e00a2014-01-29 22:07:36 +00003297bool Sema::checkMSInheritanceAttrOnDefinition(
David Majnemer4bb09802014-02-10 19:50:15 +00003298 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00003299 MSInheritanceAttr::Spelling SemanticSpelling) {
3300 assert(RD->hasDefinition() && "RD has no definition!");
3301
David Majnemer98c9ee22014-02-07 00:43:07 +00003302 // We may not have seen base specifiers or any virtual methods yet. We will
3303 // have to wait until the record is defined to catch any mismatches.
3304 if (!RD->getDefinition()->isCompleteDefinition())
3305 return false;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003306
David Majnemer98c9ee22014-02-07 00:43:07 +00003307 // The unspecified model never matches what a definition could need.
3308 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3309 return false;
3310
David Majnemer4bb09802014-02-10 19:50:15 +00003311 if (BestCase) {
3312 if (RD->calculateInheritanceModel() == SemanticSpelling)
3313 return false;
3314 } else {
3315 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3316 return false;
3317 }
David Majnemer98c9ee22014-02-07 00:43:07 +00003318
3319 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3320 << 0 /*definition*/;
3321 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3322 << RD->getNameAsString();
3323 return true;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003324}
3325
Alexey Bataevf278eb12015-11-19 10:13:11 +00003326/// parseModeAttrArg - Parses attribute mode string and returns parsed type
3327/// attribute.
3328static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3329 bool &IntegerMode, bool &ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003330 IntegerMode = true;
3331 ComplexMode = false;
Daniel Dunbarafff4342009-10-18 02:09:24 +00003332 switch (Str.size()) {
Chris Lattneracbc2d22008-06-27 22:18:37 +00003333 case 2:
Eli Friedman4735374e2009-03-03 06:41:03 +00003334 switch (Str[0]) {
Alexey Bataevf278eb12015-11-19 10:13:11 +00003335 case 'Q':
3336 DestWidth = 8;
3337 break;
3338 case 'H':
3339 DestWidth = 16;
3340 break;
3341 case 'S':
3342 DestWidth = 32;
3343 break;
3344 case 'D':
3345 DestWidth = 64;
3346 break;
3347 case 'X':
3348 DestWidth = 96;
3349 break;
3350 case 'T':
3351 DestWidth = 128;
3352 break;
Eli Friedman4735374e2009-03-03 06:41:03 +00003353 }
3354 if (Str[1] == 'F') {
3355 IntegerMode = false;
3356 } else if (Str[1] == 'C') {
3357 IntegerMode = false;
3358 ComplexMode = true;
3359 } else if (Str[1] != 'I') {
3360 DestWidth = 0;
3361 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003362 break;
3363 case 4:
3364 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3365 // pointer on PIC16 and other embedded platforms.
Daniel Dunbarafff4342009-10-18 02:09:24 +00003366 if (Str == "word")
Reid Klecknerf27e7522016-02-01 18:58:24 +00003367 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
Daniel Dunbarafff4342009-10-18 02:09:24 +00003368 else if (Str == "byte")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003369 DestWidth = S.Context.getTargetInfo().getCharWidth();
Chris Lattneracbc2d22008-06-27 22:18:37 +00003370 break;
3371 case 7:
Daniel Dunbarafff4342009-10-18 02:09:24 +00003372 if (Str == "pointer")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003373 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
Chris Lattneracbc2d22008-06-27 22:18:37 +00003374 break;
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003375 case 11:
3376 if (Str == "unwind_word")
Rafael Espindola03705972013-01-07 20:01:57 +00003377 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003378 break;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003379 }
Alexey Bataevf278eb12015-11-19 10:13:11 +00003380}
3381
3382/// handleModeAttr - This attribute modifies the width of a decl with primitive
3383/// type.
3384///
3385/// Despite what would be logical, the mode attribute is a decl attribute, not a
3386/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3387/// HImode, not an intermediate pointer.
3388static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3389 // This attribute isn't documented, but glibc uses it. It changes
3390 // the width of an int or unsigned int to the specified size.
3391 if (!Attr.isArgIdent(0)) {
3392 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3393 << AANT_ArgumentIdentifier;
3394 return;
3395 }
3396
3397 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003398
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003399 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3400}
3401
3402void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3403 unsigned SpellingListIndex, bool InInstantiation) {
3404 StringRef Str = Name->getName();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003405 normalizeName(Str);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003406 SourceLocation AttrLoc = AttrRange.getBegin();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003407
3408 unsigned DestWidth = 0;
3409 bool IntegerMode = true;
3410 bool ComplexMode = false;
3411 llvm::APInt VectorSize(64, 0);
3412 if (Str.size() >= 4 && Str[0] == 'V') {
3413 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3414 size_t StrSize = Str.size();
3415 size_t VectorStringLength = 0;
3416 while ((VectorStringLength + 1) < StrSize &&
3417 isdigit(Str[VectorStringLength + 1]))
3418 ++VectorStringLength;
3419 if (VectorStringLength &&
3420 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3421 VectorSize.isPowerOf2()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003422 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
Alexey Bataevf278eb12015-11-19 10:13:11 +00003423 IntegerMode, ComplexMode);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003424 // Avoid duplicate warning from template instantiation.
3425 if (!InInstantiation)
3426 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003427 } else {
3428 VectorSize = 0;
3429 }
3430 }
3431
3432 if (!VectorSize)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003433 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3434
3435 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3436 // and friends, at least with glibc.
3437 // FIXME: Make sure floating-point mappings are accurate
3438 // FIXME: Support XF and TF types
3439 if (!DestWidth) {
3440 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3441 return;
3442 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003443
3444 QualType OldTy;
Richard Smithdda56e42011-04-15 14:24:37 +00003445 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
Chris Lattneracbc2d22008-06-27 22:18:37 +00003446 OldTy = TD->getUnderlyingType();
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003447 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3448 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3449 // Try to get type from enum declaration, default to int.
3450 OldTy = ED->getIntegerType();
3451 if (OldTy.isNull())
3452 OldTy = Context.IntTy;
3453 } else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003454 OldTy = cast<ValueDecl>(D)->getType();
Eli Friedman4735374e2009-03-03 06:41:03 +00003455
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003456 if (OldTy->isDependentType()) {
3457 D->addAttr(::new (Context)
3458 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3459 return;
3460 }
3461
Alexey Bataev326057d2015-06-19 07:46:21 +00003462 // Base type can also be a vector type (see PR17453).
3463 // Distinguish between base type and base element type.
3464 QualType OldElemTy = OldTy;
3465 if (const VectorType *VT = OldTy->getAs<VectorType>())
3466 OldElemTy = VT->getElementType();
3467
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003468 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3469 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3470 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3471 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3472 VectorSize.getBoolValue()) {
3473 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3474 return;
3475 }
3476 bool IntegralOrAnyEnumType =
3477 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3478
3479 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3480 !IntegralOrAnyEnumType)
3481 Diag(AttrLoc, diag::err_mode_not_primitive);
Eli Friedman4735374e2009-03-03 06:41:03 +00003482 else if (IntegerMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003483 if (!IntegralOrAnyEnumType)
3484 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003485 } else if (ComplexMode) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003486 if (!OldElemTy->isComplexType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003487 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003488 } else {
Alexey Bataev326057d2015-06-19 07:46:21 +00003489 if (!OldElemTy->isFloatingType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003490 Diag(AttrLoc, diag::err_mode_wrong_type);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003491 }
3492
Alexey Bataev326057d2015-06-19 07:46:21 +00003493 QualType NewElemTy;
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003494
3495 if (IntegerMode)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003496 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3497 OldElemTy->isSignedIntegerType());
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003498 else
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003499 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003500
Alexey Bataev326057d2015-06-19 07:46:21 +00003501 if (NewElemTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003502 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003503 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003504 }
3505
Eli Friedman4735374e2009-03-03 06:41:03 +00003506 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003507 NewElemTy = Context.getComplexType(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003508 }
3509
3510 QualType NewTy = NewElemTy;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003511 if (VectorSize.getBoolValue()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003512 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3513 VectorType::GenericVector);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003514 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003515 // Complex machine mode does not support base vector types.
3516 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003517 Diag(AttrLoc, diag::err_complex_mode_vector_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003518 return;
3519 }
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003520 unsigned NumElements = Context.getTypeSize(OldElemTy) *
Alexey Bataev326057d2015-06-19 07:46:21 +00003521 OldVT->getNumElements() /
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003522 Context.getTypeSize(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003523 NewTy =
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003524 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
Alexey Bataev326057d2015-06-19 07:46:21 +00003525 }
3526
3527 if (NewTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003528 Diag(AttrLoc, diag::err_mode_wrong_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003529 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003530 }
3531
3532 // Install the new type.
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003533 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3534 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003535 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3536 ED->setIntegerType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003537 else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003538 cast<ValueDecl>(D)->setType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003539
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003540 D->addAttr(::new (Context)
3541 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
Chris Lattneracbc2d22008-06-27 22:18:37 +00003542}
Chris Lattner9e2aafe2008-06-29 00:23:49 +00003543
Chandler Carruthedc2c642011-07-02 00:01:44 +00003544static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Nick Lewycky08597072012-07-24 01:40:49 +00003545 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3546 if (!VD->hasGlobalStorage())
3547 S.Diag(Attr.getLoc(),
3548 diag::warn_attribute_requires_functions_or_static_globals)
3549 << Attr.getName();
3550 } else if (!isFunctionOrMethod(D)) {
3551 S.Diag(Attr.getLoc(),
3552 diag::warn_attribute_requires_functions_or_static_globals)
3553 << Attr.getName();
Anders Carlsson76187b42009-02-13 06:46:13 +00003554 return;
3555 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003556
Michael Han99315932013-01-24 16:46:58 +00003557 D->addAttr(::new (S.Context)
3558 NoDebugAttr(Attr.getRange(), S.Context,
3559 Attr.getAttributeSpellingListIndex()));
Anders Carlsson76187b42009-02-13 06:46:13 +00003560}
3561
Paul Robinson30e41fb2014-12-15 18:57:28 +00003562AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
Paul Robinson080b1f32015-01-13 18:34:56 +00003563 IdentifierInfo *Ident,
Paul Robinson30e41fb2014-12-15 18:57:28 +00003564 unsigned AttrSpellingListIndex) {
3565 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
Paul Robinson080b1f32015-01-13 18:34:56 +00003566 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
Paul Robinson30e41fb2014-12-15 18:57:28 +00003567 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3568 return nullptr;
3569 }
3570
3571 if (D->hasAttr<AlwaysInlineAttr>())
3572 return nullptr;
3573
3574 return ::new (Context) AlwaysInlineAttr(Range, Context,
3575 AttrSpellingListIndex);
3576}
3577
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00003578CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3579 IdentifierInfo *Ident,
3580 unsigned AttrSpellingListIndex) {
3581 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3582 return nullptr;
3583
3584 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3585}
3586
3587InternalLinkageAttr *
3588Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3589 IdentifierInfo *Ident,
3590 unsigned AttrSpellingListIndex) {
3591 if (auto VD = dyn_cast<VarDecl>(D)) {
3592 // Attribute applies to Var but not any subclass of it (like ParmVar,
3593 // ImplicitParm or VarTemplateSpecialization).
3594 if (VD->getKind() != Decl::Var) {
3595 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3596 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3597 : ExpectedVariableOrFunction);
3598 return nullptr;
3599 }
3600 // Attribute does not apply to non-static local variables.
3601 if (VD->hasLocalStorage()) {
3602 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3603 return nullptr;
3604 }
3605 }
3606
3607 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3608 return nullptr;
3609
3610 return ::new (Context)
3611 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3612}
3613
Paul Robinson30e41fb2014-12-15 18:57:28 +00003614MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3615 unsigned AttrSpellingListIndex) {
3616 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3617 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3618 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3619 return nullptr;
3620 }
3621
3622 if (D->hasAttr<MinSizeAttr>())
3623 return nullptr;
3624
3625 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3626}
3627
3628OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3629 unsigned AttrSpellingListIndex) {
3630 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3631 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3632 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3633 D->dropAttr<AlwaysInlineAttr>();
3634 }
3635 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3636 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3637 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3638 D->dropAttr<MinSizeAttr>();
3639 }
3640
3641 if (D->hasAttr<OptimizeNoneAttr>())
3642 return nullptr;
3643
3644 return ::new (Context) OptimizeNoneAttr(Range, Context,
3645 AttrSpellingListIndex);
3646}
3647
Paul Robinsonf0674352014-03-31 22:29:15 +00003648static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3649 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00003650 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
3651 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00003652 return;
3653
Paul Robinson080b1f32015-01-13 18:34:56 +00003654 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3655 D, Attr.getRange(), Attr.getName(),
3656 Attr.getAttributeSpellingListIndex()))
3657 D->addAttr(Inline);
Paul Robinsonf0674352014-03-31 22:29:15 +00003658}
3659
Paul Robinson080b1f32015-01-13 18:34:56 +00003660static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3661 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3662 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3663 D->addAttr(MinSize);
Paul Robinsonaae2fba2014-12-10 23:34:36 +00003664}
3665
Paul Robinsonf0674352014-03-31 22:29:15 +00003666static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3667 const AttributeList &Attr) {
Paul Robinson080b1f32015-01-13 18:34:56 +00003668 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3669 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3670 D->addAttr(Optnone);
Paul Robinsonf0674352014-03-31 22:29:15 +00003671}
3672
Chandler Carruthedc2c642011-07-02 00:01:44 +00003673static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Justin Lebar3eaaf862016-01-13 01:07:35 +00003674 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
3675 Attr.getName()) ||
3676 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
3677 Attr.getName())) {
3678 return;
3679 }
Aaron Ballman3aff6332013-12-02 19:30:36 +00003680 FunctionDecl *FD = cast<FunctionDecl>(D);
Alp Toker314cc812014-01-25 16:55:45 +00003681 if (!FD->getReturnType()->isVoidType()) {
Alp Tokerf5b10792014-07-02 12:55:58 +00003682 SourceRange RTRange = FD->getReturnTypeSourceRange();
3683 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
Aaron Ballman3aff6332013-12-02 19:30:36 +00003684 << FD->getType()
Alp Tokerf5b10792014-07-02 12:55:58 +00003685 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3686 : FixItHint());
Aaron Ballman3aff6332013-12-02 19:30:36 +00003687 return;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00003688 }
Justin Lebarc66a1062016-01-20 00:26:57 +00003689 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
3690 if (Method->isInstance()) {
3691 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
3692 << Method;
3693 return;
3694 }
3695 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
3696 }
3697 // Only warn for "inline" when compiling for host, to cut down on noise.
3698 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
3699 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00003700
Aaron Ballman3aff6332013-12-02 19:30:36 +00003701 D->addAttr(::new (S.Context)
3702 CUDAGlobalAttr(Attr.getRange(), S.Context,
Eli Bendersky83860042014-09-02 22:00:06 +00003703 Attr.getAttributeSpellingListIndex()));
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00003704}
3705
Chandler Carruthedc2c642011-07-02 00:01:44 +00003706static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003707 FunctionDecl *Fn = cast<FunctionDecl>(D);
Douglas Gregor35b57532009-10-27 21:01:01 +00003708 if (!Fn->isInlineSpecified()) {
Chris Lattnerddf6ca02009-04-20 19:12:28 +00003709 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
Chris Lattner4225e232009-04-14 17:02:11 +00003710 return;
3711 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003712
Michael Han99315932013-01-24 16:46:58 +00003713 D->addAttr(::new (S.Context)
3714 GNUInlineAttr(Attr.getRange(), S.Context,
3715 Attr.getAttributeSpellingListIndex()));
Chris Lattnereaad6b72009-04-14 16:30:50 +00003716}
3717
Chandler Carruthedc2c642011-07-02 00:01:44 +00003718static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003719 if (hasDeclarator(D)) return;
Abramo Bagnara50099372010-04-30 13:10:51 +00003720
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003721 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
John McCall3882ace2011-01-05 12:14:39 +00003722 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3723 CallingConv CC;
Richard Smitheec7cb12015-05-28 23:38:53 +00003724 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
John McCall3882ace2011-01-05 12:14:39 +00003725 return;
3726
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003727 if (!isa<ObjCMethodDecl>(D)) {
3728 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3729 << Attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00003730 return;
3731 }
3732
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003733 switch (Attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003734 case AttributeList::AT_FastCall:
Michael Han99315932013-01-24 16:46:58 +00003735 D->addAttr(::new (S.Context)
3736 FastCallAttr(Attr.getRange(), S.Context,
3737 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00003738 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003739 case AttributeList::AT_StdCall:
Michael Han99315932013-01-24 16:46:58 +00003740 D->addAttr(::new (S.Context)
3741 StdCallAttr(Attr.getRange(), S.Context,
3742 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00003743 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003744 case AttributeList::AT_ThisCall:
Michael Han99315932013-01-24 16:46:58 +00003745 D->addAttr(::new (S.Context)
3746 ThisCallAttr(Attr.getRange(), S.Context,
3747 Attr.getAttributeSpellingListIndex()));
Douglas Gregor4d13d102010-08-30 23:30:49 +00003748 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003749 case AttributeList::AT_CDecl:
Michael Han99315932013-01-24 16:46:58 +00003750 D->addAttr(::new (S.Context)
3751 CDeclAttr(Attr.getRange(), S.Context,
3752 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00003753 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003754 case AttributeList::AT_Pascal:
Michael Han99315932013-01-24 16:46:58 +00003755 D->addAttr(::new (S.Context)
3756 PascalAttr(Attr.getRange(), S.Context,
3757 Attr.getAttributeSpellingListIndex()));
Dawn Perchik335e16b2010-09-03 01:29:35 +00003758 return;
John McCall477f2bb2016-03-03 06:39:32 +00003759 case AttributeList::AT_SwiftCall:
3760 D->addAttr(::new (S.Context)
3761 SwiftCallAttr(Attr.getRange(), S.Context,
3762 Attr.getAttributeSpellingListIndex()));
3763 return;
Reid Klecknerd7857f02014-10-24 17:42:17 +00003764 case AttributeList::AT_VectorCall:
3765 D->addAttr(::new (S.Context)
3766 VectorCallAttr(Attr.getRange(), S.Context,
3767 Attr.getAttributeSpellingListIndex()));
3768 return;
Charles Davisb5a214e2013-08-30 04:39:01 +00003769 case AttributeList::AT_MSABI:
3770 D->addAttr(::new (S.Context)
3771 MSABIAttr(Attr.getRange(), S.Context,
3772 Attr.getAttributeSpellingListIndex()));
3773 return;
3774 case AttributeList::AT_SysVABI:
3775 D->addAttr(::new (S.Context)
3776 SysVABIAttr(Attr.getRange(), S.Context,
3777 Attr.getAttributeSpellingListIndex()));
3778 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003779 case AttributeList::AT_Pcs: {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003780 PcsAttr::PCSType PCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00003781 switch (CC) {
3782 case CC_AAPCS:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003783 PCS = PcsAttr::AAPCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00003784 break;
3785 case CC_AAPCS_VFP:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003786 PCS = PcsAttr::AAPCS_VFP;
Benjamin Kramer25885f42012-08-14 13:24:39 +00003787 break;
3788 default:
3789 llvm_unreachable("unexpected calling convention in pcs attribute");
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003790 }
3791
Michael Han99315932013-01-24 16:46:58 +00003792 D->addAttr(::new (S.Context)
3793 PcsAttr(Attr.getRange(), S.Context, PCS,
3794 Attr.getAttributeSpellingListIndex()));
Derek Schuffa2020962012-10-16 22:30:41 +00003795 return;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003796 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00003797 case AttributeList::AT_IntelOclBicc:
Michael Han99315932013-01-24 16:46:58 +00003798 D->addAttr(::new (S.Context)
3799 IntelOclBiccAttr(Attr.getRange(), S.Context,
3800 Attr.getAttributeSpellingListIndex()));
Guy Benyeif0a014b2012-12-25 08:53:55 +00003801 return;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00003802 case AttributeList::AT_PreserveMost:
3803 D->addAttr(::new (S.Context) PreserveMostAttr(
3804 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3805 return;
3806 case AttributeList::AT_PreserveAll:
3807 D->addAttr(::new (S.Context) PreserveAllAttr(
3808 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3809 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00003810 default:
3811 llvm_unreachable("unexpected attribute kind");
Abramo Bagnara50099372010-04-30 13:10:51 +00003812 }
3813}
3814
Aaron Ballman02df2e02012-12-09 17:45:41 +00003815bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3816 const FunctionDecl *FD) {
John McCall3882ace2011-01-05 12:14:39 +00003817 if (attr.isInvalid())
3818 return true;
3819
John McCall3b5a8f52016-03-03 00:10:03 +00003820 if (attr.hasProcessingCache()) {
3821 CC = (CallingConv) attr.getProcessingCache();
3822 return false;
3823 }
3824
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00003825 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
Aaron Ballman00e99962013-08-31 01:11:41 +00003826 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
John McCall3882ace2011-01-05 12:14:39 +00003827 attr.setInvalid();
3828 return true;
3829 }
3830
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003831 // TODO: diagnose uses of these conventions on the wrong target.
John McCall3882ace2011-01-05 12:14:39 +00003832 switch (attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003833 case AttributeList::AT_CDecl: CC = CC_C; break;
3834 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3835 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3836 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3837 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
John McCall477f2bb2016-03-03 06:39:32 +00003838 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +00003839 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
Charles Davisb5a214e2013-08-30 04:39:01 +00003840 case AttributeList::AT_MSABI:
3841 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3842 CC_X86_64Win64;
3843 break;
3844 case AttributeList::AT_SysVABI:
3845 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3846 CC_C;
3847 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003848 case AttributeList::AT_Pcs: {
Aaron Ballmand6600a52013-09-13 17:48:25 +00003849 StringRef StrRef;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003850 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003851 attr.setInvalid();
3852 return true;
3853 }
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003854 if (StrRef == "aapcs") {
3855 CC = CC_AAPCS;
3856 break;
3857 } else if (StrRef == "aapcs-vfp") {
3858 CC = CC_AAPCS_VFP;
3859 break;
3860 }
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00003861
3862 attr.setInvalid();
3863 Diag(attr.getLoc(), diag::err_invalid_pcs);
3864 return true;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003865 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00003866 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00003867 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
3868 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
David Blaikie8a40f702012-01-17 06:56:22 +00003869 default: llvm_unreachable("unexpected attribute kind");
John McCall3882ace2011-01-05 12:14:39 +00003870 }
3871
Aaron Ballmane91c6be2012-10-02 14:26:08 +00003872 const TargetInfo &TI = Context.getTargetInfo();
3873 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
Reid Kleckner9fde2e02015-02-26 19:43:46 +00003874 if (A != TargetInfo::CCCR_OK) {
3875 if (A == TargetInfo::CCCR_Warning)
3876 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
Aaron Ballman02df2e02012-12-09 17:45:41 +00003877
Reid Kleckner9fde2e02015-02-26 19:43:46 +00003878 // This convention is not valid for the target. Use the default function or
3879 // method calling convention.
Aaron Ballman02df2e02012-12-09 17:45:41 +00003880 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3881 if (FD)
3882 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3883 TargetInfo::CCMT_NonMember;
3884 CC = TI.getDefaultCallingConv(MT);
Aaron Ballmane91c6be2012-10-02 14:26:08 +00003885 }
3886
John McCall3b5a8f52016-03-03 00:10:03 +00003887 attr.setProcessingCache((unsigned) CC);
John McCall3882ace2011-01-05 12:14:39 +00003888 return false;
3889}
3890
John McCall477f2bb2016-03-03 06:39:32 +00003891/// Pointer-like types in the default address space.
3892static bool isValidSwiftContextType(QualType type) {
3893 if (!type->hasPointerRepresentation())
3894 return type->isDependentType();
3895 return type->getPointeeType().getAddressSpace() == 0;
3896}
3897
3898/// Pointers and references in the default address space.
3899static bool isValidSwiftIndirectResultType(QualType type) {
3900 if (auto ptrType = type->getAs<PointerType>()) {
3901 type = ptrType->getPointeeType();
3902 } else if (auto refType = type->getAs<ReferenceType>()) {
3903 type = refType->getPointeeType();
3904 } else {
3905 return type->isDependentType();
3906 }
3907 return type.getAddressSpace() == 0;
3908}
3909
3910/// Pointers and references to pointers in the default address space.
3911static bool isValidSwiftErrorResultType(QualType type) {
3912 if (auto ptrType = type->getAs<PointerType>()) {
3913 type = ptrType->getPointeeType();
3914 } else if (auto refType = type->getAs<ReferenceType>()) {
3915 type = refType->getPointeeType();
3916 } else {
3917 return type->isDependentType();
3918 }
3919 if (!type.getQualifiers().empty())
3920 return false;
3921 return isValidSwiftContextType(type);
3922}
3923
3924static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
3925 ParameterABI abi) {
3926 S.AddParameterABIAttr(attr.getRange(), D, abi,
3927 attr.getAttributeSpellingListIndex());
3928}
3929
3930void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
3931 unsigned spellingIndex) {
3932
3933 QualType type = cast<ParmVarDecl>(D)->getType();
3934
3935 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
3936 if (existingAttr->getABI() != abi) {
3937 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
3938 << getParameterABISpelling(abi) << existingAttr;
3939 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
3940 return;
3941 }
3942 }
3943
3944 switch (abi) {
3945 case ParameterABI::Ordinary:
3946 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
3947
3948 case ParameterABI::SwiftContext:
3949 if (!isValidSwiftContextType(type)) {
3950 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
3951 << getParameterABISpelling(abi)
3952 << /*pointer to pointer */ 0 << type;
3953 }
3954 D->addAttr(::new (Context)
3955 SwiftContextAttr(range, Context, spellingIndex));
3956 return;
3957
3958 case ParameterABI::SwiftErrorResult:
3959 if (!isValidSwiftErrorResultType(type)) {
3960 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
3961 << getParameterABISpelling(abi)
3962 << /*pointer to pointer */ 1 << type;
3963 }
3964 D->addAttr(::new (Context)
3965 SwiftErrorResultAttr(range, Context, spellingIndex));
3966 return;
3967
3968 case ParameterABI::SwiftIndirectResult:
3969 if (!isValidSwiftIndirectResultType(type)) {
3970 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
3971 << getParameterABISpelling(abi)
3972 << /*pointer*/ 0 << type;
3973 }
3974 D->addAttr(::new (Context)
3975 SwiftIndirectResultAttr(range, Context, spellingIndex));
3976 return;
3977 }
3978 llvm_unreachable("bad parameter ABI attribute");
3979}
3980
John McCall3882ace2011-01-05 12:14:39 +00003981/// Checks a regparm attribute, returning true if it is ill-formed and
3982/// otherwise setting numParams to the appropriate value.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003983bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3984 if (Attr.isInvalid())
John McCall3882ace2011-01-05 12:14:39 +00003985 return true;
3986
Aaron Ballmanc2cbc662013-07-18 18:01:48 +00003987 if (!checkAttributeNumArgs(*this, Attr, 1)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003988 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00003989 return true;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00003990 }
Eli Friedman7044b762009-03-27 21:06:47 +00003991
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003992 uint32_t NP;
Aaron Ballman00e99962013-08-31 01:11:41 +00003993 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003994 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003995 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00003996 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00003997 }
3998
Douglas Gregore8bbc122011-09-02 00:18:52 +00003999 if (Context.getTargetInfo().getRegParmMax() == 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004000 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
Eli Friedman7044b762009-03-27 21:06:47 +00004001 << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004002 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004003 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004004 }
4005
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004006 numParams = NP;
Douglas Gregore8bbc122011-09-02 00:18:52 +00004007 if (numParams > Context.getTargetInfo().getRegParmMax()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004008 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
Douglas Gregore8bbc122011-09-02 00:18:52 +00004009 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004010 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004011 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004012 }
4013
John McCall3882ace2011-01-05 12:14:39 +00004014 return false;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004015}
4016
Artem Belevich7093e402015-04-21 22:55:54 +00004017// Checks whether an argument of launch_bounds attribute is acceptable
4018// May output an error.
4019static bool checkLaunchBoundsArgument(Sema &S, Expr *E,
4020 const CUDALaunchBoundsAttr &Attr,
4021 const unsigned Idx) {
Artem Belevich7093e402015-04-21 22:55:54 +00004022 if (S.DiagnoseUnexpandedParameterPack(E))
4023 return false;
4024
4025 // Accept template arguments for now as they depend on something else.
4026 // We'll get to check them when they eventually get instantiated.
4027 if (E->isValueDependent())
4028 return true;
4029
4030 llvm::APSInt I(64);
4031 if (!E->isIntegerConstantExpr(I, S.Context)) {
4032 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4033 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4034 return false;
4035 }
4036 // Make sure we can fit it in 32 bits.
4037 if (!I.isIntN(32)) {
4038 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4039 << 32 << /* Unsigned */ 1;
4040 return false;
4041 }
4042 if (I < 0)
4043 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4044 << &Attr << Idx << E->getSourceRange();
4045
4046 return true;
4047}
4048
4049void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4050 Expr *MinBlocks, unsigned SpellingListIndex) {
4051 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4052 SpellingListIndex);
4053
4054 if (!checkLaunchBoundsArgument(*this, MaxThreads, TmpAttr, 0))
Aaron Ballman3aff6332013-12-02 19:30:36 +00004055 return;
4056
Artem Belevich7093e402015-04-21 22:55:54 +00004057 if (MinBlocks && !checkLaunchBoundsArgument(*this, MinBlocks, TmpAttr, 1))
4058 return;
4059
4060 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4061 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4062}
4063
4064static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4065 const AttributeList &Attr) {
4066 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4067 !checkAttributeAtMostNumArgs(S, Attr, 2))
4068 return;
4069
4070 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4071 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4072 Attr.getAttributeSpellingListIndex());
Peter Collingbourne827301e2010-12-12 23:03:07 +00004073}
4074
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004075static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4076 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004077 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004078 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004079 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004080 return;
4081 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004082
4083 if (!checkAttributeNumArgs(S, Attr, 3))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004084 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004085
Aaron Ballman00e99962013-08-31 01:11:41 +00004086 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004087
4088 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4089 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4090 << Attr.getName() << ExpectedFunctionOrMethod;
4091 return;
4092 }
4093
4094 uint64_t ArgumentIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004095 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4096 ArgumentIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004097 return;
4098
4099 uint64_t TypeTagIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004100 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4101 TypeTagIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004102 return;
4103
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00004104 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004105 if (IsPointer) {
4106 // Ensure that buffer has a pointer type.
Alp Toker601b22c2014-01-21 23:35:24 +00004107 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004108 if (!BufferTy->isPointerType()) {
4109 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004110 << Attr.getName() << 0;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004111 }
4112 }
4113
Michael Han99315932013-01-24 16:46:58 +00004114 D->addAttr(::new (S.Context)
4115 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4116 ArgumentIdx, TypeTagIdx, IsPointer,
4117 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004118}
4119
4120static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4121 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004122 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004123 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004124 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004125 return;
4126 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004127
4128 if (!checkAttributeNumArgs(S, Attr, 1))
4129 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004130
Aaron Ballman90f8c6f2013-11-25 18:50:49 +00004131 if (!isa<VarDecl>(D)) {
4132 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4133 << Attr.getName() << ExpectedVariable;
4134 return;
4135 }
4136
Aaron Ballman00e99962013-08-31 01:11:41 +00004137 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
Craig Topperc3ec1492014-05-26 06:22:03 +00004138 TypeSourceInfo *MatchingCTypeLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00004139 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4140 assert(MatchingCTypeLoc && "no type source info for attribute argument");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004141
Michael Han99315932013-01-24 16:46:58 +00004142 D->addAttr(::new (S.Context)
4143 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
Richard Smithb87c4652013-10-31 21:23:20 +00004144 MatchingCTypeLoc,
Michael Han99315932013-01-24 16:46:58 +00004145 Attr.getLayoutCompatible(),
4146 Attr.getMustBeNull(),
4147 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004148}
4149
Chris Lattner9e2aafe2008-06-29 00:23:49 +00004150//===----------------------------------------------------------------------===//
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004151// Checker-specific attribute handlers.
4152//===----------------------------------------------------------------------===//
4153
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004154static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004155 return type->isDependentType() ||
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004156 type->isObjCRetainableType();
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004157}
4158
John McCalled433932011-01-25 03:31:58 +00004159static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004160 return type->isDependentType() ||
4161 type->isObjCObjectPointerType() ||
4162 S.Context.isObjCNSObjectType(type);
John McCalled433932011-01-25 03:31:58 +00004163}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004164
John McCalled433932011-01-25 03:31:58 +00004165static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004166 return type->isDependentType() ||
4167 type->isPointerType() ||
4168 isValidSubjectOfNSAttribute(S, type);
John McCalled433932011-01-25 03:31:58 +00004169}
4170
Chandler Carruthedc2c642011-07-02 00:01:44 +00004171static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John McCall3b5a8f52016-03-03 00:10:03 +00004172 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4173 Attr.getKind() == AttributeList::AT_NSConsumed,
4174 /*template instantiation*/ false);
4175}
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004176
John McCall3b5a8f52016-03-03 00:10:03 +00004177void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4178 unsigned spellingIndex, bool isNSConsumed,
4179 bool isTemplateInstantiation) {
4180 ParmVarDecl *param = cast<ParmVarDecl>(D);
4181 bool typeOK;
4182
4183 if (isNSConsumed) {
4184 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004185 } else {
John McCall3b5a8f52016-03-03 00:10:03 +00004186 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004187 }
4188
4189 if (!typeOK) {
John McCall3b5a8f52016-03-03 00:10:03 +00004190 // These attributes are normally just advisory, but in ARC, ns_consumed
4191 // is significant. Allow non-dependent code to contain inappropriate
4192 // attributes even in ARC, but require template instantiations to be
4193 // set up correctly.
4194 Diag(D->getLocStart(),
4195 (isTemplateInstantiation && isNSConsumed &&
4196 getLangOpts().ObjCAutoRefCount
4197 ? diag::err_ns_attribute_wrong_parameter_type
4198 : diag::warn_ns_attribute_wrong_parameter_type))
4199 << attrRange
4200 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4201 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
John McCalled433932011-01-25 03:31:58 +00004202 return;
4203 }
4204
John McCall3b5a8f52016-03-03 00:10:03 +00004205 if (isNSConsumed)
4206 param->addAttr(::new (Context)
4207 NSConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004208 else
John McCall3b5a8f52016-03-03 00:10:03 +00004209 param->addAttr(::new (Context)
4210 CFConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004211}
4212
Chandler Carruthedc2c642011-07-02 00:01:44 +00004213static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4214 const AttributeList &Attr) {
John McCalled433932011-01-25 03:31:58 +00004215 QualType returnType;
Mike Stumpd3bb5572009-07-24 19:02:52 +00004216
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004217 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004218 returnType = MD->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004219 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004220 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
John McCall31168b02011-06-15 23:02:42 +00004221 return; // ignore: was handled as a type attribute
Fariborz Jahanian272b7dc2012-08-28 22:26:21 +00004222 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4223 returnType = PD->getType();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004224 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004225 returnType = FD->getReturnType();
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004226 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4227 returnType = Param->getType()->getPointeeType();
4228 if (returnType.isNull()) {
4229 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4230 << Attr.getName() << /*pointer-to-CF*/2
4231 << Attr.getRange();
4232 return;
4233 }
4234 } else {
4235 AttributeDeclKind ExpectedDeclKind;
4236 switch (Attr.getKind()) {
4237 default: llvm_unreachable("invalid ownership attribute");
4238 case AttributeList::AT_NSReturnsRetained:
4239 case AttributeList::AT_NSReturnsAutoreleased:
4240 case AttributeList::AT_NSReturnsNotRetained:
4241 ExpectedDeclKind = ExpectedFunctionOrMethod;
4242 break;
4243
4244 case AttributeList::AT_CFReturnsRetained:
4245 case AttributeList::AT_CFReturnsNotRetained:
4246 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4247 break;
4248 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004249 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004250 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004251 return;
4252 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004253
John McCalled433932011-01-25 03:31:58 +00004254 bool typeOK;
4255 bool cf;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004256 switch (Attr.getKind()) {
David Blaikie8a40f702012-01-17 06:56:22 +00004257 default: llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004258 case AttributeList::AT_NSReturnsRetained:
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004259 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004260 cf = false;
4261 break;
4262
4263 case AttributeList::AT_NSReturnsAutoreleased:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004264 case AttributeList::AT_NSReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004265 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4266 cf = false;
4267 break;
4268
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004269 case AttributeList::AT_CFReturnsRetained:
4270 case AttributeList::AT_CFReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004271 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4272 cf = true;
4273 break;
4274 }
4275
4276 if (!typeOK) {
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004277 if (isa<ParmVarDecl>(D)) {
4278 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4279 << Attr.getName() << /*pointer-to-CF*/2
4280 << Attr.getRange();
4281 } else {
4282 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4283 enum : unsigned {
4284 Function,
4285 Method,
4286 Property
4287 } SubjectKind = Function;
4288 if (isa<ObjCMethodDecl>(D))
4289 SubjectKind = Method;
4290 else if (isa<ObjCPropertyDecl>(D))
4291 SubjectKind = Property;
4292 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4293 << Attr.getName() << SubjectKind << cf
4294 << Attr.getRange();
4295 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004296 return;
Ted Kremenek3b204e42009-05-13 21:07:32 +00004297 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004298
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004299 switch (Attr.getKind()) {
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004300 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004301 llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004302 case AttributeList::AT_NSReturnsAutoreleased:
Nico Weber462fd1e2015-01-07 23:50:05 +00004303 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4304 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
John McCalled433932011-01-25 03:31:58 +00004305 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004306 case AttributeList::AT_CFReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004307 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4308 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004309 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004310 case AttributeList::AT_NSReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004311 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4312 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004313 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004314 case AttributeList::AT_CFReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004315 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4316 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004317 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004318 case AttributeList::AT_NSReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004319 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4320 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004321 return;
4322 };
4323}
4324
John McCallcf166702011-07-22 08:53:00 +00004325static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4326 const AttributeList &attr) {
Fariborz Jahanian8bf05562013-09-19 17:52:50 +00004327 const int EP_ObjCMethod = 1;
4328 const int EP_ObjCProperty = 2;
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004329
John McCallcf166702011-07-22 08:53:00 +00004330 SourceLocation loc = attr.getLoc();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004331 QualType resultType;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004332 if (isa<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004333 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004334 else
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004335 resultType = cast<ObjCPropertyDecl>(D)->getType();
John McCallcf166702011-07-22 08:53:00 +00004336
Fariborz Jahanian044a5be2011-09-30 20:50:23 +00004337 if (!resultType->isReferenceType() &&
4338 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004339 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
John McCallcf166702011-07-22 08:53:00 +00004340 << SourceRange(loc)
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004341 << attr.getName()
4342 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004343 << /*non-retainable pointer*/ 2;
John McCallcf166702011-07-22 08:53:00 +00004344
4345 // Drop the attribute.
4346 return;
4347 }
4348
Nico Weber462fd1e2015-01-07 23:50:05 +00004349 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4350 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
John McCallcf166702011-07-22 08:53:00 +00004351}
4352
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004353static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4354 const AttributeList &attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004355 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004356
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004357 DeclContext *DC = method->getDeclContext();
4358 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4359 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4360 << attr.getName() << 0;
4361 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4362 return;
4363 }
4364 if (method->getMethodFamily() == OMF_dealloc) {
4365 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4366 << attr.getName() << 1;
4367 return;
4368 }
4369
Michael Han99315932013-01-24 16:46:58 +00004370 method->addAttr(::new (S.Context)
4371 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4372 attr.getAttributeSpellingListIndex()));
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004373}
4374
Aaron Ballmanfb763042013-12-02 18:05:46 +00004375static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4376 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004377 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4378 Attr.getName()))
John McCall32f5fe12011-09-30 05:12:12 +00004379 return;
John McCall32f5fe12011-09-30 05:12:12 +00004380
Aaron Ballmanfb763042013-12-02 18:05:46 +00004381 D->addAttr(::new (S.Context)
4382 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4383 Attr.getAttributeSpellingListIndex()));
4384}
4385
4386static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4387 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004388 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4389 Attr.getName()))
Aaron Ballmanfb763042013-12-02 18:05:46 +00004390 return;
4391
4392 D->addAttr(::new (S.Context)
4393 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4394 Attr.getAttributeSpellingListIndex()));
John McCall32f5fe12011-09-30 05:12:12 +00004395}
4396
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004397static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4398 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004399 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004400
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004401 if (!Parm) {
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004402 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004403 return;
4404 }
John McCall28592582015-02-01 22:34:06 +00004405
4406 // Typedefs only allow objc_bridge(id) and have some additional checking.
4407 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4408 if (!Parm->Ident->isStr("id")) {
4409 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4410 << Attr.getName();
4411 return;
4412 }
4413
4414 // Only allow 'cv void *'.
4415 QualType T = TD->getUnderlyingType();
4416 if (!T->isVoidPointerType()) {
4417 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4418 return;
4419 }
4420 }
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004421
4422 D->addAttr(::new (S.Context)
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004423 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004424 Attr.getAttributeSpellingListIndex()));
4425}
4426
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004427static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4428 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004429 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4430
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004431 if (!Parm) {
4432 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4433 return;
4434 }
4435
4436 D->addAttr(::new (S.Context)
4437 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4438 Attr.getAttributeSpellingListIndex()));
4439}
4440
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004441static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4442 const AttributeList &Attr) {
4443 IdentifierInfo *RelatedClass =
Craig Topperc3ec1492014-05-26 06:22:03 +00004444 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004445 if (!RelatedClass) {
4446 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4447 return;
4448 }
4449 IdentifierInfo *ClassMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004450 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004451 IdentifierInfo *InstanceMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004452 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004453 D->addAttr(::new (S.Context)
4454 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4455 ClassMethod, InstanceMethod,
4456 Attr.getAttributeSpellingListIndex()));
4457}
4458
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004459static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4460 const AttributeList &Attr) {
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004461 ObjCInterfaceDecl *IFace;
Nico Weber462fd1e2015-01-07 23:50:05 +00004462 if (ObjCCategoryDecl *CatDecl =
4463 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004464 IFace = CatDecl->getClassInterface();
4465 else
4466 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00004467
4468 if (!IFace)
4469 return;
4470
Argyrios Kyrtzidis9ed9e5f2013-12-03 21:11:30 +00004471 IFace->setHasDesignatedInitializers();
Argyrios Kyrtzidise8186812013-12-07 06:08:04 +00004472 D->addAttr(::new (S.Context)
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004473 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4474 Attr.getAttributeSpellingListIndex()));
4475}
4476
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004477static void handleObjCRuntimeName(Sema &S, Decl *D,
4478 const AttributeList &Attr) {
Fariborz Jahaniana2e5deb2014-07-16 19:44:34 +00004479 StringRef MetaDataName;
4480 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4481 return;
4482 D->addAttr(::new (S.Context)
4483 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4484 MetaDataName,
4485 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004486}
4487
Alex Denisovfde64952015-06-26 05:28:36 +00004488// when a user wants to use objc_boxable with a union or struct
4489// but she doesn't have access to the declaration (legacy/third-party code)
4490// then she can 'enable' this feature via trick with a typedef
4491// e.g.:
4492// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4493static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4494 bool notify = false;
4495
4496 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4497 if (RD && RD->getDefinition()) {
4498 RD = RD->getDefinition();
4499 notify = true;
4500 }
4501
4502 if (RD) {
4503 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4504 ObjCBoxableAttr(Attr.getRange(), S.Context,
4505 Attr.getAttributeSpellingListIndex());
4506 RD->addAttr(BoxableAttr);
4507 if (notify) {
4508 // we need to notify ASTReader/ASTWriter about
4509 // modification of existing declaration
4510 if (ASTMutationListener *L = S.getASTMutationListener())
4511 L->AddedAttributeToRecord(BoxableAttr, RD);
4512 }
4513 }
4514}
4515
Chandler Carruthedc2c642011-07-02 00:01:44 +00004516static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4517 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004518 if (hasDeclarator(D)) return;
John McCall31168b02011-06-15 23:02:42 +00004519
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004520 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
Douglas Gregor5c3cc422012-03-14 16:55:17 +00004521 << Attr.getRange() << Attr.getName() << ExpectedVariable;
John McCall31168b02011-06-15 23:02:42 +00004522}
4523
Chandler Carruthedc2c642011-07-02 00:01:44 +00004524static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4525 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004526 ValueDecl *vd = cast<ValueDecl>(D);
John McCall31168b02011-06-15 23:02:42 +00004527 QualType type = vd->getType();
4528
4529 if (!type->isDependentType() &&
4530 !type->isObjCLifetimeType()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004531 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
John McCall31168b02011-06-15 23:02:42 +00004532 << type;
4533 return;
4534 }
4535
4536 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4537
4538 // If we have no lifetime yet, check the lifetime we're presumably
4539 // going to infer.
4540 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4541 lifetime = type->getObjCARCImplicitLifetime();
4542
4543 switch (lifetime) {
4544 case Qualifiers::OCL_None:
4545 assert(type->isDependentType() &&
4546 "didn't infer lifetime for non-dependent type?");
4547 break;
4548
4549 case Qualifiers::OCL_Weak: // meaningful
4550 case Qualifiers::OCL_Strong: // meaningful
4551 break;
4552
4553 case Qualifiers::OCL_ExplicitNone:
4554 case Qualifiers::OCL_Autoreleasing:
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004555 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
John McCall31168b02011-06-15 23:02:42 +00004556 << (lifetime == Qualifiers::OCL_Autoreleasing);
4557 break;
4558 }
4559
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004560 D->addAttr(::new (S.Context)
Michael Han99315932013-01-24 16:46:58 +00004561 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4562 Attr.getAttributeSpellingListIndex()));
John McCall31168b02011-06-15 23:02:42 +00004563}
4564
Francois Picheta83957a2010-12-19 06:50:37 +00004565//===----------------------------------------------------------------------===//
4566// Microsoft specific attribute handlers.
4567//===----------------------------------------------------------------------===//
4568
Chandler Carruthedc2c642011-07-02 00:01:44 +00004569static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +00004570 if (!S.LangOpts.CPlusPlus) {
4571 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4572 << Attr.getName() << AttributeLangSupport::C;
4573 return;
4574 }
4575
Aaron Ballman60e705e2013-11-24 20:58:02 +00004576 if (!isa<CXXRecordDecl>(D)) {
4577 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4578 << Attr.getName() << ExpectedClass;
4579 return;
4580 }
4581
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004582 StringRef StrRef;
4583 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00004584 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
Reid Kleckner140c4a72013-05-17 14:04:52 +00004585 return;
Francois Pichet7da11662010-12-20 01:41:49 +00004586
David Majnemer89085342013-08-09 08:56:20 +00004587 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4588 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
David Majnemer89085342013-08-09 08:56:20 +00004589 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4590 StrRef = StrRef.drop_front().drop_back();
Francois Pichet7da11662010-12-20 01:41:49 +00004591
Reid Kleckner140c4a72013-05-17 14:04:52 +00004592 // Validate GUID length.
David Majnemer89085342013-08-09 08:56:20 +00004593 if (StrRef.size() != 36) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004594 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00004595 return;
4596 }
Anders Carlsson19588aa2011-01-23 21:07:30 +00004597
David Majnemer89085342013-08-09 08:56:20 +00004598 for (unsigned i = 0; i < 36; ++i) {
Reid Kleckner140c4a72013-05-17 14:04:52 +00004599 if (i == 8 || i == 13 || i == 18 || i == 23) {
David Majnemer89085342013-08-09 08:56:20 +00004600 if (StrRef[i] != '-') {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004601 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Francois Pichet7da11662010-12-20 01:41:49 +00004602 return;
4603 }
David Majnemer89085342013-08-09 08:56:20 +00004604 } else if (!isHexDigit(StrRef[i])) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004605 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00004606 return;
Francois Pichet7da11662010-12-20 01:41:49 +00004607 }
Reid Kleckner140c4a72013-05-17 14:04:52 +00004608 }
Francois Picheta83957a2010-12-19 06:50:37 +00004609
David Majnemer89085342013-08-09 08:56:20 +00004610 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
4611 Attr.getAttributeSpellingListIndex()));
Charles Davis163855f2010-02-16 18:27:26 +00004612}
4613
David Majnemer2c4e00a2014-01-29 22:07:36 +00004614static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4615 if (!S.LangOpts.CPlusPlus) {
4616 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4617 << Attr.getName() << AttributeLangSupport::C;
4618 return;
4619 }
4620 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
David Majnemer4bb09802014-02-10 19:50:15 +00004621 D, Attr.getRange(), /*BestCase=*/true,
4622 Attr.getAttributeSpellingListIndex(),
David Majnemer2c4e00a2014-01-29 22:07:36 +00004623 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
David Majnemer929025d2016-01-26 19:30:26 +00004624 if (IA) {
David Majnemer2c4e00a2014-01-29 22:07:36 +00004625 D->addAttr(IA);
David Majnemer929025d2016-01-26 19:30:26 +00004626 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
4627 }
David Majnemer2c4e00a2014-01-29 22:07:36 +00004628}
4629
Reid Kleckner7d6d2702014-05-01 03:16:47 +00004630static void handleDeclspecThreadAttr(Sema &S, Decl *D,
4631 const AttributeList &Attr) {
4632 VarDecl *VD = cast<VarDecl>(D);
4633 if (!S.Context.getTargetInfo().isTLSSupported()) {
4634 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
4635 return;
4636 }
4637 if (VD->getTSCSpec() != TSCS_unspecified) {
4638 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
4639 return;
4640 }
4641 if (VD->hasLocalStorage()) {
4642 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4643 return;
4644 }
4645 VD->addAttr(::new (S.Context) ThreadAttr(
4646 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4647}
4648
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00004649static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4650 SmallVector<StringRef, 4> Tags;
4651 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4652 StringRef Tag;
4653 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
4654 return;
4655 Tags.push_back(Tag);
4656 }
4657
4658 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
4659 if (!NS->isInline()) {
4660 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
4661 return;
4662 }
4663 if (NS->isAnonymousNamespace()) {
4664 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
4665 return;
4666 }
4667 if (Attr.getNumArgs() == 0)
4668 Tags.push_back(NS->getName());
4669 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4670 return;
4671
4672 // Store tags sorted and without duplicates.
4673 std::sort(Tags.begin(), Tags.end());
4674 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
4675
4676 D->addAttr(::new (S.Context)
4677 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
4678 Attr.getAttributeSpellingListIndex()));
4679
4680 // FIXME: remove this warning as soon as mangled part is ready.
4681 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
4682 << Attr.getName();
4683}
4684
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004685static void handleARMInterruptAttr(Sema &S, Decl *D,
4686 const AttributeList &Attr) {
4687 // Check the attribute arguments.
4688 if (Attr.getNumArgs() > 1) {
4689 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4690 << Attr.getName() << 1;
4691 return;
4692 }
4693
4694 StringRef Str;
4695 SourceLocation ArgLoc;
4696
4697 if (Attr.getNumArgs() == 0)
4698 Str = "";
4699 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4700 return;
4701
4702 ARMInterruptAttr::InterruptType Kind;
4703 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4704 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4705 << Attr.getName() << Str << ArgLoc;
4706 return;
4707 }
4708
4709 unsigned Index = Attr.getAttributeSpellingListIndex();
4710 D->addAttr(::new (S.Context)
4711 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
4712}
4713
4714static void handleMSP430InterruptAttr(Sema &S, Decl *D,
4715 const AttributeList &Attr) {
4716 if (!checkAttributeNumArgs(S, Attr, 1))
4717 return;
4718
4719 if (!Attr.isArgExpr(0)) {
4720 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
4721 << AANT_ArgumentIntegerConstant;
4722 return;
4723 }
4724
4725 // FIXME: Check for decl - it should be void ()(void).
4726
4727 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4728 llvm::APSInt NumParams(32);
4729 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
4730 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4731 << Attr.getName() << AANT_ArgumentIntegerConstant
4732 << NumParamsExpr->getSourceRange();
4733 return;
4734 }
4735
4736 unsigned Num = NumParams.getLimitedValue(255);
4737 if ((Num & 1) || Num > 30) {
4738 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4739 << Attr.getName() << (int)NumParams.getSExtValue()
4740 << NumParamsExpr->getSourceRange();
4741 return;
4742 }
4743
Aaron Ballman36a53502014-01-16 13:03:14 +00004744 D->addAttr(::new (S.Context)
4745 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
4746 Attr.getAttributeSpellingListIndex()));
4747 D->addAttr(UsedAttr::CreateImplicit(S.Context));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004748}
4749
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00004750static void handleMipsInterruptAttr(Sema &S, Decl *D,
4751 const AttributeList &Attr) {
4752 // Only one optional argument permitted.
4753 if (Attr.getNumArgs() > 1) {
4754 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4755 << Attr.getName() << 1;
4756 return;
4757 }
4758
4759 StringRef Str;
4760 SourceLocation ArgLoc;
4761
4762 if (Attr.getNumArgs() == 0)
4763 Str = "";
4764 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4765 return;
4766
4767 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
4768 // a) Must be a function.
4769 // b) Must have no parameters.
4770 // c) Must have the 'void' return type.
4771 // d) Cannot have the 'mips16' attribute, as that instruction set
4772 // lacks the 'eret' instruction.
4773 // e) The attribute itself must either have no argument or one of the
4774 // valid interrupt types, see [MipsInterruptDocs].
4775
4776 if (!isFunctionOrMethod(D)) {
4777 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
4778 << "'interrupt'" << ExpectedFunctionOrMethod;
4779 return;
4780 }
4781
4782 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
4783 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4784 << 0;
4785 return;
4786 }
4787
4788 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
4789 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4790 << 1;
4791 return;
4792 }
4793
4794 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
4795 Attr.getName()))
4796 return;
4797
4798 MipsInterruptAttr::InterruptType Kind;
4799 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4800 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4801 << Attr.getName() << "'" + std::string(Str) + "'";
4802 return;
4803 }
4804
4805 D->addAttr(::new (S.Context) MipsInterruptAttr(
4806 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
4807}
4808
Alexey Bataevd51e9932016-01-15 04:06:31 +00004809static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
4810 const AttributeList &Attr) {
4811 // Semantic checks for a function with the 'interrupt' attribute.
4812 // a) Must be a function.
4813 // b) Must have the 'void' return type.
4814 // c) Must take 1 or 2 arguments.
4815 // d) The 1st argument must be a pointer.
4816 // e) The 2nd argument (if any) must be an unsigned integer.
4817 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
4818 CXXMethodDecl::isStaticOverloadedOperator(
4819 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
4820 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4821 << Attr.getName() << ExpectedFunctionWithProtoType;
4822 return;
4823 }
4824 // Interrupt handler must have void return type.
4825 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
4826 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
4827 diag::err_anyx86_interrupt_attribute)
4828 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4829 ? 0
4830 : 1)
4831 << 0;
4832 return;
4833 }
4834 // Interrupt handler must have 1 or 2 parameters.
4835 unsigned NumParams = getFunctionOrMethodNumParams(D);
4836 if (NumParams < 1 || NumParams > 2) {
4837 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
4838 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4839 ? 0
4840 : 1)
4841 << 1;
4842 return;
4843 }
4844 // The first argument must be a pointer.
4845 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
4846 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
4847 diag::err_anyx86_interrupt_attribute)
4848 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4849 ? 0
4850 : 1)
4851 << 2;
4852 return;
4853 }
4854 // The second argument, if present, must be an unsigned integer.
4855 unsigned TypeSize =
4856 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
4857 ? 64
4858 : 32;
4859 if (NumParams == 2 &&
4860 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
4861 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
4862 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
4863 diag::err_anyx86_interrupt_attribute)
4864 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4865 ? 0
4866 : 1)
4867 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
4868 return;
4869 }
4870 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
4871 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
4872 D->addAttr(UsedAttr::CreateImplicit(S.Context));
4873}
4874
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004875static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4876 // Dispatch the interrupt attribute based on the current target.
Alexey Bataevd51e9932016-01-15 04:06:31 +00004877 switch (S.Context.getTargetInfo().getTriple().getArch()) {
4878 case llvm::Triple::msp430:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004879 handleMSP430InterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00004880 break;
4881 case llvm::Triple::mipsel:
4882 case llvm::Triple::mips:
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00004883 handleMipsInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00004884 break;
4885 case llvm::Triple::x86:
4886 case llvm::Triple::x86_64:
4887 handleAnyX86InterruptAttr(S, D, Attr);
4888 break;
4889 default:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004890 handleARMInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00004891 break;
4892 }
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004893}
4894
Matt Arsenault43fae6c2014-12-04 20:38:18 +00004895static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
4896 const AttributeList &Attr) {
4897 uint32_t NumRegs;
4898 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4899 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4900 return;
4901
4902 D->addAttr(::new (S.Context)
4903 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context,
4904 NumRegs,
4905 Attr.getAttributeSpellingListIndex()));
4906}
4907
4908static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
4909 const AttributeList &Attr) {
4910 uint32_t NumRegs;
4911 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4912 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4913 return;
4914
4915 D->addAttr(::new (S.Context)
4916 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context,
4917 NumRegs,
4918 Attr.getAttributeSpellingListIndex()));
4919}
4920
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004921static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
4922 const AttributeList& Attr) {
4923 // If we try to apply it to a function pointer, don't warn, but don't
4924 // do anything, either. It doesn't matter anyway, because there's nothing
4925 // special about calling a force_align_arg_pointer function.
4926 ValueDecl *VD = dyn_cast<ValueDecl>(D);
4927 if (VD && VD->getType()->isFunctionPointerType())
4928 return;
4929 // Also don't warn on function pointer typedefs.
4930 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
4931 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
4932 TD->getUnderlyingType()->isFunctionType()))
4933 return;
4934 // Attribute can only be applied to function types.
4935 if (!isa<FunctionDecl>(D)) {
4936 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4937 << Attr.getName() << /* function */0;
4938 return;
4939 }
4940
Aaron Ballman36a53502014-01-16 13:03:14 +00004941 D->addAttr(::new (S.Context)
4942 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
4943 Attr.getAttributeSpellingListIndex()));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004944}
4945
4946DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
4947 unsigned AttrSpellingListIndex) {
4948 if (D->hasAttr<DLLExportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00004949 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
Craig Topperc3ec1492014-05-26 06:22:03 +00004950 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004951 }
4952
4953 if (D->hasAttr<DLLImportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00004954 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004955
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00004956 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004957}
4958
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004959DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
4960 unsigned AttrSpellingListIndex) {
4961 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00004962 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004963 D->dropAttr<DLLImportAttr>();
4964 }
4965
4966 if (D->hasAttr<DLLExportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00004967 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004968
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00004969 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004970}
4971
Hans Wennborge82f19c2014-06-24 23:57:05 +00004972static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
Hans Wennborg5e645282014-06-24 23:57:13 +00004973 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
4974 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4975 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
4976 << A.getName();
4977 return;
4978 }
4979
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004980 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4981 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
4982 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4983 // MinGW doesn't allow dllimport on inline functions.
4984 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
4985 << A.getName();
4986 return;
4987 }
4988 }
4989
Hans Wennborg5869ec42015-09-15 21:05:30 +00004990 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
4991 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4992 MD->getParent()->isLambda()) {
4993 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
4994 return;
4995 }
4996 }
4997
Hans Wennborge82f19c2014-06-24 23:57:05 +00004998 unsigned Index = A.getAttributeSpellingListIndex();
4999 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5000 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5001 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005002 if (NewAttr)
5003 D->addAttr(NewAttr);
5004}
5005
David Majnemer2c4e00a2014-01-29 22:07:36 +00005006MSInheritanceAttr *
David Majnemer4bb09802014-02-10 19:50:15 +00005007Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00005008 unsigned AttrSpellingListIndex,
5009 MSInheritanceAttr::Spelling SemanticSpelling) {
5010 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5011 if (IA->getSemanticSpelling() == SemanticSpelling)
Craig Topperc3ec1492014-05-26 06:22:03 +00005012 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005013 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5014 << 1 /*previous declaration*/;
5015 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5016 D->dropAttr<MSInheritanceAttr>();
5017 }
5018
5019 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5020 if (RD->hasDefinition()) {
David Majnemer4bb09802014-02-10 19:50:15 +00005021 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5022 SemanticSpelling)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005023 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005024 }
5025 } else {
5026 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5027 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5028 << 1 /*partial specialization*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005029 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005030 }
5031 if (RD->getDescribedClassTemplate()) {
5032 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5033 << 0 /*primary template*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005034 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005035 }
5036 }
5037
5038 return ::new (Context)
David Majnemer4bb09802014-02-10 19:50:15 +00005039 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
David Majnemer2c4e00a2014-01-29 22:07:36 +00005040}
5041
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005042static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5043 // The capability attributes take a single string parameter for the name of
5044 // the capability they represent. The lockable attribute does not take any
5045 // parameters. However, semantically, both attributes represent the same
5046 // concept, and so they use the same semantic attribute. Eventually, the
5047 // lockable attribute will be removed.
Aaron Ballman6c810072014-03-05 21:47:13 +00005048 //
Alp Toker958027b2014-07-14 19:42:55 +00005049 // For backward compatibility, any capability which has no specified string
Aaron Ballman6c810072014-03-05 21:47:13 +00005050 // literal will be considered a "mutex."
5051 StringRef N("mutex");
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005052 SourceLocation LiteralLoc;
5053 if (Attr.getKind() == AttributeList::AT_Capability &&
5054 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5055 return;
5056
Aaron Ballman6c810072014-03-05 21:47:13 +00005057 // Currently, there are only two names allowed for a capability: role and
5058 // mutex (case insensitive). Diagnose other capability names.
5059 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5060 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5061
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005062 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5063 Attr.getAttributeSpellingListIndex()));
5064}
5065
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005066static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5067 const AttributeList &Attr) {
5068 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5069 Attr.getArgAsExpr(0),
5070 Attr.getAttributeSpellingListIndex()));
5071}
5072
5073static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5074 const AttributeList &Attr) {
5075 SmallVector<Expr*, 1> Args;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005076 if (!checkLockFunAttrCommon(S, D, Attr, Args))
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005077 return;
5078
5079 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5080 S.Context,
5081 Args.data(), Args.size(),
5082 Attr.getAttributeSpellingListIndex()));
5083}
5084
5085static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5086 const AttributeList &Attr) {
5087 SmallVector<Expr*, 2> Args;
5088 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5089 return;
5090
5091 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5092 S.Context,
5093 Attr.getArgAsExpr(0),
5094 Args.data(),
5095 Args.size(),
5096 Attr.getAttributeSpellingListIndex()));
5097}
5098
5099static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5100 const AttributeList &Attr) {
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005101 // Check that all arguments are lockable objects.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005102 SmallVector<Expr *, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005103 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005104
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005105 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5106 Attr.getRange(), S.Context, Args.data(), Args.size(),
5107 Attr.getAttributeSpellingListIndex()));
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005108}
5109
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005110static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5111 const AttributeList &Attr) {
5112 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5113 return;
5114
5115 // check that all arguments are lockable objects
5116 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005117 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005118 if (Args.empty())
5119 return;
5120
5121 RequiresCapabilityAttr *RCA = ::new (S.Context)
5122 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5123 Args.size(), Attr.getAttributeSpellingListIndex());
5124
5125 D->addAttr(RCA);
5126}
5127
Aaron Ballman43f40102014-11-14 22:34:56 +00005128static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5129 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5130 if (NSD->isAnonymousNamespace()) {
5131 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5132 // Do not want to attach the attribute to the namespace because that will
5133 // cause confusing diagnostic reports for uses of declarations within the
5134 // namespace.
5135 return;
5136 }
5137 }
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005138
Manman Renc7890fe2016-03-16 18:50:49 +00005139 // Handle the cases where the attribute has a text message.
5140 StringRef Str, Replacement;
5141 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5142 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5143 return;
5144
5145 // Only support a single optional message for Declspec and CXX11.
5146 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5147 checkAttributeAtMostNumArgs(S, Attr, 1);
5148 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5149 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5150 return;
5151
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005152 if (!S.getLangOpts().CPlusPlus14)
5153 if (Attr.isCXX11Attribute() &&
5154 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
Richard Smith4f902c72016-03-08 00:32:55 +00005155 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005156
Manman Renc7890fe2016-03-16 18:50:49 +00005157 D->addAttr(::new (S.Context) DeprecatedAttr(Attr.getRange(), S.Context, Str,
5158 Replacement,
5159 Attr.getAttributeSpellingListIndex()));
Aaron Ballman43f40102014-11-14 22:34:56 +00005160}
5161
Peter Collingbourne915df992015-05-15 18:33:32 +00005162static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5163 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5164 return;
5165
Benjamin Kramer1b582012016-02-13 18:11:49 +00005166 std::vector<StringRef> Sanitizers;
Peter Collingbourne915df992015-05-15 18:33:32 +00005167
5168 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5169 StringRef SanitizerName;
5170 SourceLocation LiteralLoc;
5171
5172 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5173 return;
5174
5175 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5176 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5177
5178 Sanitizers.push_back(SanitizerName);
5179 }
5180
5181 D->addAttr(::new (S.Context) NoSanitizeAttr(
5182 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5183 Attr.getAttributeSpellingListIndex()));
5184}
5185
5186static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5187 const AttributeList &Attr) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00005188 StringRef AttrName = Attr.getName()->getName();
5189 normalizeName(AttrName);
Benjamin Kramer1b582012016-02-13 18:11:49 +00005190 StringRef SanitizerName =
5191 llvm::StringSwitch<StringRef>(AttrName)
Peter Collingbourne915df992015-05-15 18:33:32 +00005192 .Case("no_address_safety_analysis", "address")
5193 .Case("no_sanitize_address", "address")
5194 .Case("no_sanitize_thread", "thread")
Peter Collingbourne94410942015-05-15 20:11:18 +00005195 .Case("no_sanitize_memory", "memory");
Peter Collingbourne915df992015-05-15 18:33:32 +00005196 D->addAttr(::new (S.Context)
5197 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5198 Attr.getAttributeSpellingListIndex()));
5199}
5200
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00005201static void handleInternalLinkageAttr(Sema &S, Decl *D,
5202 const AttributeList &Attr) {
5203 if (InternalLinkageAttr *Internal =
5204 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5205 Attr.getAttributeSpellingListIndex()))
5206 D->addAttr(Internal);
5207}
5208
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005209/// Handles semantic checking for features that are common to all attributes,
5210/// such as checking whether a parameter was properly specified, or the correct
5211/// number of arguments were passed, etc.
5212static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5213 const AttributeList &Attr) {
5214 // Several attributes carry different semantics than the parsing requires, so
5215 // those are opted out of the common handling.
5216 //
5217 // We also bail on unknown and ignored attributes because those are handled
5218 // as part of the target-specific handling logic.
5219 if (Attr.hasCustomParsing() ||
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005220 Attr.getKind() == AttributeList::UnknownAttribute)
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005221 return false;
5222
Aaron Ballman3aff6332013-12-02 19:30:36 +00005223 // Check whether the attribute requires specific language extensions to be
5224 // enabled.
5225 if (!Attr.diagnoseLangOpts(S))
5226 return true;
5227
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00005228 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5229 // If there are no optional arguments, then checking for the argument count
5230 // is trivial.
5231 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5232 return true;
5233 } else {
5234 // There are optional arguments, so checking is slightly more involved.
5235 if (Attr.getMinArgs() &&
5236 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5237 return true;
5238 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5239 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5240 return true;
5241 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00005242
5243 // Check whether the attribute appertains to the given subject.
5244 if (!Attr.diagnoseAppertainsTo(S, D))
5245 return true;
5246
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005247 return false;
5248}
5249
Xiuli Pan11e13f62016-02-26 03:13:03 +00005250static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5251 const AttributeList &Attr) {
5252 if (D->isInvalidDecl())
5253 return;
5254
5255 // Check if there is only one access qualifier.
5256 if (D->hasAttr<OpenCLAccessAttr>()) {
5257 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5258 << D->getSourceRange();
5259 D->setInvalidDecl(true);
5260 return;
5261 }
5262
5263 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5264 // image object can be read and written.
5265 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5266 // object. Using the read_write (or __read_write) qualifier with the pipe
5267 // qualifier is a compilation error.
5268 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5269 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5270 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5271 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5272 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5273 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5274 D->setInvalidDecl(true);
5275 return;
5276 }
5277 }
5278 }
5279
5280 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5281 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5282}
5283
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00005284//===----------------------------------------------------------------------===//
Chris Lattner9e2aafe2008-06-29 00:23:49 +00005285// Top Level Sema Entry Points
5286//===----------------------------------------------------------------------===//
5287
Richard Smithf8a75c32013-08-29 00:47:48 +00005288/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5289/// the attribute applies to decls. If the attribute is a type attribute, just
5290/// silently ignore it if a GNU attribute.
5291static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5292 const AttributeList &Attr,
5293 bool IncludeCXX11Attributes) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005294 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
Richard Smithf8a75c32013-08-29 00:47:48 +00005295 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00005296
Richard Smithf8a75c32013-08-29 00:47:48 +00005297 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5298 // instead.
5299 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5300 return;
5301
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005302 // Unknown attributes are automatically warned on. Target-specific attributes
5303 // which do not apply to the current target architecture are treated as
5304 // though they were unknown attributes.
5305 if (Attr.getKind() == AttributeList::UnknownAttribute ||
Bob Wilson7c730832015-07-20 22:57:31 +00005306 !Attr.existsInTarget(S.Context.getTargetInfo())) {
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005307 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5308 ? diag::warn_unhandled_ms_attribute_ignored
5309 : diag::warn_unknown_attribute_ignored)
5310 << Attr.getName();
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005311 return;
5312 }
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005313
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005314 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5315 return;
5316
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005317 switch (Attr.getKind()) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005318 default:
Richard Smith4f902c72016-03-08 00:32:55 +00005319 if (!Attr.isStmtAttr()) {
5320 // Type attributes are handled elsewhere; silently move on.
5321 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5322 break;
5323 }
5324 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5325 << Attr.getName() << D->getLocation();
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005326 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005327 case AttributeList::AT_Interrupt:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005328 handleInterruptAttr(S, D, Attr);
5329 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005330 case AttributeList::AT_X86ForceAlignArgPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005331 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5332 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005333 case AttributeList::AT_DLLExport:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005334 case AttributeList::AT_DLLImport:
Hans Wennborge82f19c2014-06-24 23:57:05 +00005335 handleDLLAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005336 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005337 case AttributeList::AT_Mips16:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005338 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
5339 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005340 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005341 case AttributeList::AT_NoMips16:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005342 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5343 break;
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005344 case AttributeList::AT_AMDGPUNumVGPR:
5345 handleAMDGPUNumVGPRAttr(S, D, Attr);
5346 break;
5347 case AttributeList::AT_AMDGPUNumSGPR:
5348 handleAMDGPUNumSGPRAttr(S, D, Attr);
5349 break;
Aaron Ballman9beb5172013-12-02 15:13:14 +00005350 case AttributeList::AT_IBAction:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005351 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5352 break;
5353 case AttributeList::AT_IBOutlet:
5354 handleIBOutlet(S, D, Attr);
5355 break;
Richard Smith10876ef2013-01-17 01:30:42 +00005356 case AttributeList::AT_IBOutletCollection:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005357 handleIBOutletCollection(S, D, Attr);
5358 break;
5359 case AttributeList::AT_Alias:
5360 handleAliasAttr(S, D, Attr);
5361 break;
5362 case AttributeList::AT_Aligned:
5363 handleAlignedAttr(S, D, Attr);
5364 break;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00005365 case AttributeList::AT_AlignValue:
5366 handleAlignValueAttr(S, D, Attr);
5367 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005368 case AttributeList::AT_AlwaysInline:
Paul Robinsonf0674352014-03-31 22:29:15 +00005369 handleAlwaysInlineAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005370 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005371 case AttributeList::AT_AnalyzerNoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005372 handleAnalyzerNoReturnAttr(S, D, Attr);
5373 break;
5374 case AttributeList::AT_TLSModel:
5375 handleTLSModelAttr(S, D, Attr);
5376 break;
5377 case AttributeList::AT_Annotate:
5378 handleAnnotateAttr(S, D, Attr);
5379 break;
5380 case AttributeList::AT_Availability:
5381 handleAvailabilityAttr(S, D, Attr);
5382 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005383 case AttributeList::AT_CarriesDependency:
Richard Smithe233fbf2013-01-28 22:42:45 +00005384 handleDependencyAttr(S, scope, D, Attr);
5385 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005386 case AttributeList::AT_Common:
5387 handleCommonAttr(S, D, Attr);
5388 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005389 case AttributeList::AT_CUDAConstant:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005390 handleSimpleAttributeWithExclusions<CUDAConstantAttr, CUDASharedAttr>(S, D,
5391 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005392 break;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005393 case AttributeList::AT_PassObjectSize:
5394 handlePassObjectSizeAttr(S, D, Attr);
5395 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005396 case AttributeList::AT_Constructor:
5397 handleConstructorAttr(S, D, Attr);
5398 break;
Richard Smith10876ef2013-01-17 01:30:42 +00005399 case AttributeList::AT_CXX11NoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005400 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5401 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005402 case AttributeList::AT_Deprecated:
Aaron Ballman43f40102014-11-14 22:34:56 +00005403 handleDeprecatedAttr(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00005404 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005405 case AttributeList::AT_Destructor:
5406 handleDestructorAttr(S, D, Attr);
5407 break;
5408 case AttributeList::AT_EnableIf:
5409 handleEnableIfAttr(S, D, Attr);
5410 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005411 case AttributeList::AT_ExtVectorType:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005412 handleExtVectorTypeAttr(S, scope, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005413 break;
Quentin Colombet4e172062012-11-01 23:55:47 +00005414 case AttributeList::AT_MinSize:
Paul Robinsonaae2fba2014-12-10 23:34:36 +00005415 handleMinSizeAttr(S, D, Attr);
Quentin Colombet4e172062012-11-01 23:55:47 +00005416 break;
Paul Robinsonf0674352014-03-31 22:29:15 +00005417 case AttributeList::AT_OptimizeNone:
5418 handleOptimizeNoneAttr(S, D, Attr);
5419 break;
Alexis Hunt724f14e2014-11-28 00:53:20 +00005420 case AttributeList::AT_FlagEnum:
5421 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5422 break;
Peter Collingbourne41af7c22014-05-20 17:12:51 +00005423 case AttributeList::AT_Flatten:
5424 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
5425 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005426 case AttributeList::AT_Format:
5427 handleFormatAttr(S, D, Attr);
5428 break;
5429 case AttributeList::AT_FormatArg:
5430 handleFormatArgAttr(S, D, Attr);
5431 break;
5432 case AttributeList::AT_CUDAGlobal:
5433 handleGlobalAttr(S, D, Attr);
5434 break;
Aaron Ballmanf79ee272013-12-02 21:09:08 +00005435 case AttributeList::AT_CUDADevice:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005436 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
5437 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005438 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005439 case AttributeList::AT_CUDAHost:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005440 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
5441 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005442 break;
5443 case AttributeList::AT_GNUInline:
5444 handleGNUInlineAttr(S, D, Attr);
5445 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005446 case AttributeList::AT_CUDALaunchBounds:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005447 handleLaunchBoundsAttr(S, D, Attr);
Peter Collingbourne827301e2010-12-12 23:03:07 +00005448 break;
David Majnemer631a90b2015-02-04 07:23:21 +00005449 case AttributeList::AT_Restrict:
5450 handleRestrictAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005451 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005452 case AttributeList::AT_MayAlias:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005453 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
5454 break;
5455 case AttributeList::AT_Mode:
5456 handleModeAttr(S, D, Attr);
5457 break;
David Majnemer1bf0f8e2015-07-20 22:51:52 +00005458 case AttributeList::AT_NoAlias:
5459 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
5460 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005461 case AttributeList::AT_NoCommon:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005462 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
5463 break;
Peter Collingbourneb4728c12014-05-19 22:14:34 +00005464 case AttributeList::AT_NoSplitStack:
5465 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
5466 break;
Ted Kremenek9aedc152014-01-17 06:24:56 +00005467 case AttributeList::AT_NonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005468 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
5469 handleNonNullAttrParameter(S, PVD, Attr);
5470 else
5471 handleNonNullAttr(S, D, Attr);
5472 break;
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00005473 case AttributeList::AT_ReturnsNonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005474 handleReturnsNonNullAttr(S, D, Attr);
5475 break;
Hal Finkelee90a222014-09-26 05:04:30 +00005476 case AttributeList::AT_AssumeAligned:
5477 handleAssumeAlignedAttr(S, D, Attr);
5478 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005479 case AttributeList::AT_Overloadable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005480 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
5481 break;
5482 case AttributeList::AT_Ownership:
5483 handleOwnershipAttr(S, D, Attr);
5484 break;
5485 case AttributeList::AT_Cold:
5486 handleColdAttr(S, D, Attr);
5487 break;
5488 case AttributeList::AT_Hot:
5489 handleHotAttr(S, D, Attr);
5490 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005491 case AttributeList::AT_Naked:
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00005492 handleNakedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005493 break;
5494 case AttributeList::AT_NoReturn:
5495 handleNoReturnAttr(S, D, Attr);
5496 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00005497 case AttributeList::AT_NoThrow:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005498 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
5499 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005500 case AttributeList::AT_CUDAShared:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005501 handleSimpleAttributeWithExclusions<CUDASharedAttr, CUDAConstantAttr>(S, D,
5502 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005503 break;
5504 case AttributeList::AT_VecReturn:
5505 handleVecReturnAttr(S, D, Attr);
5506 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005507 case AttributeList::AT_ObjCOwnership:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005508 handleObjCOwnershipAttr(S, D, Attr);
5509 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005510 case AttributeList::AT_ObjCPreciseLifetime:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005511 handleObjCPreciseLifetimeAttr(S, D, Attr);
5512 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005513 case AttributeList::AT_ObjCReturnsInnerPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005514 handleObjCReturnsInnerPointerAttr(S, D, Attr);
5515 break;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00005516 case AttributeList::AT_ObjCRequiresSuper:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005517 handleObjCRequiresSuperAttr(S, D, Attr);
5518 break;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00005519 case AttributeList::AT_ObjCBridge:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005520 handleObjCBridgeAttr(S, scope, D, Attr);
5521 break;
Fariborz Jahanian87c77912013-11-21 20:50:32 +00005522 case AttributeList::AT_ObjCBridgeMutable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005523 handleObjCBridgeMutableAttr(S, scope, D, Attr);
5524 break;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00005525 case AttributeList::AT_ObjCBridgeRelated:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005526 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
5527 break;
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00005528 case AttributeList::AT_ObjCDesignatedInitializer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005529 handleObjCDesignatedInitializer(S, D, Attr);
5530 break;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005531 case AttributeList::AT_ObjCRuntimeName:
5532 handleObjCRuntimeName(S, D, Attr);
5533 break;
Alex Denisovfde64952015-06-26 05:28:36 +00005534 case AttributeList::AT_ObjCBoxable:
5535 handleObjCBoxable(S, D, Attr);
5536 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005537 case AttributeList::AT_CFAuditedTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005538 handleCFAuditedTransferAttr(S, D, Attr);
5539 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005540 case AttributeList::AT_CFUnknownTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005541 handleCFUnknownTransferAttr(S, D, Attr);
5542 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005543 case AttributeList::AT_CFConsumed:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005544 case AttributeList::AT_NSConsumed:
5545 handleNSConsumedAttr(S, D, Attr);
5546 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005547 case AttributeList::AT_NSConsumesSelf:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005548 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
5549 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005550 case AttributeList::AT_NSReturnsAutoreleased:
5551 case AttributeList::AT_NSReturnsNotRetained:
5552 case AttributeList::AT_CFReturnsNotRetained:
5553 case AttributeList::AT_NSReturnsRetained:
5554 case AttributeList::AT_CFReturnsRetained:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005555 handleNSReturnsRetainedAttr(S, D, Attr);
5556 break;
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00005557 case AttributeList::AT_WorkGroupSizeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005558 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
5559 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005560 case AttributeList::AT_ReqdWorkGroupSize:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005561 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
5562 break;
Joey Goulyaba589c2013-03-08 09:42:32 +00005563 case AttributeList::AT_VecTypeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005564 handleVecTypeHint(S, D, Attr);
5565 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005566 case AttributeList::AT_InitPriority:
5567 handleInitPriorityAttr(S, D, Attr);
5568 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005569 case AttributeList::AT_Packed:
5570 handlePackedAttr(S, D, Attr);
5571 break;
5572 case AttributeList::AT_Section:
5573 handleSectionAttr(S, D, Attr);
5574 break;
Eric Christopher11acf732015-06-12 01:35:52 +00005575 case AttributeList::AT_Target:
5576 handleTargetAttr(S, D, Attr);
5577 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005578 case AttributeList::AT_Unavailable:
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00005579 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00005580 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005581 case AttributeList::AT_ArcWeakrefUnavailable:
5582 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
5583 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005584 case AttributeList::AT_ObjCRootClass:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005585 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
5586 break;
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00005587 case AttributeList::AT_ObjCExplicitProtocolImpl:
Ted Kremenek438f8db2014-02-22 01:06:05 +00005588 handleObjCSuppresProtocolAttr(S, D, Attr);
Ted Kremenek28eace62013-11-23 01:01:34 +00005589 break;
5590 case AttributeList::AT_ObjCRequiresPropertyDefs:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005591 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
5592 break;
Aaron Ballman12b9f652014-01-16 13:55:42 +00005593 case AttributeList::AT_Unused:
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00005594 handleUnusedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005595 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005596 case AttributeList::AT_ReturnsTwice:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005597 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
5598 break;
Akira Hatanakac8667622015-11-06 23:56:15 +00005599 case AttributeList::AT_NotTailCalled:
5600 handleNotTailCalledAttr(S, D, Attr);
5601 break;
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00005602 case AttributeList::AT_DisableTailCalls:
5603 handleDisableTailCallsAttr(S, D, Attr);
5604 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005605 case AttributeList::AT_Used:
5606 handleUsedAttr(S, D, Attr);
5607 break;
John McCalld041a9b2013-02-20 01:54:26 +00005608 case AttributeList::AT_Visibility:
5609 handleVisibilityAttr(S, D, Attr, false);
5610 break;
5611 case AttributeList::AT_TypeVisibility:
5612 handleVisibilityAttr(S, D, Attr, true);
5613 break;
Lubos Lunakedc13882013-07-20 15:05:36 +00005614 case AttributeList::AT_WarnUnused:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005615 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
5616 break;
5617 case AttributeList::AT_WarnUnusedResult:
5618 handleWarnUnusedResult(S, D, Attr);
Chris Lattner237f2752009-02-14 07:37:35 +00005619 break;
Aaron Ballman604dfec2013-12-02 17:07:07 +00005620 case AttributeList::AT_Weak:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005621 handleSimpleAttribute<WeakAttr>(S, D, Attr);
5622 break;
5623 case AttributeList::AT_WeakRef:
5624 handleWeakRefAttr(S, D, Attr);
5625 break;
5626 case AttributeList::AT_WeakImport:
5627 handleWeakImportAttr(S, D, Attr);
5628 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005629 case AttributeList::AT_TransparentUnion:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005630 handleTransparentUnionAttr(S, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005631 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005632 case AttributeList::AT_ObjCException:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005633 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
5634 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005635 case AttributeList::AT_ObjCMethodFamily:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005636 handleObjCMethodFamilyAttr(S, D, Attr);
John McCall86bc21f2011-03-02 11:33:24 +00005637 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005638 case AttributeList::AT_ObjCNSObject:
5639 handleObjCNSObject(S, D, Attr);
5640 break;
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00005641 case AttributeList::AT_ObjCIndependentClass:
5642 handleObjCIndependentClass(S, D, Attr);
5643 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005644 case AttributeList::AT_Blocks:
5645 handleBlocksAttr(S, D, Attr);
5646 break;
5647 case AttributeList::AT_Sentinel:
5648 handleSentinelAttr(S, D, Attr);
5649 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00005650 case AttributeList::AT_Const:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005651 handleSimpleAttribute<ConstAttr>(S, D, Attr);
5652 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005653 case AttributeList::AT_Pure:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005654 handleSimpleAttribute<PureAttr>(S, D, Attr);
5655 break;
5656 case AttributeList::AT_Cleanup:
5657 handleCleanupAttr(S, D, Attr);
5658 break;
5659 case AttributeList::AT_NoDebug:
5660 handleNoDebugAttr(S, D, Attr);
5661 break;
Aaron Ballman7c19ab12014-02-22 16:59:24 +00005662 case AttributeList::AT_NoDuplicate:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005663 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
5664 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005665 case AttributeList::AT_NoInline:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005666 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
5667 break;
5668 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
5669 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
5670 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005671 case AttributeList::AT_StdCall:
5672 case AttributeList::AT_CDecl:
5673 case AttributeList::AT_FastCall:
5674 case AttributeList::AT_ThisCall:
5675 case AttributeList::AT_Pascal:
John McCall477f2bb2016-03-03 06:39:32 +00005676 case AttributeList::AT_SwiftCall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005677 case AttributeList::AT_VectorCall:
Charles Davisb5a214e2013-08-30 04:39:01 +00005678 case AttributeList::AT_MSABI:
5679 case AttributeList::AT_SysVABI:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005680 case AttributeList::AT_Pcs:
Guy Benyeif0a014b2012-12-25 08:53:55 +00005681 case AttributeList::AT_IntelOclBicc:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00005682 case AttributeList::AT_PreserveMost:
5683 case AttributeList::AT_PreserveAll:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005684 handleCallConvAttr(S, D, Attr);
John McCallab26cfa2010-02-05 21:31:56 +00005685 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005686 case AttributeList::AT_OpenCLKernel:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005687 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
5688 break;
Xiuli Pan11e13f62016-02-26 03:13:03 +00005689 case AttributeList::AT_OpenCLAccess:
5690 handleOpenCLAccessAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005691 break;
John McCall477f2bb2016-03-03 06:39:32 +00005692 case AttributeList::AT_SwiftContext:
5693 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
5694 break;
5695 case AttributeList::AT_SwiftErrorResult:
5696 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
5697 break;
5698 case AttributeList::AT_SwiftIndirectResult:
5699 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
5700 break;
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00005701 case AttributeList::AT_InternalLinkage:
5702 handleInternalLinkageAttr(S, D, Attr);
5703 break;
John McCall8d32c052012-05-22 21:28:12 +00005704
5705 // Microsoft attributes:
David Majnemer8ab003a2015-02-02 19:30:52 +00005706 case AttributeList::AT_MSNoVTable:
5707 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
David Majnemer129f4172015-02-02 10:22:20 +00005708 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00005709 case AttributeList::AT_MSStruct:
5710 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
John McCall8d32c052012-05-22 21:28:12 +00005711 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005712 case AttributeList::AT_Uuid:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005713 handleUuidAttr(S, D, Attr);
Francois Picheta83957a2010-12-19 06:50:37 +00005714 break;
Aaron Ballman8edb5c22013-12-18 23:44:18 +00005715 case AttributeList::AT_MSInheritance:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005716 handleMSInheritanceAttr(S, D, Attr);
5717 break;
Reid Klecknerb144d362013-05-20 14:02:37 +00005718 case AttributeList::AT_SelectAny:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005719 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
5720 break;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00005721 case AttributeList::AT_Thread:
5722 handleDeclspecThreadAttr(S, D, Attr);
5723 break;
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005724 case AttributeList::AT_AbiTag:
5725 handleAbiTagAttr(S, D, Attr);
5726 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00005727
5728 // Thread safety attributes:
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00005729 case AttributeList::AT_AssertExclusiveLock:
5730 handleAssertExclusiveLockAttr(S, D, Attr);
5731 break;
5732 case AttributeList::AT_AssertSharedLock:
5733 handleAssertSharedLockAttr(S, D, Attr);
5734 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005735 case AttributeList::AT_GuardedVar:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005736 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
5737 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005738 case AttributeList::AT_PtGuardedVar:
Michael Han3be3b442012-07-23 18:48:41 +00005739 handlePtGuardedVarAttr(S, D, Attr);
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00005740 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005741 case AttributeList::AT_ScopedLockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005742 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
5743 break;
Peter Collingbourne915df992015-05-15 18:33:32 +00005744 case AttributeList::AT_NoSanitize:
5745 handleNoSanitizeAttr(S, D, Attr);
5746 break;
5747 case AttributeList::AT_NoSanitizeSpecific:
5748 handleNoSanitizeSpecificAttr(S, D, Attr);
Kostya Serebryany588d6ab2012-01-24 19:25:38 +00005749 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005750 case AttributeList::AT_NoThreadSafetyAnalysis:
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005751 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00005752 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005753 case AttributeList::AT_GuardedBy:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005754 handleGuardedByAttr(S, D, Attr);
5755 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005756 case AttributeList::AT_PtGuardedBy:
Michael Han3be3b442012-07-23 18:48:41 +00005757 handlePtGuardedByAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005758 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005759 case AttributeList::AT_ExclusiveTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00005760 handleExclusiveTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005761 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005762 case AttributeList::AT_LockReturned:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005763 handleLockReturnedAttr(S, D, Attr);
5764 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005765 case AttributeList::AT_LocksExcluded:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005766 handleLocksExcludedAttr(S, D, Attr);
5767 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005768 case AttributeList::AT_SharedTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00005769 handleSharedTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005770 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005771 case AttributeList::AT_AcquiredBefore:
Michael Han3be3b442012-07-23 18:48:41 +00005772 handleAcquiredBeforeAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005773 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005774 case AttributeList::AT_AcquiredAfter:
Michael Han3be3b442012-07-23 18:48:41 +00005775 handleAcquiredAfterAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005776 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00005777
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005778 // Capability analysis attributes.
5779 case AttributeList::AT_Capability:
5780 case AttributeList::AT_Lockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005781 handleCapabilityAttr(S, D, Attr);
5782 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005783 case AttributeList::AT_RequiresCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005784 handleRequiresCapabilityAttr(S, D, Attr);
5785 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005786
5787 case AttributeList::AT_AssertCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005788 handleAssertCapabilityAttr(S, D, Attr);
5789 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005790 case AttributeList::AT_AcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005791 handleAcquireCapabilityAttr(S, D, Attr);
5792 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005793 case AttributeList::AT_ReleaseCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005794 handleReleaseCapabilityAttr(S, D, Attr);
5795 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005796 case AttributeList::AT_TryAcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005797 handleTryAcquireCapabilityAttr(S, D, Attr);
5798 break;
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005799
DeLesley Hutchins8d41d992013-10-11 22:30:48 +00005800 // Consumed analysis attributes.
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00005801 case AttributeList::AT_Consumable:
5802 handleConsumableAttr(S, D, Attr);
5803 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00005804 case AttributeList::AT_ConsumableAutoCast:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005805 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
5806 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00005807 case AttributeList::AT_ConsumableSetOnRead:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005808 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
5809 break;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00005810 case AttributeList::AT_CallableWhen:
5811 handleCallableWhenAttr(S, D, Attr);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00005812 break;
DeLesley Hutchins69391772013-10-17 23:23:53 +00005813 case AttributeList::AT_ParamTypestate:
5814 handleParamTypestateAttr(S, D, Attr);
5815 break;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00005816 case AttributeList::AT_ReturnTypestate:
5817 handleReturnTypestateAttr(S, D, Attr);
5818 break;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00005819 case AttributeList::AT_SetTypestate:
5820 handleSetTypestateAttr(S, D, Attr);
5821 break;
Chris Wailes9385f9f2013-10-29 20:28:41 +00005822 case AttributeList::AT_TestTypestate:
5823 handleTestTypestateAttr(S, D, Attr);
DeLesley Hutchins33a29342013-10-11 23:03:26 +00005824 break;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00005825
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00005826 // Type safety attributes.
5827 case AttributeList::AT_ArgumentWithTypeTag:
5828 handleArgumentWithTypeTagAttr(S, D, Attr);
5829 break;
5830 case AttributeList::AT_TypeTagForDatatype:
5831 handleTypeTagForDatatypeAttr(S, D, Attr);
5832 break;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005833 }
5834}
5835
5836/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5837/// attribute list to the specified decl, ignoring any type attributes.
Eric Christopherbc638a82010-12-01 22:13:54 +00005838void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
Peter Collingbourneb331b262011-01-21 02:08:45 +00005839 const AttributeList *AttrList,
Richard Smith10876ef2013-01-17 01:30:42 +00005840 bool IncludeCXX11Attributes) {
5841 for (const AttributeList* l = AttrList; l; l = l->getNext())
Richard Smithf8a75c32013-08-29 00:47:48 +00005842 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
Rafael Espindolac18086a2010-02-23 22:00:30 +00005843
Joey Gouly2cd9db12013-12-13 16:15:28 +00005844 // FIXME: We should be able to handle these cases in TableGen.
Rafael Espindolac18086a2010-02-23 22:00:30 +00005845 // GCC accepts
5846 // static int a9 __attribute__((weakref));
5847 // but that looks really pointless. We reject it.
Richard Smithf8a75c32013-08-29 00:47:48 +00005848 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00005849 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
5850 << cast<NamedDecl>(D);
Rafael Espindolab3069002013-01-16 23:49:06 +00005851 D->dropAttr<WeakRefAttr>();
Rafael Espindolac18086a2010-02-23 22:00:30 +00005852 return;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005853 }
Joey Gouly2cd9db12013-12-13 16:15:28 +00005854
Aaron Ballmanbe243a72014-12-04 22:45:31 +00005855 // FIXME: We should be able to handle this in TableGen as well. It would be
5856 // good to have a way to specify "these attributes must appear as a group",
5857 // for these. Additionally, it would be good to have a way to specify "these
5858 // attribute must never appear as a group" for attributes like cold and hot.
Joey Gouly2cd9db12013-12-13 16:15:28 +00005859 if (!D->hasAttr<OpenCLKernelAttr>()) {
5860 // These attributes cannot be applied to a non-kernel function.
Aaron Ballman3e424b52013-12-26 18:30:57 +00005861 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00005862 // FIXME: This emits a different error message than
5863 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
Aaron Ballman3e424b52013-12-26 18:30:57 +00005864 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00005865 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00005866 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00005867 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00005868 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00005869 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00005870 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00005871 D->setInvalidDecl();
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00005872 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
5873 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5874 << A << ExpectedKernelFunction;
5875 D->setInvalidDecl();
5876 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
5877 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5878 << A << ExpectedKernelFunction;
5879 D->setInvalidDecl();
Joey Gouly2cd9db12013-12-13 16:15:28 +00005880 }
5881 }
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005882}
5883
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00005884// Annotation attributes are the only attributes allowed after an access
5885// specifier.
5886bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5887 const AttributeList *AttrList) {
5888 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005889 if (l->getKind() == AttributeList::AT_Annotate) {
David Majnemer706f3152014-12-14 01:05:01 +00005890 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00005891 } else {
5892 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
5893 return true;
5894 }
5895 }
5896
5897 return false;
5898}
5899
John McCall42856de2011-10-01 05:17:03 +00005900/// checkUnusedDeclAttributes - Check a list of attributes to see if it
5901/// contains any decl attributes that we should warn about.
5902static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
5903 for ( ; A; A = A->getNext()) {
5904 // Only warn if the attribute is an unignored, non-type attribute.
Richard Smith810ad3e2013-01-29 10:02:16 +00005905 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
John McCall42856de2011-10-01 05:17:03 +00005906 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
5907
5908 if (A->getKind() == AttributeList::UnknownAttribute) {
5909 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
5910 << A->getName() << A->getRange();
5911 } else {
5912 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
5913 << A->getName() << A->getRange();
5914 }
5915 }
5916}
5917
5918/// checkUnusedDeclAttributes - Given a declarator which is not being
5919/// used to build a declaration, complain about any decl attributes
5920/// which might be lying around on it.
5921void Sema::checkUnusedDeclAttributes(Declarator &D) {
5922 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
5923 ::checkUnusedDeclAttributes(*this, D.getAttributes());
5924 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
5925 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
5926}
5927
Ryan Flynn7d470f32009-07-30 03:15:39 +00005928/// DeclClonePragmaWeak - clone existing decl (maybe definition),
James Dennett634962f2012-06-14 21:40:34 +00005929/// \#pragma weak needs a non-definition decl and source may not have one.
Eli Friedmance3e2c82011-09-07 04:05:06 +00005930NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
5931 SourceLocation Loc) {
Ryan Flynnd963a492009-07-31 02:52:19 +00005932 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
Craig Topperc3ec1492014-05-26 06:22:03 +00005933 NamedDecl *NewD = nullptr;
Ryan Flynn7d470f32009-07-30 03:15:39 +00005934 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Alexander Kornienko061900f2015-12-03 11:37:28 +00005935 FunctionDecl *NewFD;
5936 // FIXME: Missing call to CheckFunctionDeclaration().
Eli Friedmance3e2c82011-09-07 04:05:06 +00005937 // FIXME: Mangling?
5938 // FIXME: Is the qualifier info correct?
5939 // FIXME: Is the DeclContext correct?
Alexander Kornienko061900f2015-12-03 11:37:28 +00005940 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
5941 Loc, Loc, DeclarationName(II),
5942 FD->getType(), FD->getTypeSourceInfo(),
5943 SC_None, false/*isInlineSpecified*/,
5944 FD->hasPrototype(),
5945 false/*isConstexprSpecified*/);
Eli Friedmance3e2c82011-09-07 04:05:06 +00005946 NewD = NewFD;
5947
5948 if (FD->getQualifier())
Douglas Gregor14454802011-02-25 02:25:35 +00005949 NewFD->setQualifierInfo(FD->getQualifierLoc());
Eli Friedmance3e2c82011-09-07 04:05:06 +00005950
5951 // Fake up parameter variables; they are declared as if this were
5952 // a typedef.
5953 QualType FDTy = FD->getType();
5954 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
5955 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005956 for (const auto &AI : FT->param_types()) {
5957 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
Eli Friedmance3e2c82011-09-07 04:05:06 +00005958 Param->setScopeInfo(0, Params.size());
5959 Params.push_back(Param);
5960 }
David Blaikie9c70e042011-09-21 18:16:56 +00005961 NewFD->setParams(Params);
John McCall3e11ebe2010-03-15 10:12:16 +00005962 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00005963 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
5964 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005965 VD->getInnerLocStart(), VD->getLocation(), II,
John McCallbcd03502009-12-07 02:54:59 +00005966 VD->getType(), VD->getTypeSourceInfo(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005967 VD->getStorageClass());
John McCall3e11ebe2010-03-15 10:12:16 +00005968 if (VD->getQualifier()) {
5969 VarDecl *NewVD = cast<VarDecl>(NewD);
Douglas Gregor14454802011-02-25 02:25:35 +00005970 NewVD->setQualifierInfo(VD->getQualifierLoc());
John McCall3e11ebe2010-03-15 10:12:16 +00005971 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00005972 }
5973 return NewD;
5974}
5975
James Dennett634962f2012-06-14 21:40:34 +00005976/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
Ryan Flynn7d470f32009-07-30 03:15:39 +00005977/// applied to it, possibly with an alias.
Ryan Flynnd963a492009-07-31 02:52:19 +00005978void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
Chris Lattnere6eab982009-09-08 18:10:11 +00005979 if (W.getUsed()) return; // only do this once
5980 W.setUsed(true);
5981 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
5982 IdentifierInfo *NDId = ND->getIdentifier();
Eli Friedmance3e2c82011-09-07 04:05:06 +00005983 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
Aaron Ballman36a53502014-01-16 13:03:14 +00005984 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
5985 W.getLocation()));
5986 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Chris Lattnere6eab982009-09-08 18:10:11 +00005987 WeakTopLevelDecl.push_back(NewD);
5988 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
5989 // to insert Decl at TU scope, sorry.
5990 DeclContext *SavedContext = CurContext;
5991 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis0098a4b2014-03-09 05:15:28 +00005992 NewD->setDeclContext(CurContext);
5993 NewD->setLexicalDeclContext(CurContext);
Chris Lattnere6eab982009-09-08 18:10:11 +00005994 PushOnScopeChains(NewD, S);
5995 CurContext = SavedContext;
5996 } else { // just add weak to existing
Aaron Ballman36a53502014-01-16 13:03:14 +00005997 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Ryan Flynn7d470f32009-07-30 03:15:39 +00005998 }
5999}
6000
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006001void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6002 // It's valid to "forward-declare" #pragma weak, in which case we
6003 // have to do this.
6004 LoadExternalWeakUndeclaredIdentifiers();
6005 if (!WeakUndeclaredIdentifiers.empty()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006006 NamedDecl *ND = nullptr;
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006007 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6008 if (VD->isExternC())
6009 ND = VD;
6010 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6011 if (FD->isExternC())
6012 ND = FD;
6013 if (ND) {
6014 if (IdentifierInfo *Id = ND->getIdentifier()) {
Chandler Carruthf85d9822015-03-26 08:32:49 +00006015 auto I = WeakUndeclaredIdentifiers.find(Id);
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006016 if (I != WeakUndeclaredIdentifiers.end()) {
6017 WeakInfo W = I->second;
6018 DeclApplyPragmaWeak(S, ND, W);
6019 WeakUndeclaredIdentifiers[Id] = W;
6020 }
6021 }
6022 }
6023 }
6024}
6025
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006026/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6027/// it, apply them to D. This is a bit tricky because PD can have attributes
6028/// specified in many different places, and we need to find and apply them all.
Richard Smithf8a75c32013-08-29 00:47:48 +00006029void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006030 // Apply decl attributes from the DeclSpec if present.
John McCall53fa7142010-12-24 02:08:15 +00006031 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
Richard Smithf8a75c32013-08-29 00:47:48 +00006032 ProcessDeclAttributeList(S, D, Attrs);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006033
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006034 // Walk the declarator structure, applying decl attributes that were in a type
6035 // position to the decl itself. This handles cases like:
6036 // int *__attr__(x)** D;
6037 // when X is a decl attribute.
6038 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6039 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
Richard Smithf8a75c32013-08-29 00:47:48 +00006040 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006041
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006042 // Finally, apply any attributes on the decl itself.
6043 if (const AttributeList *Attrs = PD.getAttributes())
Richard Smithf8a75c32013-08-29 00:47:48 +00006044 ProcessDeclAttributeList(S, D, Attrs);
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006045}
John McCall28a6aea2009-11-04 02:18:39 +00006046
John McCall31168b02011-06-15 23:02:42 +00006047/// Is the given declaration allowed to use a forbidden type?
John McCallb61e14e2015-10-27 04:54:50 +00006048/// If so, it'll still be annotated with an attribute that makes it
6049/// illegal to actually use.
6050static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6051 const DelayedDiagnostic &diag,
John McCallc6af8c62015-10-28 05:03:19 +00006052 UnavailableAttr::ImplicitReason &reason) {
John McCall31168b02011-06-15 23:02:42 +00006053 // Private ivars are always okay. Unfortunately, people don't
6054 // always properly make their ivars private, even in system headers.
6055 // Plus we need to make fields okay, too.
Fariborz Jahanian6d5d6a22011-09-26 21:23:35 +00006056 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6057 !isa<FunctionDecl>(decl))
John McCall31168b02011-06-15 23:02:42 +00006058 return false;
6059
John McCallc6af8c62015-10-28 05:03:19 +00006060 // Silently accept unsupported uses of __weak in both user and system
6061 // declarations when it's been disabled, for ease of integration with
6062 // -fno-objc-arc files. We do have to take some care against attempts
6063 // to define such things; for now, we've only done that for ivars
6064 // and properties.
6065 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6066 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6067 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6068 reason = UnavailableAttr::IR_ForbiddenWeak;
6069 return true;
6070 }
John McCallb61e14e2015-10-27 04:54:50 +00006071 }
6072
John McCallc6af8c62015-10-28 05:03:19 +00006073 // Allow all sorts of things in system headers.
6074 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6075 // Currently, all the failures dealt with this way are due to ARC
6076 // restrictions.
6077 reason = UnavailableAttr::IR_ARCForbiddenType;
6078 return true;
John McCallb61e14e2015-10-27 04:54:50 +00006079 }
6080
6081 return false;
John McCall31168b02011-06-15 23:02:42 +00006082}
6083
6084/// Handle a delayed forbidden-type diagnostic.
6085static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6086 Decl *decl) {
John McCallc6af8c62015-10-28 05:03:19 +00006087 auto reason = UnavailableAttr::IR_None;
6088 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6089 assert(reason && "didn't set reason?");
6090 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6091 diag.Loc));
John McCall31168b02011-06-15 23:02:42 +00006092 return;
6093 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00006094 if (S.getLangOpts().ObjCAutoRefCount)
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006095 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
Benjamin Kramer474261a2012-06-02 10:20:41 +00006096 // FIXME: we may want to suppress diagnostics for all
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006097 // kind of forbidden type messages on unavailable functions.
6098 if (FD->hasAttr<UnavailableAttr>() &&
6099 diag.getForbiddenTypeDiagnostic() ==
6100 diag::err_arc_array_param_no_ownership) {
6101 diag.Triggered = true;
6102 return;
6103 }
6104 }
John McCall31168b02011-06-15 23:02:42 +00006105
6106 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6107 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6108 diag.Triggered = true;
6109}
6110
Aaron Ballmanfb237522014-10-15 15:37:51 +00006111static bool isDeclDeprecated(Decl *D) {
6112 do {
6113 if (D->isDeprecated())
6114 return true;
6115 // A category implicitly has the availability of the interface.
6116 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00006117 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6118 return Interface->isDeprecated();
Aaron Ballmanfb237522014-10-15 15:37:51 +00006119 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
6120 return false;
6121}
6122
6123static bool isDeclUnavailable(Decl *D) {
6124 do {
6125 if (D->isUnavailable())
6126 return true;
6127 // A category implicitly has the availability of the interface.
6128 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00006129 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6130 return Interface->isUnavailable();
Aaron Ballmanfb237522014-10-15 15:37:51 +00006131 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
6132 return false;
6133}
6134
Nico Weber0055a192015-03-19 19:18:22 +00006135static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K,
Aaron Ballmanfb237522014-10-15 15:37:51 +00006136 Decl *Ctx, const NamedDecl *D,
6137 StringRef Message, SourceLocation Loc,
6138 const ObjCInterfaceDecl *UnknownObjCClass,
6139 const ObjCPropertyDecl *ObjCProperty,
6140 bool ObjCPropertyAccess) {
6141 // Diagnostics for deprecated or unavailable.
6142 unsigned diag, diag_message, diag_fwdclass_message;
John McCallb61e14e2015-10-27 04:54:50 +00006143 unsigned diag_available_here = diag::note_availability_specified_here;
Aaron Ballmanfb237522014-10-15 15:37:51 +00006144
6145 // Matches 'diag::note_property_attribute' options.
6146 unsigned property_note_select;
6147
6148 // Matches diag::note_availability_specified_here.
6149 unsigned available_here_select_kind;
6150
6151 // Don't warn if our current context is deprecated or unavailable.
6152 switch (K) {
Nico Weber0055a192015-03-19 19:18:22 +00006153 case Sema::AD_Deprecation:
Jordan Rosed17c03e2015-04-30 17:20:35 +00006154 if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx))
Aaron Ballmanfb237522014-10-15 15:37:51 +00006155 return;
6156 diag = !ObjCPropertyAccess ? diag::warn_deprecated
6157 : diag::warn_property_method_deprecated;
6158 diag_message = diag::warn_deprecated_message;
6159 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6160 property_note_select = /* deprecated */ 0;
6161 available_here_select_kind = /* deprecated */ 2;
6162 break;
6163
Nico Weber0055a192015-03-19 19:18:22 +00006164 case Sema::AD_Unavailable:
Aaron Ballmanfb237522014-10-15 15:37:51 +00006165 if (isDeclUnavailable(Ctx))
6166 return;
6167 diag = !ObjCPropertyAccess ? diag::err_unavailable
6168 : diag::err_property_method_unavailable;
6169 diag_message = diag::err_unavailable_message;
6170 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6171 property_note_select = /* unavailable */ 1;
6172 available_here_select_kind = /* unavailable */ 0;
John McCallb61e14e2015-10-27 04:54:50 +00006173
John McCallc6af8c62015-10-28 05:03:19 +00006174 if (auto attr = D->getAttr<UnavailableAttr>()) {
6175 if (attr->isImplicit() && attr->getImplicitReason()) {
6176 // Most of these failures are due to extra restrictions in ARC;
6177 // reflect that in the primary diagnostic when applicable.
6178 auto flagARCError = [&] {
6179 if (S.getLangOpts().ObjCAutoRefCount &&
6180 S.getSourceManager().isInSystemHeader(D->getLocation()))
6181 diag = diag::err_unavailable_in_arc;
6182 };
6183
6184 switch (attr->getImplicitReason()) {
6185 case UnavailableAttr::IR_None: break;
6186
6187 case UnavailableAttr::IR_ARCForbiddenType:
6188 flagARCError();
6189 diag_available_here = diag::note_arc_forbidden_type;
6190 break;
6191
6192 case UnavailableAttr::IR_ForbiddenWeak:
6193 if (S.getLangOpts().ObjCWeakRuntime)
6194 diag_available_here = diag::note_arc_weak_disabled;
6195 else
6196 diag_available_here = diag::note_arc_weak_no_runtime;
6197 break;
6198
6199 case UnavailableAttr::IR_ARCForbiddenConversion:
6200 flagARCError();
6201 diag_available_here = diag::note_performs_forbidden_arc_conversion;
6202 break;
6203
6204 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6205 flagARCError();
6206 diag_available_here = diag::note_arc_init_returns_unrelated;
6207 break;
6208
6209 case UnavailableAttr::IR_ARCFieldWithOwnership:
6210 flagARCError();
6211 diag_available_here = diag::note_arc_field_with_ownership;
6212 break;
6213 }
6214 }
John McCallb61e14e2015-10-27 04:54:50 +00006215 }
Aaron Ballmanfb237522014-10-15 15:37:51 +00006216 break;
6217
Nico Weber0055a192015-03-19 19:18:22 +00006218 case Sema::AD_Partial:
6219 diag = diag::warn_partial_availability;
6220 diag_message = diag::warn_partial_message;
6221 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6222 property_note_select = /* partial */ 2;
6223 available_here_select_kind = /* partial */ 3;
6224 break;
Aaron Ballmanfb237522014-10-15 15:37:51 +00006225 }
6226
Manman Renc7890fe2016-03-16 18:50:49 +00006227 CharSourceRange UseRange;
6228 StringRef Replacement;
6229 if (K == Sema::AD_Deprecation) {
6230 if (auto attr = D->getAttr<DeprecatedAttr>())
6231 Replacement = attr->getReplacement();
6232
6233 if (!Replacement.empty())
6234 UseRange =
6235 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
6236 }
6237
Aaron Ballmanfb237522014-10-15 15:37:51 +00006238 if (!Message.empty()) {
Manman Renc7890fe2016-03-16 18:50:49 +00006239 S.Diag(Loc, diag_message) << D << Message
6240 << (UseRange.isValid() ?
6241 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006242 if (ObjCProperty)
6243 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6244 << ObjCProperty->getDeclName() << property_note_select;
6245 } else if (!UnknownObjCClass) {
Manman Renc7890fe2016-03-16 18:50:49 +00006246 S.Diag(Loc, diag) << D
6247 << (UseRange.isValid() ?
6248 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006249 if (ObjCProperty)
6250 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6251 << ObjCProperty->getDeclName() << property_note_select;
6252 } else {
Manman Renc7890fe2016-03-16 18:50:49 +00006253 S.Diag(Loc, diag_fwdclass_message) << D
6254 << (UseRange.isValid() ?
6255 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006256 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
6257 }
6258
John McCallb61e14e2015-10-27 04:54:50 +00006259 S.Diag(D->getLocation(), diag_available_here)
Aaron Ballmanfb237522014-10-15 15:37:51 +00006260 << D << available_here_select_kind;
Nico Weber0055a192015-03-19 19:18:22 +00006261 if (K == Sema::AD_Partial)
6262 S.Diag(Loc, diag::note_partial_availability_silence) << D;
Aaron Ballmanfb237522014-10-15 15:37:51 +00006263}
6264
6265static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
6266 Decl *Ctx) {
Nico Weber0055a192015-03-19 19:18:22 +00006267 assert(DD.Kind == DelayedDiagnostic::Deprecation ||
Manman Rend8039df2016-02-22 04:47:24 +00006268 DD.Kind == DelayedDiagnostic::Unavailable);
6269 Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation
6270 ? Sema::AD_Deprecation
6271 : Sema::AD_Unavailable;
Aaron Ballmanfb237522014-10-15 15:37:51 +00006272 DD.Triggered = true;
Nico Weber0055a192015-03-19 19:18:22 +00006273 DoEmitAvailabilityWarning(
6274 S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc,
6275 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
Aaron Ballmanfb237522014-10-15 15:37:51 +00006276}
6277
John McCall2ec85372012-05-07 06:16:41 +00006278void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
6279 assert(DelayedDiagnostics.getCurrentPool());
John McCall6347b682012-05-07 06:16:58 +00006280 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
John McCall2ec85372012-05-07 06:16:41 +00006281 DelayedDiagnostics.popWithoutEmitting(state);
John McCallc1465822011-02-14 07:13:47 +00006282
John McCall2ec85372012-05-07 06:16:41 +00006283 // When delaying diagnostics to run in the context of a parsed
6284 // declaration, we only want to actually emit anything if parsing
6285 // succeeds.
6286 if (!decl) return;
John McCallc1465822011-02-14 07:13:47 +00006287
John McCall2ec85372012-05-07 06:16:41 +00006288 // We emit all the active diagnostics in this pool or any of its
6289 // parents. In general, we'll get one pool for the decl spec
6290 // and a child pool for each declarator; in a decl group like:
6291 // deprecated_typedef foo, *bar, baz();
6292 // only the declarator pops will be passed decls. This is correct;
6293 // we really do need to consider delayed diagnostics from the decl spec
6294 // for each of the different declarations.
John McCall6347b682012-05-07 06:16:58 +00006295 const DelayedDiagnosticPool *pool = &poppedPool;
John McCall2ec85372012-05-07 06:16:41 +00006296 do {
John McCall6347b682012-05-07 06:16:58 +00006297 for (DelayedDiagnosticPool::pool_iterator
John McCall2ec85372012-05-07 06:16:41 +00006298 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
6299 // This const_cast is a bit lame. Really, Triggered should be mutable.
6300 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
John McCallc1465822011-02-14 07:13:47 +00006301 if (diag.Triggered)
John McCall86121512010-01-27 03:50:35 +00006302 continue;
6303
John McCallc1465822011-02-14 07:13:47 +00006304 switch (diag.Kind) {
John McCall86121512010-01-27 03:50:35 +00006305 case DelayedDiagnostic::Deprecation:
Ted Kremenekb79ee572013-12-18 23:30:06 +00006306 case DelayedDiagnostic::Unavailable:
6307 // Don't bother giving deprecation/unavailable diagnostics if
6308 // the decl is invalid.
John McCall18a962b2012-01-26 20:04:03 +00006309 if (!decl->isInvalidDecl())
Aaron Ballmanfb237522014-10-15 15:37:51 +00006310 handleDelayedAvailabilityCheck(*this, diag, decl);
John McCall86121512010-01-27 03:50:35 +00006311 break;
6312
6313 case DelayedDiagnostic::Access:
John McCall2ec85372012-05-07 06:16:41 +00006314 HandleDelayedAccessCheck(diag, decl);
John McCall86121512010-01-27 03:50:35 +00006315 break;
John McCall31168b02011-06-15 23:02:42 +00006316
6317 case DelayedDiagnostic::ForbiddenType:
John McCall2ec85372012-05-07 06:16:41 +00006318 handleDelayedForbiddenType(*this, diag, decl);
John McCall31168b02011-06-15 23:02:42 +00006319 break;
John McCall86121512010-01-27 03:50:35 +00006320 }
6321 }
John McCall2ec85372012-05-07 06:16:41 +00006322 } while ((pool = pool->getParent()));
John McCall28a6aea2009-11-04 02:18:39 +00006323}
6324
John McCall6347b682012-05-07 06:16:58 +00006325/// Given a set of delayed diagnostics, re-emit them as if they had
6326/// been delayed in the current context instead of in the given pool.
6327/// Essentially, this just moves them to the current pool.
6328void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
6329 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
6330 assert(curPool && "re-emitting in undelayed context not supported");
6331 curPool->steal(pool);
6332}
6333
Ted Kremenekb79ee572013-12-18 23:30:06 +00006334void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
6335 NamedDecl *D, StringRef Message,
6336 SourceLocation Loc,
6337 const ObjCInterfaceDecl *UnknownObjCClass,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +00006338 const ObjCPropertyDecl *ObjCProperty,
6339 bool ObjCPropertyAccess) {
John McCall28a6aea2009-11-04 02:18:39 +00006340 // Delay if we're currently parsing a declaration.
Nico Weber0055a192015-03-19 19:18:22 +00006341 if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) {
Nico Weber462fd1e2015-01-07 23:50:05 +00006342 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
6343 AD, Loc, D, UnknownObjCClass, ObjCProperty, Message,
6344 ObjCPropertyAccess));
John McCall28a6aea2009-11-04 02:18:39 +00006345 return;
6346 }
6347
Ted Kremenekb79ee572013-12-18 23:30:06 +00006348 Decl *Ctx = cast<Decl>(getCurLexicalContext());
Nico Weber0055a192015-03-19 19:18:22 +00006349 DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass,
6350 ObjCProperty, ObjCPropertyAccess);
John McCall28a6aea2009-11-04 02:18:39 +00006351}