1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements decl-related attribute processing.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/Basic/CharInfo.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/DeclSpec.h"
28 #include "clang/Sema/DelayedDiagnostic.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/Scope.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/MathExtras.h"
33 using namespace clang;
34 using namespace sema;
35 
36 namespace AttributeLangSupport {
37   enum LANG {
38     C,
39     Cpp,
40     ObjC
41   };
42 }
43 
44 //===----------------------------------------------------------------------===//
45 //  Helper functions
46 //===----------------------------------------------------------------------===//
47 
48 /// isFunctionOrMethod - Return true if the given decl has function
49 /// type (function or function-typed variable) or an Objective-C
50 /// method.
isFunctionOrMethod(const Decl * D)51 static bool isFunctionOrMethod(const Decl *D) {
52   return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
53 }
54 /// \brief Return true if the given decl has function type (function or
55 /// function-typed variable) or an Objective-C method or a block.
isFunctionOrMethodOrBlock(const Decl * D)56 static bool isFunctionOrMethodOrBlock(const Decl *D) {
57   return isFunctionOrMethod(D) || isa<BlockDecl>(D);
58 }
59 
60 /// Return true if the given decl has a declarator that should have
61 /// been processed by Sema::GetTypeForDeclarator.
hasDeclarator(const Decl * D)62 static bool hasDeclarator(const Decl *D) {
63   // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
64   return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
65          isa<ObjCPropertyDecl>(D);
66 }
67 
68 /// hasFunctionProto - Return true if the given decl has a argument
69 /// information. This decl should have already passed
70 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
hasFunctionProto(const Decl * D)71 static bool hasFunctionProto(const Decl *D) {
72   if (const FunctionType *FnTy = D->getFunctionType())
73     return isa<FunctionProtoType>(FnTy);
74   return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
75 }
76 
77 /// getFunctionOrMethodNumParams - Return number of function or method
78 /// parameters. It is an error to call this on a K&R function (use
79 /// hasFunctionProto first).
getFunctionOrMethodNumParams(const Decl * D)80 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
81   if (const FunctionType *FnTy = D->getFunctionType())
82     return cast<FunctionProtoType>(FnTy)->getNumParams();
83   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
84     return BD->getNumParams();
85   return cast<ObjCMethodDecl>(D)->param_size();
86 }
87 
getFunctionOrMethodParamType(const Decl * D,unsigned Idx)88 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
89   if (const FunctionType *FnTy = D->getFunctionType())
90     return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
91   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
92     return BD->getParamDecl(Idx)->getType();
93 
94   return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
95 }
96 
getFunctionOrMethodParamRange(const Decl * D,unsigned Idx)97 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
98   if (const auto *FD = dyn_cast<FunctionDecl>(D))
99     return FD->getParamDecl(Idx)->getSourceRange();
100   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
101     return MD->parameters()[Idx]->getSourceRange();
102   if (const auto *BD = dyn_cast<BlockDecl>(D))
103     return BD->getParamDecl(Idx)->getSourceRange();
104   return SourceRange();
105 }
106 
getFunctionOrMethodResultType(const Decl * D)107 static QualType getFunctionOrMethodResultType(const Decl *D) {
108   if (const FunctionType *FnTy = D->getFunctionType())
109     return cast<FunctionType>(FnTy)->getReturnType();
110   return cast<ObjCMethodDecl>(D)->getReturnType();
111 }
112 
getFunctionOrMethodResultSourceRange(const Decl * D)113 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
114   if (const auto *FD = dyn_cast<FunctionDecl>(D))
115     return FD->getReturnTypeSourceRange();
116   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
117     return MD->getReturnTypeSourceRange();
118   return SourceRange();
119 }
120 
isFunctionOrMethodVariadic(const Decl * D)121 static bool isFunctionOrMethodVariadic(const Decl *D) {
122   if (const FunctionType *FnTy = D->getFunctionType()) {
123     const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
124     return proto->isVariadic();
125   }
126   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
127     return BD->isVariadic();
128 
129   return cast<ObjCMethodDecl>(D)->isVariadic();
130 }
131 
isInstanceMethod(const Decl * D)132 static bool isInstanceMethod(const Decl *D) {
133   if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
134     return MethodDecl->isInstance();
135   return false;
136 }
137 
isNSStringType(QualType T,ASTContext & Ctx)138 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
139   const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
140   if (!PT)
141     return false;
142 
143   ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
144   if (!Cls)
145     return false;
146 
147   IdentifierInfo* ClsName = Cls->getIdentifier();
148 
149   // FIXME: Should we walk the chain of classes?
150   return ClsName == &Ctx.Idents.get("NSString") ||
151          ClsName == &Ctx.Idents.get("NSMutableString");
152 }
153 
isCFStringType(QualType T,ASTContext & Ctx)154 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
155   const PointerType *PT = T->getAs<PointerType>();
156   if (!PT)
157     return false;
158 
159   const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
160   if (!RT)
161     return false;
162 
163   const RecordDecl *RD = RT->getDecl();
164   if (RD->getTagKind() != TTK_Struct)
165     return false;
166 
167   return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
168 }
169 
getNumAttributeArgs(const AttributeList & Attr)170 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
171   // FIXME: Include the type in the argument list.
172   return Attr.getNumArgs() + Attr.hasParsedType();
173 }
174 
175 template <typename Compare>
checkAttributeNumArgsImpl(Sema & S,const AttributeList & Attr,unsigned Num,unsigned Diag,Compare Comp)176 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
177                                       unsigned Num, unsigned Diag,
178                                       Compare Comp) {
179   if (Comp(getNumAttributeArgs(Attr), Num)) {
180     S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
181     return false;
182   }
183 
184   return true;
185 }
186 
187 /// \brief Check if the attribute has exactly as many args as Num. May
188 /// output an error.
checkAttributeNumArgs(Sema & S,const AttributeList & Attr,unsigned Num)189 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
190                                   unsigned Num) {
191   return checkAttributeNumArgsImpl(S, Attr, Num,
192                                    diag::err_attribute_wrong_number_arguments,
193                                    std::not_equal_to<unsigned>());
194 }
195 
196 /// \brief Check if the attribute has at least as many args as Num. May
197 /// output an error.
checkAttributeAtLeastNumArgs(Sema & S,const AttributeList & Attr,unsigned Num)198 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
199                                          unsigned Num) {
200   return checkAttributeNumArgsImpl(S, Attr, Num,
201                                    diag::err_attribute_too_few_arguments,
202                                    std::less<unsigned>());
203 }
204 
205 /// \brief Check if the attribute has at most as many args as Num. May
206 /// output an error.
checkAttributeAtMostNumArgs(Sema & S,const AttributeList & Attr,unsigned Num)207 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
208                                          unsigned Num) {
209   return checkAttributeNumArgsImpl(S, Attr, Num,
210                                    diag::err_attribute_too_many_arguments,
211                                    std::greater<unsigned>());
212 }
213 
214 /// \brief If Expr is a valid integer constant, get the value of the integer
215 /// expression and return success or failure. May output an error.
checkUInt32Argument(Sema & S,const AttributeList & Attr,const Expr * Expr,uint32_t & Val,unsigned Idx=UINT_MAX)216 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
217                                 const Expr *Expr, uint32_t &Val,
218                                 unsigned Idx = UINT_MAX) {
219   llvm::APSInt I(32);
220   if (Expr->isTypeDependent() || Expr->isValueDependent() ||
221       !Expr->isIntegerConstantExpr(I, S.Context)) {
222     if (Idx != UINT_MAX)
223       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
224         << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
225         << Expr->getSourceRange();
226     else
227       S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
228         << Attr.getName() << AANT_ArgumentIntegerConstant
229         << Expr->getSourceRange();
230     return false;
231   }
232 
233   if (!I.isIntN(32)) {
234     S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
235         << I.toString(10, false) << 32 << /* Unsigned */ 1;
236     return false;
237   }
238 
239   Val = (uint32_t)I.getZExtValue();
240   return true;
241 }
242 
243 /// \brief Diagnose mutually exclusive attributes when present on a given
244 /// declaration. Returns true if diagnosed.
245 template <typename AttrTy>
checkAttrMutualExclusion(Sema & S,Decl * D,const AttributeList & Attr)246 static bool checkAttrMutualExclusion(Sema &S, Decl *D,
247                                      const AttributeList &Attr) {
248   if (AttrTy *A = D->getAttr<AttrTy>()) {
249     S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
250       << Attr.getName() << A;
251     return true;
252   }
253   return false;
254 }
255 
256 /// \brief Check if IdxExpr is a valid parameter index for a function or
257 /// instance method D.  May output an error.
258 ///
259 /// \returns true if IdxExpr is a valid index.
checkFunctionOrMethodParameterIndex(Sema & S,const Decl * D,const AttributeList & Attr,unsigned AttrArgNum,const Expr * IdxExpr,uint64_t & Idx)260 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
261                                                 const AttributeList &Attr,
262                                                 unsigned AttrArgNum,
263                                                 const Expr *IdxExpr,
264                                                 uint64_t &Idx) {
265   assert(isFunctionOrMethodOrBlock(D));
266 
267   // In C++ the implicit 'this' function parameter also counts.
268   // Parameters are counted from one.
269   bool HP = hasFunctionProto(D);
270   bool HasImplicitThisParam = isInstanceMethod(D);
271   bool IV = HP && isFunctionOrMethodVariadic(D);
272   unsigned NumParams =
273       (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
274 
275   llvm::APSInt IdxInt;
276   if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
277       !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
278     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
279       << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
280       << IdxExpr->getSourceRange();
281     return false;
282   }
283 
284   Idx = IdxInt.getLimitedValue();
285   if (Idx < 1 || (!IV && Idx > NumParams)) {
286     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
287       << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
288     return false;
289   }
290   Idx--; // Convert to zero-based.
291   if (HasImplicitThisParam) {
292     if (Idx == 0) {
293       S.Diag(Attr.getLoc(),
294              diag::err_attribute_invalid_implicit_this_argument)
295         << Attr.getName() << IdxExpr->getSourceRange();
296       return false;
297     }
298     --Idx;
299   }
300 
301   return true;
302 }
303 
304 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
305 /// If not emit an error and return false. If the argument is an identifier it
306 /// will emit an error with a fixit hint and treat it as if it was a string
307 /// literal.
checkStringLiteralArgumentAttr(const AttributeList & Attr,unsigned ArgNum,StringRef & Str,SourceLocation * ArgLocation)308 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
309                                           unsigned ArgNum, StringRef &Str,
310                                           SourceLocation *ArgLocation) {
311   // Look for identifiers. If we have one emit a hint to fix it to a literal.
312   if (Attr.isArgIdent(ArgNum)) {
313     IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
314     Diag(Loc->Loc, diag::err_attribute_argument_type)
315         << Attr.getName() << AANT_ArgumentString
316         << FixItHint::CreateInsertion(Loc->Loc, "\"")
317         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(Loc->Loc), "\"");
318     Str = Loc->Ident->getName();
319     if (ArgLocation)
320       *ArgLocation = Loc->Loc;
321     return true;
322   }
323 
324   // Now check for an actual string literal.
325   Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
326   StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
327   if (ArgLocation)
328     *ArgLocation = ArgExpr->getLocStart();
329 
330   if (!Literal || !Literal->isAscii()) {
331     Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
332         << Attr.getName() << AANT_ArgumentString;
333     return false;
334   }
335 
336   Str = Literal->getString();
337   return true;
338 }
339 
340 /// \brief Applies the given attribute to the Decl without performing any
341 /// additional semantic checking.
342 template <typename AttrType>
handleSimpleAttribute(Sema & S,Decl * D,const AttributeList & Attr)343 static void handleSimpleAttribute(Sema &S, Decl *D,
344                                   const AttributeList &Attr) {
345   D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
346                                         Attr.getAttributeSpellingListIndex()));
347 }
348 
349 /// \brief Check if the passed-in expression is of type int or bool.
isIntOrBool(Expr * Exp)350 static bool isIntOrBool(Expr *Exp) {
351   QualType QT = Exp->getType();
352   return QT->isBooleanType() || QT->isIntegerType();
353 }
354 
355 
356 // Check to see if the type is a smart pointer of some kind.  We assume
357 // it's a smart pointer if it defines both operator-> and operator*.
threadSafetyCheckIsSmartPointer(Sema & S,const RecordType * RT)358 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
359   DeclContextLookupResult Res1 = RT->getDecl()->lookup(
360       S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
361   if (Res1.empty())
362     return false;
363 
364   DeclContextLookupResult Res2 = RT->getDecl()->lookup(
365       S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
366   if (Res2.empty())
367     return false;
368 
369   return true;
370 }
371 
372 /// \brief Check if passed in Decl is a pointer type.
373 /// Note that this function may produce an error message.
374 /// \return true if the Decl is a pointer type; false otherwise
threadSafetyCheckIsPointer(Sema & S,const Decl * D,const AttributeList & Attr)375 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
376                                        const AttributeList &Attr) {
377   const ValueDecl *vd = cast<ValueDecl>(D);
378   QualType QT = vd->getType();
379   if (QT->isAnyPointerType())
380     return true;
381 
382   if (const RecordType *RT = QT->getAs<RecordType>()) {
383     // If it's an incomplete type, it could be a smart pointer; skip it.
384     // (We don't want to force template instantiation if we can avoid it,
385     // since that would alter the order in which templates are instantiated.)
386     if (RT->isIncompleteType())
387       return true;
388 
389     if (threadSafetyCheckIsSmartPointer(S, RT))
390       return true;
391   }
392 
393   S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
394     << Attr.getName() << QT;
395   return false;
396 }
397 
398 /// \brief Checks that the passed in QualType either is of RecordType or points
399 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
getRecordType(QualType QT)400 static const RecordType *getRecordType(QualType QT) {
401   if (const RecordType *RT = QT->getAs<RecordType>())
402     return RT;
403 
404   // Now check if we point to record type.
405   if (const PointerType *PT = QT->getAs<PointerType>())
406     return PT->getPointeeType()->getAs<RecordType>();
407 
408   return nullptr;
409 }
410 
checkRecordTypeForCapability(Sema & S,QualType Ty)411 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
412   const RecordType *RT = getRecordType(Ty);
413 
414   if (!RT)
415     return false;
416 
417   // Don't check for the capability if the class hasn't been defined yet.
418   if (RT->isIncompleteType())
419     return true;
420 
421   // Allow smart pointers to be used as capability objects.
422   // FIXME -- Check the type that the smart pointer points to.
423   if (threadSafetyCheckIsSmartPointer(S, RT))
424     return true;
425 
426   // Check if the record itself has a capability.
427   RecordDecl *RD = RT->getDecl();
428   if (RD->hasAttr<CapabilityAttr>())
429     return true;
430 
431   // Else check if any base classes have a capability.
432   if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
433     CXXBasePaths BPaths(false, false);
434     if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &P,
435       void *) {
436       return BS->getType()->getAs<RecordType>()
437         ->getDecl()->hasAttr<CapabilityAttr>();
438     }, nullptr, BPaths))
439       return true;
440   }
441   return false;
442 }
443 
checkTypedefTypeForCapability(QualType Ty)444 static bool checkTypedefTypeForCapability(QualType Ty) {
445   const auto *TD = Ty->getAs<TypedefType>();
446   if (!TD)
447     return false;
448 
449   TypedefNameDecl *TN = TD->getDecl();
450   if (!TN)
451     return false;
452 
453   return TN->hasAttr<CapabilityAttr>();
454 }
455 
typeHasCapability(Sema & S,QualType Ty)456 static bool typeHasCapability(Sema &S, QualType Ty) {
457   if (checkTypedefTypeForCapability(Ty))
458     return true;
459 
460   if (checkRecordTypeForCapability(S, Ty))
461     return true;
462 
463   return false;
464 }
465 
isCapabilityExpr(Sema & S,const Expr * Ex)466 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
467   // Capability expressions are simple expressions involving the boolean logic
468   // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
469   // a DeclRefExpr is found, its type should be checked to determine whether it
470   // is a capability or not.
471 
472   if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
473     return typeHasCapability(S, E->getType());
474   else if (const auto *E = dyn_cast<CastExpr>(Ex))
475     return isCapabilityExpr(S, E->getSubExpr());
476   else if (const auto *E = dyn_cast<ParenExpr>(Ex))
477     return isCapabilityExpr(S, E->getSubExpr());
478   else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
479     if (E->getOpcode() == UO_LNot)
480       return isCapabilityExpr(S, E->getSubExpr());
481     return false;
482   } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
483     if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
484       return isCapabilityExpr(S, E->getLHS()) &&
485              isCapabilityExpr(S, E->getRHS());
486     return false;
487   }
488 
489   return false;
490 }
491 
492 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
493 /// a capability object.
494 /// \param Sidx The attribute argument index to start checking with.
495 /// \param ParamIdxOk Whether an argument can be indexing into a function
496 /// parameter list.
checkAttrArgsAreCapabilityObjs(Sema & S,Decl * D,const AttributeList & Attr,SmallVectorImpl<Expr * > & Args,int Sidx=0,bool ParamIdxOk=false)497 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
498                                            const AttributeList &Attr,
499                                            SmallVectorImpl<Expr *> &Args,
500                                            int Sidx = 0,
501                                            bool ParamIdxOk = false) {
502   for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
503     Expr *ArgExp = Attr.getArgAsExpr(Idx);
504 
505     if (ArgExp->isTypeDependent()) {
506       // FIXME -- need to check this again on template instantiation
507       Args.push_back(ArgExp);
508       continue;
509     }
510 
511     if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
512       if (StrLit->getLength() == 0 ||
513           (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
514         // Pass empty strings to the analyzer without warnings.
515         // Treat "*" as the universal lock.
516         Args.push_back(ArgExp);
517         continue;
518       }
519 
520       // We allow constant strings to be used as a placeholder for expressions
521       // that are not valid C++ syntax, but warn that they are ignored.
522       S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
523         Attr.getName();
524       Args.push_back(ArgExp);
525       continue;
526     }
527 
528     QualType ArgTy = ArgExp->getType();
529 
530     // A pointer to member expression of the form  &MyClass::mu is treated
531     // specially -- we need to look at the type of the member.
532     if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
533       if (UOp->getOpcode() == UO_AddrOf)
534         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
535           if (DRE->getDecl()->isCXXInstanceMember())
536             ArgTy = DRE->getDecl()->getType();
537 
538     // First see if we can just cast to record type, or pointer to record type.
539     const RecordType *RT = getRecordType(ArgTy);
540 
541     // Now check if we index into a record type function param.
542     if(!RT && ParamIdxOk) {
543       FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
544       IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
545       if(FD && IL) {
546         unsigned int NumParams = FD->getNumParams();
547         llvm::APInt ArgValue = IL->getValue();
548         uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
549         uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
550         if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
551           S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
552             << Attr.getName() << Idx + 1 << NumParams;
553           continue;
554         }
555         ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
556       }
557     }
558 
559     // If the type does not have a capability, see if the components of the
560     // expression have capabilities. This allows for writing C code where the
561     // capability may be on the type, and the expression is a capability
562     // boolean logic expression. Eg) requires_capability(A || B && !C)
563     if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
564       S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
565           << Attr.getName() << ArgTy;
566 
567     Args.push_back(ArgExp);
568   }
569 }
570 
571 //===----------------------------------------------------------------------===//
572 // Attribute Implementations
573 //===----------------------------------------------------------------------===//
574 
handlePtGuardedVarAttr(Sema & S,Decl * D,const AttributeList & Attr)575 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
576                                    const AttributeList &Attr) {
577   if (!threadSafetyCheckIsPointer(S, D, Attr))
578     return;
579 
580   D->addAttr(::new (S.Context)
581              PtGuardedVarAttr(Attr.getRange(), S.Context,
582                               Attr.getAttributeSpellingListIndex()));
583 }
584 
checkGuardedByAttrCommon(Sema & S,Decl * D,const AttributeList & Attr,Expr * & Arg)585 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
586                                      const AttributeList &Attr,
587                                      Expr* &Arg) {
588   SmallVector<Expr*, 1> Args;
589   // check that all arguments are lockable objects
590   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
591   unsigned Size = Args.size();
592   if (Size != 1)
593     return false;
594 
595   Arg = Args[0];
596 
597   return true;
598 }
599 
handleGuardedByAttr(Sema & S,Decl * D,const AttributeList & Attr)600 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
601   Expr *Arg = nullptr;
602   if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
603     return;
604 
605   D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
606                                         Attr.getAttributeSpellingListIndex()));
607 }
608 
handlePtGuardedByAttr(Sema & S,Decl * D,const AttributeList & Attr)609 static void handlePtGuardedByAttr(Sema &S, Decl *D,
610                                   const AttributeList &Attr) {
611   Expr *Arg = nullptr;
612   if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
613     return;
614 
615   if (!threadSafetyCheckIsPointer(S, D, Attr))
616     return;
617 
618   D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
619                                                S.Context, Arg,
620                                         Attr.getAttributeSpellingListIndex()));
621 }
622 
checkAcquireOrderAttrCommon(Sema & S,Decl * D,const AttributeList & Attr,SmallVectorImpl<Expr * > & Args)623 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
624                                         const AttributeList &Attr,
625                                         SmallVectorImpl<Expr *> &Args) {
626   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
627     return false;
628 
629   // Check that this attribute only applies to lockable types.
630   QualType QT = cast<ValueDecl>(D)->getType();
631   if (!QT->isDependentType()) {
632     const RecordType *RT = getRecordType(QT);
633     if (!RT || !RT->getDecl()->hasAttr<CapabilityAttr>()) {
634       S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
635         << Attr.getName();
636       return false;
637     }
638   }
639 
640   // Check that all arguments are lockable objects.
641   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
642   if (Args.empty())
643     return false;
644 
645   return true;
646 }
647 
handleAcquiredAfterAttr(Sema & S,Decl * D,const AttributeList & Attr)648 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
649                                     const AttributeList &Attr) {
650   SmallVector<Expr*, 1> Args;
651   if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
652     return;
653 
654   Expr **StartArg = &Args[0];
655   D->addAttr(::new (S.Context)
656              AcquiredAfterAttr(Attr.getRange(), S.Context,
657                                StartArg, Args.size(),
658                                Attr.getAttributeSpellingListIndex()));
659 }
660 
handleAcquiredBeforeAttr(Sema & S,Decl * D,const AttributeList & Attr)661 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
662                                      const AttributeList &Attr) {
663   SmallVector<Expr*, 1> Args;
664   if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
665     return;
666 
667   Expr **StartArg = &Args[0];
668   D->addAttr(::new (S.Context)
669              AcquiredBeforeAttr(Attr.getRange(), S.Context,
670                                 StartArg, Args.size(),
671                                 Attr.getAttributeSpellingListIndex()));
672 }
673 
checkLockFunAttrCommon(Sema & S,Decl * D,const AttributeList & Attr,SmallVectorImpl<Expr * > & Args)674 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
675                                    const AttributeList &Attr,
676                                    SmallVectorImpl<Expr *> &Args) {
677   // zero or more arguments ok
678   // check that all arguments are lockable objects
679   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
680 
681   return true;
682 }
683 
handleAssertSharedLockAttr(Sema & S,Decl * D,const AttributeList & Attr)684 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
685                                        const AttributeList &Attr) {
686   SmallVector<Expr*, 1> Args;
687   if (!checkLockFunAttrCommon(S, D, Attr, Args))
688     return;
689 
690   unsigned Size = Args.size();
691   Expr **StartArg = Size == 0 ? nullptr : &Args[0];
692   D->addAttr(::new (S.Context)
693              AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
694                                   Attr.getAttributeSpellingListIndex()));
695 }
696 
handleAssertExclusiveLockAttr(Sema & S,Decl * D,const AttributeList & Attr)697 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
698                                           const AttributeList &Attr) {
699   SmallVector<Expr*, 1> Args;
700   if (!checkLockFunAttrCommon(S, D, Attr, Args))
701     return;
702 
703   unsigned Size = Args.size();
704   Expr **StartArg = Size == 0 ? nullptr : &Args[0];
705   D->addAttr(::new (S.Context)
706              AssertExclusiveLockAttr(Attr.getRange(), S.Context,
707                                      StartArg, Size,
708                                      Attr.getAttributeSpellingListIndex()));
709 }
710 
711 
checkTryLockFunAttrCommon(Sema & S,Decl * D,const AttributeList & Attr,SmallVectorImpl<Expr * > & Args)712 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
713                                       const AttributeList &Attr,
714                                       SmallVectorImpl<Expr *> &Args) {
715   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
716     return false;
717 
718   if (!isIntOrBool(Attr.getArgAsExpr(0))) {
719     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
720       << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
721     return false;
722   }
723 
724   // check that all arguments are lockable objects
725   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
726 
727   return true;
728 }
729 
handleSharedTrylockFunctionAttr(Sema & S,Decl * D,const AttributeList & Attr)730 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
731                                             const AttributeList &Attr) {
732   SmallVector<Expr*, 2> Args;
733   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
734     return;
735 
736   D->addAttr(::new (S.Context)
737              SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
738                                        Attr.getArgAsExpr(0),
739                                        Args.data(), Args.size(),
740                                        Attr.getAttributeSpellingListIndex()));
741 }
742 
handleExclusiveTrylockFunctionAttr(Sema & S,Decl * D,const AttributeList & Attr)743 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
744                                                const AttributeList &Attr) {
745   SmallVector<Expr*, 2> Args;
746   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
747     return;
748 
749   D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
750       Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
751       Args.size(), Attr.getAttributeSpellingListIndex()));
752 }
753 
handleLockReturnedAttr(Sema & S,Decl * D,const AttributeList & Attr)754 static void handleLockReturnedAttr(Sema &S, Decl *D,
755                                    const AttributeList &Attr) {
756   // check that the argument is lockable object
757   SmallVector<Expr*, 1> Args;
758   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
759   unsigned Size = Args.size();
760   if (Size == 0)
761     return;
762 
763   D->addAttr(::new (S.Context)
764              LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
765                               Attr.getAttributeSpellingListIndex()));
766 }
767 
handleLocksExcludedAttr(Sema & S,Decl * D,const AttributeList & Attr)768 static void handleLocksExcludedAttr(Sema &S, Decl *D,
769                                     const AttributeList &Attr) {
770   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
771     return;
772 
773   // check that all arguments are lockable objects
774   SmallVector<Expr*, 1> Args;
775   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
776   unsigned Size = Args.size();
777   if (Size == 0)
778     return;
779   Expr **StartArg = &Args[0];
780 
781   D->addAttr(::new (S.Context)
782              LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
783                                Attr.getAttributeSpellingListIndex()));
784 }
785 
handleEnableIfAttr(Sema & S,Decl * D,const AttributeList & Attr)786 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
787   Expr *Cond = Attr.getArgAsExpr(0);
788   if (!Cond->isTypeDependent()) {
789     ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
790     if (Converted.isInvalid())
791       return;
792     Cond = Converted.get();
793   }
794 
795   StringRef Msg;
796   if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
797     return;
798 
799   SmallVector<PartialDiagnosticAt, 8> Diags;
800   if (!Cond->isValueDependent() &&
801       !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
802                                                 Diags)) {
803     S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
804     for (int I = 0, N = Diags.size(); I != N; ++I)
805       S.Diag(Diags[I].first, Diags[I].second);
806     return;
807   }
808 
809   D->addAttr(::new (S.Context)
810              EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
811                           Attr.getAttributeSpellingListIndex()));
812 }
813 
handleConsumableAttr(Sema & S,Decl * D,const AttributeList & Attr)814 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
815   ConsumableAttr::ConsumedState DefaultState;
816 
817   if (Attr.isArgIdent(0)) {
818     IdentifierLoc *IL = Attr.getArgAsIdent(0);
819     if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
820                                                    DefaultState)) {
821       S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
822         << Attr.getName() << IL->Ident;
823       return;
824     }
825   } else {
826     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
827         << Attr.getName() << AANT_ArgumentIdentifier;
828     return;
829   }
830 
831   D->addAttr(::new (S.Context)
832              ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
833                             Attr.getAttributeSpellingListIndex()));
834 }
835 
836 
checkForConsumableClass(Sema & S,const CXXMethodDecl * MD,const AttributeList & Attr)837 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
838                                         const AttributeList &Attr) {
839   ASTContext &CurrContext = S.getASTContext();
840   QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
841 
842   if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
843     if (!RD->hasAttr<ConsumableAttr>()) {
844       S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
845         RD->getNameAsString();
846 
847       return false;
848     }
849   }
850 
851   return true;
852 }
853 
854 
handleCallableWhenAttr(Sema & S,Decl * D,const AttributeList & Attr)855 static void handleCallableWhenAttr(Sema &S, Decl *D,
856                                    const AttributeList &Attr) {
857   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
858     return;
859 
860   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
861     return;
862 
863   SmallVector<CallableWhenAttr::ConsumedState, 3> States;
864   for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
865     CallableWhenAttr::ConsumedState CallableState;
866 
867     StringRef StateString;
868     SourceLocation Loc;
869     if (Attr.isArgIdent(ArgIndex)) {
870       IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
871       StateString = Ident->Ident->getName();
872       Loc = Ident->Loc;
873     } else {
874       if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
875         return;
876     }
877 
878     if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
879                                                      CallableState)) {
880       S.Diag(Loc, diag::warn_attribute_type_not_supported)
881         << Attr.getName() << StateString;
882       return;
883     }
884 
885     States.push_back(CallableState);
886   }
887 
888   D->addAttr(::new (S.Context)
889              CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
890                States.size(), Attr.getAttributeSpellingListIndex()));
891 }
892 
893 
handleParamTypestateAttr(Sema & S,Decl * D,const AttributeList & Attr)894 static void handleParamTypestateAttr(Sema &S, Decl *D,
895                                     const AttributeList &Attr) {
896   ParamTypestateAttr::ConsumedState ParamState;
897 
898   if (Attr.isArgIdent(0)) {
899     IdentifierLoc *Ident = Attr.getArgAsIdent(0);
900     StringRef StateString = Ident->Ident->getName();
901 
902     if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
903                                                        ParamState)) {
904       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
905         << Attr.getName() << StateString;
906       return;
907     }
908   } else {
909     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
910       Attr.getName() << AANT_ArgumentIdentifier;
911     return;
912   }
913 
914   // FIXME: This check is currently being done in the analysis.  It can be
915   //        enabled here only after the parser propagates attributes at
916   //        template specialization definition, not declaration.
917   //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
918   //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
919   //
920   //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
921   //    S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
922   //      ReturnType.getAsString();
923   //    return;
924   //}
925 
926   D->addAttr(::new (S.Context)
927              ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
928                                 Attr.getAttributeSpellingListIndex()));
929 }
930 
931 
handleReturnTypestateAttr(Sema & S,Decl * D,const AttributeList & Attr)932 static void handleReturnTypestateAttr(Sema &S, Decl *D,
933                                       const AttributeList &Attr) {
934   ReturnTypestateAttr::ConsumedState ReturnState;
935 
936   if (Attr.isArgIdent(0)) {
937     IdentifierLoc *IL = Attr.getArgAsIdent(0);
938     if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
939                                                         ReturnState)) {
940       S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
941         << Attr.getName() << IL->Ident;
942       return;
943     }
944   } else {
945     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
946       Attr.getName() << AANT_ArgumentIdentifier;
947     return;
948   }
949 
950   // FIXME: This check is currently being done in the analysis.  It can be
951   //        enabled here only after the parser propagates attributes at
952   //        template specialization definition, not declaration.
953   //QualType ReturnType;
954   //
955   //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
956   //  ReturnType = Param->getType();
957   //
958   //} else if (const CXXConstructorDecl *Constructor =
959   //             dyn_cast<CXXConstructorDecl>(D)) {
960   //  ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
961   //
962   //} else {
963   //
964   //  ReturnType = cast<FunctionDecl>(D)->getCallResultType();
965   //}
966   //
967   //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
968   //
969   //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
970   //    S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
971   //      ReturnType.getAsString();
972   //    return;
973   //}
974 
975   D->addAttr(::new (S.Context)
976              ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
977                                  Attr.getAttributeSpellingListIndex()));
978 }
979 
980 
handleSetTypestateAttr(Sema & S,Decl * D,const AttributeList & Attr)981 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
982   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
983     return;
984 
985   SetTypestateAttr::ConsumedState NewState;
986   if (Attr.isArgIdent(0)) {
987     IdentifierLoc *Ident = Attr.getArgAsIdent(0);
988     StringRef Param = Ident->Ident->getName();
989     if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
990       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
991         << Attr.getName() << Param;
992       return;
993     }
994   } else {
995     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
996       Attr.getName() << AANT_ArgumentIdentifier;
997     return;
998   }
999 
1000   D->addAttr(::new (S.Context)
1001              SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1002                               Attr.getAttributeSpellingListIndex()));
1003 }
1004 
handleTestTypestateAttr(Sema & S,Decl * D,const AttributeList & Attr)1005 static void handleTestTypestateAttr(Sema &S, Decl *D,
1006                                     const AttributeList &Attr) {
1007   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1008     return;
1009 
1010   TestTypestateAttr::ConsumedState TestState;
1011   if (Attr.isArgIdent(0)) {
1012     IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1013     StringRef Param = Ident->Ident->getName();
1014     if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1015       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1016         << Attr.getName() << Param;
1017       return;
1018     }
1019   } else {
1020     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1021       Attr.getName() << AANT_ArgumentIdentifier;
1022     return;
1023   }
1024 
1025   D->addAttr(::new (S.Context)
1026              TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1027                                 Attr.getAttributeSpellingListIndex()));
1028 }
1029 
handleExtVectorTypeAttr(Sema & S,Scope * scope,Decl * D,const AttributeList & Attr)1030 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1031                                     const AttributeList &Attr) {
1032   // Remember this typedef decl, we will need it later for diagnostics.
1033   S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1034 }
1035 
handlePackedAttr(Sema & S,Decl * D,const AttributeList & Attr)1036 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1037   if (TagDecl *TD = dyn_cast<TagDecl>(D))
1038     TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1039                                         Attr.getAttributeSpellingListIndex()));
1040   else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1041     // If the alignment is less than or equal to 8 bits, the packed attribute
1042     // has no effect.
1043     if (!FD->getType()->isDependentType() &&
1044         !FD->getType()->isIncompleteType() &&
1045         S.Context.getTypeAlign(FD->getType()) <= 8)
1046       S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1047         << Attr.getName() << FD->getType();
1048     else
1049       FD->addAttr(::new (S.Context)
1050                   PackedAttr(Attr.getRange(), S.Context,
1051                              Attr.getAttributeSpellingListIndex()));
1052   } else
1053     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1054 }
1055 
checkIBOutletCommon(Sema & S,Decl * D,const AttributeList & Attr)1056 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1057   // The IBOutlet/IBOutletCollection attributes only apply to instance
1058   // variables or properties of Objective-C classes.  The outlet must also
1059   // have an object reference type.
1060   if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1061     if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1062       S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1063         << Attr.getName() << VD->getType() << 0;
1064       return false;
1065     }
1066   }
1067   else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1068     if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1069       S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1070         << Attr.getName() << PD->getType() << 1;
1071       return false;
1072     }
1073   }
1074   else {
1075     S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1076     return false;
1077   }
1078 
1079   return true;
1080 }
1081 
handleIBOutlet(Sema & S,Decl * D,const AttributeList & Attr)1082 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1083   if (!checkIBOutletCommon(S, D, Attr))
1084     return;
1085 
1086   D->addAttr(::new (S.Context)
1087              IBOutletAttr(Attr.getRange(), S.Context,
1088                           Attr.getAttributeSpellingListIndex()));
1089 }
1090 
handleIBOutletCollection(Sema & S,Decl * D,const AttributeList & Attr)1091 static void handleIBOutletCollection(Sema &S, Decl *D,
1092                                      const AttributeList &Attr) {
1093 
1094   // The iboutletcollection attribute can have zero or one arguments.
1095   if (Attr.getNumArgs() > 1) {
1096     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1097       << Attr.getName() << 1;
1098     return;
1099   }
1100 
1101   if (!checkIBOutletCommon(S, D, Attr))
1102     return;
1103 
1104   ParsedType PT;
1105 
1106   if (Attr.hasParsedType())
1107     PT = Attr.getTypeArg();
1108   else {
1109     PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1110                        S.getScopeForContext(D->getDeclContext()->getParent()));
1111     if (!PT) {
1112       S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1113       return;
1114     }
1115   }
1116 
1117   TypeSourceInfo *QTLoc = nullptr;
1118   QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1119   if (!QTLoc)
1120     QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1121 
1122   // Diagnose use of non-object type in iboutletcollection attribute.
1123   // FIXME. Gnu attribute extension ignores use of builtin types in
1124   // attributes. So, __attribute__((iboutletcollection(char))) will be
1125   // treated as __attribute__((iboutletcollection())).
1126   if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1127     S.Diag(Attr.getLoc(),
1128            QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1129                                : diag::err_iboutletcollection_type) << QT;
1130     return;
1131   }
1132 
1133   D->addAttr(::new (S.Context)
1134              IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1135                                     Attr.getAttributeSpellingListIndex()));
1136 }
1137 
isValidPointerAttrType(QualType T,bool RefOkay)1138 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1139   if (RefOkay) {
1140     if (T->isReferenceType())
1141       return true;
1142   } else {
1143     T = T.getNonReferenceType();
1144   }
1145 
1146   // The nonnull attribute, and other similar attributes, can be applied to a
1147   // transparent union that contains a pointer type.
1148   if (const RecordType *UT = T->getAsUnionType()) {
1149     if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1150       RecordDecl *UD = UT->getDecl();
1151       for (const auto *I : UD->fields()) {
1152         QualType QT = I->getType();
1153         if (QT->isAnyPointerType() || QT->isBlockPointerType())
1154           return true;
1155       }
1156     }
1157   }
1158 
1159   return T->isAnyPointerType() || T->isBlockPointerType();
1160 }
1161 
attrNonNullArgCheck(Sema & S,QualType T,const AttributeList & Attr,SourceRange AttrParmRange,SourceRange TypeRange,bool isReturnValue=false)1162 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1163                                 SourceRange AttrParmRange,
1164                                 SourceRange TypeRange,
1165                                 bool isReturnValue = false) {
1166   if (!S.isValidPointerAttrType(T)) {
1167     S.Diag(Attr.getLoc(), isReturnValue
1168                               ? diag::warn_attribute_return_pointers_only
1169                               : diag::warn_attribute_pointers_only)
1170         << Attr.getName() << AttrParmRange << TypeRange;
1171     return false;
1172   }
1173   return true;
1174 }
1175 
handleNonNullAttr(Sema & S,Decl * D,const AttributeList & Attr)1176 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1177   SmallVector<unsigned, 8> NonNullArgs;
1178   for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1179     Expr *Ex = Attr.getArgAsExpr(I);
1180     uint64_t Idx;
1181     if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1182       return;
1183 
1184     // Is the function argument a pointer type?
1185     if (Idx < getFunctionOrMethodNumParams(D) &&
1186         !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1187                              Ex->getSourceRange(),
1188                              getFunctionOrMethodParamRange(D, Idx)))
1189       continue;
1190 
1191     NonNullArgs.push_back(Idx);
1192   }
1193 
1194   // If no arguments were specified to __attribute__((nonnull)) then all pointer
1195   // arguments have a nonnull attribute; warn if there aren't any. Skip this
1196   // check if the attribute came from a macro expansion or a template
1197   // instantiation.
1198   if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1199       S.ActiveTemplateInstantiations.empty()) {
1200     bool AnyPointers = isFunctionOrMethodVariadic(D);
1201     for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1202          I != E && !AnyPointers; ++I) {
1203       QualType T = getFunctionOrMethodParamType(D, I);
1204       if (T->isDependentType() || S.isValidPointerAttrType(T))
1205         AnyPointers = true;
1206     }
1207 
1208     if (!AnyPointers)
1209       S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1210   }
1211 
1212   unsigned *Start = NonNullArgs.data();
1213   unsigned Size = NonNullArgs.size();
1214   llvm::array_pod_sort(Start, Start + Size);
1215   D->addAttr(::new (S.Context)
1216              NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1217                          Attr.getAttributeSpellingListIndex()));
1218 }
1219 
handleNonNullAttrParameter(Sema & S,ParmVarDecl * D,const AttributeList & Attr)1220 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1221                                        const AttributeList &Attr) {
1222   if (Attr.getNumArgs() > 0) {
1223     if (D->getFunctionType()) {
1224       handleNonNullAttr(S, D, Attr);
1225     } else {
1226       S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1227         << D->getSourceRange();
1228     }
1229     return;
1230   }
1231 
1232   // Is the argument a pointer type?
1233   if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1234                            D->getSourceRange()))
1235     return;
1236 
1237   D->addAttr(::new (S.Context)
1238              NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1239                          Attr.getAttributeSpellingListIndex()));
1240 }
1241 
handleReturnsNonNullAttr(Sema & S,Decl * D,const AttributeList & Attr)1242 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1243                                      const AttributeList &Attr) {
1244   QualType ResultType = getFunctionOrMethodResultType(D);
1245   SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1246   if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1247                            /* isReturnValue */ true))
1248     return;
1249 
1250   D->addAttr(::new (S.Context)
1251             ReturnsNonNullAttr(Attr.getRange(), S.Context,
1252                                Attr.getAttributeSpellingListIndex()));
1253 }
1254 
handleAssumeAlignedAttr(Sema & S,Decl * D,const AttributeList & Attr)1255 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1256                                     const AttributeList &Attr) {
1257   Expr *E = Attr.getArgAsExpr(0),
1258        *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1259   S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1260                          Attr.getAttributeSpellingListIndex());
1261 }
1262 
AddAssumeAlignedAttr(SourceRange AttrRange,Decl * D,Expr * E,Expr * OE,unsigned SpellingListIndex)1263 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1264                                 Expr *OE, unsigned SpellingListIndex) {
1265   QualType ResultType = getFunctionOrMethodResultType(D);
1266   SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1267 
1268   AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1269   SourceLocation AttrLoc = AttrRange.getBegin();
1270 
1271   if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1272     Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1273       << &TmpAttr << AttrRange << SR;
1274     return;
1275   }
1276 
1277   if (!E->isValueDependent()) {
1278     llvm::APSInt I(64);
1279     if (!E->isIntegerConstantExpr(I, Context)) {
1280       if (OE)
1281         Diag(AttrLoc, diag::err_attribute_argument_n_type)
1282           << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1283           << E->getSourceRange();
1284       else
1285         Diag(AttrLoc, diag::err_attribute_argument_type)
1286           << &TmpAttr << AANT_ArgumentIntegerConstant
1287           << E->getSourceRange();
1288       return;
1289     }
1290 
1291     if (!I.isPowerOf2()) {
1292       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1293         << E->getSourceRange();
1294       return;
1295     }
1296   }
1297 
1298   if (OE) {
1299     if (!OE->isValueDependent()) {
1300       llvm::APSInt I(64);
1301       if (!OE->isIntegerConstantExpr(I, Context)) {
1302         Diag(AttrLoc, diag::err_attribute_argument_n_type)
1303           << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1304           << OE->getSourceRange();
1305         return;
1306       }
1307     }
1308   }
1309 
1310   D->addAttr(::new (Context)
1311             AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1312 }
1313 
handleOwnershipAttr(Sema & S,Decl * D,const AttributeList & AL)1314 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1315   // This attribute must be applied to a function declaration. The first
1316   // argument to the attribute must be an identifier, the name of the resource,
1317   // for example: malloc. The following arguments must be argument indexes, the
1318   // arguments must be of integer type for Returns, otherwise of pointer type.
1319   // The difference between Holds and Takes is that a pointer may still be used
1320   // after being held. free() should be __attribute((ownership_takes)), whereas
1321   // a list append function may well be __attribute((ownership_holds)).
1322 
1323   if (!AL.isArgIdent(0)) {
1324     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1325       << AL.getName() << 1 << AANT_ArgumentIdentifier;
1326     return;
1327   }
1328 
1329   // Figure out our Kind.
1330   OwnershipAttr::OwnershipKind K =
1331       OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1332                     AL.getAttributeSpellingListIndex()).getOwnKind();
1333 
1334   // Check arguments.
1335   switch (K) {
1336   case OwnershipAttr::Takes:
1337   case OwnershipAttr::Holds:
1338     if (AL.getNumArgs() < 2) {
1339       S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1340         << AL.getName() << 2;
1341       return;
1342     }
1343     break;
1344   case OwnershipAttr::Returns:
1345     if (AL.getNumArgs() > 2) {
1346       S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1347         << AL.getName() << 1;
1348       return;
1349     }
1350     break;
1351   }
1352 
1353   IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1354 
1355   // Normalize the argument, __foo__ becomes foo.
1356   StringRef ModuleName = Module->getName();
1357   if (ModuleName.startswith("__") && ModuleName.endswith("__") &&
1358       ModuleName.size() > 4) {
1359     ModuleName = ModuleName.drop_front(2).drop_back(2);
1360     Module = &S.PP.getIdentifierTable().get(ModuleName);
1361   }
1362 
1363   SmallVector<unsigned, 8> OwnershipArgs;
1364   for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1365     Expr *Ex = AL.getArgAsExpr(i);
1366     uint64_t Idx;
1367     if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1368       return;
1369 
1370     // Is the function argument a pointer type?
1371     QualType T = getFunctionOrMethodParamType(D, Idx);
1372     int Err = -1;  // No error
1373     switch (K) {
1374       case OwnershipAttr::Takes:
1375       case OwnershipAttr::Holds:
1376         if (!T->isAnyPointerType() && !T->isBlockPointerType())
1377           Err = 0;
1378         break;
1379       case OwnershipAttr::Returns:
1380         if (!T->isIntegerType())
1381           Err = 1;
1382         break;
1383     }
1384     if (-1 != Err) {
1385       S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1386         << Ex->getSourceRange();
1387       return;
1388     }
1389 
1390     // Check we don't have a conflict with another ownership attribute.
1391     for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1392       // Cannot have two ownership attributes of different kinds for the same
1393       // index.
1394       if (I->getOwnKind() != K && I->args_end() !=
1395           std::find(I->args_begin(), I->args_end(), Idx)) {
1396         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1397           << AL.getName() << I;
1398         return;
1399       } else if (K == OwnershipAttr::Returns &&
1400                  I->getOwnKind() == OwnershipAttr::Returns) {
1401         // A returns attribute conflicts with any other returns attribute using
1402         // a different index. Note, diagnostic reporting is 1-based, but stored
1403         // argument indexes are 0-based.
1404         if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1405           S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1406               << *(I->args_begin()) + 1;
1407           if (I->args_size())
1408             S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1409                 << (unsigned)Idx + 1 << Ex->getSourceRange();
1410           return;
1411         }
1412       }
1413     }
1414     OwnershipArgs.push_back(Idx);
1415   }
1416 
1417   unsigned* start = OwnershipArgs.data();
1418   unsigned size = OwnershipArgs.size();
1419   llvm::array_pod_sort(start, start + size);
1420 
1421   D->addAttr(::new (S.Context)
1422              OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1423                            AL.getAttributeSpellingListIndex()));
1424 }
1425 
handleWeakRefAttr(Sema & S,Decl * D,const AttributeList & Attr)1426 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1427   // Check the attribute arguments.
1428   if (Attr.getNumArgs() > 1) {
1429     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1430       << Attr.getName() << 1;
1431     return;
1432   }
1433 
1434   NamedDecl *nd = cast<NamedDecl>(D);
1435 
1436   // gcc rejects
1437   // class c {
1438   //   static int a __attribute__((weakref ("v2")));
1439   //   static int b() __attribute__((weakref ("f3")));
1440   // };
1441   // and ignores the attributes of
1442   // void f(void) {
1443   //   static int a __attribute__((weakref ("v2")));
1444   // }
1445   // we reject them
1446   const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1447   if (!Ctx->isFileContext()) {
1448     S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1449       << nd;
1450     return;
1451   }
1452 
1453   // The GCC manual says
1454   //
1455   // At present, a declaration to which `weakref' is attached can only
1456   // be `static'.
1457   //
1458   // It also says
1459   //
1460   // Without a TARGET,
1461   // given as an argument to `weakref' or to `alias', `weakref' is
1462   // equivalent to `weak'.
1463   //
1464   // gcc 4.4.1 will accept
1465   // int a7 __attribute__((weakref));
1466   // as
1467   // int a7 __attribute__((weak));
1468   // This looks like a bug in gcc. We reject that for now. We should revisit
1469   // it if this behaviour is actually used.
1470 
1471   // GCC rejects
1472   // static ((alias ("y"), weakref)).
1473   // Should we? How to check that weakref is before or after alias?
1474 
1475   // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1476   // of transforming it into an AliasAttr.  The WeakRefAttr never uses the
1477   // StringRef parameter it was given anyway.
1478   StringRef Str;
1479   if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1480     // GCC will accept anything as the argument of weakref. Should we
1481     // check for an existing decl?
1482     D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1483                                         Attr.getAttributeSpellingListIndex()));
1484 
1485   D->addAttr(::new (S.Context)
1486              WeakRefAttr(Attr.getRange(), S.Context,
1487                          Attr.getAttributeSpellingListIndex()));
1488 }
1489 
handleAliasAttr(Sema & S,Decl * D,const AttributeList & Attr)1490 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1491   StringRef Str;
1492   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1493     return;
1494 
1495   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1496     S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1497     return;
1498   }
1499 
1500   // Aliases should be on declarations, not definitions.
1501   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1502     if (FD->isThisDeclarationADefinition()) {
1503       S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD;
1504       return;
1505     }
1506   } else {
1507     const auto *VD = cast<VarDecl>(D);
1508     if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1509       S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD;
1510       return;
1511     }
1512   }
1513 
1514   // FIXME: check if target symbol exists in current file
1515 
1516   D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1517                                          Attr.getAttributeSpellingListIndex()));
1518 }
1519 
handleColdAttr(Sema & S,Decl * D,const AttributeList & Attr)1520 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1521   if (checkAttrMutualExclusion<HotAttr>(S, D, Attr))
1522     return;
1523 
1524   D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1525                                         Attr.getAttributeSpellingListIndex()));
1526 }
1527 
handleHotAttr(Sema & S,Decl * D,const AttributeList & Attr)1528 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1529   if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr))
1530     return;
1531 
1532   D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1533                                        Attr.getAttributeSpellingListIndex()));
1534 }
1535 
handleTLSModelAttr(Sema & S,Decl * D,const AttributeList & Attr)1536 static void handleTLSModelAttr(Sema &S, Decl *D,
1537                                const AttributeList &Attr) {
1538   StringRef Model;
1539   SourceLocation LiteralLoc;
1540   // Check that it is a string.
1541   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1542     return;
1543 
1544   // Check that the value.
1545   if (Model != "global-dynamic" && Model != "local-dynamic"
1546       && Model != "initial-exec" && Model != "local-exec") {
1547     S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1548     return;
1549   }
1550 
1551   D->addAttr(::new (S.Context)
1552              TLSModelAttr(Attr.getRange(), S.Context, Model,
1553                           Attr.getAttributeSpellingListIndex()));
1554 }
1555 
handleKernelAttr(Sema & S,Decl * D,const AttributeList & Attr)1556 static void handleKernelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1557   if (S.LangOpts.Renderscript) {
1558     D->addAttr(::new (S.Context)
1559                KernelAttr(Attr.getRange(), S.Context,
1560                           Attr.getAttributeSpellingListIndex()));
1561   } else {
1562     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "kernel";
1563   }
1564 }
1565 
handleRestrictAttr(Sema & S,Decl * D,const AttributeList & Attr)1566 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1567   QualType ResultType = getFunctionOrMethodResultType(D);
1568   if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1569     D->addAttr(::new (S.Context) RestrictAttr(
1570         Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1571     return;
1572   }
1573 
1574   S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1575       << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1576 }
1577 
handleCommonAttr(Sema & S,Decl * D,const AttributeList & Attr)1578 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1579   if (S.LangOpts.CPlusPlus) {
1580     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1581       << Attr.getName() << AttributeLangSupport::Cpp;
1582     return;
1583   }
1584 
1585   D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context,
1586                                         Attr.getAttributeSpellingListIndex()));
1587 }
1588 
handleNoReturnAttr(Sema & S,Decl * D,const AttributeList & attr)1589 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1590   if (hasDeclarator(D)) return;
1591 
1592   if (S.CheckNoReturnAttr(attr)) return;
1593 
1594   if (!isa<ObjCMethodDecl>(D)) {
1595     S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1596       << attr.getName() << ExpectedFunctionOrMethod;
1597     return;
1598   }
1599 
1600   D->addAttr(::new (S.Context)
1601              NoReturnAttr(attr.getRange(), S.Context,
1602                           attr.getAttributeSpellingListIndex()));
1603 }
1604 
CheckNoReturnAttr(const AttributeList & attr)1605 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1606   if (!checkAttributeNumArgs(*this, attr, 0)) {
1607     attr.setInvalid();
1608     return true;
1609   }
1610 
1611   return false;
1612 }
1613 
handleAnalyzerNoReturnAttr(Sema & S,Decl * D,const AttributeList & Attr)1614 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1615                                        const AttributeList &Attr) {
1616 
1617   // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1618   // because 'analyzer_noreturn' does not impact the type.
1619   if (!isFunctionOrMethodOrBlock(D)) {
1620     ValueDecl *VD = dyn_cast<ValueDecl>(D);
1621     if (!VD || (!VD->getType()->isBlockPointerType() &&
1622                 !VD->getType()->isFunctionPointerType())) {
1623       S.Diag(Attr.getLoc(),
1624              Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1625              : diag::warn_attribute_wrong_decl_type)
1626         << Attr.getName() << ExpectedFunctionMethodOrBlock;
1627       return;
1628     }
1629   }
1630 
1631   D->addAttr(::new (S.Context)
1632              AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1633                                   Attr.getAttributeSpellingListIndex()));
1634 }
1635 
1636 // PS3 PPU-specific.
handleVecReturnAttr(Sema & S,Decl * D,const AttributeList & Attr)1637 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1638 /*
1639   Returning a Vector Class in Registers
1640 
1641   According to the PPU ABI specifications, a class with a single member of
1642   vector type is returned in memory when used as the return value of a function.
1643   This results in inefficient code when implementing vector classes. To return
1644   the value in a single vector register, add the vecreturn attribute to the
1645   class definition. This attribute is also applicable to struct types.
1646 
1647   Example:
1648 
1649   struct Vector
1650   {
1651     __vector float xyzw;
1652   } __attribute__((vecreturn));
1653 
1654   Vector Add(Vector lhs, Vector rhs)
1655   {
1656     Vector result;
1657     result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1658     return result; // This will be returned in a register
1659   }
1660 */
1661   if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1662     S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1663     return;
1664   }
1665 
1666   RecordDecl *record = cast<RecordDecl>(D);
1667   int count = 0;
1668 
1669   if (!isa<CXXRecordDecl>(record)) {
1670     S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1671     return;
1672   }
1673 
1674   if (!cast<CXXRecordDecl>(record)->isPOD()) {
1675     S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1676     return;
1677   }
1678 
1679   for (const auto *I : record->fields()) {
1680     if ((count == 1) || !I->getType()->isVectorType()) {
1681       S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1682       return;
1683     }
1684     count++;
1685   }
1686 
1687   D->addAttr(::new (S.Context)
1688              VecReturnAttr(Attr.getRange(), S.Context,
1689                            Attr.getAttributeSpellingListIndex()));
1690 }
1691 
handleDependencyAttr(Sema & S,Scope * Scope,Decl * D,const AttributeList & Attr)1692 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1693                                  const AttributeList &Attr) {
1694   if (isa<ParmVarDecl>(D)) {
1695     // [[carries_dependency]] can only be applied to a parameter if it is a
1696     // parameter of a function declaration or lambda.
1697     if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1698       S.Diag(Attr.getLoc(),
1699              diag::err_carries_dependency_param_not_function_decl);
1700       return;
1701     }
1702   }
1703 
1704   D->addAttr(::new (S.Context) CarriesDependencyAttr(
1705                                    Attr.getRange(), S.Context,
1706                                    Attr.getAttributeSpellingListIndex()));
1707 }
1708 
handleUsedAttr(Sema & S,Decl * D,const AttributeList & Attr)1709 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1710   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1711     if (VD->hasLocalStorage()) {
1712       S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1713       return;
1714     }
1715   } else if (!isFunctionOrMethod(D)) {
1716     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1717       << Attr.getName() << ExpectedVariableOrFunction;
1718     return;
1719   }
1720 
1721   D->addAttr(::new (S.Context)
1722              UsedAttr(Attr.getRange(), S.Context,
1723                       Attr.getAttributeSpellingListIndex()));
1724 }
1725 
handleConstructorAttr(Sema & S,Decl * D,const AttributeList & Attr)1726 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1727   uint32_t priority = ConstructorAttr::DefaultPriority;
1728   if (Attr.getNumArgs() &&
1729       !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1730     return;
1731 
1732   D->addAttr(::new (S.Context)
1733              ConstructorAttr(Attr.getRange(), S.Context, priority,
1734                              Attr.getAttributeSpellingListIndex()));
1735 }
1736 
handleDestructorAttr(Sema & S,Decl * D,const AttributeList & Attr)1737 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1738   uint32_t priority = DestructorAttr::DefaultPriority;
1739   if (Attr.getNumArgs() &&
1740       !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1741     return;
1742 
1743   D->addAttr(::new (S.Context)
1744              DestructorAttr(Attr.getRange(), S.Context, priority,
1745                             Attr.getAttributeSpellingListIndex()));
1746 }
1747 
1748 template <typename AttrTy>
handleAttrWithMessage(Sema & S,Decl * D,const AttributeList & Attr)1749 static void handleAttrWithMessage(Sema &S, Decl *D,
1750                                   const AttributeList &Attr) {
1751   // Handle the case where the attribute has a text message.
1752   StringRef Str;
1753   if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1754     return;
1755 
1756   D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1757                                       Attr.getAttributeSpellingListIndex()));
1758 }
1759 
handleObjCSuppresProtocolAttr(Sema & S,Decl * D,const AttributeList & Attr)1760 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
1761                                           const AttributeList &Attr) {
1762   if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
1763     S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1764       << Attr.getName() << Attr.getRange();
1765     return;
1766   }
1767 
1768   D->addAttr(::new (S.Context)
1769           ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1770                                        Attr.getAttributeSpellingListIndex()));
1771 }
1772 
checkAvailabilityAttr(Sema & S,SourceRange Range,IdentifierInfo * Platform,VersionTuple Introduced,VersionTuple Deprecated,VersionTuple Obsoleted)1773 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1774                                   IdentifierInfo *Platform,
1775                                   VersionTuple Introduced,
1776                                   VersionTuple Deprecated,
1777                                   VersionTuple Obsoleted) {
1778   StringRef PlatformName
1779     = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1780   if (PlatformName.empty())
1781     PlatformName = Platform->getName();
1782 
1783   // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1784   // of these steps are needed).
1785   if (!Introduced.empty() && !Deprecated.empty() &&
1786       !(Introduced <= Deprecated)) {
1787     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1788       << 1 << PlatformName << Deprecated.getAsString()
1789       << 0 << Introduced.getAsString();
1790     return true;
1791   }
1792 
1793   if (!Introduced.empty() && !Obsoleted.empty() &&
1794       !(Introduced <= Obsoleted)) {
1795     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1796       << 2 << PlatformName << Obsoleted.getAsString()
1797       << 0 << Introduced.getAsString();
1798     return true;
1799   }
1800 
1801   if (!Deprecated.empty() && !Obsoleted.empty() &&
1802       !(Deprecated <= Obsoleted)) {
1803     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1804       << 2 << PlatformName << Obsoleted.getAsString()
1805       << 1 << Deprecated.getAsString();
1806     return true;
1807   }
1808 
1809   return false;
1810 }
1811 
1812 /// \brief Check whether the two versions match.
1813 ///
1814 /// If either version tuple is empty, then they are assumed to match. If
1815 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
versionsMatch(const VersionTuple & X,const VersionTuple & Y,bool BeforeIsOkay)1816 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1817                           bool BeforeIsOkay) {
1818   if (X.empty() || Y.empty())
1819     return true;
1820 
1821   if (X == Y)
1822     return true;
1823 
1824   if (BeforeIsOkay && X < Y)
1825     return true;
1826 
1827   return false;
1828 }
1829 
mergeAvailabilityAttr(NamedDecl * D,SourceRange Range,IdentifierInfo * Platform,VersionTuple Introduced,VersionTuple Deprecated,VersionTuple Obsoleted,bool IsUnavailable,StringRef Message,bool Override,unsigned AttrSpellingListIndex)1830 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1831                                               IdentifierInfo *Platform,
1832                                               VersionTuple Introduced,
1833                                               VersionTuple Deprecated,
1834                                               VersionTuple Obsoleted,
1835                                               bool IsUnavailable,
1836                                               StringRef Message,
1837                                               bool Override,
1838                                               unsigned AttrSpellingListIndex) {
1839   VersionTuple MergedIntroduced = Introduced;
1840   VersionTuple MergedDeprecated = Deprecated;
1841   VersionTuple MergedObsoleted = Obsoleted;
1842   bool FoundAny = false;
1843 
1844   if (D->hasAttrs()) {
1845     AttrVec &Attrs = D->getAttrs();
1846     for (unsigned i = 0, e = Attrs.size(); i != e;) {
1847       const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1848       if (!OldAA) {
1849         ++i;
1850         continue;
1851       }
1852 
1853       IdentifierInfo *OldPlatform = OldAA->getPlatform();
1854       if (OldPlatform != Platform) {
1855         ++i;
1856         continue;
1857       }
1858 
1859       FoundAny = true;
1860       VersionTuple OldIntroduced = OldAA->getIntroduced();
1861       VersionTuple OldDeprecated = OldAA->getDeprecated();
1862       VersionTuple OldObsoleted = OldAA->getObsoleted();
1863       bool OldIsUnavailable = OldAA->getUnavailable();
1864 
1865       if (!versionsMatch(OldIntroduced, Introduced, Override) ||
1866           !versionsMatch(Deprecated, OldDeprecated, Override) ||
1867           !versionsMatch(Obsoleted, OldObsoleted, Override) ||
1868           !(OldIsUnavailable == IsUnavailable ||
1869             (Override && !OldIsUnavailable && IsUnavailable))) {
1870         if (Override) {
1871           int Which = -1;
1872           VersionTuple FirstVersion;
1873           VersionTuple SecondVersion;
1874           if (!versionsMatch(OldIntroduced, Introduced, Override)) {
1875             Which = 0;
1876             FirstVersion = OldIntroduced;
1877             SecondVersion = Introduced;
1878           } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) {
1879             Which = 1;
1880             FirstVersion = Deprecated;
1881             SecondVersion = OldDeprecated;
1882           } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) {
1883             Which = 2;
1884             FirstVersion = Obsoleted;
1885             SecondVersion = OldObsoleted;
1886           }
1887 
1888           if (Which == -1) {
1889             Diag(OldAA->getLocation(),
1890                  diag::warn_mismatched_availability_override_unavail)
1891               << AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1892           } else {
1893             Diag(OldAA->getLocation(),
1894                  diag::warn_mismatched_availability_override)
1895               << Which
1896               << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
1897               << FirstVersion.getAsString() << SecondVersion.getAsString();
1898           }
1899           Diag(Range.getBegin(), diag::note_overridden_method);
1900         } else {
1901           Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
1902           Diag(Range.getBegin(), diag::note_previous_attribute);
1903         }
1904 
1905         Attrs.erase(Attrs.begin() + i);
1906         --e;
1907         continue;
1908       }
1909 
1910       VersionTuple MergedIntroduced2 = MergedIntroduced;
1911       VersionTuple MergedDeprecated2 = MergedDeprecated;
1912       VersionTuple MergedObsoleted2 = MergedObsoleted;
1913 
1914       if (MergedIntroduced2.empty())
1915         MergedIntroduced2 = OldIntroduced;
1916       if (MergedDeprecated2.empty())
1917         MergedDeprecated2 = OldDeprecated;
1918       if (MergedObsoleted2.empty())
1919         MergedObsoleted2 = OldObsoleted;
1920 
1921       if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
1922                                 MergedIntroduced2, MergedDeprecated2,
1923                                 MergedObsoleted2)) {
1924         Attrs.erase(Attrs.begin() + i);
1925         --e;
1926         continue;
1927       }
1928 
1929       MergedIntroduced = MergedIntroduced2;
1930       MergedDeprecated = MergedDeprecated2;
1931       MergedObsoleted = MergedObsoleted2;
1932       ++i;
1933     }
1934   }
1935 
1936   if (FoundAny &&
1937       MergedIntroduced == Introduced &&
1938       MergedDeprecated == Deprecated &&
1939       MergedObsoleted == Obsoleted)
1940     return nullptr;
1941 
1942   // Only create a new attribute if !Override, but we want to do
1943   // the checking.
1944   if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
1945                              MergedDeprecated, MergedObsoleted) &&
1946       !Override) {
1947     return ::new (Context) AvailabilityAttr(Range, Context, Platform,
1948                                             Introduced, Deprecated,
1949                                             Obsoleted, IsUnavailable, Message,
1950                                             AttrSpellingListIndex);
1951   }
1952   return nullptr;
1953 }
1954 
handleAvailabilityAttr(Sema & S,Decl * D,const AttributeList & Attr)1955 static void handleAvailabilityAttr(Sema &S, Decl *D,
1956                                    const AttributeList &Attr) {
1957   if (!checkAttributeNumArgs(S, Attr, 1))
1958     return;
1959   IdentifierLoc *Platform = Attr.getArgAsIdent(0);
1960   unsigned Index = Attr.getAttributeSpellingListIndex();
1961 
1962   IdentifierInfo *II = Platform->Ident;
1963   if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
1964     S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
1965       << Platform->Ident;
1966 
1967   NamedDecl *ND = dyn_cast<NamedDecl>(D);
1968   if (!ND) {
1969     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1970     return;
1971   }
1972 
1973   AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
1974   AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
1975   AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
1976   bool IsUnavailable = Attr.getUnavailableLoc().isValid();
1977   StringRef Str;
1978   if (const StringLiteral *SE =
1979           dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
1980     Str = SE->getString();
1981 
1982   AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
1983                                                       Introduced.Version,
1984                                                       Deprecated.Version,
1985                                                       Obsoleted.Version,
1986                                                       IsUnavailable, Str,
1987                                                       /*Override=*/false,
1988                                                       Index);
1989   if (NewAttr)
1990     D->addAttr(NewAttr);
1991 }
1992 
1993 template <class T>
mergeVisibilityAttr(Sema & S,Decl * D,SourceRange range,typename T::VisibilityType value,unsigned attrSpellingListIndex)1994 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
1995                               typename T::VisibilityType value,
1996                               unsigned attrSpellingListIndex) {
1997   T *existingAttr = D->getAttr<T>();
1998   if (existingAttr) {
1999     typename T::VisibilityType existingValue = existingAttr->getVisibility();
2000     if (existingValue == value)
2001       return nullptr;
2002     S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2003     S.Diag(range.getBegin(), diag::note_previous_attribute);
2004     D->dropAttr<T>();
2005   }
2006   return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2007 }
2008 
mergeVisibilityAttr(Decl * D,SourceRange Range,VisibilityAttr::VisibilityType Vis,unsigned AttrSpellingListIndex)2009 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2010                                           VisibilityAttr::VisibilityType Vis,
2011                                           unsigned AttrSpellingListIndex) {
2012   return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2013                                                AttrSpellingListIndex);
2014 }
2015 
mergeTypeVisibilityAttr(Decl * D,SourceRange Range,TypeVisibilityAttr::VisibilityType Vis,unsigned AttrSpellingListIndex)2016 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2017                                       TypeVisibilityAttr::VisibilityType Vis,
2018                                       unsigned AttrSpellingListIndex) {
2019   return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2020                                                    AttrSpellingListIndex);
2021 }
2022 
handleVisibilityAttr(Sema & S,Decl * D,const AttributeList & Attr,bool isTypeVisibility)2023 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2024                                  bool isTypeVisibility) {
2025   // Visibility attributes don't mean anything on a typedef.
2026   if (isa<TypedefNameDecl>(D)) {
2027     S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2028       << Attr.getName();
2029     return;
2030   }
2031 
2032   // 'type_visibility' can only go on a type or namespace.
2033   if (isTypeVisibility &&
2034       !(isa<TagDecl>(D) ||
2035         isa<ObjCInterfaceDecl>(D) ||
2036         isa<NamespaceDecl>(D))) {
2037     S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2038       << Attr.getName() << ExpectedTypeOrNamespace;
2039     return;
2040   }
2041 
2042   // Check that the argument is a string literal.
2043   StringRef TypeStr;
2044   SourceLocation LiteralLoc;
2045   if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2046     return;
2047 
2048   VisibilityAttr::VisibilityType type;
2049   if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2050     S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2051       << Attr.getName() << TypeStr;
2052     return;
2053   }
2054 
2055   // Complain about attempts to use protected visibility on targets
2056   // (like Darwin) that don't support it.
2057   if (type == VisibilityAttr::Protected &&
2058       !S.Context.getTargetInfo().hasProtectedVisibility()) {
2059     S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2060     type = VisibilityAttr::Default;
2061   }
2062 
2063   unsigned Index = Attr.getAttributeSpellingListIndex();
2064   clang::Attr *newAttr;
2065   if (isTypeVisibility) {
2066     newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2067                                     (TypeVisibilityAttr::VisibilityType) type,
2068                                         Index);
2069   } else {
2070     newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2071   }
2072   if (newAttr)
2073     D->addAttr(newAttr);
2074 }
2075 
handleObjCMethodFamilyAttr(Sema & S,Decl * decl,const AttributeList & Attr)2076 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2077                                        const AttributeList &Attr) {
2078   ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2079   if (!Attr.isArgIdent(0)) {
2080     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2081       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2082     return;
2083   }
2084 
2085   IdentifierLoc *IL = Attr.getArgAsIdent(0);
2086   ObjCMethodFamilyAttr::FamilyKind F;
2087   if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2088     S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2089       << IL->Ident;
2090     return;
2091   }
2092 
2093   if (F == ObjCMethodFamilyAttr::OMF_init &&
2094       !method->getReturnType()->isObjCObjectPointerType()) {
2095     S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2096         << method->getReturnType();
2097     // Ignore the attribute.
2098     return;
2099   }
2100 
2101   method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2102                                                        S.Context, F,
2103                                         Attr.getAttributeSpellingListIndex()));
2104 }
2105 
handleObjCNSObject(Sema & S,Decl * D,const AttributeList & Attr)2106 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2107   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2108     QualType T = TD->getUnderlyingType();
2109     if (!T->isCARCBridgableType()) {
2110       S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2111       return;
2112     }
2113   }
2114   else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2115     QualType T = PD->getType();
2116     if (!T->isCARCBridgableType()) {
2117       S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2118       return;
2119     }
2120   }
2121   else {
2122     // It is okay to include this attribute on properties, e.g.:
2123     //
2124     //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2125     //
2126     // In this case it follows tradition and suppresses an error in the above
2127     // case.
2128     S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2129   }
2130   D->addAttr(::new (S.Context)
2131              ObjCNSObjectAttr(Attr.getRange(), S.Context,
2132                               Attr.getAttributeSpellingListIndex()));
2133 }
2134 
handleObjCIndependentClass(Sema & S,Decl * D,const AttributeList & Attr)2135 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2136   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2137     QualType T = TD->getUnderlyingType();
2138     if (!T->isObjCObjectPointerType()) {
2139       S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2140       return;
2141     }
2142   } else {
2143     S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2144     return;
2145   }
2146   D->addAttr(::new (S.Context)
2147              ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2148                               Attr.getAttributeSpellingListIndex()));
2149 }
2150 
handleBlocksAttr(Sema & S,Decl * D,const AttributeList & Attr)2151 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2152   if (!Attr.isArgIdent(0)) {
2153     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2154       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2155     return;
2156   }
2157 
2158   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2159   BlocksAttr::BlockType type;
2160   if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2161     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2162       << Attr.getName() << II;
2163     return;
2164   }
2165 
2166   D->addAttr(::new (S.Context)
2167              BlocksAttr(Attr.getRange(), S.Context, type,
2168                         Attr.getAttributeSpellingListIndex()));
2169 }
2170 
handleSentinelAttr(Sema & S,Decl * D,const AttributeList & Attr)2171 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2172   unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2173   if (Attr.getNumArgs() > 0) {
2174     Expr *E = Attr.getArgAsExpr(0);
2175     llvm::APSInt Idx(32);
2176     if (E->isTypeDependent() || E->isValueDependent() ||
2177         !E->isIntegerConstantExpr(Idx, S.Context)) {
2178       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2179         << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2180         << E->getSourceRange();
2181       return;
2182     }
2183 
2184     if (Idx.isSigned() && Idx.isNegative()) {
2185       S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2186         << E->getSourceRange();
2187       return;
2188     }
2189 
2190     sentinel = Idx.getZExtValue();
2191   }
2192 
2193   unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2194   if (Attr.getNumArgs() > 1) {
2195     Expr *E = Attr.getArgAsExpr(1);
2196     llvm::APSInt Idx(32);
2197     if (E->isTypeDependent() || E->isValueDependent() ||
2198         !E->isIntegerConstantExpr(Idx, S.Context)) {
2199       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2200         << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2201         << E->getSourceRange();
2202       return;
2203     }
2204     nullPos = Idx.getZExtValue();
2205 
2206     if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2207       // FIXME: This error message could be improved, it would be nice
2208       // to say what the bounds actually are.
2209       S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2210         << E->getSourceRange();
2211       return;
2212     }
2213   }
2214 
2215   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2216     const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2217     if (isa<FunctionNoProtoType>(FT)) {
2218       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2219       return;
2220     }
2221 
2222     if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2223       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2224       return;
2225     }
2226   } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2227     if (!MD->isVariadic()) {
2228       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2229       return;
2230     }
2231   } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2232     if (!BD->isVariadic()) {
2233       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2234       return;
2235     }
2236   } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2237     QualType Ty = V->getType();
2238     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2239       const FunctionType *FT = Ty->isFunctionPointerType()
2240        ? D->getFunctionType()
2241        : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2242       if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2243         int m = Ty->isFunctionPointerType() ? 0 : 1;
2244         S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2245         return;
2246       }
2247     } else {
2248       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2249         << Attr.getName() << ExpectedFunctionMethodOrBlock;
2250       return;
2251     }
2252   } else {
2253     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2254       << Attr.getName() << ExpectedFunctionMethodOrBlock;
2255     return;
2256   }
2257   D->addAttr(::new (S.Context)
2258              SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2259                           Attr.getAttributeSpellingListIndex()));
2260 }
2261 
handleWarnUnusedResult(Sema & S,Decl * D,const AttributeList & Attr)2262 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2263   if (D->getFunctionType() &&
2264       D->getFunctionType()->getReturnType()->isVoidType()) {
2265     S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2266       << Attr.getName() << 0;
2267     return;
2268   }
2269   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2270     if (MD->getReturnType()->isVoidType()) {
2271       S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2272       << Attr.getName() << 1;
2273       return;
2274     }
2275 
2276   D->addAttr(::new (S.Context)
2277              WarnUnusedResultAttr(Attr.getRange(), S.Context,
2278                                   Attr.getAttributeSpellingListIndex()));
2279 }
2280 
handleWeakImportAttr(Sema & S,Decl * D,const AttributeList & Attr)2281 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2282   // weak_import only applies to variable & function declarations.
2283   bool isDef = false;
2284   if (!D->canBeWeakImported(isDef)) {
2285     if (isDef)
2286       S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2287         << "weak_import";
2288     else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2289              (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2290               (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2291       // Nothing to warn about here.
2292     } else
2293       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2294         << Attr.getName() << ExpectedVariableOrFunction;
2295 
2296     return;
2297   }
2298 
2299   D->addAttr(::new (S.Context)
2300              WeakImportAttr(Attr.getRange(), S.Context,
2301                             Attr.getAttributeSpellingListIndex()));
2302 }
2303 
2304 // Handles reqd_work_group_size and work_group_size_hint.
2305 template <typename WorkGroupAttr>
handleWorkGroupSize(Sema & S,Decl * D,const AttributeList & Attr)2306 static void handleWorkGroupSize(Sema &S, Decl *D,
2307                                 const AttributeList &Attr) {
2308   uint32_t WGSize[3];
2309   for (unsigned i = 0; i < 3; ++i) {
2310     const Expr *E = Attr.getArgAsExpr(i);
2311     if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2312       return;
2313     if (WGSize[i] == 0) {
2314       S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2315         << Attr.getName() << E->getSourceRange();
2316       return;
2317     }
2318   }
2319 
2320   WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2321   if (Existing && !(Existing->getXDim() == WGSize[0] &&
2322                     Existing->getYDim() == WGSize[1] &&
2323                     Existing->getZDim() == WGSize[2]))
2324     S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2325 
2326   D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2327                                              WGSize[0], WGSize[1], WGSize[2],
2328                                        Attr.getAttributeSpellingListIndex()));
2329 }
2330 
handleVecTypeHint(Sema & S,Decl * D,const AttributeList & Attr)2331 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2332   if (!Attr.hasParsedType()) {
2333     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2334       << Attr.getName() << 1;
2335     return;
2336   }
2337 
2338   TypeSourceInfo *ParmTSI = nullptr;
2339   QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2340   assert(ParmTSI && "no type source info for attribute argument");
2341 
2342   if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2343       (ParmType->isBooleanType() ||
2344        !ParmType->isIntegralType(S.getASTContext()))) {
2345     S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2346         << ParmType;
2347     return;
2348   }
2349 
2350   if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2351     if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2352       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2353       return;
2354     }
2355   }
2356 
2357   D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2358                                                ParmTSI,
2359                                         Attr.getAttributeSpellingListIndex()));
2360 }
2361 
mergeSectionAttr(Decl * D,SourceRange Range,StringRef Name,unsigned AttrSpellingListIndex)2362 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2363                                     StringRef Name,
2364                                     unsigned AttrSpellingListIndex) {
2365   if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2366     if (ExistingAttr->getName() == Name)
2367       return nullptr;
2368     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2369     Diag(Range.getBegin(), diag::note_previous_attribute);
2370     return nullptr;
2371   }
2372   return ::new (Context) SectionAttr(Range, Context, Name,
2373                                      AttrSpellingListIndex);
2374 }
2375 
checkSectionName(SourceLocation LiteralLoc,StringRef SecName)2376 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2377   std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2378   if (!Error.empty()) {
2379     Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2380     return false;
2381   }
2382   return true;
2383 }
2384 
handleSectionAttr(Sema & S,Decl * D,const AttributeList & Attr)2385 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2386   // Make sure that there is a string literal as the sections's single
2387   // argument.
2388   StringRef Str;
2389   SourceLocation LiteralLoc;
2390   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2391     return;
2392 
2393   if (!S.checkSectionName(LiteralLoc, Str))
2394     return;
2395 
2396   // If the target wants to validate the section specifier, make it happen.
2397   std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2398   if (!Error.empty()) {
2399     S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2400     << Error;
2401     return;
2402   }
2403 
2404   unsigned Index = Attr.getAttributeSpellingListIndex();
2405   SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2406   if (NewAttr)
2407     D->addAttr(NewAttr);
2408 }
2409 
2410 
handleCleanupAttr(Sema & S,Decl * D,const AttributeList & Attr)2411 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2412   VarDecl *VD = cast<VarDecl>(D);
2413   if (!VD->hasLocalStorage()) {
2414     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2415     return;
2416   }
2417 
2418   Expr *E = Attr.getArgAsExpr(0);
2419   SourceLocation Loc = E->getExprLoc();
2420   FunctionDecl *FD = nullptr;
2421   DeclarationNameInfo NI;
2422 
2423   // gcc only allows for simple identifiers. Since we support more than gcc, we
2424   // will warn the user.
2425   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2426     if (DRE->hasQualifier())
2427       S.Diag(Loc, diag::warn_cleanup_ext);
2428     FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2429     NI = DRE->getNameInfo();
2430     if (!FD) {
2431       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2432         << NI.getName();
2433       return;
2434     }
2435   } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2436     if (ULE->hasExplicitTemplateArgs())
2437       S.Diag(Loc, diag::warn_cleanup_ext);
2438     FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2439     NI = ULE->getNameInfo();
2440     if (!FD) {
2441       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2442         << NI.getName();
2443       if (ULE->getType() == S.Context.OverloadTy)
2444         S.NoteAllOverloadCandidates(ULE);
2445       return;
2446     }
2447   } else {
2448     S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2449     return;
2450   }
2451 
2452   if (FD->getNumParams() != 1) {
2453     S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2454       << NI.getName();
2455     return;
2456   }
2457 
2458   // We're currently more strict than GCC about what function types we accept.
2459   // If this ever proves to be a problem it should be easy to fix.
2460   QualType Ty = S.Context.getPointerType(VD->getType());
2461   QualType ParamTy = FD->getParamDecl(0)->getType();
2462   if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2463                                    ParamTy, Ty) != Sema::Compatible) {
2464     S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2465       << NI.getName() << ParamTy << Ty;
2466     return;
2467   }
2468 
2469   D->addAttr(::new (S.Context)
2470              CleanupAttr(Attr.getRange(), S.Context, FD,
2471                          Attr.getAttributeSpellingListIndex()));
2472 }
2473 
2474 /// Handle __attribute__((format_arg((idx)))) attribute based on
2475 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
handleFormatArgAttr(Sema & S,Decl * D,const AttributeList & Attr)2476 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2477   Expr *IdxExpr = Attr.getArgAsExpr(0);
2478   uint64_t Idx;
2479   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2480     return;
2481 
2482   // make sure the format string is really a string
2483   QualType Ty = getFunctionOrMethodParamType(D, Idx);
2484 
2485   bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2486   if (not_nsstring_type &&
2487       !isCFStringType(Ty, S.Context) &&
2488       (!Ty->isPointerType() ||
2489        !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2490     S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2491         << (not_nsstring_type ? "a string type" : "an NSString")
2492         << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2493     return;
2494   }
2495   Ty = getFunctionOrMethodResultType(D);
2496   if (!isNSStringType(Ty, S.Context) &&
2497       !isCFStringType(Ty, S.Context) &&
2498       (!Ty->isPointerType() ||
2499        !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2500     S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2501         << (not_nsstring_type ? "string type" : "NSString")
2502         << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2503     return;
2504   }
2505 
2506   // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2507   // because that has corrected for the implicit this parameter, and is zero-
2508   // based.  The attribute expects what the user wrote explicitly.
2509   llvm::APSInt Val;
2510   IdxExpr->EvaluateAsInt(Val, S.Context);
2511 
2512   D->addAttr(::new (S.Context)
2513              FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2514                            Attr.getAttributeSpellingListIndex()));
2515 }
2516 
2517 enum FormatAttrKind {
2518   CFStringFormat,
2519   NSStringFormat,
2520   StrftimeFormat,
2521   SupportedFormat,
2522   IgnoredFormat,
2523   InvalidFormat
2524 };
2525 
2526 /// getFormatAttrKind - Map from format attribute names to supported format
2527 /// types.
getFormatAttrKind(StringRef Format)2528 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2529   return llvm::StringSwitch<FormatAttrKind>(Format)
2530     // Check for formats that get handled specially.
2531     .Case("NSString", NSStringFormat)
2532     .Case("CFString", CFStringFormat)
2533     .Case("strftime", StrftimeFormat)
2534 
2535     // Otherwise, check for supported formats.
2536     .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2537     .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2538     .Case("kprintf", SupportedFormat) // OpenBSD.
2539     .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
2540     .Case("os_trace", SupportedFormat)
2541 
2542     .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2543     .Default(InvalidFormat);
2544 }
2545 
2546 /// Handle __attribute__((init_priority(priority))) attributes based on
2547 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
handleInitPriorityAttr(Sema & S,Decl * D,const AttributeList & Attr)2548 static void handleInitPriorityAttr(Sema &S, Decl *D,
2549                                    const AttributeList &Attr) {
2550   if (!S.getLangOpts().CPlusPlus) {
2551     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2552     return;
2553   }
2554 
2555   if (S.getCurFunctionOrMethodDecl()) {
2556     S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2557     Attr.setInvalid();
2558     return;
2559   }
2560   QualType T = cast<VarDecl>(D)->getType();
2561   if (S.Context.getAsArrayType(T))
2562     T = S.Context.getBaseElementType(T);
2563   if (!T->getAs<RecordType>()) {
2564     S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2565     Attr.setInvalid();
2566     return;
2567   }
2568 
2569   Expr *E = Attr.getArgAsExpr(0);
2570   uint32_t prioritynum;
2571   if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
2572     Attr.setInvalid();
2573     return;
2574   }
2575 
2576   if (prioritynum < 101 || prioritynum > 65535) {
2577     S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2578       << E->getSourceRange();
2579     Attr.setInvalid();
2580     return;
2581   }
2582   D->addAttr(::new (S.Context)
2583              InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2584                               Attr.getAttributeSpellingListIndex()));
2585 }
2586 
mergeFormatAttr(Decl * D,SourceRange Range,IdentifierInfo * Format,int FormatIdx,int FirstArg,unsigned AttrSpellingListIndex)2587 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2588                                   IdentifierInfo *Format, int FormatIdx,
2589                                   int FirstArg,
2590                                   unsigned AttrSpellingListIndex) {
2591   // Check whether we already have an equivalent format attribute.
2592   for (auto *F : D->specific_attrs<FormatAttr>()) {
2593     if (F->getType() == Format &&
2594         F->getFormatIdx() == FormatIdx &&
2595         F->getFirstArg() == FirstArg) {
2596       // If we don't have a valid location for this attribute, adopt the
2597       // location.
2598       if (F->getLocation().isInvalid())
2599         F->setRange(Range);
2600       return nullptr;
2601     }
2602   }
2603 
2604   return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2605                                     FirstArg, AttrSpellingListIndex);
2606 }
2607 
2608 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2609 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
handleFormatAttr(Sema & S,Decl * D,const AttributeList & Attr)2610 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2611   if (!Attr.isArgIdent(0)) {
2612     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2613       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2614     return;
2615   }
2616 
2617   // In C++ the implicit 'this' function parameter also counts, and they are
2618   // counted from one.
2619   bool HasImplicitThisParam = isInstanceMethod(D);
2620   unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
2621 
2622   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2623   StringRef Format = II->getName();
2624 
2625   // Normalize the argument, __foo__ becomes foo.
2626   if (Format.startswith("__") && Format.endswith("__")) {
2627     Format = Format.substr(2, Format.size() - 4);
2628     // If we've modified the string name, we need a new identifier for it.
2629     II = &S.Context.Idents.get(Format);
2630   }
2631 
2632   // Check for supported formats.
2633   FormatAttrKind Kind = getFormatAttrKind(Format);
2634 
2635   if (Kind == IgnoredFormat)
2636     return;
2637 
2638   if (Kind == InvalidFormat) {
2639     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2640       << Attr.getName() << II->getName();
2641     return;
2642   }
2643 
2644   // checks for the 2nd argument
2645   Expr *IdxExpr = Attr.getArgAsExpr(1);
2646   uint32_t Idx;
2647   if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
2648     return;
2649 
2650   if (Idx < 1 || Idx > NumArgs) {
2651     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2652       << Attr.getName() << 2 << IdxExpr->getSourceRange();
2653     return;
2654   }
2655 
2656   // FIXME: Do we need to bounds check?
2657   unsigned ArgIdx = Idx - 1;
2658 
2659   if (HasImplicitThisParam) {
2660     if (ArgIdx == 0) {
2661       S.Diag(Attr.getLoc(),
2662              diag::err_format_attribute_implicit_this_format_string)
2663         << IdxExpr->getSourceRange();
2664       return;
2665     }
2666     ArgIdx--;
2667   }
2668 
2669   // make sure the format string is really a string
2670   QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
2671 
2672   if (Kind == CFStringFormat) {
2673     if (!isCFStringType(Ty, S.Context)) {
2674       S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2675         << "a CFString" << IdxExpr->getSourceRange()
2676         << getFunctionOrMethodParamRange(D, ArgIdx);
2677       return;
2678     }
2679   } else if (Kind == NSStringFormat) {
2680     // FIXME: do we need to check if the type is NSString*?  What are the
2681     // semantics?
2682     if (!isNSStringType(Ty, S.Context)) {
2683       S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2684         << "an NSString" << IdxExpr->getSourceRange()
2685         << getFunctionOrMethodParamRange(D, ArgIdx);
2686       return;
2687     }
2688   } else if (!Ty->isPointerType() ||
2689              !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2690     S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2691       << "a string type" << IdxExpr->getSourceRange()
2692       << getFunctionOrMethodParamRange(D, ArgIdx);
2693     return;
2694   }
2695 
2696   // check the 3rd argument
2697   Expr *FirstArgExpr = Attr.getArgAsExpr(2);
2698   uint32_t FirstArg;
2699   if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
2700     return;
2701 
2702   // check if the function is variadic if the 3rd argument non-zero
2703   if (FirstArg != 0) {
2704     if (isFunctionOrMethodVariadic(D)) {
2705       ++NumArgs; // +1 for ...
2706     } else {
2707       S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2708       return;
2709     }
2710   }
2711 
2712   // strftime requires FirstArg to be 0 because it doesn't read from any
2713   // variable the input is just the current time + the format string.
2714   if (Kind == StrftimeFormat) {
2715     if (FirstArg != 0) {
2716       S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2717         << FirstArgExpr->getSourceRange();
2718       return;
2719     }
2720   // if 0 it disables parameter checking (to use with e.g. va_list)
2721   } else if (FirstArg != 0 && FirstArg != NumArgs) {
2722     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2723       << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
2724     return;
2725   }
2726 
2727   FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
2728                                           Idx, FirstArg,
2729                                           Attr.getAttributeSpellingListIndex());
2730   if (NewAttr)
2731     D->addAttr(NewAttr);
2732 }
2733 
handleTransparentUnionAttr(Sema & S,Decl * D,const AttributeList & Attr)2734 static void handleTransparentUnionAttr(Sema &S, Decl *D,
2735                                        const AttributeList &Attr) {
2736   // Try to find the underlying union declaration.
2737   RecordDecl *RD = nullptr;
2738   TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
2739   if (TD && TD->getUnderlyingType()->isUnionType())
2740     RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2741   else
2742     RD = dyn_cast<RecordDecl>(D);
2743 
2744   if (!RD || !RD->isUnion()) {
2745     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2746       << Attr.getName() << ExpectedUnion;
2747     return;
2748   }
2749 
2750   if (!RD->isCompleteDefinition()) {
2751     S.Diag(Attr.getLoc(),
2752         diag::warn_transparent_union_attribute_not_definition);
2753     return;
2754   }
2755 
2756   RecordDecl::field_iterator Field = RD->field_begin(),
2757                           FieldEnd = RD->field_end();
2758   if (Field == FieldEnd) {
2759     S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
2760     return;
2761   }
2762 
2763   FieldDecl *FirstField = *Field;
2764   QualType FirstType = FirstField->getType();
2765   if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
2766     S.Diag(FirstField->getLocation(),
2767            diag::warn_transparent_union_attribute_floating)
2768       << FirstType->isVectorType() << FirstType;
2769     return;
2770   }
2771 
2772   uint64_t FirstSize = S.Context.getTypeSize(FirstType);
2773   uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
2774   for (; Field != FieldEnd; ++Field) {
2775     QualType FieldType = Field->getType();
2776     // FIXME: this isn't fully correct; we also need to test whether the
2777     // members of the union would all have the same calling convention as the
2778     // first member of the union. Checking just the size and alignment isn't
2779     // sufficient (consider structs passed on the stack instead of in registers
2780     // as an example).
2781     if (S.Context.getTypeSize(FieldType) != FirstSize ||
2782         S.Context.getTypeAlign(FieldType) > FirstAlign) {
2783       // Warn if we drop the attribute.
2784       bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
2785       unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
2786                                  : S.Context.getTypeAlign(FieldType);
2787       S.Diag(Field->getLocation(),
2788           diag::warn_transparent_union_attribute_field_size_align)
2789         << isSize << Field->getDeclName() << FieldBits;
2790       unsigned FirstBits = isSize? FirstSize : FirstAlign;
2791       S.Diag(FirstField->getLocation(),
2792              diag::note_transparent_union_first_field_size_align)
2793         << isSize << FirstBits;
2794       return;
2795     }
2796   }
2797 
2798   RD->addAttr(::new (S.Context)
2799               TransparentUnionAttr(Attr.getRange(), S.Context,
2800                                    Attr.getAttributeSpellingListIndex()));
2801 }
2802 
handleAnnotateAttr(Sema & S,Decl * D,const AttributeList & Attr)2803 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2804   // Make sure that there is a string literal as the annotation's single
2805   // argument.
2806   StringRef Str;
2807   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2808     return;
2809 
2810   // Don't duplicate annotations that are already set.
2811   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2812     if (I->getAnnotation() == Str)
2813       return;
2814   }
2815 
2816   D->addAttr(::new (S.Context)
2817              AnnotateAttr(Attr.getRange(), S.Context, Str,
2818                           Attr.getAttributeSpellingListIndex()));
2819 }
2820 
handleAlignValueAttr(Sema & S,Decl * D,const AttributeList & Attr)2821 static void handleAlignValueAttr(Sema &S, Decl *D,
2822                                  const AttributeList &Attr) {
2823   S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
2824                       Attr.getAttributeSpellingListIndex());
2825 }
2826 
AddAlignValueAttr(SourceRange AttrRange,Decl * D,Expr * E,unsigned SpellingListIndex)2827 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
2828                              unsigned SpellingListIndex) {
2829   AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
2830   SourceLocation AttrLoc = AttrRange.getBegin();
2831 
2832   QualType T;
2833   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
2834     T = TD->getUnderlyingType();
2835   else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2836     T = VD->getType();
2837   else
2838     llvm_unreachable("Unknown decl type for align_value");
2839 
2840   if (!T->isDependentType() && !T->isAnyPointerType() &&
2841       !T->isReferenceType() && !T->isMemberPointerType()) {
2842     Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
2843       << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
2844     return;
2845   }
2846 
2847   if (!E->isValueDependent()) {
2848     llvm::APSInt Alignment(32);
2849     ExprResult ICE
2850       = VerifyIntegerConstantExpression(E, &Alignment,
2851           diag::err_align_value_attribute_argument_not_int,
2852             /*AllowFold*/ false);
2853     if (ICE.isInvalid())
2854       return;
2855 
2856     if (!Alignment.isPowerOf2()) {
2857       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
2858         << E->getSourceRange();
2859       return;
2860     }
2861 
2862     D->addAttr(::new (Context)
2863                AlignValueAttr(AttrRange, Context, ICE.get(),
2864                SpellingListIndex));
2865     return;
2866   }
2867 
2868   // Save dependent expressions in the AST to be instantiated.
2869   D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
2870   return;
2871 }
2872 
handleAlignedAttr(Sema & S,Decl * D,const AttributeList & Attr)2873 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2874   // check the attribute arguments.
2875   if (Attr.getNumArgs() > 1) {
2876     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2877       << Attr.getName() << 1;
2878     return;
2879   }
2880 
2881   if (Attr.getNumArgs() == 0) {
2882     D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
2883                true, nullptr, Attr.getAttributeSpellingListIndex()));
2884     return;
2885   }
2886 
2887   Expr *E = Attr.getArgAsExpr(0);
2888   if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
2889     S.Diag(Attr.getEllipsisLoc(),
2890            diag::err_pack_expansion_without_parameter_packs);
2891     return;
2892   }
2893 
2894   if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
2895     return;
2896 
2897   if (E->isValueDependent()) {
2898     if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
2899       if (!TND->getUnderlyingType()->isDependentType()) {
2900         S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
2901             << E->getSourceRange();
2902         return;
2903       }
2904     }
2905   }
2906 
2907   S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
2908                    Attr.isPackExpansion());
2909 }
2910 
AddAlignedAttr(SourceRange AttrRange,Decl * D,Expr * E,unsigned SpellingListIndex,bool IsPackExpansion)2911 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
2912                           unsigned SpellingListIndex, bool IsPackExpansion) {
2913   AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
2914   SourceLocation AttrLoc = AttrRange.getBegin();
2915 
2916   // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
2917   if (TmpAttr.isAlignas()) {
2918     // C++11 [dcl.align]p1:
2919     //   An alignment-specifier may be applied to a variable or to a class
2920     //   data member, but it shall not be applied to a bit-field, a function
2921     //   parameter, the formal parameter of a catch clause, or a variable
2922     //   declared with the register storage class specifier. An
2923     //   alignment-specifier may also be applied to the declaration of a class
2924     //   or enumeration type.
2925     // C11 6.7.5/2:
2926     //   An alignment attribute shall not be specified in a declaration of
2927     //   a typedef, or a bit-field, or a function, or a parameter, or an
2928     //   object declared with the register storage-class specifier.
2929     int DiagKind = -1;
2930     if (isa<ParmVarDecl>(D)) {
2931       DiagKind = 0;
2932     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2933       if (VD->getStorageClass() == SC_Register)
2934         DiagKind = 1;
2935       if (VD->isExceptionVariable())
2936         DiagKind = 2;
2937     } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2938       if (FD->isBitField())
2939         DiagKind = 3;
2940     } else if (!isa<TagDecl>(D)) {
2941       Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
2942         << (TmpAttr.isC11() ? ExpectedVariableOrField
2943                             : ExpectedVariableFieldOrTag);
2944       return;
2945     }
2946     if (DiagKind != -1) {
2947       Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
2948         << &TmpAttr << DiagKind;
2949       return;
2950     }
2951   }
2952 
2953   if (E->isTypeDependent() || E->isValueDependent()) {
2954     // Save dependent expressions in the AST to be instantiated.
2955     AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
2956     AA->setPackExpansion(IsPackExpansion);
2957     D->addAttr(AA);
2958     return;
2959   }
2960 
2961   // FIXME: Cache the number on the Attr object?
2962   llvm::APSInt Alignment(32);
2963   ExprResult ICE
2964     = VerifyIntegerConstantExpression(E, &Alignment,
2965         diag::err_aligned_attribute_argument_not_int,
2966         /*AllowFold*/ false);
2967   if (ICE.isInvalid())
2968     return;
2969 
2970   // C++11 [dcl.align]p2:
2971   //   -- if the constant expression evaluates to zero, the alignment
2972   //      specifier shall have no effect
2973   // C11 6.7.5p6:
2974   //   An alignment specification of zero has no effect.
2975   if (!(TmpAttr.isAlignas() && !Alignment) &&
2976       !llvm::isPowerOf2_64(Alignment.getZExtValue())) {
2977     Diag(AttrLoc, diag::err_alignment_not_power_of_two)
2978       << E->getSourceRange();
2979     return;
2980   }
2981 
2982   // Alignment calculations can wrap around if it's greater than 2**28.
2983   unsigned MaxValidAlignment = TmpAttr.isDeclspec() ? 8192 : 268435456;
2984   if (Alignment.getZExtValue() > MaxValidAlignment) {
2985     Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
2986                                                          << E->getSourceRange();
2987     return;
2988   }
2989 
2990   AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
2991                                                 ICE.get(), SpellingListIndex);
2992   AA->setPackExpansion(IsPackExpansion);
2993   D->addAttr(AA);
2994 }
2995 
AddAlignedAttr(SourceRange AttrRange,Decl * D,TypeSourceInfo * TS,unsigned SpellingListIndex,bool IsPackExpansion)2996 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
2997                           unsigned SpellingListIndex, bool IsPackExpansion) {
2998   // FIXME: Cache the number on the Attr object if non-dependent?
2999   // FIXME: Perform checking of type validity
3000   AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3001                                                 SpellingListIndex);
3002   AA->setPackExpansion(IsPackExpansion);
3003   D->addAttr(AA);
3004 }
3005 
CheckAlignasUnderalignment(Decl * D)3006 void Sema::CheckAlignasUnderalignment(Decl *D) {
3007   assert(D->hasAttrs() && "no attributes on decl");
3008 
3009   QualType UnderlyingTy, DiagTy;
3010   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3011     UnderlyingTy = DiagTy = VD->getType();
3012   } else {
3013     UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3014     if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3015       UnderlyingTy = ED->getIntegerType();
3016   }
3017   if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3018     return;
3019 
3020   // C++11 [dcl.align]p5, C11 6.7.5/4:
3021   //   The combined effect of all alignment attributes in a declaration shall
3022   //   not specify an alignment that is less strict than the alignment that
3023   //   would otherwise be required for the entity being declared.
3024   AlignedAttr *AlignasAttr = nullptr;
3025   unsigned Align = 0;
3026   for (auto *I : D->specific_attrs<AlignedAttr>()) {
3027     if (I->isAlignmentDependent())
3028       return;
3029     if (I->isAlignas())
3030       AlignasAttr = I;
3031     Align = std::max(Align, I->getAlignment(Context));
3032   }
3033 
3034   if (AlignasAttr && Align) {
3035     CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3036     CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3037     if (NaturalAlign > RequestedAlign)
3038       Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3039         << DiagTy << (unsigned)NaturalAlign.getQuantity();
3040   }
3041 }
3042 
checkMSInheritanceAttrOnDefinition(CXXRecordDecl * RD,SourceRange Range,bool BestCase,MSInheritanceAttr::Spelling SemanticSpelling)3043 bool Sema::checkMSInheritanceAttrOnDefinition(
3044     CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3045     MSInheritanceAttr::Spelling SemanticSpelling) {
3046   assert(RD->hasDefinition() && "RD has no definition!");
3047 
3048   // We may not have seen base specifiers or any virtual methods yet.  We will
3049   // have to wait until the record is defined to catch any mismatches.
3050   if (!RD->getDefinition()->isCompleteDefinition())
3051     return false;
3052 
3053   // The unspecified model never matches what a definition could need.
3054   if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3055     return false;
3056 
3057   if (BestCase) {
3058     if (RD->calculateInheritanceModel() == SemanticSpelling)
3059       return false;
3060   } else {
3061     if (RD->calculateInheritanceModel() <= SemanticSpelling)
3062       return false;
3063   }
3064 
3065   Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3066       << 0 /*definition*/;
3067   Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3068       << RD->getNameAsString();
3069   return true;
3070 }
3071 
3072 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3073 /// type.
3074 ///
3075 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3076 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3077 /// HImode, not an intermediate pointer.
handleModeAttr(Sema & S,Decl * D,const AttributeList & Attr)3078 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3079   // This attribute isn't documented, but glibc uses it.  It changes
3080   // the width of an int or unsigned int to the specified size.
3081   if (!Attr.isArgIdent(0)) {
3082     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3083       << AANT_ArgumentIdentifier;
3084     return;
3085   }
3086 
3087   IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3088   StringRef Str = Name->getName();
3089 
3090   // Normalize the attribute name, __foo__ becomes foo.
3091   if (Str.startswith("__") && Str.endswith("__"))
3092     Str = Str.substr(2, Str.size() - 4);
3093 
3094   unsigned DestWidth = 0;
3095   bool IntegerMode = true;
3096   bool ComplexMode = false;
3097   switch (Str.size()) {
3098   case 2:
3099     switch (Str[0]) {
3100     case 'Q': DestWidth = 8; break;
3101     case 'H': DestWidth = 16; break;
3102     case 'S': DestWidth = 32; break;
3103     case 'D': DestWidth = 64; break;
3104     case 'X': DestWidth = 96; break;
3105     case 'T': DestWidth = 128; break;
3106     }
3107     if (Str[1] == 'F') {
3108       IntegerMode = false;
3109     } else if (Str[1] == 'C') {
3110       IntegerMode = false;
3111       ComplexMode = true;
3112     } else if (Str[1] != 'I') {
3113       DestWidth = 0;
3114     }
3115     break;
3116   case 4:
3117     // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3118     // pointer on PIC16 and other embedded platforms.
3119     if (Str == "word")
3120       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3121     else if (Str == "byte")
3122       DestWidth = S.Context.getTargetInfo().getCharWidth();
3123     break;
3124   case 7:
3125     if (Str == "pointer")
3126       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3127     break;
3128   case 11:
3129     if (Str == "unwind_word")
3130       DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3131     break;
3132   }
3133 
3134   QualType OldTy;
3135   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3136     OldTy = TD->getUnderlyingType();
3137   else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3138     OldTy = VD->getType();
3139   else {
3140     S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3141       << Attr.getName() << Attr.getRange();
3142     return;
3143   }
3144 
3145   if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
3146     S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3147   else if (IntegerMode) {
3148     if (!OldTy->isIntegralOrEnumerationType())
3149       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3150   } else if (ComplexMode) {
3151     if (!OldTy->isComplexType())
3152       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3153   } else {
3154     if (!OldTy->isFloatingType())
3155       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3156   }
3157 
3158   // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3159   // and friends, at least with glibc.
3160   // FIXME: Make sure floating-point mappings are accurate
3161   // FIXME: Support XF and TF types
3162   if (!DestWidth) {
3163     S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3164     return;
3165   }
3166 
3167   QualType NewTy;
3168 
3169   if (IntegerMode)
3170     NewTy = S.Context.getIntTypeForBitwidth(DestWidth,
3171                                             OldTy->isSignedIntegerType());
3172   else
3173     NewTy = S.Context.getRealTypeForBitwidth(DestWidth);
3174 
3175   if (NewTy.isNull()) {
3176     S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3177     return;
3178   }
3179 
3180   if (ComplexMode) {
3181     NewTy = S.Context.getComplexType(NewTy);
3182   }
3183 
3184   // Install the new type.
3185   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3186     TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3187   else
3188     cast<ValueDecl>(D)->setType(NewTy);
3189 
3190   D->addAttr(::new (S.Context)
3191              ModeAttr(Attr.getRange(), S.Context, Name,
3192                       Attr.getAttributeSpellingListIndex()));
3193 }
3194 
handleNoDebugAttr(Sema & S,Decl * D,const AttributeList & Attr)3195 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3196   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3197     if (!VD->hasGlobalStorage())
3198       S.Diag(Attr.getLoc(),
3199              diag::warn_attribute_requires_functions_or_static_globals)
3200         << Attr.getName();
3201   } else if (!isFunctionOrMethod(D)) {
3202     S.Diag(Attr.getLoc(),
3203            diag::warn_attribute_requires_functions_or_static_globals)
3204       << Attr.getName();
3205     return;
3206   }
3207 
3208   D->addAttr(::new (S.Context)
3209              NoDebugAttr(Attr.getRange(), S.Context,
3210                          Attr.getAttributeSpellingListIndex()));
3211 }
3212 
mergeAlwaysInlineAttr(Decl * D,SourceRange Range,IdentifierInfo * Ident,unsigned AttrSpellingListIndex)3213 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3214                                               IdentifierInfo *Ident,
3215                                               unsigned AttrSpellingListIndex) {
3216   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3217     Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3218     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3219     return nullptr;
3220   }
3221 
3222   if (D->hasAttr<AlwaysInlineAttr>())
3223     return nullptr;
3224 
3225   return ::new (Context) AlwaysInlineAttr(Range, Context,
3226                                           AttrSpellingListIndex);
3227 }
3228 
mergeMinSizeAttr(Decl * D,SourceRange Range,unsigned AttrSpellingListIndex)3229 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3230                                     unsigned AttrSpellingListIndex) {
3231   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3232     Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3233     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3234     return nullptr;
3235   }
3236 
3237   if (D->hasAttr<MinSizeAttr>())
3238     return nullptr;
3239 
3240   return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3241 }
3242 
mergeOptimizeNoneAttr(Decl * D,SourceRange Range,unsigned AttrSpellingListIndex)3243 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3244                                               unsigned AttrSpellingListIndex) {
3245   if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3246     Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3247     Diag(Range.getBegin(), diag::note_conflicting_attribute);
3248     D->dropAttr<AlwaysInlineAttr>();
3249   }
3250   if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3251     Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3252     Diag(Range.getBegin(), diag::note_conflicting_attribute);
3253     D->dropAttr<MinSizeAttr>();
3254   }
3255 
3256   if (D->hasAttr<OptimizeNoneAttr>())
3257     return nullptr;
3258 
3259   return ::new (Context) OptimizeNoneAttr(Range, Context,
3260                                           AttrSpellingListIndex);
3261 }
3262 
handleAlwaysInlineAttr(Sema & S,Decl * D,const AttributeList & Attr)3263 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3264                                    const AttributeList &Attr) {
3265   if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3266           D, Attr.getRange(), Attr.getName(),
3267           Attr.getAttributeSpellingListIndex()))
3268     D->addAttr(Inline);
3269 }
3270 
handleMinSizeAttr(Sema & S,Decl * D,const AttributeList & Attr)3271 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3272   if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3273           D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3274     D->addAttr(MinSize);
3275 }
3276 
handleOptimizeNoneAttr(Sema & S,Decl * D,const AttributeList & Attr)3277 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3278                                    const AttributeList &Attr) {
3279   if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3280           D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3281     D->addAttr(Optnone);
3282 }
3283 
handleGlobalAttr(Sema & S,Decl * D,const AttributeList & Attr)3284 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3285   FunctionDecl *FD = cast<FunctionDecl>(D);
3286   if (!FD->getReturnType()->isVoidType()) {
3287     SourceRange RTRange = FD->getReturnTypeSourceRange();
3288     S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3289         << FD->getType()
3290         << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3291                               : FixItHint());
3292     return;
3293   }
3294 
3295   D->addAttr(::new (S.Context)
3296               CUDAGlobalAttr(Attr.getRange(), S.Context,
3297                              Attr.getAttributeSpellingListIndex()));
3298 }
3299 
handleGNUInlineAttr(Sema & S,Decl * D,const AttributeList & Attr)3300 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3301   FunctionDecl *Fn = cast<FunctionDecl>(D);
3302   if (!Fn->isInlineSpecified()) {
3303     S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3304     return;
3305   }
3306 
3307   D->addAttr(::new (S.Context)
3308              GNUInlineAttr(Attr.getRange(), S.Context,
3309                            Attr.getAttributeSpellingListIndex()));
3310 }
3311 
handleCallConvAttr(Sema & S,Decl * D,const AttributeList & Attr)3312 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3313   if (hasDeclarator(D)) return;
3314 
3315   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3316   // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3317   // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3318   CallingConv CC;
3319   if (S.CheckCallingConvAttr(Attr, CC, FD))
3320     return;
3321 
3322   if (!isa<ObjCMethodDecl>(D)) {
3323     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3324       << Attr.getName() << ExpectedFunctionOrMethod;
3325     return;
3326   }
3327 
3328   switch (Attr.getKind()) {
3329   case AttributeList::AT_FastCall:
3330     D->addAttr(::new (S.Context)
3331                FastCallAttr(Attr.getRange(), S.Context,
3332                             Attr.getAttributeSpellingListIndex()));
3333     return;
3334   case AttributeList::AT_StdCall:
3335     D->addAttr(::new (S.Context)
3336                StdCallAttr(Attr.getRange(), S.Context,
3337                            Attr.getAttributeSpellingListIndex()));
3338     return;
3339   case AttributeList::AT_ThisCall:
3340     D->addAttr(::new (S.Context)
3341                ThisCallAttr(Attr.getRange(), S.Context,
3342                             Attr.getAttributeSpellingListIndex()));
3343     return;
3344   case AttributeList::AT_CDecl:
3345     D->addAttr(::new (S.Context)
3346                CDeclAttr(Attr.getRange(), S.Context,
3347                          Attr.getAttributeSpellingListIndex()));
3348     return;
3349   case AttributeList::AT_Pascal:
3350     D->addAttr(::new (S.Context)
3351                PascalAttr(Attr.getRange(), S.Context,
3352                           Attr.getAttributeSpellingListIndex()));
3353     return;
3354   case AttributeList::AT_VectorCall:
3355     D->addAttr(::new (S.Context)
3356                VectorCallAttr(Attr.getRange(), S.Context,
3357                               Attr.getAttributeSpellingListIndex()));
3358     return;
3359   case AttributeList::AT_MSABI:
3360     D->addAttr(::new (S.Context)
3361                MSABIAttr(Attr.getRange(), S.Context,
3362                          Attr.getAttributeSpellingListIndex()));
3363     return;
3364   case AttributeList::AT_SysVABI:
3365     D->addAttr(::new (S.Context)
3366                SysVABIAttr(Attr.getRange(), S.Context,
3367                            Attr.getAttributeSpellingListIndex()));
3368     return;
3369   case AttributeList::AT_Pcs: {
3370     PcsAttr::PCSType PCS;
3371     switch (CC) {
3372     case CC_AAPCS:
3373       PCS = PcsAttr::AAPCS;
3374       break;
3375     case CC_AAPCS_VFP:
3376       PCS = PcsAttr::AAPCS_VFP;
3377       break;
3378     default:
3379       llvm_unreachable("unexpected calling convention in pcs attribute");
3380     }
3381 
3382     D->addAttr(::new (S.Context)
3383                PcsAttr(Attr.getRange(), S.Context, PCS,
3384                        Attr.getAttributeSpellingListIndex()));
3385     return;
3386   }
3387   case AttributeList::AT_IntelOclBicc:
3388     D->addAttr(::new (S.Context)
3389                IntelOclBiccAttr(Attr.getRange(), S.Context,
3390                                 Attr.getAttributeSpellingListIndex()));
3391     return;
3392 
3393   default:
3394     llvm_unreachable("unexpected attribute kind");
3395   }
3396 }
3397 
CheckCallingConvAttr(const AttributeList & attr,CallingConv & CC,const FunctionDecl * FD)3398 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3399                                 const FunctionDecl *FD) {
3400   if (attr.isInvalid())
3401     return true;
3402 
3403   unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3404   if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3405     attr.setInvalid();
3406     return true;
3407   }
3408 
3409   // TODO: diagnose uses of these conventions on the wrong target.
3410   switch (attr.getKind()) {
3411   case AttributeList::AT_CDecl: CC = CC_C; break;
3412   case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3413   case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3414   case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3415   case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3416   case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
3417   case AttributeList::AT_MSABI:
3418     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3419                                                              CC_X86_64Win64;
3420     break;
3421   case AttributeList::AT_SysVABI:
3422     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3423                                                              CC_C;
3424     break;
3425   case AttributeList::AT_Pcs: {
3426     StringRef StrRef;
3427     if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3428       attr.setInvalid();
3429       return true;
3430     }
3431     if (StrRef == "aapcs") {
3432       CC = CC_AAPCS;
3433       break;
3434     } else if (StrRef == "aapcs-vfp") {
3435       CC = CC_AAPCS_VFP;
3436       break;
3437     }
3438 
3439     attr.setInvalid();
3440     Diag(attr.getLoc(), diag::err_invalid_pcs);
3441     return true;
3442   }
3443   case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3444   default: llvm_unreachable("unexpected attribute kind");
3445   }
3446 
3447   const TargetInfo &TI = Context.getTargetInfo();
3448   TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3449   if (A != TargetInfo::CCCR_OK) {
3450     if (A == TargetInfo::CCCR_Warning)
3451       Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3452 
3453     // This convention is not valid for the target. Use the default function or
3454     // method calling convention.
3455     TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3456     if (FD)
3457       MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3458                                     TargetInfo::CCMT_NonMember;
3459     CC = TI.getDefaultCallingConv(MT);
3460   }
3461 
3462   return false;
3463 }
3464 
3465 /// Checks a regparm attribute, returning true if it is ill-formed and
3466 /// otherwise setting numParams to the appropriate value.
CheckRegparmAttr(const AttributeList & Attr,unsigned & numParams)3467 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3468   if (Attr.isInvalid())
3469     return true;
3470 
3471   if (!checkAttributeNumArgs(*this, Attr, 1)) {
3472     Attr.setInvalid();
3473     return true;
3474   }
3475 
3476   uint32_t NP;
3477   Expr *NumParamsExpr = Attr.getArgAsExpr(0);
3478   if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
3479     Attr.setInvalid();
3480     return true;
3481   }
3482 
3483   if (Context.getTargetInfo().getRegParmMax() == 0) {
3484     Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3485       << NumParamsExpr->getSourceRange();
3486     Attr.setInvalid();
3487     return true;
3488   }
3489 
3490   numParams = NP;
3491   if (numParams > Context.getTargetInfo().getRegParmMax()) {
3492     Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3493       << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3494     Attr.setInvalid();
3495     return true;
3496   }
3497 
3498   return false;
3499 }
3500 
handleLaunchBoundsAttr(Sema & S,Decl * D,const AttributeList & Attr)3501 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
3502                                    const AttributeList &Attr) {
3503   uint32_t MaxThreads, MinBlocks = 0;
3504   if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), MaxThreads, 1))
3505     return;
3506   if (Attr.getNumArgs() > 1 && !checkUInt32Argument(S, Attr,
3507                                                     Attr.getArgAsExpr(1),
3508                                                     MinBlocks, 2))
3509     return;
3510 
3511   D->addAttr(::new (S.Context)
3512               CUDALaunchBoundsAttr(Attr.getRange(), S.Context,
3513                                   MaxThreads, MinBlocks,
3514                                   Attr.getAttributeSpellingListIndex()));
3515 }
3516 
handleArgumentWithTypeTagAttr(Sema & S,Decl * D,const AttributeList & Attr)3517 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
3518                                           const AttributeList &Attr) {
3519   if (!Attr.isArgIdent(0)) {
3520     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3521       << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
3522     return;
3523   }
3524 
3525   if (!checkAttributeNumArgs(S, Attr, 3))
3526     return;
3527 
3528   IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
3529 
3530   if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
3531     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3532       << Attr.getName() << ExpectedFunctionOrMethod;
3533     return;
3534   }
3535 
3536   uint64_t ArgumentIdx;
3537   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
3538                                            ArgumentIdx))
3539     return;
3540 
3541   uint64_t TypeTagIdx;
3542   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
3543                                            TypeTagIdx))
3544     return;
3545 
3546   bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
3547   if (IsPointer) {
3548     // Ensure that buffer has a pointer type.
3549     QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
3550     if (!BufferTy->isPointerType()) {
3551       S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
3552         << Attr.getName();
3553     }
3554   }
3555 
3556   D->addAttr(::new (S.Context)
3557              ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
3558                                      ArgumentIdx, TypeTagIdx, IsPointer,
3559                                      Attr.getAttributeSpellingListIndex()));
3560 }
3561 
handleTypeTagForDatatypeAttr(Sema & S,Decl * D,const AttributeList & Attr)3562 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
3563                                          const AttributeList &Attr) {
3564   if (!Attr.isArgIdent(0)) {
3565     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3566       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3567     return;
3568   }
3569 
3570   if (!checkAttributeNumArgs(S, Attr, 1))
3571     return;
3572 
3573   if (!isa<VarDecl>(D)) {
3574     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3575       << Attr.getName() << ExpectedVariable;
3576     return;
3577   }
3578 
3579   IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
3580   TypeSourceInfo *MatchingCTypeLoc = nullptr;
3581   S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
3582   assert(MatchingCTypeLoc && "no type source info for attribute argument");
3583 
3584   D->addAttr(::new (S.Context)
3585              TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
3586                                     MatchingCTypeLoc,
3587                                     Attr.getLayoutCompatible(),
3588                                     Attr.getMustBeNull(),
3589                                     Attr.getAttributeSpellingListIndex()));
3590 }
3591 
3592 //===----------------------------------------------------------------------===//
3593 // Checker-specific attribute handlers.
3594 //===----------------------------------------------------------------------===//
3595 
isValidSubjectOfNSReturnsRetainedAttribute(QualType type)3596 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
3597   return type->isDependentType() ||
3598          type->isObjCRetainableType();
3599 }
3600 
isValidSubjectOfNSAttribute(Sema & S,QualType type)3601 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3602   return type->isDependentType() ||
3603          type->isObjCObjectPointerType() ||
3604          S.Context.isObjCNSObjectType(type);
3605 }
isValidSubjectOfCFAttribute(Sema & S,QualType type)3606 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3607   return type->isDependentType() ||
3608          type->isPointerType() ||
3609          isValidSubjectOfNSAttribute(S, type);
3610 }
3611 
handleNSConsumedAttr(Sema & S,Decl * D,const AttributeList & Attr)3612 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3613   ParmVarDecl *param = cast<ParmVarDecl>(D);
3614   bool typeOK, cf;
3615 
3616   if (Attr.getKind() == AttributeList::AT_NSConsumed) {
3617     typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3618     cf = false;
3619   } else {
3620     typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3621     cf = true;
3622   }
3623 
3624   if (!typeOK) {
3625     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3626       << Attr.getRange() << Attr.getName() << cf;
3627     return;
3628   }
3629 
3630   if (cf)
3631     param->addAttr(::new (S.Context)
3632                    CFConsumedAttr(Attr.getRange(), S.Context,
3633                                   Attr.getAttributeSpellingListIndex()));
3634   else
3635     param->addAttr(::new (S.Context)
3636                    NSConsumedAttr(Attr.getRange(), S.Context,
3637                                   Attr.getAttributeSpellingListIndex()));
3638 }
3639 
handleNSReturnsRetainedAttr(Sema & S,Decl * D,const AttributeList & Attr)3640 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
3641                                         const AttributeList &Attr) {
3642 
3643   QualType returnType;
3644 
3645   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3646     returnType = MD->getReturnType();
3647   else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
3648            (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
3649     return; // ignore: was handled as a type attribute
3650   else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
3651     returnType = PD->getType();
3652   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3653     returnType = FD->getReturnType();
3654   else {
3655     S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3656         << Attr.getRange() << Attr.getName()
3657         << ExpectedFunctionOrMethod;
3658     return;
3659   }
3660 
3661   bool typeOK;
3662   bool cf;
3663   switch (Attr.getKind()) {
3664   default: llvm_unreachable("invalid ownership attribute");
3665   case AttributeList::AT_NSReturnsRetained:
3666     typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
3667     cf = false;
3668     break;
3669 
3670   case AttributeList::AT_NSReturnsAutoreleased:
3671   case AttributeList::AT_NSReturnsNotRetained:
3672     typeOK = isValidSubjectOfNSAttribute(S, returnType);
3673     cf = false;
3674     break;
3675 
3676   case AttributeList::AT_CFReturnsRetained:
3677   case AttributeList::AT_CFReturnsNotRetained:
3678     typeOK = isValidSubjectOfCFAttribute(S, returnType);
3679     cf = true;
3680     break;
3681   }
3682 
3683   if (!typeOK) {
3684     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3685       << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf;
3686     return;
3687   }
3688 
3689   switch (Attr.getKind()) {
3690     default:
3691       llvm_unreachable("invalid ownership attribute");
3692     case AttributeList::AT_NSReturnsAutoreleased:
3693       D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
3694           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3695       return;
3696     case AttributeList::AT_CFReturnsNotRetained:
3697       D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
3698           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3699       return;
3700     case AttributeList::AT_NSReturnsNotRetained:
3701       D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
3702           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3703       return;
3704     case AttributeList::AT_CFReturnsRetained:
3705       D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
3706           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3707       return;
3708     case AttributeList::AT_NSReturnsRetained:
3709       D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
3710           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3711       return;
3712   };
3713 }
3714 
handleObjCReturnsInnerPointerAttr(Sema & S,Decl * D,const AttributeList & attr)3715 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
3716                                               const AttributeList &attr) {
3717   const int EP_ObjCMethod = 1;
3718   const int EP_ObjCProperty = 2;
3719 
3720   SourceLocation loc = attr.getLoc();
3721   QualType resultType;
3722   if (isa<ObjCMethodDecl>(D))
3723     resultType = cast<ObjCMethodDecl>(D)->getReturnType();
3724   else
3725     resultType = cast<ObjCPropertyDecl>(D)->getType();
3726 
3727   if (!resultType->isReferenceType() &&
3728       (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
3729     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3730       << SourceRange(loc)
3731     << attr.getName()
3732     << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
3733     << /*non-retainable pointer*/ 2;
3734 
3735     // Drop the attribute.
3736     return;
3737   }
3738 
3739   D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
3740       attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
3741 }
3742 
handleObjCRequiresSuperAttr(Sema & S,Decl * D,const AttributeList & attr)3743 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
3744                                         const AttributeList &attr) {
3745   ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
3746 
3747   DeclContext *DC = method->getDeclContext();
3748   if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
3749     S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3750     << attr.getName() << 0;
3751     S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
3752     return;
3753   }
3754   if (method->getMethodFamily() == OMF_dealloc) {
3755     S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3756     << attr.getName() << 1;
3757     return;
3758   }
3759 
3760   method->addAttr(::new (S.Context)
3761                   ObjCRequiresSuperAttr(attr.getRange(), S.Context,
3762                                         attr.getAttributeSpellingListIndex()));
3763 }
3764 
handleCFAuditedTransferAttr(Sema & S,Decl * D,const AttributeList & Attr)3765 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
3766                                         const AttributeList &Attr) {
3767   if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr))
3768     return;
3769 
3770   D->addAttr(::new (S.Context)
3771              CFAuditedTransferAttr(Attr.getRange(), S.Context,
3772                                    Attr.getAttributeSpellingListIndex()));
3773 }
3774 
handleCFUnknownTransferAttr(Sema & S,Decl * D,const AttributeList & Attr)3775 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
3776                                         const AttributeList &Attr) {
3777   if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr))
3778     return;
3779 
3780   D->addAttr(::new (S.Context)
3781              CFUnknownTransferAttr(Attr.getRange(), S.Context,
3782              Attr.getAttributeSpellingListIndex()));
3783 }
3784 
handleObjCBridgeAttr(Sema & S,Scope * Sc,Decl * D,const AttributeList & Attr)3785 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
3786                                 const AttributeList &Attr) {
3787   IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
3788 
3789   if (!Parm) {
3790     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3791     return;
3792   }
3793 
3794   // Typedefs only allow objc_bridge(id) and have some additional checking.
3795   if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
3796     if (!Parm->Ident->isStr("id")) {
3797       S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
3798         << Attr.getName();
3799       return;
3800     }
3801 
3802     // Only allow 'cv void *'.
3803     QualType T = TD->getUnderlyingType();
3804     if (!T->isVoidPointerType()) {
3805       S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
3806       return;
3807     }
3808   }
3809 
3810   D->addAttr(::new (S.Context)
3811              ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
3812                            Attr.getAttributeSpellingListIndex()));
3813 }
3814 
handleObjCBridgeMutableAttr(Sema & S,Scope * Sc,Decl * D,const AttributeList & Attr)3815 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
3816                                         const AttributeList &Attr) {
3817   IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
3818 
3819   if (!Parm) {
3820     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3821     return;
3822   }
3823 
3824   D->addAttr(::new (S.Context)
3825              ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
3826                             Attr.getAttributeSpellingListIndex()));
3827 }
3828 
handleObjCBridgeRelatedAttr(Sema & S,Scope * Sc,Decl * D,const AttributeList & Attr)3829 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
3830                                  const AttributeList &Attr) {
3831   IdentifierInfo *RelatedClass =
3832     Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
3833   if (!RelatedClass) {
3834     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3835     return;
3836   }
3837   IdentifierInfo *ClassMethod =
3838     Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
3839   IdentifierInfo *InstanceMethod =
3840     Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
3841   D->addAttr(::new (S.Context)
3842              ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
3843                                    ClassMethod, InstanceMethod,
3844                                    Attr.getAttributeSpellingListIndex()));
3845 }
3846 
handleObjCDesignatedInitializer(Sema & S,Decl * D,const AttributeList & Attr)3847 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
3848                                             const AttributeList &Attr) {
3849   ObjCInterfaceDecl *IFace;
3850   if (ObjCCategoryDecl *CatDecl =
3851           dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
3852     IFace = CatDecl->getClassInterface();
3853   else
3854     IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
3855 
3856   if (!IFace)
3857     return;
3858 
3859   IFace->setHasDesignatedInitializers();
3860   D->addAttr(::new (S.Context)
3861                   ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
3862                                          Attr.getAttributeSpellingListIndex()));
3863 }
3864 
handleObjCRuntimeName(Sema & S,Decl * D,const AttributeList & Attr)3865 static void handleObjCRuntimeName(Sema &S, Decl *D,
3866                                   const AttributeList &Attr) {
3867   StringRef MetaDataName;
3868   if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
3869     return;
3870   D->addAttr(::new (S.Context)
3871              ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
3872                                  MetaDataName,
3873                                  Attr.getAttributeSpellingListIndex()));
3874 }
3875 
handleObjCOwnershipAttr(Sema & S,Decl * D,const AttributeList & Attr)3876 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
3877                                     const AttributeList &Attr) {
3878   if (hasDeclarator(D)) return;
3879 
3880   S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
3881     << Attr.getRange() << Attr.getName() << ExpectedVariable;
3882 }
3883 
handleObjCPreciseLifetimeAttr(Sema & S,Decl * D,const AttributeList & Attr)3884 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
3885                                           const AttributeList &Attr) {
3886   ValueDecl *vd = cast<ValueDecl>(D);
3887   QualType type = vd->getType();
3888 
3889   if (!type->isDependentType() &&
3890       !type->isObjCLifetimeType()) {
3891     S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
3892       << type;
3893     return;
3894   }
3895 
3896   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3897 
3898   // If we have no lifetime yet, check the lifetime we're presumably
3899   // going to infer.
3900   if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
3901     lifetime = type->getObjCARCImplicitLifetime();
3902 
3903   switch (lifetime) {
3904   case Qualifiers::OCL_None:
3905     assert(type->isDependentType() &&
3906            "didn't infer lifetime for non-dependent type?");
3907     break;
3908 
3909   case Qualifiers::OCL_Weak:   // meaningful
3910   case Qualifiers::OCL_Strong: // meaningful
3911     break;
3912 
3913   case Qualifiers::OCL_ExplicitNone:
3914   case Qualifiers::OCL_Autoreleasing:
3915     S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
3916       << (lifetime == Qualifiers::OCL_Autoreleasing);
3917     break;
3918   }
3919 
3920   D->addAttr(::new (S.Context)
3921              ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
3922                                      Attr.getAttributeSpellingListIndex()));
3923 }
3924 
3925 //===----------------------------------------------------------------------===//
3926 // Microsoft specific attribute handlers.
3927 //===----------------------------------------------------------------------===//
3928 
handleUuidAttr(Sema & S,Decl * D,const AttributeList & Attr)3929 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3930   if (!S.LangOpts.CPlusPlus) {
3931     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
3932       << Attr.getName() << AttributeLangSupport::C;
3933     return;
3934   }
3935 
3936   if (!isa<CXXRecordDecl>(D)) {
3937     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3938       << Attr.getName() << ExpectedClass;
3939     return;
3940   }
3941 
3942   StringRef StrRef;
3943   SourceLocation LiteralLoc;
3944   if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
3945     return;
3946 
3947   // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
3948   // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
3949   if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
3950     StrRef = StrRef.drop_front().drop_back();
3951 
3952   // Validate GUID length.
3953   if (StrRef.size() != 36) {
3954     S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3955     return;
3956   }
3957 
3958   for (unsigned i = 0; i < 36; ++i) {
3959     if (i == 8 || i == 13 || i == 18 || i == 23) {
3960       if (StrRef[i] != '-') {
3961         S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3962         return;
3963       }
3964     } else if (!isHexDigit(StrRef[i])) {
3965       S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
3966       return;
3967     }
3968   }
3969 
3970   D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
3971                                         Attr.getAttributeSpellingListIndex()));
3972 }
3973 
handleMSInheritanceAttr(Sema & S,Decl * D,const AttributeList & Attr)3974 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3975   if (!S.LangOpts.CPlusPlus) {
3976     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
3977       << Attr.getName() << AttributeLangSupport::C;
3978     return;
3979   }
3980   MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
3981       D, Attr.getRange(), /*BestCase=*/true,
3982       Attr.getAttributeSpellingListIndex(),
3983       (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
3984   if (IA)
3985     D->addAttr(IA);
3986 }
3987 
handleDeclspecThreadAttr(Sema & S,Decl * D,const AttributeList & Attr)3988 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
3989                                      const AttributeList &Attr) {
3990   VarDecl *VD = cast<VarDecl>(D);
3991   if (!S.Context.getTargetInfo().isTLSSupported()) {
3992     S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
3993     return;
3994   }
3995   if (VD->getTSCSpec() != TSCS_unspecified) {
3996     S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
3997     return;
3998   }
3999   if (VD->hasLocalStorage()) {
4000     S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4001     return;
4002   }
4003   VD->addAttr(::new (S.Context) ThreadAttr(
4004       Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4005 }
4006 
handleARMInterruptAttr(Sema & S,Decl * D,const AttributeList & Attr)4007 static void handleARMInterruptAttr(Sema &S, Decl *D,
4008                                    const AttributeList &Attr) {
4009   // Check the attribute arguments.
4010   if (Attr.getNumArgs() > 1) {
4011     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4012       << Attr.getName() << 1;
4013     return;
4014   }
4015 
4016   StringRef Str;
4017   SourceLocation ArgLoc;
4018 
4019   if (Attr.getNumArgs() == 0)
4020     Str = "";
4021   else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4022     return;
4023 
4024   ARMInterruptAttr::InterruptType Kind;
4025   if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4026     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4027       << Attr.getName() << Str << ArgLoc;
4028     return;
4029   }
4030 
4031   unsigned Index = Attr.getAttributeSpellingListIndex();
4032   D->addAttr(::new (S.Context)
4033              ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
4034 }
4035 
handleMSP430InterruptAttr(Sema & S,Decl * D,const AttributeList & Attr)4036 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
4037                                       const AttributeList &Attr) {
4038   if (!checkAttributeNumArgs(S, Attr, 1))
4039     return;
4040 
4041   if (!Attr.isArgExpr(0)) {
4042     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
4043       << AANT_ArgumentIntegerConstant;
4044     return;
4045   }
4046 
4047   // FIXME: Check for decl - it should be void ()(void).
4048 
4049   Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4050   llvm::APSInt NumParams(32);
4051   if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
4052     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4053       << Attr.getName() << AANT_ArgumentIntegerConstant
4054       << NumParamsExpr->getSourceRange();
4055     return;
4056   }
4057 
4058   unsigned Num = NumParams.getLimitedValue(255);
4059   if ((Num & 1) || Num > 30) {
4060     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4061       << Attr.getName() << (int)NumParams.getSExtValue()
4062       << NumParamsExpr->getSourceRange();
4063     return;
4064   }
4065 
4066   D->addAttr(::new (S.Context)
4067               MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
4068                                   Attr.getAttributeSpellingListIndex()));
4069   D->addAttr(UsedAttr::CreateImplicit(S.Context));
4070 }
4071 
handleInterruptAttr(Sema & S,Decl * D,const AttributeList & Attr)4072 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4073   // Dispatch the interrupt attribute based on the current target.
4074   if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430)
4075     handleMSP430InterruptAttr(S, D, Attr);
4076   else
4077     handleARMInterruptAttr(S, D, Attr);
4078 }
4079 
handleAMDGPUNumVGPRAttr(Sema & S,Decl * D,const AttributeList & Attr)4080 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
4081                                     const AttributeList &Attr) {
4082   uint32_t NumRegs;
4083   Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4084   if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4085     return;
4086 
4087   D->addAttr(::new (S.Context)
4088              AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context,
4089                                NumRegs,
4090                                Attr.getAttributeSpellingListIndex()));
4091 }
4092 
handleAMDGPUNumSGPRAttr(Sema & S,Decl * D,const AttributeList & Attr)4093 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
4094                                     const AttributeList &Attr) {
4095   uint32_t NumRegs;
4096   Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4097   if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4098     return;
4099 
4100   D->addAttr(::new (S.Context)
4101              AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context,
4102                                NumRegs,
4103                                Attr.getAttributeSpellingListIndex()));
4104 }
4105 
handleX86ForceAlignArgPointerAttr(Sema & S,Decl * D,const AttributeList & Attr)4106 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
4107                                               const AttributeList& Attr) {
4108   // If we try to apply it to a function pointer, don't warn, but don't
4109   // do anything, either. It doesn't matter anyway, because there's nothing
4110   // special about calling a force_align_arg_pointer function.
4111   ValueDecl *VD = dyn_cast<ValueDecl>(D);
4112   if (VD && VD->getType()->isFunctionPointerType())
4113     return;
4114   // Also don't warn on function pointer typedefs.
4115   TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
4116   if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
4117     TD->getUnderlyingType()->isFunctionType()))
4118     return;
4119   // Attribute can only be applied to function types.
4120   if (!isa<FunctionDecl>(D)) {
4121     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4122       << Attr.getName() << /* function */0;
4123     return;
4124   }
4125 
4126   D->addAttr(::new (S.Context)
4127               X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
4128                                         Attr.getAttributeSpellingListIndex()));
4129 }
4130 
mergeDLLImportAttr(Decl * D,SourceRange Range,unsigned AttrSpellingListIndex)4131 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
4132                                         unsigned AttrSpellingListIndex) {
4133   if (D->hasAttr<DLLExportAttr>()) {
4134     Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
4135     return nullptr;
4136   }
4137 
4138   if (D->hasAttr<DLLImportAttr>())
4139     return nullptr;
4140 
4141   return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
4142 }
4143 
mergeDLLExportAttr(Decl * D,SourceRange Range,unsigned AttrSpellingListIndex)4144 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
4145                                         unsigned AttrSpellingListIndex) {
4146   if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
4147     Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
4148     D->dropAttr<DLLImportAttr>();
4149   }
4150 
4151   if (D->hasAttr<DLLExportAttr>())
4152     return nullptr;
4153 
4154   return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
4155 }
4156 
handleDLLAttr(Sema & S,Decl * D,const AttributeList & A)4157 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
4158   if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
4159       S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4160     S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
4161         << A.getName();
4162     return;
4163   }
4164 
4165   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4166     if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
4167         !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4168       // MinGW doesn't allow dllimport on inline functions.
4169       S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
4170           << A.getName();
4171       return;
4172     }
4173   }
4174 
4175   unsigned Index = A.getAttributeSpellingListIndex();
4176   Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
4177                       ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
4178                       : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
4179   if (NewAttr)
4180     D->addAttr(NewAttr);
4181 }
4182 
4183 MSInheritanceAttr *
mergeMSInheritanceAttr(Decl * D,SourceRange Range,bool BestCase,unsigned AttrSpellingListIndex,MSInheritanceAttr::Spelling SemanticSpelling)4184 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
4185                              unsigned AttrSpellingListIndex,
4186                              MSInheritanceAttr::Spelling SemanticSpelling) {
4187   if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
4188     if (IA->getSemanticSpelling() == SemanticSpelling)
4189       return nullptr;
4190     Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
4191         << 1 /*previous declaration*/;
4192     Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
4193     D->dropAttr<MSInheritanceAttr>();
4194   }
4195 
4196   CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
4197   if (RD->hasDefinition()) {
4198     if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
4199                                            SemanticSpelling)) {
4200       return nullptr;
4201     }
4202   } else {
4203     if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
4204       Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4205           << 1 /*partial specialization*/;
4206       return nullptr;
4207     }
4208     if (RD->getDescribedClassTemplate()) {
4209       Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4210           << 0 /*primary template*/;
4211       return nullptr;
4212     }
4213   }
4214 
4215   return ::new (Context)
4216       MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
4217 }
4218 
handleCapabilityAttr(Sema & S,Decl * D,const AttributeList & Attr)4219 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4220   // The capability attributes take a single string parameter for the name of
4221   // the capability they represent. The lockable attribute does not take any
4222   // parameters. However, semantically, both attributes represent the same
4223   // concept, and so they use the same semantic attribute. Eventually, the
4224   // lockable attribute will be removed.
4225   //
4226   // For backward compatibility, any capability which has no specified string
4227   // literal will be considered a "mutex."
4228   StringRef N("mutex");
4229   SourceLocation LiteralLoc;
4230   if (Attr.getKind() == AttributeList::AT_Capability &&
4231       !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
4232     return;
4233 
4234   // Currently, there are only two names allowed for a capability: role and
4235   // mutex (case insensitive). Diagnose other capability names.
4236   if (!N.equals_lower("mutex") && !N.equals_lower("role"))
4237     S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
4238 
4239   D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
4240                                         Attr.getAttributeSpellingListIndex()));
4241 }
4242 
handleAssertCapabilityAttr(Sema & S,Decl * D,const AttributeList & Attr)4243 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
4244                                        const AttributeList &Attr) {
4245   D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
4246                                                     Attr.getArgAsExpr(0),
4247                                         Attr.getAttributeSpellingListIndex()));
4248 }
4249 
handleAcquireCapabilityAttr(Sema & S,Decl * D,const AttributeList & Attr)4250 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
4251                                         const AttributeList &Attr) {
4252   SmallVector<Expr*, 1> Args;
4253   if (!checkLockFunAttrCommon(S, D, Attr, Args))
4254     return;
4255 
4256   D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
4257                                                      S.Context,
4258                                                      Args.data(), Args.size(),
4259                                         Attr.getAttributeSpellingListIndex()));
4260 }
4261 
handleTryAcquireCapabilityAttr(Sema & S,Decl * D,const AttributeList & Attr)4262 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
4263                                            const AttributeList &Attr) {
4264   SmallVector<Expr*, 2> Args;
4265   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
4266     return;
4267 
4268   D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
4269                                                         S.Context,
4270                                                         Attr.getArgAsExpr(0),
4271                                                         Args.data(),
4272                                                         Args.size(),
4273                                         Attr.getAttributeSpellingListIndex()));
4274 }
4275 
handleReleaseCapabilityAttr(Sema & S,Decl * D,const AttributeList & Attr)4276 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
4277                                         const AttributeList &Attr) {
4278   // Check that all arguments are lockable objects.
4279   SmallVector<Expr *, 1> Args;
4280   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
4281 
4282   D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
4283       Attr.getRange(), S.Context, Args.data(), Args.size(),
4284       Attr.getAttributeSpellingListIndex()));
4285 }
4286 
handleRequiresCapabilityAttr(Sema & S,Decl * D,const AttributeList & Attr)4287 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
4288                                          const AttributeList &Attr) {
4289   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4290     return;
4291 
4292   // check that all arguments are lockable objects
4293   SmallVector<Expr*, 1> Args;
4294   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
4295   if (Args.empty())
4296     return;
4297 
4298   RequiresCapabilityAttr *RCA = ::new (S.Context)
4299     RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
4300                            Args.size(), Attr.getAttributeSpellingListIndex());
4301 
4302   D->addAttr(RCA);
4303 }
4304 
handleDeprecatedAttr(Sema & S,Decl * D,const AttributeList & Attr)4305 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4306   if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
4307     if (NSD->isAnonymousNamespace()) {
4308       S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
4309       // Do not want to attach the attribute to the namespace because that will
4310       // cause confusing diagnostic reports for uses of declarations within the
4311       // namespace.
4312       return;
4313     }
4314   }
4315 
4316   if (!S.getLangOpts().CPlusPlus14)
4317     if (Attr.isCXX11Attribute() &&
4318         !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
4319       S.Diag(Attr.getLoc(), diag::ext_deprecated_attr_is_a_cxx14_extension);
4320 
4321   handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
4322 }
4323 
4324 /// Handles semantic checking for features that are common to all attributes,
4325 /// such as checking whether a parameter was properly specified, or the correct
4326 /// number of arguments were passed, etc.
handleCommonAttributeFeatures(Sema & S,Scope * scope,Decl * D,const AttributeList & Attr)4327 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
4328                                           const AttributeList &Attr) {
4329   // Several attributes carry different semantics than the parsing requires, so
4330   // those are opted out of the common handling.
4331   //
4332   // We also bail on unknown and ignored attributes because those are handled
4333   // as part of the target-specific handling logic.
4334   if (Attr.hasCustomParsing() ||
4335       Attr.getKind() == AttributeList::UnknownAttribute)
4336     return false;
4337 
4338   // Check whether the attribute requires specific language extensions to be
4339   // enabled.
4340   if (!Attr.diagnoseLangOpts(S))
4341     return true;
4342 
4343   if (Attr.getMinArgs() == Attr.getMaxArgs()) {
4344     // If there are no optional arguments, then checking for the argument count
4345     // is trivial.
4346     if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
4347       return true;
4348   } else {
4349     // There are optional arguments, so checking is slightly more involved.
4350     if (Attr.getMinArgs() &&
4351         !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
4352       return true;
4353     else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
4354              !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
4355       return true;
4356   }
4357 
4358   // Check whether the attribute appertains to the given subject.
4359   if (!Attr.diagnoseAppertainsTo(S, D))
4360     return true;
4361 
4362   return false;
4363 }
4364 
4365 //===----------------------------------------------------------------------===//
4366 // Top Level Sema Entry Points
4367 //===----------------------------------------------------------------------===//
4368 
4369 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4370 /// the attribute applies to decls.  If the attribute is a type attribute, just
4371 /// silently ignore it if a GNU attribute.
ProcessDeclAttribute(Sema & S,Scope * scope,Decl * D,const AttributeList & Attr,bool IncludeCXX11Attributes)4372 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4373                                  const AttributeList &Attr,
4374                                  bool IncludeCXX11Attributes) {
4375   if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
4376     return;
4377 
4378   // Ignore C++11 attributes on declarator chunks: they appertain to the type
4379   // instead.
4380   if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
4381     return;
4382 
4383   // Unknown attributes are automatically warned on. Target-specific attributes
4384   // which do not apply to the current target architecture are treated as
4385   // though they were unknown attributes.
4386   if (Attr.getKind() == AttributeList::UnknownAttribute ||
4387       !Attr.existsInTarget(S.Context.getTargetInfo().getTriple())) {
4388     S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
4389                               ? diag::warn_unhandled_ms_attribute_ignored
4390                               : diag::warn_unknown_attribute_ignored)
4391         << Attr.getName();
4392     return;
4393   }
4394 
4395   if (handleCommonAttributeFeatures(S, scope, D, Attr))
4396     return;
4397 
4398   switch (Attr.getKind()) {
4399   default:
4400     // Type attributes are handled elsewhere; silently move on.
4401     assert(Attr.isTypeAttr() && "Non-type attribute not handled");
4402     break;
4403   case AttributeList::AT_Interrupt:
4404     handleInterruptAttr(S, D, Attr);
4405     break;
4406   case AttributeList::AT_X86ForceAlignArgPointer:
4407     handleX86ForceAlignArgPointerAttr(S, D, Attr);
4408     break;
4409   case AttributeList::AT_DLLExport:
4410   case AttributeList::AT_DLLImport:
4411     handleDLLAttr(S, D, Attr);
4412     break;
4413   case AttributeList::AT_Mips16:
4414     handleSimpleAttribute<Mips16Attr>(S, D, Attr);
4415     break;
4416   case AttributeList::AT_NoMips16:
4417     handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
4418     break;
4419   case AttributeList::AT_AMDGPUNumVGPR:
4420     handleAMDGPUNumVGPRAttr(S, D, Attr);
4421     break;
4422   case AttributeList::AT_AMDGPUNumSGPR:
4423     handleAMDGPUNumSGPRAttr(S, D, Attr);
4424     break;
4425   case AttributeList::AT_IBAction:
4426     handleSimpleAttribute<IBActionAttr>(S, D, Attr);
4427     break;
4428   case AttributeList::AT_IBOutlet:
4429     handleIBOutlet(S, D, Attr);
4430     break;
4431   case AttributeList::AT_IBOutletCollection:
4432     handleIBOutletCollection(S, D, Attr);
4433     break;
4434   case AttributeList::AT_Alias:
4435     handleAliasAttr(S, D, Attr);
4436     break;
4437   case AttributeList::AT_Aligned:
4438     handleAlignedAttr(S, D, Attr);
4439     break;
4440   case AttributeList::AT_AlignValue:
4441     handleAlignValueAttr(S, D, Attr);
4442     break;
4443   case AttributeList::AT_AlwaysInline:
4444     handleAlwaysInlineAttr(S, D, Attr);
4445     break;
4446   case AttributeList::AT_AnalyzerNoReturn:
4447     handleAnalyzerNoReturnAttr(S, D, Attr);
4448     break;
4449   case AttributeList::AT_TLSModel:
4450     handleTLSModelAttr(S, D, Attr);
4451     break;
4452   case AttributeList::AT_Annotate:
4453     handleAnnotateAttr(S, D, Attr);
4454     break;
4455   case AttributeList::AT_Availability:
4456     handleAvailabilityAttr(S, D, Attr);
4457     break;
4458   case AttributeList::AT_CarriesDependency:
4459     handleDependencyAttr(S, scope, D, Attr);
4460     break;
4461   case AttributeList::AT_Common:
4462     handleCommonAttr(S, D, Attr);
4463     break;
4464   case AttributeList::AT_CUDAConstant:
4465     handleSimpleAttribute<CUDAConstantAttr>(S, D, Attr);
4466     break;
4467   case AttributeList::AT_Constructor:
4468     handleConstructorAttr(S, D, Attr);
4469     break;
4470   case AttributeList::AT_CXX11NoReturn:
4471     handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
4472     break;
4473   case AttributeList::AT_Deprecated:
4474     handleDeprecatedAttr(S, D, Attr);
4475     break;
4476   case AttributeList::AT_Destructor:
4477     handleDestructorAttr(S, D, Attr);
4478     break;
4479   case AttributeList::AT_EnableIf:
4480     handleEnableIfAttr(S, D, Attr);
4481     break;
4482   case AttributeList::AT_ExtVectorType:
4483     handleExtVectorTypeAttr(S, scope, D, Attr);
4484     break;
4485   case AttributeList::AT_MinSize:
4486     handleMinSizeAttr(S, D, Attr);
4487     break;
4488   case AttributeList::AT_OptimizeNone:
4489     handleOptimizeNoneAttr(S, D, Attr);
4490     break;
4491   case AttributeList::AT_FlagEnum:
4492     handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
4493     break;
4494   case AttributeList::AT_Flatten:
4495     handleSimpleAttribute<FlattenAttr>(S, D, Attr);
4496     break;
4497   case AttributeList::AT_Format:
4498     handleFormatAttr(S, D, Attr);
4499     break;
4500   case AttributeList::AT_FormatArg:
4501     handleFormatArgAttr(S, D, Attr);
4502     break;
4503   case AttributeList::AT_CUDAGlobal:
4504     handleGlobalAttr(S, D, Attr);
4505     break;
4506   case AttributeList::AT_CUDADevice:
4507     handleSimpleAttribute<CUDADeviceAttr>(S, D, Attr);
4508     break;
4509   case AttributeList::AT_CUDAHost:
4510     handleSimpleAttribute<CUDAHostAttr>(S, D, Attr);
4511     break;
4512   case AttributeList::AT_GNUInline:
4513     handleGNUInlineAttr(S, D, Attr);
4514     break;
4515   case AttributeList::AT_CUDALaunchBounds:
4516     handleLaunchBoundsAttr(S, D, Attr);
4517     break;
4518   case AttributeList::AT_Kernel:
4519     handleKernelAttr(S, D, Attr);
4520     break;
4521   case AttributeList::AT_Restrict:
4522     handleRestrictAttr(S, D, Attr);
4523     break;
4524   case AttributeList::AT_MayAlias:
4525     handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
4526     break;
4527   case AttributeList::AT_Mode:
4528     handleModeAttr(S, D, Attr);
4529     break;
4530   case AttributeList::AT_NoCommon:
4531     handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
4532     break;
4533   case AttributeList::AT_NoSplitStack:
4534     handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
4535     break;
4536   case AttributeList::AT_NonNull:
4537     if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
4538       handleNonNullAttrParameter(S, PVD, Attr);
4539     else
4540       handleNonNullAttr(S, D, Attr);
4541     break;
4542   case AttributeList::AT_ReturnsNonNull:
4543     handleReturnsNonNullAttr(S, D, Attr);
4544     break;
4545   case AttributeList::AT_AssumeAligned:
4546     handleAssumeAlignedAttr(S, D, Attr);
4547     break;
4548   case AttributeList::AT_Overloadable:
4549     handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
4550     break;
4551   case AttributeList::AT_Ownership:
4552     handleOwnershipAttr(S, D, Attr);
4553     break;
4554   case AttributeList::AT_Cold:
4555     handleColdAttr(S, D, Attr);
4556     break;
4557   case AttributeList::AT_Hot:
4558     handleHotAttr(S, D, Attr);
4559     break;
4560   case AttributeList::AT_Naked:
4561     handleSimpleAttribute<NakedAttr>(S, D, Attr);
4562     break;
4563   case AttributeList::AT_NoReturn:
4564     handleNoReturnAttr(S, D, Attr);
4565     break;
4566   case AttributeList::AT_NoThrow:
4567     handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
4568     break;
4569   case AttributeList::AT_CUDAShared:
4570     handleSimpleAttribute<CUDASharedAttr>(S, D, Attr);
4571     break;
4572   case AttributeList::AT_VecReturn:
4573     handleVecReturnAttr(S, D, Attr);
4574     break;
4575 
4576   case AttributeList::AT_ObjCOwnership:
4577     handleObjCOwnershipAttr(S, D, Attr);
4578     break;
4579   case AttributeList::AT_ObjCPreciseLifetime:
4580     handleObjCPreciseLifetimeAttr(S, D, Attr);
4581     break;
4582 
4583   case AttributeList::AT_ObjCReturnsInnerPointer:
4584     handleObjCReturnsInnerPointerAttr(S, D, Attr);
4585     break;
4586 
4587   case AttributeList::AT_ObjCRequiresSuper:
4588     handleObjCRequiresSuperAttr(S, D, Attr);
4589     break;
4590 
4591   case AttributeList::AT_ObjCBridge:
4592     handleObjCBridgeAttr(S, scope, D, Attr);
4593     break;
4594 
4595   case AttributeList::AT_ObjCBridgeMutable:
4596     handleObjCBridgeMutableAttr(S, scope, D, Attr);
4597     break;
4598 
4599   case AttributeList::AT_ObjCBridgeRelated:
4600     handleObjCBridgeRelatedAttr(S, scope, D, Attr);
4601     break;
4602 
4603   case AttributeList::AT_ObjCDesignatedInitializer:
4604     handleObjCDesignatedInitializer(S, D, Attr);
4605     break;
4606 
4607   case AttributeList::AT_ObjCRuntimeName:
4608     handleObjCRuntimeName(S, D, Attr);
4609     break;
4610 
4611   case AttributeList::AT_CFAuditedTransfer:
4612     handleCFAuditedTransferAttr(S, D, Attr);
4613     break;
4614   case AttributeList::AT_CFUnknownTransfer:
4615     handleCFUnknownTransferAttr(S, D, Attr);
4616     break;
4617 
4618   case AttributeList::AT_CFConsumed:
4619   case AttributeList::AT_NSConsumed:
4620     handleNSConsumedAttr(S, D, Attr);
4621     break;
4622   case AttributeList::AT_NSConsumesSelf:
4623     handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
4624     break;
4625 
4626   case AttributeList::AT_NSReturnsAutoreleased:
4627   case AttributeList::AT_NSReturnsNotRetained:
4628   case AttributeList::AT_CFReturnsNotRetained:
4629   case AttributeList::AT_NSReturnsRetained:
4630   case AttributeList::AT_CFReturnsRetained:
4631     handleNSReturnsRetainedAttr(S, D, Attr);
4632     break;
4633   case AttributeList::AT_WorkGroupSizeHint:
4634     handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
4635     break;
4636   case AttributeList::AT_ReqdWorkGroupSize:
4637     handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
4638     break;
4639   case AttributeList::AT_VecTypeHint:
4640     handleVecTypeHint(S, D, Attr);
4641     break;
4642 
4643   case AttributeList::AT_InitPriority:
4644     handleInitPriorityAttr(S, D, Attr);
4645     break;
4646 
4647   case AttributeList::AT_Packed:
4648     handlePackedAttr(S, D, Attr);
4649     break;
4650   case AttributeList::AT_Section:
4651     handleSectionAttr(S, D, Attr);
4652     break;
4653   case AttributeList::AT_Unavailable:
4654     handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
4655     break;
4656   case AttributeList::AT_ArcWeakrefUnavailable:
4657     handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
4658     break;
4659   case AttributeList::AT_ObjCRootClass:
4660     handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
4661     break;
4662   case AttributeList::AT_ObjCExplicitProtocolImpl:
4663     handleObjCSuppresProtocolAttr(S, D, Attr);
4664     break;
4665   case AttributeList::AT_ObjCRequiresPropertyDefs:
4666     handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
4667     break;
4668   case AttributeList::AT_Unused:
4669     handleSimpleAttribute<UnusedAttr>(S, D, Attr);
4670     break;
4671   case AttributeList::AT_ReturnsTwice:
4672     handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
4673     break;
4674   case AttributeList::AT_Used:
4675     handleUsedAttr(S, D, Attr);
4676     break;
4677   case AttributeList::AT_Visibility:
4678     handleVisibilityAttr(S, D, Attr, false);
4679     break;
4680   case AttributeList::AT_TypeVisibility:
4681     handleVisibilityAttr(S, D, Attr, true);
4682     break;
4683   case AttributeList::AT_WarnUnused:
4684     handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
4685     break;
4686   case AttributeList::AT_WarnUnusedResult:
4687     handleWarnUnusedResult(S, D, Attr);
4688     break;
4689   case AttributeList::AT_Weak:
4690     handleSimpleAttribute<WeakAttr>(S, D, Attr);
4691     break;
4692   case AttributeList::AT_WeakRef:
4693     handleWeakRefAttr(S, D, Attr);
4694     break;
4695   case AttributeList::AT_WeakImport:
4696     handleWeakImportAttr(S, D, Attr);
4697     break;
4698   case AttributeList::AT_TransparentUnion:
4699     handleTransparentUnionAttr(S, D, Attr);
4700     break;
4701   case AttributeList::AT_ObjCException:
4702     handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
4703     break;
4704   case AttributeList::AT_ObjCMethodFamily:
4705     handleObjCMethodFamilyAttr(S, D, Attr);
4706     break;
4707   case AttributeList::AT_ObjCNSObject:
4708     handleObjCNSObject(S, D, Attr);
4709     break;
4710   case AttributeList::AT_ObjCIndependentClass:
4711     handleObjCIndependentClass(S, D, Attr);
4712     break;
4713   case AttributeList::AT_Blocks:
4714     handleBlocksAttr(S, D, Attr);
4715     break;
4716   case AttributeList::AT_Sentinel:
4717     handleSentinelAttr(S, D, Attr);
4718     break;
4719   case AttributeList::AT_Const:
4720     handleSimpleAttribute<ConstAttr>(S, D, Attr);
4721     break;
4722   case AttributeList::AT_Pure:
4723     handleSimpleAttribute<PureAttr>(S, D, Attr);
4724     break;
4725   case AttributeList::AT_Cleanup:
4726     handleCleanupAttr(S, D, Attr);
4727     break;
4728   case AttributeList::AT_NoDebug:
4729     handleNoDebugAttr(S, D, Attr);
4730     break;
4731   case AttributeList::AT_NoDuplicate:
4732     handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
4733     break;
4734   case AttributeList::AT_NoInline:
4735     handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
4736     break;
4737   case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
4738     handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
4739     break;
4740   case AttributeList::AT_StdCall:
4741   case AttributeList::AT_CDecl:
4742   case AttributeList::AT_FastCall:
4743   case AttributeList::AT_ThisCall:
4744   case AttributeList::AT_Pascal:
4745   case AttributeList::AT_VectorCall:
4746   case AttributeList::AT_MSABI:
4747   case AttributeList::AT_SysVABI:
4748   case AttributeList::AT_Pcs:
4749   case AttributeList::AT_IntelOclBicc:
4750     handleCallConvAttr(S, D, Attr);
4751     break;
4752   case AttributeList::AT_OpenCLKernel:
4753     handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
4754     break;
4755   case AttributeList::AT_OpenCLImageAccess:
4756     handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr);
4757     break;
4758 
4759   // Microsoft attributes:
4760   case AttributeList::AT_MSNoVTable:
4761     handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
4762     break;
4763   case AttributeList::AT_MSStruct:
4764     handleSimpleAttribute<MSStructAttr>(S, D, Attr);
4765     break;
4766   case AttributeList::AT_Uuid:
4767     handleUuidAttr(S, D, Attr);
4768     break;
4769   case AttributeList::AT_MSInheritance:
4770     handleMSInheritanceAttr(S, D, Attr);
4771     break;
4772   case AttributeList::AT_SelectAny:
4773     handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
4774     break;
4775   case AttributeList::AT_Thread:
4776     handleDeclspecThreadAttr(S, D, Attr);
4777     break;
4778 
4779   // Thread safety attributes:
4780   case AttributeList::AT_AssertExclusiveLock:
4781     handleAssertExclusiveLockAttr(S, D, Attr);
4782     break;
4783   case AttributeList::AT_AssertSharedLock:
4784     handleAssertSharedLockAttr(S, D, Attr);
4785     break;
4786   case AttributeList::AT_GuardedVar:
4787     handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
4788     break;
4789   case AttributeList::AT_PtGuardedVar:
4790     handlePtGuardedVarAttr(S, D, Attr);
4791     break;
4792   case AttributeList::AT_ScopedLockable:
4793     handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
4794     break;
4795   case AttributeList::AT_NoSanitizeAddress:
4796     handleSimpleAttribute<NoSanitizeAddressAttr>(S, D, Attr);
4797     break;
4798   case AttributeList::AT_NoThreadSafetyAnalysis:
4799     handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
4800     break;
4801   case AttributeList::AT_NoSanitizeThread:
4802     handleSimpleAttribute<NoSanitizeThreadAttr>(S, D, Attr);
4803     break;
4804   case AttributeList::AT_NoSanitizeMemory:
4805     handleSimpleAttribute<NoSanitizeMemoryAttr>(S, D, Attr);
4806     break;
4807   case AttributeList::AT_GuardedBy:
4808     handleGuardedByAttr(S, D, Attr);
4809     break;
4810   case AttributeList::AT_PtGuardedBy:
4811     handlePtGuardedByAttr(S, D, Attr);
4812     break;
4813   case AttributeList::AT_ExclusiveTrylockFunction:
4814     handleExclusiveTrylockFunctionAttr(S, D, Attr);
4815     break;
4816   case AttributeList::AT_LockReturned:
4817     handleLockReturnedAttr(S, D, Attr);
4818     break;
4819   case AttributeList::AT_LocksExcluded:
4820     handleLocksExcludedAttr(S, D, Attr);
4821     break;
4822   case AttributeList::AT_SharedTrylockFunction:
4823     handleSharedTrylockFunctionAttr(S, D, Attr);
4824     break;
4825   case AttributeList::AT_AcquiredBefore:
4826     handleAcquiredBeforeAttr(S, D, Attr);
4827     break;
4828   case AttributeList::AT_AcquiredAfter:
4829     handleAcquiredAfterAttr(S, D, Attr);
4830     break;
4831 
4832   // Capability analysis attributes.
4833   case AttributeList::AT_Capability:
4834   case AttributeList::AT_Lockable:
4835     handleCapabilityAttr(S, D, Attr);
4836     break;
4837   case AttributeList::AT_RequiresCapability:
4838     handleRequiresCapabilityAttr(S, D, Attr);
4839     break;
4840 
4841   case AttributeList::AT_AssertCapability:
4842     handleAssertCapabilityAttr(S, D, Attr);
4843     break;
4844   case AttributeList::AT_AcquireCapability:
4845     handleAcquireCapabilityAttr(S, D, Attr);
4846     break;
4847   case AttributeList::AT_ReleaseCapability:
4848     handleReleaseCapabilityAttr(S, D, Attr);
4849     break;
4850   case AttributeList::AT_TryAcquireCapability:
4851     handleTryAcquireCapabilityAttr(S, D, Attr);
4852     break;
4853 
4854   // Consumed analysis attributes.
4855   case AttributeList::AT_Consumable:
4856     handleConsumableAttr(S, D, Attr);
4857     break;
4858   case AttributeList::AT_ConsumableAutoCast:
4859     handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
4860     break;
4861   case AttributeList::AT_ConsumableSetOnRead:
4862     handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
4863     break;
4864   case AttributeList::AT_CallableWhen:
4865     handleCallableWhenAttr(S, D, Attr);
4866     break;
4867   case AttributeList::AT_ParamTypestate:
4868     handleParamTypestateAttr(S, D, Attr);
4869     break;
4870   case AttributeList::AT_ReturnTypestate:
4871     handleReturnTypestateAttr(S, D, Attr);
4872     break;
4873   case AttributeList::AT_SetTypestate:
4874     handleSetTypestateAttr(S, D, Attr);
4875     break;
4876   case AttributeList::AT_TestTypestate:
4877     handleTestTypestateAttr(S, D, Attr);
4878     break;
4879 
4880   // Type safety attributes.
4881   case AttributeList::AT_ArgumentWithTypeTag:
4882     handleArgumentWithTypeTagAttr(S, D, Attr);
4883     break;
4884   case AttributeList::AT_TypeTagForDatatype:
4885     handleTypeTagForDatatypeAttr(S, D, Attr);
4886     break;
4887   }
4888 }
4889 
4890 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
4891 /// attribute list to the specified decl, ignoring any type attributes.
ProcessDeclAttributeList(Scope * S,Decl * D,const AttributeList * AttrList,bool IncludeCXX11Attributes)4892 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
4893                                     const AttributeList *AttrList,
4894                                     bool IncludeCXX11Attributes) {
4895   for (const AttributeList* l = AttrList; l; l = l->getNext())
4896     ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
4897 
4898   // FIXME: We should be able to handle these cases in TableGen.
4899   // GCC accepts
4900   // static int a9 __attribute__((weakref));
4901   // but that looks really pointless. We reject it.
4902   if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
4903     Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
4904       << cast<NamedDecl>(D);
4905     D->dropAttr<WeakRefAttr>();
4906     return;
4907   }
4908 
4909   // FIXME: We should be able to handle this in TableGen as well. It would be
4910   // good to have a way to specify "these attributes must appear as a group",
4911   // for these. Additionally, it would be good to have a way to specify "these
4912   // attribute must never appear as a group" for attributes like cold and hot.
4913   if (!D->hasAttr<OpenCLKernelAttr>()) {
4914     // These attributes cannot be applied to a non-kernel function.
4915     if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
4916       // FIXME: This emits a different error message than
4917       // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
4918       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4919       D->setInvalidDecl();
4920     } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
4921       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4922       D->setInvalidDecl();
4923     } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
4924       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
4925       D->setInvalidDecl();
4926     } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
4927       Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
4928         << A << ExpectedKernelFunction;
4929       D->setInvalidDecl();
4930     } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
4931       Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
4932         << A << ExpectedKernelFunction;
4933       D->setInvalidDecl();
4934     }
4935   }
4936 }
4937 
4938 // Annotation attributes are the only attributes allowed after an access
4939 // specifier.
ProcessAccessDeclAttributeList(AccessSpecDecl * ASDecl,const AttributeList * AttrList)4940 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4941                                           const AttributeList *AttrList) {
4942   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4943     if (l->getKind() == AttributeList::AT_Annotate) {
4944       ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
4945     } else {
4946       Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
4947       return true;
4948     }
4949   }
4950 
4951   return false;
4952 }
4953 
4954 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
4955 /// contains any decl attributes that we should warn about.
checkUnusedDeclAttributes(Sema & S,const AttributeList * A)4956 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
4957   for ( ; A; A = A->getNext()) {
4958     // Only warn if the attribute is an unignored, non-type attribute.
4959     if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
4960     if (A->getKind() == AttributeList::IgnoredAttribute) continue;
4961 
4962     if (A->getKind() == AttributeList::UnknownAttribute) {
4963       S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
4964         << A->getName() << A->getRange();
4965     } else {
4966       S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
4967         << A->getName() << A->getRange();
4968     }
4969   }
4970 }
4971 
4972 /// checkUnusedDeclAttributes - Given a declarator which is not being
4973 /// used to build a declaration, complain about any decl attributes
4974 /// which might be lying around on it.
checkUnusedDeclAttributes(Declarator & D)4975 void Sema::checkUnusedDeclAttributes(Declarator &D) {
4976   ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
4977   ::checkUnusedDeclAttributes(*this, D.getAttributes());
4978   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
4979     ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
4980 }
4981 
4982 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
4983 /// \#pragma weak needs a non-definition decl and source may not have one.
DeclClonePragmaWeak(NamedDecl * ND,IdentifierInfo * II,SourceLocation Loc)4984 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
4985                                       SourceLocation Loc) {
4986   assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
4987   NamedDecl *NewD = nullptr;
4988   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4989     FunctionDecl *NewFD;
4990     // FIXME: Missing call to CheckFunctionDeclaration().
4991     // FIXME: Mangling?
4992     // FIXME: Is the qualifier info correct?
4993     // FIXME: Is the DeclContext correct?
4994     NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
4995                                  Loc, Loc, DeclarationName(II),
4996                                  FD->getType(), FD->getTypeSourceInfo(),
4997                                  SC_None, false/*isInlineSpecified*/,
4998                                  FD->hasPrototype(),
4999                                  false/*isConstexprSpecified*/);
5000     NewD = NewFD;
5001 
5002     if (FD->getQualifier())
5003       NewFD->setQualifierInfo(FD->getQualifierLoc());
5004 
5005     // Fake up parameter variables; they are declared as if this were
5006     // a typedef.
5007     QualType FDTy = FD->getType();
5008     if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
5009       SmallVector<ParmVarDecl*, 16> Params;
5010       for (const auto &AI : FT->param_types()) {
5011         ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
5012         Param->setScopeInfo(0, Params.size());
5013         Params.push_back(Param);
5014       }
5015       NewFD->setParams(Params);
5016     }
5017   } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
5018     NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
5019                            VD->getInnerLocStart(), VD->getLocation(), II,
5020                            VD->getType(), VD->getTypeSourceInfo(),
5021                            VD->getStorageClass());
5022     if (VD->getQualifier()) {
5023       VarDecl *NewVD = cast<VarDecl>(NewD);
5024       NewVD->setQualifierInfo(VD->getQualifierLoc());
5025     }
5026   }
5027   return NewD;
5028 }
5029 
5030 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5031 /// applied to it, possibly with an alias.
DeclApplyPragmaWeak(Scope * S,NamedDecl * ND,WeakInfo & W)5032 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
5033   if (W.getUsed()) return; // only do this once
5034   W.setUsed(true);
5035   if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
5036     IdentifierInfo *NDId = ND->getIdentifier();
5037     NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
5038     NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
5039                                             W.getLocation()));
5040     NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
5041     WeakTopLevelDecl.push_back(NewD);
5042     // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
5043     // to insert Decl at TU scope, sorry.
5044     DeclContext *SavedContext = CurContext;
5045     CurContext = Context.getTranslationUnitDecl();
5046     NewD->setDeclContext(CurContext);
5047     NewD->setLexicalDeclContext(CurContext);
5048     PushOnScopeChains(NewD, S);
5049     CurContext = SavedContext;
5050   } else { // just add weak to existing
5051     ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
5052   }
5053 }
5054 
ProcessPragmaWeak(Scope * S,Decl * D)5055 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
5056   // It's valid to "forward-declare" #pragma weak, in which case we
5057   // have to do this.
5058   LoadExternalWeakUndeclaredIdentifiers();
5059   if (!WeakUndeclaredIdentifiers.empty()) {
5060     NamedDecl *ND = nullptr;
5061     if (VarDecl *VD = dyn_cast<VarDecl>(D))
5062       if (VD->isExternC())
5063         ND = VD;
5064     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5065       if (FD->isExternC())
5066         ND = FD;
5067     if (ND) {
5068       if (IdentifierInfo *Id = ND->getIdentifier()) {
5069         auto I = WeakUndeclaredIdentifiers.find(Id);
5070         if (I != WeakUndeclaredIdentifiers.end()) {
5071           WeakInfo W = I->second;
5072           DeclApplyPragmaWeak(S, ND, W);
5073           WeakUndeclaredIdentifiers[Id] = W;
5074         }
5075       }
5076     }
5077   }
5078 }
5079 
5080 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
5081 /// it, apply them to D.  This is a bit tricky because PD can have attributes
5082 /// specified in many different places, and we need to find and apply them all.
ProcessDeclAttributes(Scope * S,Decl * D,const Declarator & PD)5083 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
5084   // Apply decl attributes from the DeclSpec if present.
5085   if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
5086     ProcessDeclAttributeList(S, D, Attrs);
5087 
5088   // Walk the declarator structure, applying decl attributes that were in a type
5089   // position to the decl itself.  This handles cases like:
5090   //   int *__attr__(x)** D;
5091   // when X is a decl attribute.
5092   for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
5093     if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
5094       ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
5095 
5096   // Finally, apply any attributes on the decl itself.
5097   if (const AttributeList *Attrs = PD.getAttributes())
5098     ProcessDeclAttributeList(S, D, Attrs);
5099 }
5100 
5101 /// Is the given declaration allowed to use a forbidden type?
isForbiddenTypeAllowed(Sema & S,Decl * decl)5102 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
5103   // Private ivars are always okay.  Unfortunately, people don't
5104   // always properly make their ivars private, even in system headers.
5105   // Plus we need to make fields okay, too.
5106   // Function declarations in sys headers will be marked unavailable.
5107   if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
5108       !isa<FunctionDecl>(decl))
5109     return false;
5110 
5111   // Require it to be declared in a system header.
5112   return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
5113 }
5114 
5115 /// Handle a delayed forbidden-type diagnostic.
handleDelayedForbiddenType(Sema & S,DelayedDiagnostic & diag,Decl * decl)5116 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
5117                                        Decl *decl) {
5118   if (decl && isForbiddenTypeAllowed(S, decl)) {
5119     decl->addAttr(UnavailableAttr::CreateImplicit(S.Context,
5120                         "this system declaration uses an unsupported type",
5121                         diag.Loc));
5122     return;
5123   }
5124   if (S.getLangOpts().ObjCAutoRefCount)
5125     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
5126       // FIXME: we may want to suppress diagnostics for all
5127       // kind of forbidden type messages on unavailable functions.
5128       if (FD->hasAttr<UnavailableAttr>() &&
5129           diag.getForbiddenTypeDiagnostic() ==
5130           diag::err_arc_array_param_no_ownership) {
5131         diag.Triggered = true;
5132         return;
5133       }
5134     }
5135 
5136   S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
5137     << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
5138   diag.Triggered = true;
5139 }
5140 
5141 
isDeclDeprecated(Decl * D)5142 static bool isDeclDeprecated(Decl *D) {
5143   do {
5144     if (D->isDeprecated())
5145       return true;
5146     // A category implicitly has the availability of the interface.
5147     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5148       if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
5149         return Interface->isDeprecated();
5150   } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5151   return false;
5152 }
5153 
isDeclUnavailable(Decl * D)5154 static bool isDeclUnavailable(Decl *D) {
5155   do {
5156     if (D->isUnavailable())
5157       return true;
5158     // A category implicitly has the availability of the interface.
5159     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5160       if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
5161         return Interface->isUnavailable();
5162   } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5163   return false;
5164 }
5165 
DoEmitAvailabilityWarning(Sema & S,Sema::AvailabilityDiagnostic K,Decl * Ctx,const NamedDecl * D,StringRef Message,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,const ObjCPropertyDecl * ObjCProperty,bool ObjCPropertyAccess)5166 static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K,
5167                                       Decl *Ctx, const NamedDecl *D,
5168                                       StringRef Message, SourceLocation Loc,
5169                                       const ObjCInterfaceDecl *UnknownObjCClass,
5170                                       const ObjCPropertyDecl *ObjCProperty,
5171                                       bool ObjCPropertyAccess) {
5172   // Diagnostics for deprecated or unavailable.
5173   unsigned diag, diag_message, diag_fwdclass_message;
5174 
5175   // Matches 'diag::note_property_attribute' options.
5176   unsigned property_note_select;
5177 
5178   // Matches diag::note_availability_specified_here.
5179   unsigned available_here_select_kind;
5180 
5181   // Don't warn if our current context is deprecated or unavailable.
5182   switch (K) {
5183   case Sema::AD_Deprecation:
5184     if (isDeclDeprecated(Ctx))
5185       return;
5186     diag = !ObjCPropertyAccess ? diag::warn_deprecated
5187                                : diag::warn_property_method_deprecated;
5188     diag_message = diag::warn_deprecated_message;
5189     diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
5190     property_note_select = /* deprecated */ 0;
5191     available_here_select_kind = /* deprecated */ 2;
5192     break;
5193 
5194   case Sema::AD_Unavailable:
5195     if (isDeclUnavailable(Ctx))
5196       return;
5197     diag = !ObjCPropertyAccess ? diag::err_unavailable
5198                                : diag::err_property_method_unavailable;
5199     diag_message = diag::err_unavailable_message;
5200     diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
5201     property_note_select = /* unavailable */ 1;
5202     available_here_select_kind = /* unavailable */ 0;
5203     break;
5204 
5205   case Sema::AD_Partial:
5206     diag = diag::warn_partial_availability;
5207     diag_message = diag::warn_partial_message;
5208     diag_fwdclass_message = diag::warn_partial_fwdclass_message;
5209     property_note_select = /* partial */ 2;
5210     available_here_select_kind = /* partial */ 3;
5211     break;
5212   }
5213 
5214   if (!Message.empty()) {
5215     S.Diag(Loc, diag_message) << D << Message;
5216     if (ObjCProperty)
5217       S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5218           << ObjCProperty->getDeclName() << property_note_select;
5219   } else if (!UnknownObjCClass) {
5220     S.Diag(Loc, diag) << D;
5221     if (ObjCProperty)
5222       S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5223           << ObjCProperty->getDeclName() << property_note_select;
5224   } else {
5225     S.Diag(Loc, diag_fwdclass_message) << D;
5226     S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
5227   }
5228 
5229   S.Diag(D->getLocation(), diag::note_availability_specified_here)
5230       << D << available_here_select_kind;
5231   if (K == Sema::AD_Partial)
5232     S.Diag(Loc, diag::note_partial_availability_silence) << D;
5233 }
5234 
handleDelayedAvailabilityCheck(Sema & S,DelayedDiagnostic & DD,Decl * Ctx)5235 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
5236                                            Decl *Ctx) {
5237   assert(DD.Kind == DelayedDiagnostic::Deprecation ||
5238          DD.Kind == DelayedDiagnostic::Unavailable);
5239   Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation
5240                                         ? Sema::AD_Deprecation
5241                                         : Sema::AD_Unavailable;
5242   DD.Triggered = true;
5243   DoEmitAvailabilityWarning(
5244       S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc,
5245       DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
5246 }
5247 
PopParsingDeclaration(ParsingDeclState state,Decl * decl)5248 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
5249   assert(DelayedDiagnostics.getCurrentPool());
5250   DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
5251   DelayedDiagnostics.popWithoutEmitting(state);
5252 
5253   // When delaying diagnostics to run in the context of a parsed
5254   // declaration, we only want to actually emit anything if parsing
5255   // succeeds.
5256   if (!decl) return;
5257 
5258   // We emit all the active diagnostics in this pool or any of its
5259   // parents.  In general, we'll get one pool for the decl spec
5260   // and a child pool for each declarator; in a decl group like:
5261   //   deprecated_typedef foo, *bar, baz();
5262   // only the declarator pops will be passed decls.  This is correct;
5263   // we really do need to consider delayed diagnostics from the decl spec
5264   // for each of the different declarations.
5265   const DelayedDiagnosticPool *pool = &poppedPool;
5266   do {
5267     for (DelayedDiagnosticPool::pool_iterator
5268            i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
5269       // This const_cast is a bit lame.  Really, Triggered should be mutable.
5270       DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
5271       if (diag.Triggered)
5272         continue;
5273 
5274       switch (diag.Kind) {
5275       case DelayedDiagnostic::Deprecation:
5276       case DelayedDiagnostic::Unavailable:
5277         // Don't bother giving deprecation/unavailable diagnostics if
5278         // the decl is invalid.
5279         if (!decl->isInvalidDecl())
5280           handleDelayedAvailabilityCheck(*this, diag, decl);
5281         break;
5282 
5283       case DelayedDiagnostic::Access:
5284         HandleDelayedAccessCheck(diag, decl);
5285         break;
5286 
5287       case DelayedDiagnostic::ForbiddenType:
5288         handleDelayedForbiddenType(*this, diag, decl);
5289         break;
5290       }
5291     }
5292   } while ((pool = pool->getParent()));
5293 }
5294 
5295 /// Given a set of delayed diagnostics, re-emit them as if they had
5296 /// been delayed in the current context instead of in the given pool.
5297 /// Essentially, this just moves them to the current pool.
redelayDiagnostics(DelayedDiagnosticPool & pool)5298 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
5299   DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
5300   assert(curPool && "re-emitting in undelayed context not supported");
5301   curPool->steal(pool);
5302 }
5303 
EmitAvailabilityWarning(AvailabilityDiagnostic AD,NamedDecl * D,StringRef Message,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,const ObjCPropertyDecl * ObjCProperty,bool ObjCPropertyAccess)5304 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
5305                                    NamedDecl *D, StringRef Message,
5306                                    SourceLocation Loc,
5307                                    const ObjCInterfaceDecl *UnknownObjCClass,
5308                                    const ObjCPropertyDecl  *ObjCProperty,
5309                                    bool ObjCPropertyAccess) {
5310   // Delay if we're currently parsing a declaration.
5311   if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) {
5312     DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
5313         AD, Loc, D, UnknownObjCClass, ObjCProperty, Message,
5314         ObjCPropertyAccess));
5315     return;
5316   }
5317 
5318   Decl *Ctx = cast<Decl>(getCurLexicalContext());
5319   DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass,
5320                             ObjCProperty, ObjCPropertyAccess);
5321 }
5322