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