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