1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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 semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "Sema.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/ExprObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Lex/LiteralSupport.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Parse/DeclSpec.h"
25 #include "clang/Parse/Designator.h"
26 #include "clang/Parse/Scope.h"
27 using namespace clang;
28 
29 /// \brief Determine whether the use of this declaration is valid, and
30 /// emit any corresponding diagnostics.
31 ///
32 /// This routine diagnoses various problems with referencing
33 /// declarations that can occur when using a declaration. For example,
34 /// it might warn if a deprecated or unavailable declaration is being
35 /// used, or produce an error (and return true) if a C++0x deleted
36 /// function is being used.
37 ///
38 /// \returns true if there was an error (this declaration cannot be
39 /// referenced), false otherwise.
40 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
41   // See if the decl is deprecated.
42   if (D->getAttr<DeprecatedAttr>()) {
43     // Implementing deprecated stuff requires referencing deprecated
44     // stuff. Don't warn if we are implementing a deprecated
45     // construct.
46     bool isSilenced = false;
47 
48     if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49       // If this reference happens *in* a deprecated function or method, don't
50       // warn.
51       isSilenced = ND->getAttr<DeprecatedAttr>();
52 
53       // If this is an Objective-C method implementation, check to see if the
54       // method was deprecated on the declaration, not the definition.
55       if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56         // The semantic decl context of a ObjCMethodDecl is the
57         // ObjCImplementationDecl.
58         if (ObjCImplementationDecl *Impl
59               = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60 
61           MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
62                                                     MD->isInstanceMethod());
63           isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
64         }
65       }
66     }
67 
68     if (!isSilenced)
69       Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70   }
71 
72   // See if this is a deleted function.
73   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74     if (FD->isDeleted()) {
75       Diag(Loc, diag::err_deleted_function_use);
76       Diag(D->getLocation(), diag::note_unavailable_here) << true;
77       return true;
78     }
79   }
80 
81   // See if the decl is unavailable
82   if (D->getAttr<UnavailableAttr>()) {
83     Diag(Loc, diag::warn_unavailable) << D->getDeclName();
84     Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85   }
86 
87   return false;
88 }
89 
90 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
91 /// (and other functions in future), which have been declared with sentinel
92 /// attribute. It warns if call does not have the sentinel argument.
93 ///
94 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
95                                  Expr **Args, unsigned NumArgs)
96 {
97   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
98   if (!attr)
99     return;
100   int sentinelPos = attr->getSentinel();
101   int nullPos = attr->getNullPos();
102 
103   // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
104   // base class. Then we won't be needing two versions of the same code.
105   unsigned int i = 0;
106   bool warnNotEnoughArgs = false;
107   int isMethod = 0;
108   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
109     // skip over named parameters.
110     ObjCMethodDecl::param_iterator P, E = MD->param_end();
111     for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
112       if (nullPos)
113         --nullPos;
114       else
115         ++i;
116     }
117     warnNotEnoughArgs = (P != E || i >= NumArgs);
118     isMethod = 1;
119   }
120   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
121     // skip over named parameters.
122     ObjCMethodDecl::param_iterator P, E = FD->param_end();
123     for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124       if (nullPos)
125         --nullPos;
126       else
127         ++i;
128     }
129     warnNotEnoughArgs = (P != E || i >= NumArgs);
130   }
131   else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
132     // block or function pointer call.
133     QualType Ty = V->getType();
134     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
135       const FunctionType *FT = Ty->isFunctionPointerType()
136       ? Ty->getAsPointerType()->getPointeeType()->getAsFunctionType()
137       : Ty->getAsBlockPointerType()->getPointeeType()->getAsFunctionType();
138       if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
139         unsigned NumArgsInProto = Proto->getNumArgs();
140         unsigned k;
141         for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
142           if (nullPos)
143             --nullPos;
144           else
145             ++i;
146         }
147         warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
148       }
149       if (Ty->isBlockPointerType())
150         isMethod = 2;
151     }
152     else
153       return;
154   }
155   else
156     return;
157 
158   if (warnNotEnoughArgs) {
159     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
160     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
161     return;
162   }
163   int sentinel = i;
164   while (sentinelPos > 0 && i < NumArgs-1) {
165     --sentinelPos;
166     ++i;
167   }
168   if (sentinelPos > 0) {
169     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
170     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
171     return;
172   }
173   while (i < NumArgs-1) {
174     ++i;
175     ++sentinel;
176   }
177   Expr *sentinelExpr = Args[sentinel];
178   if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
179                        !sentinelExpr->isNullPointerConstant(Context))) {
180     Diag(Loc, diag::warn_missing_sentinel) << isMethod;
181     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
182   }
183   return;
184 }
185 
186 SourceRange Sema::getExprRange(ExprTy *E) const {
187   Expr *Ex = (Expr *)E;
188   return Ex? Ex->getSourceRange() : SourceRange();
189 }
190 
191 //===----------------------------------------------------------------------===//
192 //  Standard Promotions and Conversions
193 //===----------------------------------------------------------------------===//
194 
195 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
196 void Sema::DefaultFunctionArrayConversion(Expr *&E) {
197   QualType Ty = E->getType();
198   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
199 
200   if (Ty->isFunctionType())
201     ImpCastExprToType(E, Context.getPointerType(Ty));
202   else if (Ty->isArrayType()) {
203     // In C90 mode, arrays only promote to pointers if the array expression is
204     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
205     // type 'array of type' is converted to an expression that has type 'pointer
206     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
207     // that has type 'array of type' ...".  The relevant change is "an lvalue"
208     // (C90) to "an expression" (C99).
209     //
210     // C++ 4.2p1:
211     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
212     // T" can be converted to an rvalue of type "pointer to T".
213     //
214     if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
215         E->isLvalue(Context) == Expr::LV_Valid)
216       ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
217   }
218 }
219 
220 /// \brief Whether this is a promotable bitfield reference according
221 /// to C99 6.3.1.1p2, bullet 2.
222 ///
223 /// \returns the type this bit-field will promote to, or NULL if no
224 /// promotion occurs.
225 static QualType isPromotableBitField(Expr *E, ASTContext &Context) {
226   FieldDecl *Field = E->getBitField();
227   if (!Field)
228     return QualType();
229 
230   const BuiltinType *BT = Field->getType()->getAsBuiltinType();
231   if (!BT)
232     return QualType();
233 
234   if (BT->getKind() != BuiltinType::Bool &&
235       BT->getKind() != BuiltinType::Int &&
236       BT->getKind() != BuiltinType::UInt)
237     return QualType();
238 
239   llvm::APSInt BitWidthAP;
240   if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context))
241     return QualType();
242 
243   uint64_t BitWidth = BitWidthAP.getZExtValue();
244   uint64_t IntSize = Context.getTypeSize(Context.IntTy);
245   if (BitWidth < IntSize ||
246       (Field->getType()->isSignedIntegerType() && BitWidth == IntSize))
247     return Context.IntTy;
248 
249   if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType())
250     return Context.UnsignedIntTy;
251 
252   return QualType();
253 }
254 
255 /// UsualUnaryConversions - Performs various conversions that are common to most
256 /// operators (C99 6.3). The conversions of array and function types are
257 /// sometimes surpressed. For example, the array->pointer conversion doesn't
258 /// apply if the array is an argument to the sizeof or address (&) operators.
259 /// In these instances, this routine should *not* be called.
260 Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
261   QualType Ty = Expr->getType();
262   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
263 
264   // C99 6.3.1.1p2:
265   //
266   //   The following may be used in an expression wherever an int or
267   //   unsigned int may be used:
268   //     - an object or expression with an integer type whose integer
269   //       conversion rank is less than or equal to the rank of int
270   //       and unsigned int.
271   //     - A bit-field of type _Bool, int, signed int, or unsigned int.
272   //
273   //   If an int can represent all values of the original type, the
274   //   value is converted to an int; otherwise, it is converted to an
275   //   unsigned int. These are called the integer promotions. All
276   //   other types are unchanged by the integer promotions.
277   if (Ty->isPromotableIntegerType()) {
278     ImpCastExprToType(Expr, Context.IntTy);
279     return Expr;
280   } else {
281     QualType T = isPromotableBitField(Expr, Context);
282     if (!T.isNull()) {
283       ImpCastExprToType(Expr, T);
284       return Expr;
285     }
286   }
287 
288   DefaultFunctionArrayConversion(Expr);
289   return Expr;
290 }
291 
292 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
293 /// do not have a prototype. Arguments that have type float are promoted to
294 /// double. All other argument types are converted by UsualUnaryConversions().
295 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
296   QualType Ty = Expr->getType();
297   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
298 
299   // If this is a 'float' (CVR qualified or typedef) promote to double.
300   if (const BuiltinType *BT = Ty->getAsBuiltinType())
301     if (BT->getKind() == BuiltinType::Float)
302       return ImpCastExprToType(Expr, Context.DoubleTy);
303 
304   UsualUnaryConversions(Expr);
305 }
306 
307 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
308 /// will warn if the resulting type is not a POD type, and rejects ObjC
309 /// interfaces passed by value.  This returns true if the argument type is
310 /// completely illegal.
311 bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
312   DefaultArgumentPromotion(Expr);
313 
314   if (Expr->getType()->isObjCInterfaceType()) {
315     Diag(Expr->getLocStart(),
316          diag::err_cannot_pass_objc_interface_to_vararg)
317       << Expr->getType() << CT;
318     return true;
319   }
320 
321   if (!Expr->getType()->isPODType())
322     Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
323       << Expr->getType() << CT;
324 
325   return false;
326 }
327 
328 
329 /// UsualArithmeticConversions - Performs various conversions that are common to
330 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
331 /// routine returns the first non-arithmetic type found. The client is
332 /// responsible for emitting appropriate error diagnostics.
333 /// FIXME: verify the conversion rules for "complex int" are consistent with
334 /// GCC.
335 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
336                                           bool isCompAssign) {
337   if (!isCompAssign)
338     UsualUnaryConversions(lhsExpr);
339 
340   UsualUnaryConversions(rhsExpr);
341 
342   // For conversion purposes, we ignore any qualifiers.
343   // For example, "const float" and "float" are equivalent.
344   QualType lhs =
345     Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
346   QualType rhs =
347     Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
348 
349   // If both types are identical, no conversion is needed.
350   if (lhs == rhs)
351     return lhs;
352 
353   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
354   // The caller can deal with this (e.g. pointer + int).
355   if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
356     return lhs;
357 
358   // Perform bitfield promotions.
359   QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context);
360   if (!LHSBitfieldPromoteTy.isNull())
361     lhs = LHSBitfieldPromoteTy;
362   QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context);
363   if (!RHSBitfieldPromoteTy.isNull())
364     rhs = RHSBitfieldPromoteTy;
365 
366   QualType destType = UsualArithmeticConversionsType(lhs, rhs);
367   if (!isCompAssign)
368     ImpCastExprToType(lhsExpr, destType);
369   ImpCastExprToType(rhsExpr, destType);
370   return destType;
371 }
372 
373 QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
374   // Perform the usual unary conversions. We do this early so that
375   // integral promotions to "int" can allow us to exit early, in the
376   // lhs == rhs check. Also, for conversion purposes, we ignore any
377   // qualifiers.  For example, "const float" and "float" are
378   // equivalent.
379   if (lhs->isPromotableIntegerType())
380     lhs = Context.IntTy;
381   else
382     lhs = lhs.getUnqualifiedType();
383   if (rhs->isPromotableIntegerType())
384     rhs = Context.IntTy;
385   else
386     rhs = rhs.getUnqualifiedType();
387 
388   // If both types are identical, no conversion is needed.
389   if (lhs == rhs)
390     return lhs;
391 
392   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
393   // The caller can deal with this (e.g. pointer + int).
394   if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
395     return lhs;
396 
397   // At this point, we have two different arithmetic types.
398 
399   // Handle complex types first (C99 6.3.1.8p1).
400   if (lhs->isComplexType() || rhs->isComplexType()) {
401     // if we have an integer operand, the result is the complex type.
402     if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
403       // convert the rhs to the lhs complex type.
404       return lhs;
405     }
406     if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
407       // convert the lhs to the rhs complex type.
408       return rhs;
409     }
410     // This handles complex/complex, complex/float, or float/complex.
411     // When both operands are complex, the shorter operand is converted to the
412     // type of the longer, and that is the type of the result. This corresponds
413     // to what is done when combining two real floating-point operands.
414     // The fun begins when size promotion occur across type domains.
415     // From H&S 6.3.4: When one operand is complex and the other is a real
416     // floating-point type, the less precise type is converted, within it's
417     // real or complex domain, to the precision of the other type. For example,
418     // when combining a "long double" with a "double _Complex", the
419     // "double _Complex" is promoted to "long double _Complex".
420     int result = Context.getFloatingTypeOrder(lhs, rhs);
421 
422     if (result > 0) { // The left side is bigger, convert rhs.
423       rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
424     } else if (result < 0) { // The right side is bigger, convert lhs.
425       lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
426     }
427     // At this point, lhs and rhs have the same rank/size. Now, make sure the
428     // domains match. This is a requirement for our implementation, C99
429     // does not require this promotion.
430     if (lhs != rhs) { // Domains don't match, we have complex/float mix.
431       if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
432         return rhs;
433       } else { // handle "_Complex double, double".
434         return lhs;
435       }
436     }
437     return lhs; // The domain/size match exactly.
438   }
439   // Now handle "real" floating types (i.e. float, double, long double).
440   if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
441     // if we have an integer operand, the result is the real floating type.
442     if (rhs->isIntegerType()) {
443       // convert rhs to the lhs floating point type.
444       return lhs;
445     }
446     if (rhs->isComplexIntegerType()) {
447       // convert rhs to the complex floating point type.
448       return Context.getComplexType(lhs);
449     }
450     if (lhs->isIntegerType()) {
451       // convert lhs to the rhs floating point type.
452       return rhs;
453     }
454     if (lhs->isComplexIntegerType()) {
455       // convert lhs to the complex floating point type.
456       return Context.getComplexType(rhs);
457     }
458     // We have two real floating types, float/complex combos were handled above.
459     // Convert the smaller operand to the bigger result.
460     int result = Context.getFloatingTypeOrder(lhs, rhs);
461     if (result > 0) // convert the rhs
462       return lhs;
463     assert(result < 0 && "illegal float comparison");
464     return rhs;   // convert the lhs
465   }
466   if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
467     // Handle GCC complex int extension.
468     const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
469     const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
470 
471     if (lhsComplexInt && rhsComplexInt) {
472       if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
473                                       rhsComplexInt->getElementType()) >= 0)
474         return lhs; // convert the rhs
475       return rhs;
476     } else if (lhsComplexInt && rhs->isIntegerType()) {
477       // convert the rhs to the lhs complex type.
478       return lhs;
479     } else if (rhsComplexInt && lhs->isIntegerType()) {
480       // convert the lhs to the rhs complex type.
481       return rhs;
482     }
483   }
484   // Finally, we have two differing integer types.
485   // The rules for this case are in C99 6.3.1.8
486   int compare = Context.getIntegerTypeOrder(lhs, rhs);
487   bool lhsSigned = lhs->isSignedIntegerType(),
488        rhsSigned = rhs->isSignedIntegerType();
489   QualType destType;
490   if (lhsSigned == rhsSigned) {
491     // Same signedness; use the higher-ranked type
492     destType = compare >= 0 ? lhs : rhs;
493   } else if (compare != (lhsSigned ? 1 : -1)) {
494     // The unsigned type has greater than or equal rank to the
495     // signed type, so use the unsigned type
496     destType = lhsSigned ? rhs : lhs;
497   } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
498     // The two types are different widths; if we are here, that
499     // means the signed type is larger than the unsigned type, so
500     // use the signed type.
501     destType = lhsSigned ? lhs : rhs;
502   } else {
503     // The signed type is higher-ranked than the unsigned type,
504     // but isn't actually any bigger (like unsigned int and long
505     // on most 32-bit systems).  Use the unsigned type corresponding
506     // to the signed type.
507     destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
508   }
509   return destType;
510 }
511 
512 //===----------------------------------------------------------------------===//
513 //  Semantic Analysis for various Expression Types
514 //===----------------------------------------------------------------------===//
515 
516 
517 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
518 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
519 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
520 /// multiple tokens.  However, the common case is that StringToks points to one
521 /// string.
522 ///
523 Action::OwningExprResult
524 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
525   assert(NumStringToks && "Must have at least one string!");
526 
527   StringLiteralParser Literal(StringToks, NumStringToks, PP);
528   if (Literal.hadError)
529     return ExprError();
530 
531   llvm::SmallVector<SourceLocation, 4> StringTokLocs;
532   for (unsigned i = 0; i != NumStringToks; ++i)
533     StringTokLocs.push_back(StringToks[i].getLocation());
534 
535   QualType StrTy = Context.CharTy;
536   if (Literal.AnyWide) StrTy = Context.getWCharType();
537   if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
538 
539   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
540   if (getLangOptions().CPlusPlus)
541     StrTy.addConst();
542 
543   // Get an array type for the string, according to C99 6.4.5.  This includes
544   // the nul terminator character as well as the string length for pascal
545   // strings.
546   StrTy = Context.getConstantArrayType(StrTy,
547                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
548                                        ArrayType::Normal, 0);
549 
550   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
551   return Owned(StringLiteral::Create(Context, Literal.GetString(),
552                                      Literal.GetStringLength(),
553                                      Literal.AnyWide, StrTy,
554                                      &StringTokLocs[0],
555                                      StringTokLocs.size()));
556 }
557 
558 /// ShouldSnapshotBlockValueReference - Return true if a reference inside of
559 /// CurBlock to VD should cause it to be snapshotted (as we do for auto
560 /// variables defined outside the block) or false if this is not needed (e.g.
561 /// for values inside the block or for globals).
562 ///
563 /// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
564 /// up-to-date.
565 ///
566 static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
567                                               ValueDecl *VD) {
568   // If the value is defined inside the block, we couldn't snapshot it even if
569   // we wanted to.
570   if (CurBlock->TheDecl == VD->getDeclContext())
571     return false;
572 
573   // If this is an enum constant or function, it is constant, don't snapshot.
574   if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
575     return false;
576 
577   // If this is a reference to an extern, static, or global variable, no need to
578   // snapshot it.
579   // FIXME: What about 'const' variables in C++?
580   if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
581     if (!Var->hasLocalStorage())
582       return false;
583 
584   // Blocks that have these can't be constant.
585   CurBlock->hasBlockDeclRefExprs = true;
586 
587   // If we have nested blocks, the decl may be declared in an outer block (in
588   // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
589   // be defined outside all of the current blocks (in which case the blocks do
590   // all get the bit).  Walk the nesting chain.
591   for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
592        NextBlock = NextBlock->PrevBlockInfo) {
593     // If we found the defining block for the variable, don't mark the block as
594     // having a reference outside it.
595     if (NextBlock->TheDecl == VD->getDeclContext())
596       break;
597 
598     // Otherwise, the DeclRef from the inner block causes the outer one to need
599     // a snapshot as well.
600     NextBlock->hasBlockDeclRefExprs = true;
601   }
602 
603   return true;
604 }
605 
606 
607 
608 /// ActOnIdentifierExpr - The parser read an identifier in expression context,
609 /// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
610 /// identifier is used in a function call context.
611 /// SS is only used for a C++ qualified-id (foo::bar) to indicate the
612 /// class or namespace that the identifier must be a member of.
613 Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
614                                                  IdentifierInfo &II,
615                                                  bool HasTrailingLParen,
616                                                  const CXXScopeSpec *SS,
617                                                  bool isAddressOfOperand) {
618   return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
619                                   isAddressOfOperand);
620 }
621 
622 /// BuildDeclRefExpr - Build either a DeclRefExpr or a
623 /// QualifiedDeclRefExpr based on whether or not SS is a
624 /// nested-name-specifier.
625 Sema::OwningExprResult
626 Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
627                        bool TypeDependent, bool ValueDependent,
628                        const CXXScopeSpec *SS) {
629   if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
630     Diag(Loc,
631          diag::err_auto_variable_cannot_appear_in_own_initializer)
632       << D->getDeclName();
633     return ExprError();
634   }
635 
636   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
637     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
638       if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
639         if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
640           Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
641             << D->getIdentifier() << FD->getDeclName();
642           Diag(D->getLocation(), diag::note_local_variable_declared_here)
643             << D->getIdentifier();
644           return ExprError();
645         }
646       }
647     }
648   }
649 
650   MarkDeclarationReferenced(Loc, D);
651 
652   Expr *E;
653   if (SS && !SS->isEmpty()) {
654     E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
655                                           ValueDependent, SS->getRange(),
656                   static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
657   } else
658     E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
659 
660   return Owned(E);
661 }
662 
663 /// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
664 /// variable corresponding to the anonymous union or struct whose type
665 /// is Record.
666 static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
667                                              RecordDecl *Record) {
668   assert(Record->isAnonymousStructOrUnion() &&
669          "Record must be an anonymous struct or union!");
670 
671   // FIXME: Once Decls are directly linked together, this will be an O(1)
672   // operation rather than a slow walk through DeclContext's vector (which
673   // itself will be eliminated). DeclGroups might make this even better.
674   DeclContext *Ctx = Record->getDeclContext();
675   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
676                                DEnd = Ctx->decls_end();
677        D != DEnd; ++D) {
678     if (*D == Record) {
679       // The object for the anonymous struct/union directly
680       // follows its type in the list of declarations.
681       ++D;
682       assert(D != DEnd && "Missing object for anonymous record");
683       assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
684       return *D;
685     }
686   }
687 
688   assert(false && "Missing object for anonymous record");
689   return 0;
690 }
691 
692 /// \brief Given a field that represents a member of an anonymous
693 /// struct/union, build the path from that field's context to the
694 /// actual member.
695 ///
696 /// Construct the sequence of field member references we'll have to
697 /// perform to get to the field in the anonymous union/struct. The
698 /// list of members is built from the field outward, so traverse it
699 /// backwards to go from an object in the current context to the field
700 /// we found.
701 ///
702 /// \returns The variable from which the field access should begin,
703 /// for an anonymous struct/union that is not a member of another
704 /// class. Otherwise, returns NULL.
705 VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
706                                    llvm::SmallVectorImpl<FieldDecl *> &Path) {
707   assert(Field->getDeclContext()->isRecord() &&
708          cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
709          && "Field must be stored inside an anonymous struct or union");
710 
711   Path.push_back(Field);
712   VarDecl *BaseObject = 0;
713   DeclContext *Ctx = Field->getDeclContext();
714   do {
715     RecordDecl *Record = cast<RecordDecl>(Ctx);
716     Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
717     if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
718       Path.push_back(AnonField);
719     else {
720       BaseObject = cast<VarDecl>(AnonObject);
721       break;
722     }
723     Ctx = Ctx->getParent();
724   } while (Ctx->isRecord() &&
725            cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
726 
727   return BaseObject;
728 }
729 
730 Sema::OwningExprResult
731 Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
732                                                FieldDecl *Field,
733                                                Expr *BaseObjectExpr,
734                                                SourceLocation OpLoc) {
735   llvm::SmallVector<FieldDecl *, 4> AnonFields;
736   VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
737                                                             AnonFields);
738 
739   // Build the expression that refers to the base object, from
740   // which we will build a sequence of member references to each
741   // of the anonymous union objects and, eventually, the field we
742   // found via name lookup.
743   bool BaseObjectIsPointer = false;
744   unsigned ExtraQuals = 0;
745   if (BaseObject) {
746     // BaseObject is an anonymous struct/union variable (and is,
747     // therefore, not part of another non-anonymous record).
748     if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
749     MarkDeclarationReferenced(Loc, BaseObject);
750     BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
751                                                SourceLocation());
752     ExtraQuals
753       = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
754   } else if (BaseObjectExpr) {
755     // The caller provided the base object expression. Determine
756     // whether its a pointer and whether it adds any qualifiers to the
757     // anonymous struct/union fields we're looking into.
758     QualType ObjectType = BaseObjectExpr->getType();
759     if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
760       BaseObjectIsPointer = true;
761       ObjectType = ObjectPtr->getPointeeType();
762     }
763     ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
764   } else {
765     // We've found a member of an anonymous struct/union that is
766     // inside a non-anonymous struct/union, so in a well-formed
767     // program our base object expression is "this".
768     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
769       if (!MD->isStatic()) {
770         QualType AnonFieldType
771           = Context.getTagDeclType(
772                      cast<RecordDecl>(AnonFields.back()->getDeclContext()));
773         QualType ThisType = Context.getTagDeclType(MD->getParent());
774         if ((Context.getCanonicalType(AnonFieldType)
775                == Context.getCanonicalType(ThisType)) ||
776             IsDerivedFrom(ThisType, AnonFieldType)) {
777           // Our base object expression is "this".
778           BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
779                                                      MD->getThisType(Context));
780           BaseObjectIsPointer = true;
781         }
782       } else {
783         return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
784           << Field->getDeclName());
785       }
786       ExtraQuals = MD->getTypeQualifiers();
787     }
788 
789     if (!BaseObjectExpr)
790       return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
791         << Field->getDeclName());
792   }
793 
794   // Build the implicit member references to the field of the
795   // anonymous struct/union.
796   Expr *Result = BaseObjectExpr;
797   for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
798          FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
799        FI != FIEnd; ++FI) {
800     QualType MemberType = (*FI)->getType();
801     if (!(*FI)->isMutable()) {
802       unsigned combinedQualifiers
803         = MemberType.getCVRQualifiers() | ExtraQuals;
804       MemberType = MemberType.getQualifiedType(combinedQualifiers);
805     }
806     MarkDeclarationReferenced(Loc, *FI);
807     Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
808                                       OpLoc, MemberType);
809     BaseObjectIsPointer = false;
810     ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
811   }
812 
813   return Owned(Result);
814 }
815 
816 /// ActOnDeclarationNameExpr - The parser has read some kind of name
817 /// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
818 /// performs lookup on that name and returns an expression that refers
819 /// to that name. This routine isn't directly called from the parser,
820 /// because the parser doesn't know about DeclarationName. Rather,
821 /// this routine is called by ActOnIdentifierExpr,
822 /// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
823 /// which form the DeclarationName from the corresponding syntactic
824 /// forms.
825 ///
826 /// HasTrailingLParen indicates whether this identifier is used in a
827 /// function call context.  LookupCtx is only used for a C++
828 /// qualified-id (foo::bar) to indicate the class or namespace that
829 /// the identifier must be a member of.
830 ///
831 /// isAddressOfOperand means that this expression is the direct operand
832 /// of an address-of operator. This matters because this is the only
833 /// situation where a qualified name referencing a non-static member may
834 /// appear outside a member function of this class.
835 Sema::OwningExprResult
836 Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
837                                DeclarationName Name, bool HasTrailingLParen,
838                                const CXXScopeSpec *SS,
839                                bool isAddressOfOperand) {
840   // Could be enum-constant, value decl, instance variable, etc.
841   if (SS && SS->isInvalid())
842     return ExprError();
843 
844   // C++ [temp.dep.expr]p3:
845   //   An id-expression is type-dependent if it contains:
846   //     -- a nested-name-specifier that contains a class-name that
847   //        names a dependent type.
848   // FIXME: Member of the current instantiation.
849   if (SS && isDependentScopeSpecifier(*SS)) {
850     return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
851                                                      Loc, SS->getRange(),
852                 static_cast<NestedNameSpecifier *>(SS->getScopeRep())));
853   }
854 
855   LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
856                                          false, true, Loc);
857 
858   if (Lookup.isAmbiguous()) {
859     DiagnoseAmbiguousLookup(Lookup, Name, Loc,
860                             SS && SS->isSet() ? SS->getRange()
861                                               : SourceRange());
862     return ExprError();
863   }
864 
865   NamedDecl *D = Lookup.getAsDecl();
866 
867   // If this reference is in an Objective-C method, then ivar lookup happens as
868   // well.
869   IdentifierInfo *II = Name.getAsIdentifierInfo();
870   if (II && getCurMethodDecl()) {
871     // There are two cases to handle here.  1) scoped lookup could have failed,
872     // in which case we should look for an ivar.  2) scoped lookup could have
873     // found a decl, but that decl is outside the current instance method (i.e.
874     // a global variable).  In these two cases, we do a lookup for an ivar with
875     // this name, if the lookup sucedes, we replace it our current decl.
876     if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
877       ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
878       ObjCInterfaceDecl *ClassDeclared;
879       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
880         // Check if referencing a field with __attribute__((deprecated)).
881         if (DiagnoseUseOfDecl(IV, Loc))
882           return ExprError();
883 
884         // If we're referencing an invalid decl, just return this as a silent
885         // error node.  The error diagnostic was already emitted on the decl.
886         if (IV->isInvalidDecl())
887           return ExprError();
888 
889         bool IsClsMethod = getCurMethodDecl()->isClassMethod();
890         // If a class method attemps to use a free standing ivar, this is
891         // an error.
892         if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
893            return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
894                            << IV->getDeclName());
895         // If a class method uses a global variable, even if an ivar with
896         // same name exists, use the global.
897         if (!IsClsMethod) {
898           if (IV->getAccessControl() == ObjCIvarDecl::Private &&
899               ClassDeclared != IFace)
900            Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
901           // FIXME: This should use a new expr for a direct reference, don't
902           // turn this into Self->ivar, just return a BareIVarExpr or something.
903           IdentifierInfo &II = Context.Idents.get("self");
904           OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
905           MarkDeclarationReferenced(Loc, IV);
906           return Owned(new (Context)
907                        ObjCIvarRefExpr(IV, IV->getType(), Loc,
908                                        SelfExpr.takeAs<Expr>(), true, true));
909         }
910       }
911     }
912     else if (getCurMethodDecl()->isInstanceMethod()) {
913       // We should warn if a local variable hides an ivar.
914       ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
915       ObjCInterfaceDecl *ClassDeclared;
916       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
917         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
918             IFace == ClassDeclared)
919           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
920       }
921     }
922     // Needed to implement property "super.method" notation.
923     if (D == 0 && II->isStr("super")) {
924       QualType T;
925 
926       if (getCurMethodDecl()->isInstanceMethod())
927         T = Context.getPointerType(Context.getObjCInterfaceType(
928                                    getCurMethodDecl()->getClassInterface()));
929       else
930         T = Context.getObjCClassType();
931       return Owned(new (Context) ObjCSuperExpr(Loc, T));
932     }
933   }
934 
935   // Determine whether this name might be a candidate for
936   // argument-dependent lookup.
937   bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
938              HasTrailingLParen;
939 
940   if (ADL && D == 0) {
941     // We've seen something of the form
942     //
943     //   identifier(
944     //
945     // and we did not find any entity by the name
946     // "identifier". However, this identifier is still subject to
947     // argument-dependent lookup, so keep track of the name.
948     return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
949                                                           Context.OverloadTy,
950                                                           Loc));
951   }
952 
953   if (D == 0) {
954     // Otherwise, this could be an implicitly declared function reference (legal
955     // in C90, extension in C99).
956     if (HasTrailingLParen && II &&
957         !getLangOptions().CPlusPlus) // Not in C++.
958       D = ImplicitlyDefineFunction(Loc, *II, S);
959     else {
960       // If this name wasn't predeclared and if this is not a function call,
961       // diagnose the problem.
962       if (SS && !SS->isEmpty())
963         return ExprError(Diag(Loc, diag::err_typecheck_no_member)
964           << Name << SS->getRange());
965       else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
966                Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
967         return ExprError(Diag(Loc, diag::err_undeclared_use)
968           << Name.getAsString());
969       else
970         return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
971     }
972   }
973 
974   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
975     // Warn about constructs like:
976     //   if (void *X = foo()) { ... } else { X }.
977     // In the else block, the pointer is always false.
978 
979     // FIXME: In a template instantiation, we don't have scope
980     // information to check this property.
981     if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
982       Scope *CheckS = S;
983       while (CheckS) {
984         if (CheckS->isWithinElse() &&
985             CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
986           if (Var->getType()->isBooleanType())
987             ExprError(Diag(Loc, diag::warn_value_always_false)
988                       << Var->getDeclName());
989           else
990             ExprError(Diag(Loc, diag::warn_value_always_zero)
991                       << Var->getDeclName());
992           break;
993         }
994 
995         // Move up one more control parent to check again.
996         CheckS = CheckS->getControlParent();
997         if (CheckS)
998           CheckS = CheckS->getParent();
999       }
1000     }
1001   } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
1002     if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1003       // C99 DR 316 says that, if a function type comes from a
1004       // function definition (without a prototype), that type is only
1005       // used for checking compatibility. Therefore, when referencing
1006       // the function, we pretend that we don't have the full function
1007       // type.
1008       if (DiagnoseUseOfDecl(Func, Loc))
1009         return ExprError();
1010 
1011       QualType T = Func->getType();
1012       QualType NoProtoType = T;
1013       if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1014         NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
1015       return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
1016     }
1017   }
1018 
1019   return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
1020 }
1021 
1022 /// \brief Complete semantic analysis for a reference to the given declaration.
1023 Sema::OwningExprResult
1024 Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
1025                                bool HasTrailingLParen,
1026                                const CXXScopeSpec *SS,
1027                                bool isAddressOfOperand) {
1028   assert(D && "Cannot refer to a NULL declaration");
1029   DeclarationName Name = D->getDeclName();
1030 
1031   // If this is an expression of the form &Class::member, don't build an
1032   // implicit member ref, because we want a pointer to the member in general,
1033   // not any specific instance's member.
1034   if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
1035     DeclContext *DC = computeDeclContext(*SS);
1036     if (D && isa<CXXRecordDecl>(DC)) {
1037       QualType DType;
1038       if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1039         DType = FD->getType().getNonReferenceType();
1040       } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1041         DType = Method->getType();
1042       } else if (isa<OverloadedFunctionDecl>(D)) {
1043         DType = Context.OverloadTy;
1044       }
1045       // Could be an inner type. That's diagnosed below, so ignore it here.
1046       if (!DType.isNull()) {
1047         // The pointer is type- and value-dependent if it points into something
1048         // dependent.
1049         bool Dependent = DC->isDependentContext();
1050         return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
1051       }
1052     }
1053   }
1054 
1055   // We may have found a field within an anonymous union or struct
1056   // (C++ [class.union]).
1057   if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
1058     if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1059       return BuildAnonymousStructUnionMemberReference(Loc, FD);
1060 
1061   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1062     if (!MD->isStatic()) {
1063       // C++ [class.mfct.nonstatic]p2:
1064       //   [...] if name lookup (3.4.1) resolves the name in the
1065       //   id-expression to a nonstatic nontype member of class X or of
1066       //   a base class of X, the id-expression is transformed into a
1067       //   class member access expression (5.2.5) using (*this) (9.3.2)
1068       //   as the postfix-expression to the left of the '.' operator.
1069       DeclContext *Ctx = 0;
1070       QualType MemberType;
1071       if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1072         Ctx = FD->getDeclContext();
1073         MemberType = FD->getType();
1074 
1075         if (const ReferenceType *RefType = MemberType->getAsReferenceType())
1076           MemberType = RefType->getPointeeType();
1077         else if (!FD->isMutable()) {
1078           unsigned combinedQualifiers
1079             = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
1080           MemberType = MemberType.getQualifiedType(combinedQualifiers);
1081         }
1082       } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1083         if (!Method->isStatic()) {
1084           Ctx = Method->getParent();
1085           MemberType = Method->getType();
1086         }
1087       } else if (OverloadedFunctionDecl *Ovl
1088                    = dyn_cast<OverloadedFunctionDecl>(D)) {
1089         for (OverloadedFunctionDecl::function_iterator
1090                Func = Ovl->function_begin(),
1091                FuncEnd = Ovl->function_end();
1092              Func != FuncEnd; ++Func) {
1093           if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
1094             if (!DMethod->isStatic()) {
1095               Ctx = Ovl->getDeclContext();
1096               MemberType = Context.OverloadTy;
1097               break;
1098             }
1099         }
1100       }
1101 
1102       if (Ctx && Ctx->isRecord()) {
1103         QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
1104         QualType ThisType = Context.getTagDeclType(MD->getParent());
1105         if ((Context.getCanonicalType(CtxType)
1106                == Context.getCanonicalType(ThisType)) ||
1107             IsDerivedFrom(ThisType, CtxType)) {
1108           // Build the implicit member access expression.
1109           Expr *This = new (Context) CXXThisExpr(SourceLocation(),
1110                                                  MD->getThisType(Context));
1111           MarkDeclarationReferenced(Loc, D);
1112           return Owned(new (Context) MemberExpr(This, true, D,
1113                                                 Loc, MemberType));
1114         }
1115       }
1116     }
1117   }
1118 
1119   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1120     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1121       if (MD->isStatic())
1122         // "invalid use of member 'x' in static member function"
1123         return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1124           << FD->getDeclName());
1125     }
1126 
1127     // Any other ways we could have found the field in a well-formed
1128     // program would have been turned into implicit member expressions
1129     // above.
1130     return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1131       << FD->getDeclName());
1132   }
1133 
1134   if (isa<TypedefDecl>(D))
1135     return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
1136   if (isa<ObjCInterfaceDecl>(D))
1137     return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
1138   if (isa<NamespaceDecl>(D))
1139     return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
1140 
1141   // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
1142   if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
1143     return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1144                            false, false, SS);
1145   else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1146     return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1147                             false, false, SS);
1148   ValueDecl *VD = cast<ValueDecl>(D);
1149 
1150   // Check whether this declaration can be used. Note that we suppress
1151   // this check when we're going to perform argument-dependent lookup
1152   // on this function name, because this might not be the function
1153   // that overload resolution actually selects.
1154   bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1155              HasTrailingLParen;
1156   if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1157     return ExprError();
1158 
1159   // Only create DeclRefExpr's for valid Decl's.
1160   if (VD->isInvalidDecl())
1161     return ExprError();
1162 
1163   // If the identifier reference is inside a block, and it refers to a value
1164   // that is outside the block, create a BlockDeclRefExpr instead of a
1165   // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
1166   // the block is formed.
1167   //
1168   // We do not do this for things like enum constants, global variables, etc,
1169   // as they do not get snapshotted.
1170   //
1171   if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
1172     MarkDeclarationReferenced(Loc, VD);
1173     QualType ExprTy = VD->getType().getNonReferenceType();
1174     // The BlocksAttr indicates the variable is bound by-reference.
1175     if (VD->getAttr<BlocksAttr>())
1176       return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
1177     // This is to record that a 'const' was actually synthesize and added.
1178     bool constAdded = !ExprTy.isConstQualified();
1179     // Variable will be bound by-copy, make it const within the closure.
1180 
1181     ExprTy.addConst();
1182     return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1183                                                 constAdded));
1184   }
1185   // If this reference is not in a block or if the referenced variable is
1186   // within the block, create a normal DeclRefExpr.
1187 
1188   bool TypeDependent = false;
1189   bool ValueDependent = false;
1190   if (getLangOptions().CPlusPlus) {
1191     // C++ [temp.dep.expr]p3:
1192     //   An id-expression is type-dependent if it contains:
1193     //     - an identifier that was declared with a dependent type,
1194     if (VD->getType()->isDependentType())
1195       TypeDependent = true;
1196     //     - FIXME: a template-id that is dependent,
1197     //     - a conversion-function-id that specifies a dependent type,
1198     else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1199              Name.getCXXNameType()->isDependentType())
1200       TypeDependent = true;
1201     //     - a nested-name-specifier that contains a class-name that
1202     //       names a dependent type.
1203     else if (SS && !SS->isEmpty()) {
1204       for (DeclContext *DC = computeDeclContext(*SS);
1205            DC; DC = DC->getParent()) {
1206         // FIXME: could stop early at namespace scope.
1207         if (DC->isRecord()) {
1208           CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1209           if (Context.getTypeDeclType(Record)->isDependentType()) {
1210             TypeDependent = true;
1211             break;
1212           }
1213         }
1214       }
1215     }
1216 
1217     // C++ [temp.dep.constexpr]p2:
1218     //
1219     //   An identifier is value-dependent if it is:
1220     //     - a name declared with a dependent type,
1221     if (TypeDependent)
1222       ValueDependent = true;
1223     //     - the name of a non-type template parameter,
1224     else if (isa<NonTypeTemplateParmDecl>(VD))
1225       ValueDependent = true;
1226     //    - a constant with integral or enumeration type and is
1227     //      initialized with an expression that is value-dependent
1228     else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1229       if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1230           Dcl->getInit()) {
1231         ValueDependent = Dcl->getInit()->isValueDependent();
1232       }
1233     }
1234   }
1235 
1236   return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1237                           TypeDependent, ValueDependent, SS);
1238 }
1239 
1240 Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1241                                                  tok::TokenKind Kind) {
1242   PredefinedExpr::IdentType IT;
1243 
1244   switch (Kind) {
1245   default: assert(0 && "Unknown simple primary expr!");
1246   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1247   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1248   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
1249   }
1250 
1251   // Pre-defined identifiers are of type char[x], where x is the length of the
1252   // string.
1253   unsigned Length;
1254   if (FunctionDecl *FD = getCurFunctionDecl())
1255     Length = FD->getIdentifier()->getLength();
1256   else if (ObjCMethodDecl *MD = getCurMethodDecl())
1257     Length = MD->getSynthesizedMethodSize();
1258   else {
1259     Diag(Loc, diag::ext_predef_outside_function);
1260     // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1261     Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1262   }
1263 
1264 
1265   llvm::APInt LengthI(32, Length + 1);
1266   QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
1267   ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1268   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1269 }
1270 
1271 Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1272   llvm::SmallString<16> CharBuffer;
1273   CharBuffer.resize(Tok.getLength());
1274   const char *ThisTokBegin = &CharBuffer[0];
1275   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1276 
1277   CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1278                             Tok.getLocation(), PP);
1279   if (Literal.hadError())
1280     return ExprError();
1281 
1282   QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1283 
1284   return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1285                                               Literal.isWide(),
1286                                               type, Tok.getLocation()));
1287 }
1288 
1289 Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1290   // Fast path for a single digit (which is quite common).  A single digit
1291   // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1292   if (Tok.getLength() == 1) {
1293     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1294     unsigned IntSize = Context.Target.getIntWidth();
1295     return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1296                     Context.IntTy, Tok.getLocation()));
1297   }
1298 
1299   llvm::SmallString<512> IntegerBuffer;
1300   // Add padding so that NumericLiteralParser can overread by one character.
1301   IntegerBuffer.resize(Tok.getLength()+1);
1302   const char *ThisTokBegin = &IntegerBuffer[0];
1303 
1304   // Get the spelling of the token, which eliminates trigraphs, etc.
1305   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1306 
1307   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1308                                Tok.getLocation(), PP);
1309   if (Literal.hadError)
1310     return ExprError();
1311 
1312   Expr *Res;
1313 
1314   if (Literal.isFloatingLiteral()) {
1315     QualType Ty;
1316     if (Literal.isFloat)
1317       Ty = Context.FloatTy;
1318     else if (!Literal.isLong)
1319       Ty = Context.DoubleTy;
1320     else
1321       Ty = Context.LongDoubleTy;
1322 
1323     const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1324 
1325     // isExact will be set by GetFloatValue().
1326     bool isExact = false;
1327     llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1328     Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
1329 
1330   } else if (!Literal.isIntegerLiteral()) {
1331     return ExprError();
1332   } else {
1333     QualType Ty;
1334 
1335     // long long is a C99 feature.
1336     if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1337         Literal.isLongLong)
1338       Diag(Tok.getLocation(), diag::ext_longlong);
1339 
1340     // Get the value in the widest-possible width.
1341     llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1342 
1343     if (Literal.GetIntegerValue(ResultVal)) {
1344       // If this value didn't fit into uintmax_t, warn and force to ull.
1345       Diag(Tok.getLocation(), diag::warn_integer_too_large);
1346       Ty = Context.UnsignedLongLongTy;
1347       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1348              "long long is not intmax_t?");
1349     } else {
1350       // If this value fits into a ULL, try to figure out what else it fits into
1351       // according to the rules of C99 6.4.4.1p5.
1352 
1353       // Octal, Hexadecimal, and integers with a U suffix are allowed to
1354       // be an unsigned int.
1355       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1356 
1357       // Check from smallest to largest, picking the smallest type we can.
1358       unsigned Width = 0;
1359       if (!Literal.isLong && !Literal.isLongLong) {
1360         // Are int/unsigned possibilities?
1361         unsigned IntSize = Context.Target.getIntWidth();
1362 
1363         // Does it fit in a unsigned int?
1364         if (ResultVal.isIntN(IntSize)) {
1365           // Does it fit in a signed int?
1366           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1367             Ty = Context.IntTy;
1368           else if (AllowUnsigned)
1369             Ty = Context.UnsignedIntTy;
1370           Width = IntSize;
1371         }
1372       }
1373 
1374       // Are long/unsigned long possibilities?
1375       if (Ty.isNull() && !Literal.isLongLong) {
1376         unsigned LongSize = Context.Target.getLongWidth();
1377 
1378         // Does it fit in a unsigned long?
1379         if (ResultVal.isIntN(LongSize)) {
1380           // Does it fit in a signed long?
1381           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1382             Ty = Context.LongTy;
1383           else if (AllowUnsigned)
1384             Ty = Context.UnsignedLongTy;
1385           Width = LongSize;
1386         }
1387       }
1388 
1389       // Finally, check long long if needed.
1390       if (Ty.isNull()) {
1391         unsigned LongLongSize = Context.Target.getLongLongWidth();
1392 
1393         // Does it fit in a unsigned long long?
1394         if (ResultVal.isIntN(LongLongSize)) {
1395           // Does it fit in a signed long long?
1396           if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1397             Ty = Context.LongLongTy;
1398           else if (AllowUnsigned)
1399             Ty = Context.UnsignedLongLongTy;
1400           Width = LongLongSize;
1401         }
1402       }
1403 
1404       // If we still couldn't decide a type, we probably have something that
1405       // does not fit in a signed long long, but has no U suffix.
1406       if (Ty.isNull()) {
1407         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1408         Ty = Context.UnsignedLongLongTy;
1409         Width = Context.Target.getLongLongWidth();
1410       }
1411 
1412       if (ResultVal.getBitWidth() != Width)
1413         ResultVal.trunc(Width);
1414     }
1415     Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1416   }
1417 
1418   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1419   if (Literal.isImaginary)
1420     Res = new (Context) ImaginaryLiteral(Res,
1421                                         Context.getComplexType(Res->getType()));
1422 
1423   return Owned(Res);
1424 }
1425 
1426 Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1427                                               SourceLocation R, ExprArg Val) {
1428   Expr *E = Val.takeAs<Expr>();
1429   assert((E != 0) && "ActOnParenExpr() missing expr");
1430   return Owned(new (Context) ParenExpr(L, R, E));
1431 }
1432 
1433 /// The UsualUnaryConversions() function is *not* called by this routine.
1434 /// See C99 6.3.2.1p[2-4] for more details.
1435 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1436                                      SourceLocation OpLoc,
1437                                      const SourceRange &ExprRange,
1438                                      bool isSizeof) {
1439   if (exprType->isDependentType())
1440     return false;
1441 
1442   // C99 6.5.3.4p1:
1443   if (isa<FunctionType>(exprType)) {
1444     // alignof(function) is allowed as an extension.
1445     if (isSizeof)
1446       Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1447     return false;
1448   }
1449 
1450   // Allow sizeof(void)/alignof(void) as an extension.
1451   if (exprType->isVoidType()) {
1452     Diag(OpLoc, diag::ext_sizeof_void_type)
1453       << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1454     return false;
1455   }
1456 
1457   if (RequireCompleteType(OpLoc, exprType,
1458                           isSizeof ? diag::err_sizeof_incomplete_type :
1459                           diag::err_alignof_incomplete_type,
1460                           ExprRange))
1461     return true;
1462 
1463   // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
1464   if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
1465     Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
1466       << exprType << isSizeof << ExprRange;
1467     return true;
1468   }
1469 
1470   return false;
1471 }
1472 
1473 bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1474                             const SourceRange &ExprRange) {
1475   E = E->IgnoreParens();
1476 
1477   // alignof decl is always ok.
1478   if (isa<DeclRefExpr>(E))
1479     return false;
1480 
1481   // Cannot know anything else if the expression is dependent.
1482   if (E->isTypeDependent())
1483     return false;
1484 
1485   if (E->getBitField()) {
1486     Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1487     return true;
1488   }
1489 
1490   // Alignment of a field access is always okay, so long as it isn't a
1491   // bit-field.
1492   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1493     if (dyn_cast<FieldDecl>(ME->getMemberDecl()))
1494       return false;
1495 
1496   return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1497 }
1498 
1499 /// \brief Build a sizeof or alignof expression given a type operand.
1500 Action::OwningExprResult
1501 Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1502                               bool isSizeOf, SourceRange R) {
1503   if (T.isNull())
1504     return ExprError();
1505 
1506   if (!T->isDependentType() &&
1507       CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1508     return ExprError();
1509 
1510   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1511   return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1512                                                Context.getSizeType(), OpLoc,
1513                                                R.getEnd()));
1514 }
1515 
1516 /// \brief Build a sizeof or alignof expression given an expression
1517 /// operand.
1518 Action::OwningExprResult
1519 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1520                               bool isSizeOf, SourceRange R) {
1521   // Verify that the operand is valid.
1522   bool isInvalid = false;
1523   if (E->isTypeDependent()) {
1524     // Delay type-checking for type-dependent expressions.
1525   } else if (!isSizeOf) {
1526     isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1527   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
1528     Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1529     isInvalid = true;
1530   } else {
1531     isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1532   }
1533 
1534   if (isInvalid)
1535     return ExprError();
1536 
1537   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1538   return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1539                                                Context.getSizeType(), OpLoc,
1540                                                R.getEnd()));
1541 }
1542 
1543 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1544 /// the same for @c alignof and @c __alignof
1545 /// Note that the ArgRange is invalid if isType is false.
1546 Action::OwningExprResult
1547 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1548                              void *TyOrEx, const SourceRange &ArgRange) {
1549   // If error parsing type, ignore.
1550   if (TyOrEx == 0) return ExprError();
1551 
1552   if (isType) {
1553     QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1554     return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1555   }
1556 
1557   // Get the end location.
1558   Expr *ArgEx = (Expr *)TyOrEx;
1559   Action::OwningExprResult Result
1560     = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1561 
1562   if (Result.isInvalid())
1563     DeleteExpr(ArgEx);
1564 
1565   return move(Result);
1566 }
1567 
1568 QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
1569   if (V->isTypeDependent())
1570     return Context.DependentTy;
1571 
1572   // These operators return the element type of a complex type.
1573   if (const ComplexType *CT = V->getType()->getAsComplexType())
1574     return CT->getElementType();
1575 
1576   // Otherwise they pass through real integer and floating point types here.
1577   if (V->getType()->isArithmeticType())
1578     return V->getType();
1579 
1580   // Reject anything else.
1581   Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1582     << (isReal ? "__real" : "__imag");
1583   return QualType();
1584 }
1585 
1586 
1587 
1588 Action::OwningExprResult
1589 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1590                           tok::TokenKind Kind, ExprArg Input) {
1591   Expr *Arg = (Expr *)Input.get();
1592 
1593   UnaryOperator::Opcode Opc;
1594   switch (Kind) {
1595   default: assert(0 && "Unknown unary op!");
1596   case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
1597   case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1598   }
1599 
1600   if (getLangOptions().CPlusPlus &&
1601       (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1602     // Which overloaded operator?
1603     OverloadedOperatorKind OverOp =
1604       (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1605 
1606     // C++ [over.inc]p1:
1607     //
1608     //     [...] If the function is a member function with one
1609     //     parameter (which shall be of type int) or a non-member
1610     //     function with two parameters (the second of which shall be
1611     //     of type int), it defines the postfix increment operator ++
1612     //     for objects of that type. When the postfix increment is
1613     //     called as a result of using the ++ operator, the int
1614     //     argument will have value zero.
1615     Expr *Args[2] = {
1616       Arg,
1617       new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1618                           /*isSigned=*/true), Context.IntTy, SourceLocation())
1619     };
1620 
1621     // Build the candidate set for overloading
1622     OverloadCandidateSet CandidateSet;
1623     AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
1624 
1625     // Perform overload resolution.
1626     OverloadCandidateSet::iterator Best;
1627     switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
1628     case OR_Success: {
1629       // We found a built-in operator or an overloaded operator.
1630       FunctionDecl *FnDecl = Best->Function;
1631 
1632       if (FnDecl) {
1633         // We matched an overloaded operator. Build a call to that
1634         // operator.
1635 
1636         // Convert the arguments.
1637         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1638           if (PerformObjectArgumentInitialization(Arg, Method))
1639             return ExprError();
1640         } else {
1641           // Convert the arguments.
1642           if (PerformCopyInitialization(Arg,
1643                                         FnDecl->getParamDecl(0)->getType(),
1644                                         "passing"))
1645             return ExprError();
1646         }
1647 
1648         // Determine the result type
1649         QualType ResultTy
1650           = FnDecl->getType()->getAsFunctionType()->getResultType();
1651         ResultTy = ResultTy.getNonReferenceType();
1652 
1653         // Build the actual expression node.
1654         Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1655                                                  SourceLocation());
1656         UsualUnaryConversions(FnExpr);
1657 
1658         Input.release();
1659         Args[0] = Arg;
1660         return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1661                                                        Args, 2, ResultTy,
1662                                                        OpLoc));
1663       } else {
1664         // We matched a built-in operator. Convert the arguments, then
1665         // break out so that we will build the appropriate built-in
1666         // operator node.
1667         if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1668                                       "passing"))
1669           return ExprError();
1670 
1671         break;
1672       }
1673     }
1674 
1675     case OR_No_Viable_Function:
1676       // No viable function; fall through to handling this as a
1677       // built-in operator, which will produce an error message for us.
1678       break;
1679 
1680     case OR_Ambiguous:
1681       Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
1682           << UnaryOperator::getOpcodeStr(Opc)
1683           << Arg->getSourceRange();
1684       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1685       return ExprError();
1686 
1687     case OR_Deleted:
1688       Diag(OpLoc, diag::err_ovl_deleted_oper)
1689         << Best->Function->isDeleted()
1690         << UnaryOperator::getOpcodeStr(Opc)
1691         << Arg->getSourceRange();
1692       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1693       return ExprError();
1694     }
1695 
1696     // Either we found no viable overloaded operator or we matched a
1697     // built-in operator. In either case, fall through to trying to
1698     // build a built-in operation.
1699   }
1700 
1701   QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1702                                                  Opc == UnaryOperator::PostInc);
1703   if (result.isNull())
1704     return ExprError();
1705   Input.release();
1706   return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
1707 }
1708 
1709 Action::OwningExprResult
1710 Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1711                               ExprArg Idx, SourceLocation RLoc) {
1712   Expr *LHSExp = static_cast<Expr*>(Base.get()),
1713        *RHSExp = static_cast<Expr*>(Idx.get());
1714 
1715   if (getLangOptions().CPlusPlus &&
1716       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1717     Base.release();
1718     Idx.release();
1719     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1720                                                   Context.DependentTy, RLoc));
1721   }
1722 
1723   if (getLangOptions().CPlusPlus &&
1724       (LHSExp->getType()->isRecordType() ||
1725        LHSExp->getType()->isEnumeralType() ||
1726        RHSExp->getType()->isRecordType() ||
1727        RHSExp->getType()->isEnumeralType())) {
1728     // Add the appropriate overloaded operators (C++ [over.match.oper])
1729     // to the candidate set.
1730     OverloadCandidateSet CandidateSet;
1731     Expr *Args[2] = { LHSExp, RHSExp };
1732     AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1733                           SourceRange(LLoc, RLoc));
1734 
1735     // Perform overload resolution.
1736     OverloadCandidateSet::iterator Best;
1737     switch (BestViableFunction(CandidateSet, LLoc, Best)) {
1738     case OR_Success: {
1739       // We found a built-in operator or an overloaded operator.
1740       FunctionDecl *FnDecl = Best->Function;
1741 
1742       if (FnDecl) {
1743         // We matched an overloaded operator. Build a call to that
1744         // operator.
1745 
1746         // Convert the arguments.
1747         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1748           if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1749               PerformCopyInitialization(RHSExp,
1750                                         FnDecl->getParamDecl(0)->getType(),
1751                                         "passing"))
1752             return ExprError();
1753         } else {
1754           // Convert the arguments.
1755           if (PerformCopyInitialization(LHSExp,
1756                                         FnDecl->getParamDecl(0)->getType(),
1757                                         "passing") ||
1758               PerformCopyInitialization(RHSExp,
1759                                         FnDecl->getParamDecl(1)->getType(),
1760                                         "passing"))
1761             return ExprError();
1762         }
1763 
1764         // Determine the result type
1765         QualType ResultTy
1766           = FnDecl->getType()->getAsFunctionType()->getResultType();
1767         ResultTy = ResultTy.getNonReferenceType();
1768 
1769         // Build the actual expression node.
1770         Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1771                                                  SourceLocation());
1772         UsualUnaryConversions(FnExpr);
1773 
1774         Base.release();
1775         Idx.release();
1776         Args[0] = LHSExp;
1777         Args[1] = RHSExp;
1778         return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1779                                                        FnExpr, Args, 2,
1780                                                        ResultTy, LLoc));
1781       } else {
1782         // We matched a built-in operator. Convert the arguments, then
1783         // break out so that we will build the appropriate built-in
1784         // operator node.
1785         if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1786                                       "passing") ||
1787             PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1788                                       "passing"))
1789           return ExprError();
1790 
1791         break;
1792       }
1793     }
1794 
1795     case OR_No_Viable_Function:
1796       // No viable function; fall through to handling this as a
1797       // built-in operator, which will produce an error message for us.
1798       break;
1799 
1800     case OR_Ambiguous:
1801       Diag(LLoc,  diag::err_ovl_ambiguous_oper)
1802           << "[]"
1803           << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1804       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1805       return ExprError();
1806 
1807     case OR_Deleted:
1808       Diag(LLoc, diag::err_ovl_deleted_oper)
1809         << Best->Function->isDeleted()
1810         << "[]"
1811         << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1812       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1813       return ExprError();
1814     }
1815 
1816     // Either we found no viable overloaded operator or we matched a
1817     // built-in operator. In either case, fall through to trying to
1818     // build a built-in operation.
1819   }
1820 
1821   // Perform default conversions.
1822   DefaultFunctionArrayConversion(LHSExp);
1823   DefaultFunctionArrayConversion(RHSExp);
1824 
1825   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1826 
1827   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1828   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1829   // in the subscript position. As a result, we need to derive the array base
1830   // and index from the expression types.
1831   Expr *BaseExpr, *IndexExpr;
1832   QualType ResultType;
1833   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1834     BaseExpr = LHSExp;
1835     IndexExpr = RHSExp;
1836     ResultType = Context.DependentTy;
1837   } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
1838     BaseExpr = LHSExp;
1839     IndexExpr = RHSExp;
1840     ResultType = PTy->getPointeeType();
1841   } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
1842      // Handle the uncommon case of "123[Ptr]".
1843     BaseExpr = RHSExp;
1844     IndexExpr = LHSExp;
1845     ResultType = PTy->getPointeeType();
1846   } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1847     BaseExpr = LHSExp;    // vectors: V[123]
1848     IndexExpr = RHSExp;
1849 
1850     // FIXME: need to deal with const...
1851     ResultType = VTy->getElementType();
1852   } else if (LHSTy->isArrayType()) {
1853     // If we see an array that wasn't promoted by
1854     // DefaultFunctionArrayConversion, it must be an array that
1855     // wasn't promoted because of the C90 rule that doesn't
1856     // allow promoting non-lvalue arrays.  Warn, then
1857     // force the promotion here.
1858     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1859         LHSExp->getSourceRange();
1860     ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1861     LHSTy = LHSExp->getType();
1862 
1863     BaseExpr = LHSExp;
1864     IndexExpr = RHSExp;
1865     ResultType = LHSTy->getAsPointerType()->getPointeeType();
1866   } else if (RHSTy->isArrayType()) {
1867     // Same as previous, except for 123[f().a] case
1868     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1869         RHSExp->getSourceRange();
1870     ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1871     RHSTy = RHSExp->getType();
1872 
1873     BaseExpr = RHSExp;
1874     IndexExpr = LHSExp;
1875     ResultType = RHSTy->getAsPointerType()->getPointeeType();
1876   } else {
1877     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1878        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
1879   }
1880   // C99 6.5.2.1p1
1881   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
1882     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1883                      << IndexExpr->getSourceRange());
1884 
1885   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1886   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1887   // type. Note that Functions are not objects, and that (in C99 parlance)
1888   // incomplete types are not object types.
1889   if (ResultType->isFunctionType()) {
1890     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1891       << ResultType << BaseExpr->getSourceRange();
1892     return ExprError();
1893   }
1894 
1895   if (!ResultType->isDependentType() &&
1896       RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
1897                           BaseExpr->getSourceRange()))
1898     return ExprError();
1899 
1900   // Diagnose bad cases where we step over interface counts.
1901   if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1902     Diag(LLoc, diag::err_subscript_nonfragile_interface)
1903       << ResultType << BaseExpr->getSourceRange();
1904     return ExprError();
1905   }
1906 
1907   Base.release();
1908   Idx.release();
1909   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1910                                                 ResultType, RLoc));
1911 }
1912 
1913 QualType Sema::
1914 CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
1915                         IdentifierInfo &CompName, SourceLocation CompLoc) {
1916   const ExtVectorType *vecType = baseType->getAsExtVectorType();
1917 
1918   // The vector accessor can't exceed the number of elements.
1919   const char *compStr = CompName.getName();
1920 
1921   // This flag determines whether or not the component is one of the four
1922   // special names that indicate a subset of exactly half the elements are
1923   // to be selected.
1924   bool HalvingSwizzle = false;
1925 
1926   // This flag determines whether or not CompName has an 's' char prefix,
1927   // indicating that it is a string of hex values to be used as vector indices.
1928   bool HexSwizzle = *compStr == 's' || *compStr == 'S';
1929 
1930   // Check that we've found one of the special components, or that the component
1931   // names must come from the same set.
1932   if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1933       !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1934     HalvingSwizzle = true;
1935   } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1936     do
1937       compStr++;
1938     while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1939   } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1940     do
1941       compStr++;
1942     while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1943   }
1944 
1945   if (!HalvingSwizzle && *compStr) {
1946     // We didn't get to the end of the string. This means the component names
1947     // didn't come from the same set *or* we encountered an illegal name.
1948     Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1949       << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1950     return QualType();
1951   }
1952 
1953   // Ensure no component accessor exceeds the width of the vector type it
1954   // operates on.
1955   if (!HalvingSwizzle) {
1956     compStr = CompName.getName();
1957 
1958     if (HexSwizzle)
1959       compStr++;
1960 
1961     while (*compStr) {
1962       if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1963         Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1964           << baseType << SourceRange(CompLoc);
1965         return QualType();
1966       }
1967     }
1968   }
1969 
1970   // If this is a halving swizzle, verify that the base type has an even
1971   // number of elements.
1972   if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1973     Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1974       << baseType << SourceRange(CompLoc);
1975     return QualType();
1976   }
1977 
1978   // The component accessor looks fine - now we need to compute the actual type.
1979   // The vector type is implied by the component accessor. For example,
1980   // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1981   // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1982   // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1983   unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1984                                      : CompName.getLength();
1985   if (HexSwizzle)
1986     CompSize--;
1987 
1988   if (CompSize == 1)
1989     return vecType->getElementType();
1990 
1991   QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1992   // Now look up the TypeDefDecl from the vector type. Without this,
1993   // diagostics look bad. We want extended vector types to appear built-in.
1994   for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1995     if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1996       return Context.getTypedefType(ExtVectorDecls[i]);
1997   }
1998   return VT; // should never get here (a typedef type should always be found).
1999 }
2000 
2001 static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
2002                                                 IdentifierInfo &Member,
2003                                                 const Selector &Sel,
2004                                                 ASTContext &Context) {
2005 
2006   if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
2007     return PD;
2008   if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
2009     return OMD;
2010 
2011   for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2012        E = PDecl->protocol_end(); I != E; ++I) {
2013     if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
2014                                                      Context))
2015       return D;
2016   }
2017   return 0;
2018 }
2019 
2020 static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
2021                                 IdentifierInfo &Member,
2022                                 const Selector &Sel,
2023                                 ASTContext &Context) {
2024   // Check protocols on qualified interfaces.
2025   Decl *GDecl = 0;
2026   for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
2027        E = QIdTy->qual_end(); I != E; ++I) {
2028     if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
2029       GDecl = PD;
2030       break;
2031     }
2032     // Also must look for a getter name which uses property syntax.
2033     if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
2034       GDecl = OMD;
2035       break;
2036     }
2037   }
2038   if (!GDecl) {
2039     for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
2040          E = QIdTy->qual_end(); I != E; ++I) {
2041       // Search in the protocol-qualifier list of current protocol.
2042       GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
2043       if (GDecl)
2044         return GDecl;
2045     }
2046   }
2047   return GDecl;
2048 }
2049 
2050 /// FindMethodInNestedImplementations - Look up a method in current and
2051 /// all base class implementations.
2052 ///
2053 ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
2054                                               const ObjCInterfaceDecl *IFace,
2055                                               const Selector &Sel) {
2056   ObjCMethodDecl *Method = 0;
2057   if (ObjCImplementationDecl *ImpDecl
2058         = LookupObjCImplementation(IFace->getIdentifier()))
2059     Method = ImpDecl->getInstanceMethod(Sel);
2060 
2061   if (!Method && IFace->getSuperClass())
2062     return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
2063   return Method;
2064 }
2065 
2066 Action::OwningExprResult
2067 Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2068                                tok::TokenKind OpKind, SourceLocation MemberLoc,
2069                                IdentifierInfo &Member,
2070                                DeclPtrTy ObjCImpDecl) {
2071   Expr *BaseExpr = Base.takeAs<Expr>();
2072   assert(BaseExpr && "no record expression");
2073 
2074   // Perform default conversions.
2075   DefaultFunctionArrayConversion(BaseExpr);
2076 
2077   QualType BaseType = BaseExpr->getType();
2078   assert(!BaseType.isNull() && "no type for member expression");
2079 
2080   // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
2081   // must have pointer type, and the accessed type is the pointee.
2082   if (OpKind == tok::arrow) {
2083     if (BaseType->isDependentType())
2084       return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2085                                                          BaseExpr, true,
2086                                                          OpLoc,
2087                                                      DeclarationName(&Member),
2088                                                          MemberLoc));
2089     else if (const PointerType *PT = BaseType->getAsPointerType())
2090       BaseType = PT->getPointeeType();
2091     else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
2092       return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
2093                                             MemberLoc, Member));
2094     else
2095       return ExprError(Diag(MemberLoc,
2096                             diag::err_typecheck_member_reference_arrow)
2097         << BaseType << BaseExpr->getSourceRange());
2098   } else {
2099     if (BaseType->isDependentType()) {
2100       // Require that the base type isn't a pointer type
2101       // (so we'll report an error for)
2102       // T* t;
2103       // t.f;
2104       //
2105       // In Obj-C++, however, the above expression is valid, since it could be
2106       // accessing the 'f' property if T is an Obj-C interface. The extra check
2107       // allows this, while still reporting an error if T is a struct pointer.
2108       const PointerType *PT = BaseType->getAsPointerType();
2109 
2110       if (!PT || (getLangOptions().ObjC1 &&
2111                   !PT->getPointeeType()->isRecordType()))
2112         return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2113                                                            BaseExpr, false,
2114                                                            OpLoc,
2115                                                      DeclarationName(&Member),
2116                                                            MemberLoc));
2117     }
2118   }
2119 
2120   // Handle field access to simple records.  This also handles access to fields
2121   // of the ObjC 'id' struct.
2122   if (const RecordType *RTy = BaseType->getAsRecordType()) {
2123     RecordDecl *RDecl = RTy->getDecl();
2124     if (RequireCompleteType(OpLoc, BaseType,
2125                                diag::err_typecheck_incomplete_tag,
2126                                BaseExpr->getSourceRange()))
2127       return ExprError();
2128 
2129     // The record definition is complete, now make sure the member is valid.
2130     // FIXME: Qualified name lookup for C++ is a bit more complicated than this.
2131     LookupResult Result
2132       = LookupQualifiedName(RDecl, DeclarationName(&Member),
2133                             LookupMemberName, false);
2134 
2135     if (!Result)
2136       return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2137                << &Member << BaseExpr->getSourceRange());
2138     if (Result.isAmbiguous()) {
2139       DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2140                               MemberLoc, BaseExpr->getSourceRange());
2141       return ExprError();
2142     }
2143 
2144     NamedDecl *MemberDecl = Result;
2145 
2146     // If the decl being referenced had an error, return an error for this
2147     // sub-expr without emitting another error, in order to avoid cascading
2148     // error cases.
2149     if (MemberDecl->isInvalidDecl())
2150       return ExprError();
2151 
2152     // Check the use of this field
2153     if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2154       return ExprError();
2155 
2156     if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2157       // We may have found a field within an anonymous union or struct
2158       // (C++ [class.union]).
2159       if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
2160         return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2161                                                         BaseExpr, OpLoc);
2162 
2163       // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2164       // FIXME: Handle address space modifiers
2165       QualType MemberType = FD->getType();
2166       if (const ReferenceType *Ref = MemberType->getAsReferenceType())
2167         MemberType = Ref->getPointeeType();
2168       else {
2169         unsigned combinedQualifiers =
2170           MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
2171         if (FD->isMutable())
2172           combinedQualifiers &= ~QualType::Const;
2173         MemberType = MemberType.getQualifiedType(combinedQualifiers);
2174       }
2175 
2176       MarkDeclarationReferenced(MemberLoc, FD);
2177       return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2178                                             MemberLoc, MemberType));
2179     }
2180 
2181     if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2182       MarkDeclarationReferenced(MemberLoc, MemberDecl);
2183       return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2184                                             Var, MemberLoc,
2185                                          Var->getType().getNonReferenceType()));
2186     }
2187     if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2188       MarkDeclarationReferenced(MemberLoc, MemberDecl);
2189       return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2190                                             MemberFn, MemberLoc,
2191                                             MemberFn->getType()));
2192     }
2193     if (OverloadedFunctionDecl *Ovl
2194           = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
2195       return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
2196                                             MemberLoc, Context.OverloadTy));
2197     if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2198       MarkDeclarationReferenced(MemberLoc, MemberDecl);
2199       return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2200                                             Enum, MemberLoc, Enum->getType()));
2201     }
2202     if (isa<TypeDecl>(MemberDecl))
2203       return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2204         << DeclarationName(&Member) << int(OpKind == tok::arrow));
2205 
2206     // We found a declaration kind that we didn't expect. This is a
2207     // generic error message that tells the user that she can't refer
2208     // to this member with '.' or '->'.
2209     return ExprError(Diag(MemberLoc,
2210                           diag::err_typecheck_member_reference_unknown)
2211       << DeclarationName(&Member) << int(OpKind == tok::arrow));
2212   }
2213 
2214   // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2215   // (*Obj).ivar.
2216   if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
2217     ObjCInterfaceDecl *ClassDeclared;
2218     if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
2219                                                              ClassDeclared)) {
2220       // If the decl being referenced had an error, return an error for this
2221       // sub-expr without emitting another error, in order to avoid cascading
2222       // error cases.
2223       if (IV->isInvalidDecl())
2224         return ExprError();
2225 
2226       // Check whether we can reference this field.
2227       if (DiagnoseUseOfDecl(IV, MemberLoc))
2228         return ExprError();
2229       if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2230           IV->getAccessControl() != ObjCIvarDecl::Package) {
2231         ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2232         if (ObjCMethodDecl *MD = getCurMethodDecl())
2233           ClassOfMethodDecl =  MD->getClassInterface();
2234         else if (ObjCImpDecl && getCurFunctionDecl()) {
2235           // Case of a c-function declared inside an objc implementation.
2236           // FIXME: For a c-style function nested inside an objc implementation
2237           // class, there is no implementation context available, so we pass
2238           // down the context as argument to this routine. Ideally, this context
2239           // need be passed down in the AST node and somehow calculated from the
2240           // AST for a function decl.
2241           Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2242           if (ObjCImplementationDecl *IMPD =
2243               dyn_cast<ObjCImplementationDecl>(ImplDecl))
2244             ClassOfMethodDecl = IMPD->getClassInterface();
2245           else if (ObjCCategoryImplDecl* CatImplClass =
2246                       dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2247             ClassOfMethodDecl = CatImplClass->getClassInterface();
2248         }
2249 
2250         if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2251           if (ClassDeclared != IFTy->getDecl() ||
2252               ClassOfMethodDecl != ClassDeclared)
2253             Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
2254         }
2255         // @protected
2256         else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
2257           Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
2258       }
2259 
2260       return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2261                                                  MemberLoc, BaseExpr,
2262                                                  OpKind == tok::arrow));
2263     }
2264     return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2265                        << IFTy->getDecl()->getDeclName() << &Member
2266                        << BaseExpr->getSourceRange());
2267   }
2268 
2269   // Handle Objective-C property access, which is "Obj.property" where Obj is a
2270   // pointer to a (potentially qualified) interface type.
2271   const PointerType *PTy;
2272   const ObjCInterfaceType *IFTy;
2273   if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
2274       (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
2275     ObjCInterfaceDecl *IFace = IFTy->getDecl();
2276 
2277     // Search for a declared property first.
2278     if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
2279       // Check whether we can reference this property.
2280       if (DiagnoseUseOfDecl(PD, MemberLoc))
2281         return ExprError();
2282       QualType ResTy = PD->getType();
2283       Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2284       ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2285       if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2286         ResTy = Getter->getResultType();
2287       return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
2288                                                      MemberLoc, BaseExpr));
2289     }
2290 
2291     // Check protocols on qualified interfaces.
2292     for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
2293          E = IFTy->qual_end(); I != E; ++I)
2294       if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
2295         // Check whether we can reference this property.
2296         if (DiagnoseUseOfDecl(PD, MemberLoc))
2297           return ExprError();
2298 
2299         return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2300                                                        MemberLoc, BaseExpr));
2301       }
2302 
2303     // If that failed, look for an "implicit" property by seeing if the nullary
2304     // selector is implemented.
2305 
2306     // FIXME: The logic for looking up nullary and unary selectors should be
2307     // shared with the code in ActOnInstanceMessage.
2308 
2309     Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2310     ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2311 
2312     // If this reference is in an @implementation, check for 'private' methods.
2313     if (!Getter)
2314       Getter = FindMethodInNestedImplementations(IFace, Sel);
2315 
2316     // Look through local category implementations associated with the class.
2317     if (!Getter) {
2318       for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
2319         if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2320           Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
2321       }
2322     }
2323     if (Getter) {
2324       // Check if we can reference this property.
2325       if (DiagnoseUseOfDecl(Getter, MemberLoc))
2326         return ExprError();
2327     }
2328     // If we found a getter then this may be a valid dot-reference, we
2329     // will look for the matching setter, in case it is needed.
2330     Selector SetterSel =
2331       SelectorTable::constructSetterName(PP.getIdentifierTable(),
2332                                          PP.getSelectorTable(), &Member);
2333     ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2334     if (!Setter) {
2335       // If this reference is in an @implementation, also check for 'private'
2336       // methods.
2337       Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2338     }
2339     // Look through local category implementations associated with the class.
2340     if (!Setter) {
2341       for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2342         if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2343           Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
2344       }
2345     }
2346 
2347     if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2348       return ExprError();
2349 
2350     if (Getter || Setter) {
2351       QualType PType;
2352 
2353       if (Getter)
2354         PType = Getter->getResultType();
2355       else {
2356         for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2357              E = Setter->param_end(); PI != E; ++PI)
2358           PType = (*PI)->getType();
2359       }
2360       // FIXME: we must check that the setter has property type.
2361       return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2362                                       Setter, MemberLoc, BaseExpr));
2363     }
2364     return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2365       << &Member << BaseType);
2366   }
2367   // Handle properties on qualified "id" protocols.
2368   const ObjCObjectPointerType *QIdTy;
2369   if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2370     // Check protocols on qualified interfaces.
2371     Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2372     if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2373       if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2374         // Check the use of this declaration
2375         if (DiagnoseUseOfDecl(PD, MemberLoc))
2376           return ExprError();
2377 
2378         return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2379                                                        MemberLoc, BaseExpr));
2380       }
2381       if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2382         // Check the use of this method.
2383         if (DiagnoseUseOfDecl(OMD, MemberLoc))
2384           return ExprError();
2385 
2386         return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2387                                                    OMD->getResultType(),
2388                                                    OMD, OpLoc, MemberLoc,
2389                                                    NULL, 0));
2390       }
2391     }
2392 
2393     return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2394                        << &Member << BaseType);
2395   }
2396   // Handle properties on ObjC 'Class' types.
2397   if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2398     // Also must look for a getter name which uses property syntax.
2399     Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2400     if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2401       ObjCInterfaceDecl *IFace = MD->getClassInterface();
2402       ObjCMethodDecl *Getter;
2403       // FIXME: need to also look locally in the implementation.
2404       if ((Getter = IFace->lookupClassMethod(Sel))) {
2405         // Check the use of this method.
2406         if (DiagnoseUseOfDecl(Getter, MemberLoc))
2407           return ExprError();
2408       }
2409       // If we found a getter then this may be a valid dot-reference, we
2410       // will look for the matching setter, in case it is needed.
2411       Selector SetterSel =
2412         SelectorTable::constructSetterName(PP.getIdentifierTable(),
2413                                            PP.getSelectorTable(), &Member);
2414       ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2415       if (!Setter) {
2416         // If this reference is in an @implementation, also check for 'private'
2417         // methods.
2418         Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2419       }
2420       // Look through local category implementations associated with the class.
2421       if (!Setter) {
2422         for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2423           if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2424             Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel);
2425         }
2426       }
2427 
2428       if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2429         return ExprError();
2430 
2431       if (Getter || Setter) {
2432         QualType PType;
2433 
2434         if (Getter)
2435           PType = Getter->getResultType();
2436         else {
2437           for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2438                E = Setter->param_end(); PI != E; ++PI)
2439             PType = (*PI)->getType();
2440         }
2441         // FIXME: we must check that the setter has property type.
2442         return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2443                                         Setter, MemberLoc, BaseExpr));
2444       }
2445       return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2446         << &Member << BaseType);
2447     }
2448   }
2449 
2450   // Handle 'field access' to vectors, such as 'V.xx'.
2451   if (BaseType->isExtVectorType()) {
2452     QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2453     if (ret.isNull())
2454       return ExprError();
2455     return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
2456                                                     MemberLoc));
2457   }
2458 
2459   Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2460     << BaseType << BaseExpr->getSourceRange();
2461 
2462   // If the user is trying to apply -> or . to a function or function
2463   // pointer, it's probably because they forgot parentheses to call
2464   // the function. Suggest the addition of those parentheses.
2465   if (BaseType == Context.OverloadTy ||
2466       BaseType->isFunctionType() ||
2467       (BaseType->isPointerType() &&
2468        BaseType->getAsPointerType()->isFunctionType())) {
2469     SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2470     Diag(Loc, diag::note_member_reference_needs_call)
2471       << CodeModificationHint::CreateInsertion(Loc, "()");
2472   }
2473 
2474   return ExprError();
2475 }
2476 
2477 /// ConvertArgumentsForCall - Converts the arguments specified in
2478 /// Args/NumArgs to the parameter types of the function FDecl with
2479 /// function prototype Proto. Call is the call expression itself, and
2480 /// Fn is the function expression. For a C++ member function, this
2481 /// routine does not attempt to convert the object argument. Returns
2482 /// true if the call is ill-formed.
2483 bool
2484 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2485                               FunctionDecl *FDecl,
2486                               const FunctionProtoType *Proto,
2487                               Expr **Args, unsigned NumArgs,
2488                               SourceLocation RParenLoc) {
2489   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
2490   // assignment, to the types of the corresponding parameter, ...
2491   unsigned NumArgsInProto = Proto->getNumArgs();
2492   unsigned NumArgsToCheck = NumArgs;
2493   bool Invalid = false;
2494 
2495   // If too few arguments are available (and we don't have default
2496   // arguments for the remaining parameters), don't make the call.
2497   if (NumArgs < NumArgsInProto) {
2498     if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2499       return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2500         << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2501     // Use default arguments for missing arguments
2502     NumArgsToCheck = NumArgsInProto;
2503     Call->setNumArgs(Context, NumArgsInProto);
2504   }
2505 
2506   // If too many are passed and not variadic, error on the extras and drop
2507   // them.
2508   if (NumArgs > NumArgsInProto) {
2509     if (!Proto->isVariadic()) {
2510       Diag(Args[NumArgsInProto]->getLocStart(),
2511            diag::err_typecheck_call_too_many_args)
2512         << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2513         << SourceRange(Args[NumArgsInProto]->getLocStart(),
2514                        Args[NumArgs-1]->getLocEnd());
2515       // This deletes the extra arguments.
2516       Call->setNumArgs(Context, NumArgsInProto);
2517       Invalid = true;
2518     }
2519     NumArgsToCheck = NumArgsInProto;
2520   }
2521 
2522   // Continue to check argument types (even if we have too few/many args).
2523   for (unsigned i = 0; i != NumArgsToCheck; i++) {
2524     QualType ProtoArgType = Proto->getArgType(i);
2525 
2526     Expr *Arg;
2527     if (i < NumArgs) {
2528       Arg = Args[i];
2529 
2530       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2531                               ProtoArgType,
2532                               diag::err_call_incomplete_argument,
2533                               Arg->getSourceRange()))
2534         return true;
2535 
2536       // Pass the argument.
2537       if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2538         return true;
2539     } else {
2540       if (FDecl->getParamDecl(i)->hasUnparsedDefaultArg()) {
2541         Diag (Call->getSourceRange().getBegin(),
2542               diag::err_use_of_default_argument_to_function_declared_later) <<
2543         FDecl << cast<CXXRecordDecl>(FDecl->getDeclContext())->getDeclName();
2544         Diag(UnparsedDefaultArgLocs[FDecl->getParamDecl(i)],
2545               diag::note_default_argument_declared_here);
2546       } else {
2547         Expr *DefaultExpr = FDecl->getParamDecl(i)->getDefaultArg();
2548 
2549         // If the default expression creates temporaries, we need to
2550         // push them to the current stack of expression temporaries so they'll
2551         // be properly destroyed.
2552         if (CXXExprWithTemporaries *E
2553               = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2554           assert(!E->shouldDestroyTemporaries() &&
2555                  "Can't destroy temporaries in a default argument expr!");
2556           for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2557             ExprTemporaries.push_back(E->getTemporary(I));
2558         }
2559       }
2560 
2561       // We already type-checked the argument, so we know it works.
2562       Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
2563     }
2564 
2565     QualType ArgType = Arg->getType();
2566 
2567     Call->setArg(i, Arg);
2568   }
2569 
2570   // If this is a variadic call, handle args passed through "...".
2571   if (Proto->isVariadic()) {
2572     VariadicCallType CallType = VariadicFunction;
2573     if (Fn->getType()->isBlockPointerType())
2574       CallType = VariadicBlock; // Block
2575     else if (isa<MemberExpr>(Fn))
2576       CallType = VariadicMethod;
2577 
2578     // Promote the arguments (C99 6.5.2.2p7).
2579     for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2580       Expr *Arg = Args[i];
2581       Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
2582       Call->setArg(i, Arg);
2583     }
2584   }
2585 
2586   return Invalid;
2587 }
2588 
2589 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2590 /// This provides the location of the left/right parens and a list of comma
2591 /// locations.
2592 Action::OwningExprResult
2593 Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2594                     MultiExprArg args,
2595                     SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2596   unsigned NumArgs = args.size();
2597   Expr *Fn = fn.takeAs<Expr>();
2598   Expr **Args = reinterpret_cast<Expr**>(args.release());
2599   assert(Fn && "no function call expression");
2600   FunctionDecl *FDecl = NULL;
2601   NamedDecl *NDecl = NULL;
2602   DeclarationName UnqualifiedName;
2603 
2604   if (getLangOptions().CPlusPlus) {
2605     // Determine whether this is a dependent call inside a C++ template,
2606     // in which case we won't do any semantic analysis now.
2607     // FIXME: Will need to cache the results of name lookup (including ADL) in
2608     // Fn.
2609     bool Dependent = false;
2610     if (Fn->isTypeDependent())
2611       Dependent = true;
2612     else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2613       Dependent = true;
2614 
2615     if (Dependent)
2616       return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2617                                           Context.DependentTy, RParenLoc));
2618 
2619     // Determine whether this is a call to an object (C++ [over.call.object]).
2620     if (Fn->getType()->isRecordType())
2621       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2622                                                 CommaLocs, RParenLoc));
2623 
2624     // Determine whether this is a call to a member function.
2625     if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2626       NamedDecl *MemDecl = MemExpr->getMemberDecl();
2627       if (isa<OverloadedFunctionDecl>(MemDecl) ||
2628           isa<CXXMethodDecl>(MemDecl) ||
2629           (isa<FunctionTemplateDecl>(MemDecl) &&
2630            isa<CXXMethodDecl>(
2631                 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
2632         return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2633                                                CommaLocs, RParenLoc));
2634     }
2635   }
2636 
2637   // If we're directly calling a function, get the appropriate declaration.
2638   // Also, in C++, keep track of whether we should perform argument-dependent
2639   // lookup and whether there were any explicitly-specified template arguments.
2640   Expr *FnExpr = Fn;
2641   bool ADL = true;
2642   bool HasExplicitTemplateArgs = 0;
2643   const TemplateArgument *ExplicitTemplateArgs = 0;
2644   unsigned NumExplicitTemplateArgs = 0;
2645   while (true) {
2646     if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2647       FnExpr = IcExpr->getSubExpr();
2648     else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2649       // Parentheses around a function disable ADL
2650       // (C++0x [basic.lookup.argdep]p1).
2651       ADL = false;
2652       FnExpr = PExpr->getSubExpr();
2653     } else if (isa<UnaryOperator>(FnExpr) &&
2654                cast<UnaryOperator>(FnExpr)->getOpcode()
2655                  == UnaryOperator::AddrOf) {
2656       FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2657     } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2658       // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2659       ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2660       NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
2661       break;
2662     } else if (UnresolvedFunctionNameExpr *DepName
2663                  = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2664       UnqualifiedName = DepName->getName();
2665       break;
2666     } else if (TemplateIdRefExpr *TemplateIdRef
2667                  = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2668       NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2669       HasExplicitTemplateArgs = true;
2670       ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2671       NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2672 
2673       // C++ [temp.arg.explicit]p6:
2674       //   [Note: For simple function names, argument dependent lookup (3.4.2)
2675       //   applies even when the function name is not visible within the
2676       //   scope of the call. This is because the call still has the syntactic
2677       //   form of a function call (3.4.1). But when a function template with
2678       //   explicit template arguments is used, the call does not have the
2679       //   correct syntactic form unless there is a function template with
2680       //   that name visible at the point of the call. If no such name is
2681       //   visible, the call is not syntactically well-formed and
2682       //   argument-dependent lookup does not apply. If some such name is
2683       //   visible, argument dependent lookup applies and additional function
2684       //   templates may be found in other namespaces.
2685       //
2686       // The summary of this paragraph is that, if we get to this point and the
2687       // template-id was not a qualified name, then argument-dependent lookup
2688       // is still possible.
2689       if (TemplateIdRef->getQualifier())
2690         ADL = false;
2691       break;
2692     } else {
2693       // Any kind of name that does not refer to a declaration (or
2694       // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2695       ADL = false;
2696       break;
2697     }
2698   }
2699 
2700   OverloadedFunctionDecl *Ovl = 0;
2701   FunctionTemplateDecl *FunctionTemplate = 0;
2702   if (NDecl) {
2703     FDecl = dyn_cast<FunctionDecl>(NDecl);
2704     if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
2705       FDecl = FunctionTemplate->getTemplatedDecl();
2706     else
2707       FDecl = dyn_cast<FunctionDecl>(NDecl);
2708     Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
2709   }
2710 
2711   if (Ovl || FunctionTemplate ||
2712       (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2713     // We don't perform ADL for implicit declarations of builtins.
2714     if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
2715       ADL = false;
2716 
2717     // We don't perform ADL in C.
2718     if (!getLangOptions().CPlusPlus)
2719       ADL = false;
2720 
2721     if (Ovl || FunctionTemplate || ADL) {
2722       FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2723                                       HasExplicitTemplateArgs,
2724                                       ExplicitTemplateArgs,
2725                                       NumExplicitTemplateArgs,
2726                                       LParenLoc, Args, NumArgs, CommaLocs,
2727                                       RParenLoc, ADL);
2728       if (!FDecl)
2729         return ExprError();
2730 
2731       // Update Fn to refer to the actual function selected.
2732       Expr *NewFn = 0;
2733       if (QualifiedDeclRefExpr *QDRExpr
2734             = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
2735         NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2736                                                    QDRExpr->getLocation(),
2737                                                    false, false,
2738                                                  QDRExpr->getQualifierRange(),
2739                                                    QDRExpr->getQualifier());
2740       else
2741         NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2742                                           Fn->getSourceRange().getBegin());
2743       Fn->Destroy(Context);
2744       Fn = NewFn;
2745     }
2746   }
2747 
2748   // Promote the function operand.
2749   UsualUnaryConversions(Fn);
2750 
2751   // Make the call expr early, before semantic checks.  This guarantees cleanup
2752   // of arguments and function on error.
2753   ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2754                                                                Args, NumArgs,
2755                                                                Context.BoolTy,
2756                                                                RParenLoc));
2757 
2758   const FunctionType *FuncT;
2759   if (!Fn->getType()->isBlockPointerType()) {
2760     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2761     // have type pointer to function".
2762     const PointerType *PT = Fn->getType()->getAsPointerType();
2763     if (PT == 0)
2764       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2765         << Fn->getType() << Fn->getSourceRange());
2766     FuncT = PT->getPointeeType()->getAsFunctionType();
2767   } else { // This is a block call.
2768     FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2769                 getAsFunctionType();
2770   }
2771   if (FuncT == 0)
2772     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2773       << Fn->getType() << Fn->getSourceRange());
2774 
2775   // Check for a valid return type
2776   if (!FuncT->getResultType()->isVoidType() &&
2777       RequireCompleteType(Fn->getSourceRange().getBegin(),
2778                           FuncT->getResultType(),
2779                           diag::err_call_incomplete_return,
2780                           TheCall->getSourceRange()))
2781     return ExprError();
2782 
2783   // We know the result type of the call, set it.
2784   TheCall->setType(FuncT->getResultType().getNonReferenceType());
2785 
2786   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
2787     if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2788                                 RParenLoc))
2789       return ExprError();
2790   } else {
2791     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
2792 
2793     if (FDecl) {
2794       // Check if we have too few/too many template arguments, based
2795       // on our knowledge of the function definition.
2796       const FunctionDecl *Def = 0;
2797       if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
2798         const FunctionProtoType *Proto =
2799             Def->getType()->getAsFunctionProtoType();
2800         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2801           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2802             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2803         }
2804       }
2805     }
2806 
2807     // Promote the arguments (C99 6.5.2.2p6).
2808     for (unsigned i = 0; i != NumArgs; i++) {
2809       Expr *Arg = Args[i];
2810       DefaultArgumentPromotion(Arg);
2811       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2812                               Arg->getType(),
2813                               diag::err_call_incomplete_argument,
2814                               Arg->getSourceRange()))
2815         return ExprError();
2816       TheCall->setArg(i, Arg);
2817     }
2818   }
2819 
2820   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2821     if (!Method->isStatic())
2822       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2823         << Fn->getSourceRange());
2824 
2825   // Check for sentinels
2826   if (NDecl)
2827     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
2828   // Do special checking on direct calls to functions.
2829   if (FDecl)
2830     return CheckFunctionCall(FDecl, TheCall.take());
2831   if (NDecl)
2832     return CheckBlockCall(NDecl, TheCall.take());
2833 
2834   return Owned(TheCall.take());
2835 }
2836 
2837 Action::OwningExprResult
2838 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2839                            SourceLocation RParenLoc, ExprArg InitExpr) {
2840   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
2841   QualType literalType = QualType::getFromOpaquePtr(Ty);
2842   // FIXME: put back this assert when initializers are worked out.
2843   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
2844   Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
2845 
2846   if (literalType->isArrayType()) {
2847     if (literalType->isVariableArrayType())
2848       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2849         << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
2850   } else if (!literalType->isDependentType() &&
2851              RequireCompleteType(LParenLoc, literalType,
2852                                  diag::err_typecheck_decl_incomplete_type,
2853                 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
2854     return ExprError();
2855 
2856   if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
2857                             DeclarationName(), /*FIXME:DirectInit=*/false))
2858     return ExprError();
2859 
2860   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
2861   if (isFileScope) { // 6.5.2.5p3
2862     if (CheckForConstantInitializer(literalExpr, literalType))
2863       return ExprError();
2864   }
2865   InitExpr.release();
2866   return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2867                                                  literalExpr, isFileScope));
2868 }
2869 
2870 Action::OwningExprResult
2871 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2872                     SourceLocation RBraceLoc) {
2873   unsigned NumInit = initlist.size();
2874   Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
2875 
2876   // Semantic analysis for initializers is done by ActOnDeclarator() and
2877   // CheckInitializer() - it requires knowledge of the object being intialized.
2878 
2879   InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
2880                                                RBraceLoc);
2881   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
2882   return Owned(E);
2883 }
2884 
2885 /// CheckCastTypes - Check type constraints for casting between types.
2886 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
2887   UsualUnaryConversions(castExpr);
2888 
2889   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2890   // type needs to be scalar.
2891   if (castType->isVoidType()) {
2892     // Cast to void allows any expr type.
2893   } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2894     // We can't check any more until template instantiation time.
2895   } else if (!castType->isScalarType() && !castType->isVectorType()) {
2896     if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2897         Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2898         (castType->isStructureType() || castType->isUnionType())) {
2899       // GCC struct/union extension: allow cast to self.
2900       // FIXME: Check that the cast destination type is complete.
2901       Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2902         << castType << castExpr->getSourceRange();
2903     } else if (castType->isUnionType()) {
2904       // GCC cast to union extension
2905       RecordDecl *RD = castType->getAsRecordType()->getDecl();
2906       RecordDecl::field_iterator Field, FieldEnd;
2907       for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2908            Field != FieldEnd; ++Field) {
2909         if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2910             Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2911           Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2912             << castExpr->getSourceRange();
2913           break;
2914         }
2915       }
2916       if (Field == FieldEnd)
2917         return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2918           << castExpr->getType() << castExpr->getSourceRange();
2919     } else {
2920       // Reject any other conversions to non-scalar types.
2921       return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
2922         << castType << castExpr->getSourceRange();
2923     }
2924   } else if (!castExpr->getType()->isScalarType() &&
2925              !castExpr->getType()->isVectorType()) {
2926     return Diag(castExpr->getLocStart(),
2927                 diag::err_typecheck_expect_scalar_operand)
2928       << castExpr->getType() << castExpr->getSourceRange();
2929   } else if (castType->isExtVectorType()) {
2930     if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
2931       return true;
2932   } else if (castType->isVectorType()) {
2933     if (CheckVectorCast(TyR, castType, castExpr->getType()))
2934       return true;
2935   } else if (castExpr->getType()->isVectorType()) {
2936     if (CheckVectorCast(TyR, castExpr->getType(), castType))
2937       return true;
2938   } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
2939     return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
2940   } else if (!castType->isArithmeticType()) {
2941     QualType castExprType = castExpr->getType();
2942     if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2943       return Diag(castExpr->getLocStart(),
2944                   diag::err_cast_pointer_from_non_pointer_int)
2945         << castExprType << castExpr->getSourceRange();
2946   } else if (!castExpr->getType()->isArithmeticType()) {
2947     if (!castType->isIntegralType() && castType->isArithmeticType())
2948       return Diag(castExpr->getLocStart(),
2949                   diag::err_cast_pointer_to_non_pointer_int)
2950         << castType << castExpr->getSourceRange();
2951   }
2952   if (isa<ObjCSelectorExpr>(castExpr))
2953     return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
2954   return false;
2955 }
2956 
2957 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
2958   assert(VectorTy->isVectorType() && "Not a vector type!");
2959 
2960   if (Ty->isVectorType() || Ty->isIntegerType()) {
2961     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
2962       return Diag(R.getBegin(),
2963                   Ty->isVectorType() ?
2964                   diag::err_invalid_conversion_between_vectors :
2965                   diag::err_invalid_conversion_between_vector_and_integer)
2966         << VectorTy << Ty << R;
2967   } else
2968     return Diag(R.getBegin(),
2969                 diag::err_invalid_conversion_between_vector_and_scalar)
2970       << VectorTy << Ty << R;
2971 
2972   return false;
2973 }
2974 
2975 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
2976   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
2977 
2978   // If SrcTy is a VectorType, the total size must match to explicitly cast to
2979   // an ExtVectorType.
2980   if (SrcTy->isVectorType()) {
2981     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
2982       return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
2983         << DestTy << SrcTy << R;
2984     return false;
2985   }
2986 
2987   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
2988   // conversion will take place first from scalar to elt type, and then
2989   // splat from elt type to vector.
2990   if (SrcTy->isPointerType())
2991     return Diag(R.getBegin(),
2992                 diag::err_invalid_conversion_between_vector_and_scalar)
2993       << DestTy << SrcTy << R;
2994   return false;
2995 }
2996 
2997 Action::OwningExprResult
2998 Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2999                     SourceLocation RParenLoc, ExprArg Op) {
3000   assert((Ty != 0) && (Op.get() != 0) &&
3001          "ActOnCastExpr(): missing type or expr");
3002 
3003   Expr *castExpr = Op.takeAs<Expr>();
3004   QualType castType = QualType::getFromOpaquePtr(Ty);
3005 
3006   if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
3007     return ExprError();
3008   return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
3009                                             LParenLoc, RParenLoc));
3010 }
3011 
3012 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3013 /// In that case, lhs = cond.
3014 /// C99 6.5.15
3015 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3016                                         SourceLocation QuestionLoc) {
3017   // C++ is sufficiently different to merit its own checker.
3018   if (getLangOptions().CPlusPlus)
3019     return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3020 
3021   UsualUnaryConversions(Cond);
3022   UsualUnaryConversions(LHS);
3023   UsualUnaryConversions(RHS);
3024   QualType CondTy = Cond->getType();
3025   QualType LHSTy = LHS->getType();
3026   QualType RHSTy = RHS->getType();
3027 
3028   // first, check the condition.
3029   if (!CondTy->isScalarType()) { // C99 6.5.15p2
3030     Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3031       << CondTy;
3032     return QualType();
3033   }
3034 
3035   // Now check the two expressions.
3036 
3037   // If both operands have arithmetic type, do the usual arithmetic conversions
3038   // to find a common type: C99 6.5.15p3,5.
3039   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3040     UsualArithmeticConversions(LHS, RHS);
3041     return LHS->getType();
3042   }
3043 
3044   // If both operands are the same structure or union type, the result is that
3045   // type.
3046   if (const RecordType *LHSRT = LHSTy->getAsRecordType()) {    // C99 6.5.15p3
3047     if (const RecordType *RHSRT = RHSTy->getAsRecordType())
3048       if (LHSRT->getDecl() == RHSRT->getDecl())
3049         // "If both the operands have structure or union type, the result has
3050         // that type."  This implies that CV qualifiers are dropped.
3051         return LHSTy.getUnqualifiedType();
3052     // FIXME: Type of conditional expression must be complete in C mode.
3053   }
3054 
3055   // C99 6.5.15p5: "If both operands have void type, the result has void type."
3056   // The following || allows only one side to be void (a GCC-ism).
3057   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3058     if (!LHSTy->isVoidType())
3059       Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3060         << RHS->getSourceRange();
3061     if (!RHSTy->isVoidType())
3062       Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3063         << LHS->getSourceRange();
3064     ImpCastExprToType(LHS, Context.VoidTy);
3065     ImpCastExprToType(RHS, Context.VoidTy);
3066     return Context.VoidTy;
3067   }
3068   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3069   // the type of the other operand."
3070   if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
3071        Context.isObjCObjectPointerType(LHSTy)) &&
3072       RHS->isNullPointerConstant(Context)) {
3073     ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3074     return LHSTy;
3075   }
3076   if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
3077        Context.isObjCObjectPointerType(RHSTy)) &&
3078       LHS->isNullPointerConstant(Context)) {
3079     ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3080     return RHSTy;
3081   }
3082   // Handle block pointer types.
3083   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3084     if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3085       if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3086         QualType destType = Context.getPointerType(Context.VoidTy);
3087         ImpCastExprToType(LHS, destType);
3088         ImpCastExprToType(RHS, destType);
3089         return destType;
3090       }
3091       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3092             << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3093       return QualType();
3094     }
3095     // We have 2 block pointer types.
3096     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3097       // Two identical block pointer types are always compatible.
3098       return LHSTy;
3099     }
3100     // The block pointer types aren't identical, continue checking.
3101     QualType lhptee = LHSTy->getAsBlockPointerType()->getPointeeType();
3102     QualType rhptee = RHSTy->getAsBlockPointerType()->getPointeeType();
3103 
3104     if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3105                                     rhptee.getUnqualifiedType())) {
3106       Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3107         << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3108       // In this situation, we assume void* type. No especially good
3109       // reason, but this is what gcc does, and we do have to pick
3110       // to get a consistent AST.
3111       QualType incompatTy = Context.getPointerType(Context.VoidTy);
3112       ImpCastExprToType(LHS, incompatTy);
3113       ImpCastExprToType(RHS, incompatTy);
3114       return incompatTy;
3115     }
3116     // The block pointer types are compatible.
3117     ImpCastExprToType(LHS, LHSTy);
3118     ImpCastExprToType(RHS, LHSTy);
3119     return LHSTy;
3120   }
3121   // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
3122   // evaluates to "struct objc_object *" (and is handled above when comparing
3123   // id with statically typed objects).
3124   if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
3125     // GCC allows qualified id and any Objective-C type to devolve to
3126     // id. Currently localizing to here until clear this should be
3127     // part of ObjCQualifiedIdTypesAreCompatible.
3128     if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
3129         (LHSTy->isObjCQualifiedIdType() &&
3130          Context.isObjCObjectPointerType(RHSTy)) ||
3131         (RHSTy->isObjCQualifiedIdType() &&
3132          Context.isObjCObjectPointerType(LHSTy))) {
3133       // FIXME: This is not the correct composite type. This only happens to
3134       // work because id can more or less be used anywhere, however this may
3135       // change the type of method sends.
3136 
3137       // FIXME: gcc adds some type-checking of the arguments and emits
3138       // (confusing) incompatible comparison warnings in some
3139       // cases. Investigate.
3140       QualType compositeType = Context.getObjCIdType();
3141       ImpCastExprToType(LHS, compositeType);
3142       ImpCastExprToType(RHS, compositeType);
3143       return compositeType;
3144     }
3145   }
3146   // Check constraints for Objective-C object pointers types.
3147   if (Context.isObjCObjectPointerType(LHSTy) &&
3148       Context.isObjCObjectPointerType(RHSTy)) {
3149 
3150     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3151       // Two identical object pointer types are always compatible.
3152       return LHSTy;
3153     }
3154     // No need to check for block pointer types or qualified id types (they
3155     // were handled above).
3156     assert((LHSTy->isPointerType() && RHSTy->isPointerType()) &&
3157            "Sema::CheckConditionalOperands(): Unexpected type");
3158     QualType lhptee = LHSTy->getAsPointerType()->getPointeeType();
3159     QualType rhptee = RHSTy->getAsPointerType()->getPointeeType();
3160 
3161     QualType compositeType = LHSTy;
3162 
3163     // If both operands are interfaces and either operand can be
3164     // assigned to the other, use that type as the composite
3165     // type. This allows
3166     //   xxx ? (A*) a : (B*) b
3167     // where B is a subclass of A.
3168     //
3169     // Additionally, as for assignment, if either type is 'id'
3170     // allow silent coercion. Finally, if the types are
3171     // incompatible then make sure to use 'id' as the composite
3172     // type so the result is acceptable for sending messages to.
3173 
3174     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3175     // It could return the composite type.
3176     const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
3177     const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
3178     if (LHSIface && RHSIface &&
3179         Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
3180       compositeType = LHSTy;
3181     } else if (LHSIface && RHSIface &&
3182                Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
3183       compositeType = RHSTy;
3184     } else if (Context.isObjCIdStructType(lhptee) ||
3185                Context.isObjCIdStructType(rhptee)) {
3186       compositeType = Context.getObjCIdType();
3187     } else {
3188       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3189         << LHSTy << RHSTy
3190         << LHS->getSourceRange() << RHS->getSourceRange();
3191       QualType incompatTy = Context.getObjCIdType();
3192       ImpCastExprToType(LHS, incompatTy);
3193       ImpCastExprToType(RHS, incompatTy);
3194       return incompatTy;
3195     }
3196     // The object pointer types are compatible.
3197     ImpCastExprToType(LHS, compositeType);
3198     ImpCastExprToType(RHS, compositeType);
3199     return compositeType;
3200   }
3201   // Check constraints for C object pointers types (C99 6.5.15p3,6).
3202   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3203     // get the "pointed to" types
3204     QualType lhptee = LHSTy->getAsPointerType()->getPointeeType();
3205     QualType rhptee = RHSTy->getAsPointerType()->getPointeeType();
3206 
3207     // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3208     if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3209       // Figure out necessary qualifiers (C99 6.5.15p6)
3210       QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3211       QualType destType = Context.getPointerType(destPointee);
3212       ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3213       ImpCastExprToType(RHS, destType); // promote to void*
3214       return destType;
3215     }
3216     if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3217       QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3218       QualType destType = Context.getPointerType(destPointee);
3219       ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3220       ImpCastExprToType(RHS, destType); // promote to void*
3221       return destType;
3222     }
3223 
3224     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3225       // Two identical pointer types are always compatible.
3226       return LHSTy;
3227     }
3228     if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3229                                     rhptee.getUnqualifiedType())) {
3230       Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3231         << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3232       // In this situation, we assume void* type. No especially good
3233       // reason, but this is what gcc does, and we do have to pick
3234       // to get a consistent AST.
3235       QualType incompatTy = Context.getPointerType(Context.VoidTy);
3236       ImpCastExprToType(LHS, incompatTy);
3237       ImpCastExprToType(RHS, incompatTy);
3238       return incompatTy;
3239     }
3240     // The pointer types are compatible.
3241     // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3242     // differently qualified versions of compatible types, the result type is
3243     // a pointer to an appropriately qualified version of the *composite*
3244     // type.
3245     // FIXME: Need to calculate the composite type.
3246     // FIXME: Need to add qualifiers
3247     ImpCastExprToType(LHS, LHSTy);
3248     ImpCastExprToType(RHS, LHSTy);
3249     return LHSTy;
3250   }
3251 
3252   // GCC compatibility: soften pointer/integer mismatch.
3253   if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3254     Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3255       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3256     ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3257     return RHSTy;
3258   }
3259   if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3260     Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3261       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3262     ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3263     return LHSTy;
3264   }
3265 
3266   // Otherwise, the operands are not compatible.
3267   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3268     << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3269   return QualType();
3270 }
3271 
3272 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3273 /// in the case of a the GNU conditional expr extension.
3274 Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3275                                                   SourceLocation ColonLoc,
3276                                                   ExprArg Cond, ExprArg LHS,
3277                                                   ExprArg RHS) {
3278   Expr *CondExpr = (Expr *) Cond.get();
3279   Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
3280 
3281   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3282   // was the condition.
3283   bool isLHSNull = LHSExpr == 0;
3284   if (isLHSNull)
3285     LHSExpr = CondExpr;
3286 
3287   QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
3288                                              RHSExpr, QuestionLoc);
3289   if (result.isNull())
3290     return ExprError();
3291 
3292   Cond.release();
3293   LHS.release();
3294   RHS.release();
3295   return Owned(new (Context) ConditionalOperator(CondExpr,
3296                                                  isLHSNull ? 0 : LHSExpr,
3297                                                  RHSExpr, result));
3298 }
3299 
3300 
3301 // CheckPointerTypesForAssignment - This is a very tricky routine (despite
3302 // being closely modeled after the C99 spec:-). The odd characteristic of this
3303 // routine is it effectively iqnores the qualifiers on the top level pointee.
3304 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3305 // FIXME: add a couple examples in this comment.
3306 Sema::AssignConvertType
3307 Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3308   QualType lhptee, rhptee;
3309 
3310   // get the "pointed to" type (ignoring qualifiers at the top level)
3311   lhptee = lhsType->getAsPointerType()->getPointeeType();
3312   rhptee = rhsType->getAsPointerType()->getPointeeType();
3313 
3314   // make sure we operate on the canonical type
3315   lhptee = Context.getCanonicalType(lhptee);
3316   rhptee = Context.getCanonicalType(rhptee);
3317 
3318   AssignConvertType ConvTy = Compatible;
3319 
3320   // C99 6.5.16.1p1: This following citation is common to constraints
3321   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3322   // qualifiers of the type *pointed to* by the right;
3323   // FIXME: Handle ExtQualType
3324   if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
3325     ConvTy = CompatiblePointerDiscardsQualifiers;
3326 
3327   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3328   // incomplete type and the other is a pointer to a qualified or unqualified
3329   // version of void...
3330   if (lhptee->isVoidType()) {
3331     if (rhptee->isIncompleteOrObjectType())
3332       return ConvTy;
3333 
3334     // As an extension, we allow cast to/from void* to function pointer.
3335     assert(rhptee->isFunctionType());
3336     return FunctionVoidPointer;
3337   }
3338 
3339   if (rhptee->isVoidType()) {
3340     if (lhptee->isIncompleteOrObjectType())
3341       return ConvTy;
3342 
3343     // As an extension, we allow cast to/from void* to function pointer.
3344     assert(lhptee->isFunctionType());
3345     return FunctionVoidPointer;
3346   }
3347   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
3348   // unqualified versions of compatible types, ...
3349   lhptee = lhptee.getUnqualifiedType();
3350   rhptee = rhptee.getUnqualifiedType();
3351   if (!Context.typesAreCompatible(lhptee, rhptee)) {
3352     // Check if the pointee types are compatible ignoring the sign.
3353     // We explicitly check for char so that we catch "char" vs
3354     // "unsigned char" on systems where "char" is unsigned.
3355     if (lhptee->isCharType()) {
3356       lhptee = Context.UnsignedCharTy;
3357     } else if (lhptee->isSignedIntegerType()) {
3358       lhptee = Context.getCorrespondingUnsignedType(lhptee);
3359     }
3360     if (rhptee->isCharType()) {
3361       rhptee = Context.UnsignedCharTy;
3362     } else if (rhptee->isSignedIntegerType()) {
3363       rhptee = Context.getCorrespondingUnsignedType(rhptee);
3364     }
3365     if (lhptee == rhptee) {
3366       // Types are compatible ignoring the sign. Qualifier incompatibility
3367       // takes priority over sign incompatibility because the sign
3368       // warning can be disabled.
3369       if (ConvTy != Compatible)
3370         return ConvTy;
3371       return IncompatiblePointerSign;
3372     }
3373     // General pointer incompatibility takes priority over qualifiers.
3374     return IncompatiblePointer;
3375   }
3376   return ConvTy;
3377 }
3378 
3379 /// CheckBlockPointerTypesForAssignment - This routine determines whether two
3380 /// block pointer types are compatible or whether a block and normal pointer
3381 /// are compatible. It is more restrict than comparing two function pointer
3382 // types.
3383 Sema::AssignConvertType
3384 Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
3385                                           QualType rhsType) {
3386   QualType lhptee, rhptee;
3387 
3388   // get the "pointed to" type (ignoring qualifiers at the top level)
3389   lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
3390   rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
3391 
3392   // make sure we operate on the canonical type
3393   lhptee = Context.getCanonicalType(lhptee);
3394   rhptee = Context.getCanonicalType(rhptee);
3395 
3396   AssignConvertType ConvTy = Compatible;
3397 
3398   // For blocks we enforce that qualifiers are identical.
3399   if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3400     ConvTy = CompatiblePointerDiscardsQualifiers;
3401 
3402   if (!Context.typesAreCompatible(lhptee, rhptee))
3403     return IncompatibleBlockPointer;
3404   return ConvTy;
3405 }
3406 
3407 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3408 /// has code to accommodate several GCC extensions when type checking
3409 /// pointers. Here are some objectionable examples that GCC considers warnings:
3410 ///
3411 ///  int a, *pint;
3412 ///  short *pshort;
3413 ///  struct foo *pfoo;
3414 ///
3415 ///  pint = pshort; // warning: assignment from incompatible pointer type
3416 ///  a = pint; // warning: assignment makes integer from pointer without a cast
3417 ///  pint = a; // warning: assignment makes pointer from integer without a cast
3418 ///  pint = pfoo; // warning: assignment from incompatible pointer type
3419 ///
3420 /// As a result, the code for dealing with pointers is more complex than the
3421 /// C99 spec dictates.
3422 ///
3423 Sema::AssignConvertType
3424 Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
3425   // Get canonical types.  We're not formatting these types, just comparing
3426   // them.
3427   lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3428   rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
3429 
3430   if (lhsType == rhsType)
3431     return Compatible; // Common case: fast path an exact match.
3432 
3433   // If the left-hand side is a reference type, then we are in a
3434   // (rare!) case where we've allowed the use of references in C,
3435   // e.g., as a parameter type in a built-in function. In this case,
3436   // just make sure that the type referenced is compatible with the
3437   // right-hand side type. The caller is responsible for adjusting
3438   // lhsType so that the resulting expression does not have reference
3439   // type.
3440   if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
3441     if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
3442       return Compatible;
3443     return Incompatible;
3444   }
3445 
3446   if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
3447     if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
3448       return Compatible;
3449     // Relax integer conversions like we do for pointers below.
3450     if (rhsType->isIntegerType())
3451       return IntToPointer;
3452     if (lhsType->isIntegerType())
3453       return PointerToInt;
3454     return IncompatibleObjCQualifiedId;
3455   }
3456 
3457   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3458   // to the same ExtVector type.
3459   if (lhsType->isExtVectorType()) {
3460     if (rhsType->isExtVectorType())
3461       return lhsType == rhsType ? Compatible : Incompatible;
3462     if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3463       return Compatible;
3464   }
3465 
3466   if (lhsType->isVectorType() || rhsType->isVectorType()) {
3467     // If we are allowing lax vector conversions, and LHS and RHS are both
3468     // vectors, the total size only needs to be the same. This is a bitcast;
3469     // no bits are changed but the result type is different.
3470     if (getLangOptions().LaxVectorConversions &&
3471         lhsType->isVectorType() && rhsType->isVectorType()) {
3472       if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
3473         return IncompatibleVectors;
3474     }
3475     return Incompatible;
3476   }
3477 
3478   if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
3479     return Compatible;
3480 
3481   if (isa<PointerType>(lhsType)) {
3482     if (rhsType->isIntegerType())
3483       return IntToPointer;
3484 
3485     if (isa<PointerType>(rhsType))
3486       return CheckPointerTypesForAssignment(lhsType, rhsType);
3487 
3488     if (rhsType->getAsBlockPointerType()) {
3489       if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
3490         return Compatible;
3491 
3492       // Treat block pointers as objects.
3493       if (getLangOptions().ObjC1 &&
3494           lhsType == Context.getCanonicalType(Context.getObjCIdType()))
3495         return Compatible;
3496     }
3497     return Incompatible;
3498   }
3499 
3500   if (isa<BlockPointerType>(lhsType)) {
3501     if (rhsType->isIntegerType())
3502       return IntToBlockPointer;
3503 
3504     // Treat block pointers as objects.
3505     if (getLangOptions().ObjC1 &&
3506         rhsType == Context.getCanonicalType(Context.getObjCIdType()))
3507       return Compatible;
3508 
3509     if (rhsType->isBlockPointerType())
3510       return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
3511 
3512     if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
3513       if (RHSPT->getPointeeType()->isVoidType())
3514         return Compatible;
3515     }
3516     return Incompatible;
3517   }
3518 
3519   if (isa<PointerType>(rhsType)) {
3520     // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3521     if (lhsType == Context.BoolTy)
3522       return Compatible;
3523 
3524     if (lhsType->isIntegerType())
3525       return PointerToInt;
3526 
3527     if (isa<PointerType>(lhsType))
3528       return CheckPointerTypesForAssignment(lhsType, rhsType);
3529 
3530     if (isa<BlockPointerType>(lhsType) &&
3531         rhsType->getAsPointerType()->getPointeeType()->isVoidType())
3532       return Compatible;
3533     return Incompatible;
3534   }
3535 
3536   if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
3537     if (Context.typesAreCompatible(lhsType, rhsType))
3538       return Compatible;
3539   }
3540   return Incompatible;
3541 }
3542 
3543 /// \brief Constructs a transparent union from an expression that is
3544 /// used to initialize the transparent union.
3545 static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3546                                       QualType UnionType, FieldDecl *Field) {
3547   // Build an initializer list that designates the appropriate member
3548   // of the transparent union.
3549   InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3550                                                    &E, 1,
3551                                                    SourceLocation());
3552   Initializer->setType(UnionType);
3553   Initializer->setInitializedFieldInUnion(Field);
3554 
3555   // Build a compound literal constructing a value of the transparent
3556   // union type from this initializer list.
3557   E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3558                                   false);
3559 }
3560 
3561 Sema::AssignConvertType
3562 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3563   QualType FromType = rExpr->getType();
3564 
3565   // If the ArgType is a Union type, we want to handle a potential
3566   // transparent_union GCC extension.
3567   const RecordType *UT = ArgType->getAsUnionType();
3568   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3569     return Incompatible;
3570 
3571   // The field to initialize within the transparent union.
3572   RecordDecl *UD = UT->getDecl();
3573   FieldDecl *InitField = 0;
3574   // It's compatible if the expression matches any of the fields.
3575   for (RecordDecl::field_iterator it = UD->field_begin(),
3576          itend = UD->field_end();
3577        it != itend; ++it) {
3578     if (it->getType()->isPointerType()) {
3579       // If the transparent union contains a pointer type, we allow:
3580       // 1) void pointer
3581       // 2) null pointer constant
3582       if (FromType->isPointerType())
3583         if (FromType->getAsPointerType()->getPointeeType()->isVoidType()) {
3584           ImpCastExprToType(rExpr, it->getType());
3585           InitField = *it;
3586           break;
3587         }
3588 
3589       if (rExpr->isNullPointerConstant(Context)) {
3590         ImpCastExprToType(rExpr, it->getType());
3591         InitField = *it;
3592         break;
3593       }
3594     }
3595 
3596     if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3597           == Compatible) {
3598       InitField = *it;
3599       break;
3600     }
3601   }
3602 
3603   if (!InitField)
3604     return Incompatible;
3605 
3606   ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3607   return Compatible;
3608 }
3609 
3610 Sema::AssignConvertType
3611 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
3612   if (getLangOptions().CPlusPlus) {
3613     if (!lhsType->isRecordType()) {
3614       // C++ 5.17p3: If the left operand is not of class type, the
3615       // expression is implicitly converted (C++ 4) to the
3616       // cv-unqualified type of the left operand.
3617       if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3618                                     "assigning"))
3619         return Incompatible;
3620       return Compatible;
3621     }
3622 
3623     // FIXME: Currently, we fall through and treat C++ classes like C
3624     // structures.
3625   }
3626 
3627   // C99 6.5.16.1p1: the left operand is a pointer and the right is
3628   // a null pointer constant.
3629   if ((lhsType->isPointerType() ||
3630        lhsType->isObjCQualifiedIdType() ||
3631        lhsType->isBlockPointerType())
3632       && rExpr->isNullPointerConstant(Context)) {
3633     ImpCastExprToType(rExpr, lhsType);
3634     return Compatible;
3635   }
3636 
3637   // This check seems unnatural, however it is necessary to ensure the proper
3638   // conversion of functions/arrays. If the conversion were done for all
3639   // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
3640   // expressions that surpress this implicit conversion (&, sizeof).
3641   //
3642   // Suppress this for references: C++ 8.5.3p5.
3643   if (!lhsType->isReferenceType())
3644     DefaultFunctionArrayConversion(rExpr);
3645 
3646   Sema::AssignConvertType result =
3647     CheckAssignmentConstraints(lhsType, rExpr->getType());
3648 
3649   // C99 6.5.16.1p2: The value of the right operand is converted to the
3650   // type of the assignment expression.
3651   // CheckAssignmentConstraints allows the left-hand side to be a reference,
3652   // so that we can use references in built-in functions even in C.
3653   // The getNonReferenceType() call makes sure that the resulting expression
3654   // does not have reference type.
3655   if (result != Incompatible && rExpr->getType() != lhsType)
3656     ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
3657   return result;
3658 }
3659 
3660 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
3661   Diag(Loc, diag::err_typecheck_invalid_operands)
3662     << lex->getType() << rex->getType()
3663     << lex->getSourceRange() << rex->getSourceRange();
3664   return QualType();
3665 }
3666 
3667 inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
3668                                                               Expr *&rex) {
3669   // For conversion purposes, we ignore any qualifiers.
3670   // For example, "const float" and "float" are equivalent.
3671   QualType lhsType =
3672     Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3673   QualType rhsType =
3674     Context.getCanonicalType(rex->getType()).getUnqualifiedType();
3675 
3676   // If the vector types are identical, return.
3677   if (lhsType == rhsType)
3678     return lhsType;
3679 
3680   // Handle the case of a vector & extvector type of the same size and element
3681   // type.  It would be nice if we only had one vector type someday.
3682   if (getLangOptions().LaxVectorConversions) {
3683     // FIXME: Should we warn here?
3684     if (const VectorType *LV = lhsType->getAsVectorType()) {
3685       if (const VectorType *RV = rhsType->getAsVectorType())
3686         if (LV->getElementType() == RV->getElementType() &&
3687             LV->getNumElements() == RV->getNumElements()) {
3688           return lhsType->isExtVectorType() ? lhsType : rhsType;
3689         }
3690     }
3691   }
3692 
3693   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3694   // swap back (so that we don't reverse the inputs to a subtract, for instance.
3695   bool swapped = false;
3696   if (rhsType->isExtVectorType()) {
3697     swapped = true;
3698     std::swap(rex, lex);
3699     std::swap(rhsType, lhsType);
3700   }
3701 
3702   // Handle the case of an ext vector and scalar.
3703   if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3704     QualType EltTy = LV->getElementType();
3705     if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3706       if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
3707         ImpCastExprToType(rex, lhsType);
3708         if (swapped) std::swap(rex, lex);
3709         return lhsType;
3710       }
3711     }
3712     if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3713         rhsType->isRealFloatingType()) {
3714       if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
3715         ImpCastExprToType(rex, lhsType);
3716         if (swapped) std::swap(rex, lex);
3717         return lhsType;
3718       }
3719     }
3720   }
3721 
3722   // Vectors of different size or scalar and non-ext-vector are errors.
3723   Diag(Loc, diag::err_typecheck_vector_not_convertable)
3724     << lex->getType() << rex->getType()
3725     << lex->getSourceRange() << rex->getSourceRange();
3726   return QualType();
3727 }
3728 
3729 inline QualType Sema::CheckMultiplyDivideOperands(
3730   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3731 {
3732   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3733     return CheckVectorOperands(Loc, lex, rex);
3734 
3735   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3736 
3737   if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3738     return compType;
3739   return InvalidOperands(Loc, lex, rex);
3740 }
3741 
3742 inline QualType Sema::CheckRemainderOperands(
3743   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3744 {
3745   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3746     if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3747       return CheckVectorOperands(Loc, lex, rex);
3748     return InvalidOperands(Loc, lex, rex);
3749   }
3750 
3751   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3752 
3753   if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3754     return compType;
3755   return InvalidOperands(Loc, lex, rex);
3756 }
3757 
3758 inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
3759   Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
3760 {
3761   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3762     QualType compType = CheckVectorOperands(Loc, lex, rex);
3763     if (CompLHSTy) *CompLHSTy = compType;
3764     return compType;
3765   }
3766 
3767   QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
3768 
3769   // handle the common case first (both operands are arithmetic).
3770   if (lex->getType()->isArithmeticType() &&
3771       rex->getType()->isArithmeticType()) {
3772     if (CompLHSTy) *CompLHSTy = compType;
3773     return compType;
3774   }
3775 
3776   // Put any potential pointer into PExp
3777   Expr* PExp = lex, *IExp = rex;
3778   if (IExp->getType()->isPointerType())
3779     std::swap(PExp, IExp);
3780 
3781   if (const PointerType *PTy = PExp->getType()->getAsPointerType()) {
3782     if (IExp->getType()->isIntegerType()) {
3783       QualType PointeeTy = PTy->getPointeeType();
3784       // Check for arithmetic on pointers to incomplete types.
3785       if (PointeeTy->isVoidType()) {
3786         if (getLangOptions().CPlusPlus) {
3787           Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3788             << lex->getSourceRange() << rex->getSourceRange();
3789           return QualType();
3790         }
3791 
3792         // GNU extension: arithmetic on pointer to void
3793         Diag(Loc, diag::ext_gnu_void_ptr)
3794           << lex->getSourceRange() << rex->getSourceRange();
3795       } else if (PointeeTy->isFunctionType()) {
3796         if (getLangOptions().CPlusPlus) {
3797           Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3798             << lex->getType() << lex->getSourceRange();
3799           return QualType();
3800         }
3801 
3802         // GNU extension: arithmetic on pointer to function
3803         Diag(Loc, diag::ext_gnu_ptr_func_arith)
3804           << lex->getType() << lex->getSourceRange();
3805       } else if (!PTy->isDependentType() &&
3806                  RequireCompleteType(Loc, PointeeTy,
3807                                 diag::err_typecheck_arithmetic_incomplete_type,
3808                                      PExp->getSourceRange(), SourceRange(),
3809                                      PExp->getType()))
3810         return QualType();
3811 
3812       // Diagnose bad cases where we step over interface counts.
3813       if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3814         Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3815           << PointeeTy << PExp->getSourceRange();
3816         return QualType();
3817       }
3818 
3819       if (CompLHSTy) {
3820         QualType LHSTy = lex->getType();
3821         if (LHSTy->isPromotableIntegerType())
3822           LHSTy = Context.IntTy;
3823         else {
3824           QualType T = isPromotableBitField(lex, Context);
3825           if (!T.isNull())
3826             LHSTy = T;
3827         }
3828 
3829         *CompLHSTy = LHSTy;
3830       }
3831       return PExp->getType();
3832     }
3833   }
3834 
3835   return InvalidOperands(Loc, lex, rex);
3836 }
3837 
3838 // C99 6.5.6
3839 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
3840                                         SourceLocation Loc, QualType* CompLHSTy) {
3841   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3842     QualType compType = CheckVectorOperands(Loc, lex, rex);
3843     if (CompLHSTy) *CompLHSTy = compType;
3844     return compType;
3845   }
3846 
3847   QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
3848 
3849   // Enforce type constraints: C99 6.5.6p3.
3850 
3851   // Handle the common case first (both operands are arithmetic).
3852   if (lex->getType()->isArithmeticType()
3853       && rex->getType()->isArithmeticType()) {
3854     if (CompLHSTy) *CompLHSTy = compType;
3855     return compType;
3856   }
3857 
3858   // Either ptr - int   or   ptr - ptr.
3859   if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
3860     QualType lpointee = LHSPTy->getPointeeType();
3861 
3862     // The LHS must be an completely-defined object type.
3863 
3864     bool ComplainAboutVoid = false;
3865     Expr *ComplainAboutFunc = 0;
3866     if (lpointee->isVoidType()) {
3867       if (getLangOptions().CPlusPlus) {
3868         Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3869           << lex->getSourceRange() << rex->getSourceRange();
3870         return QualType();
3871       }
3872 
3873       // GNU C extension: arithmetic on pointer to void
3874       ComplainAboutVoid = true;
3875     } else if (lpointee->isFunctionType()) {
3876       if (getLangOptions().CPlusPlus) {
3877         Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3878           << lex->getType() << lex->getSourceRange();
3879         return QualType();
3880       }
3881 
3882       // GNU C extension: arithmetic on pointer to function
3883       ComplainAboutFunc = lex;
3884     } else if (!lpointee->isDependentType() &&
3885                RequireCompleteType(Loc, lpointee,
3886                                    diag::err_typecheck_sub_ptr_object,
3887                                    lex->getSourceRange(),
3888                                    SourceRange(),
3889                                    lex->getType()))
3890       return QualType();
3891 
3892     // Diagnose bad cases where we step over interface counts.
3893     if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3894       Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3895         << lpointee << lex->getSourceRange();
3896       return QualType();
3897     }
3898 
3899     // The result type of a pointer-int computation is the pointer type.
3900     if (rex->getType()->isIntegerType()) {
3901       if (ComplainAboutVoid)
3902         Diag(Loc, diag::ext_gnu_void_ptr)
3903           << lex->getSourceRange() << rex->getSourceRange();
3904       if (ComplainAboutFunc)
3905         Diag(Loc, diag::ext_gnu_ptr_func_arith)
3906           << ComplainAboutFunc->getType()
3907           << ComplainAboutFunc->getSourceRange();
3908 
3909       if (CompLHSTy) *CompLHSTy = lex->getType();
3910       return lex->getType();
3911     }
3912 
3913     // Handle pointer-pointer subtractions.
3914     if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
3915       QualType rpointee = RHSPTy->getPointeeType();
3916 
3917       // RHS must be a completely-type object type.
3918       // Handle the GNU void* extension.
3919       if (rpointee->isVoidType()) {
3920         if (getLangOptions().CPlusPlus) {
3921           Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3922             << lex->getSourceRange() << rex->getSourceRange();
3923           return QualType();
3924         }
3925 
3926         ComplainAboutVoid = true;
3927       } else if (rpointee->isFunctionType()) {
3928         if (getLangOptions().CPlusPlus) {
3929           Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3930             << rex->getType() << rex->getSourceRange();
3931           return QualType();
3932         }
3933 
3934         // GNU extension: arithmetic on pointer to function
3935         if (!ComplainAboutFunc)
3936           ComplainAboutFunc = rex;
3937       } else if (!rpointee->isDependentType() &&
3938                  RequireCompleteType(Loc, rpointee,
3939                                      diag::err_typecheck_sub_ptr_object,
3940                                      rex->getSourceRange(),
3941                                      SourceRange(),
3942                                      rex->getType()))
3943         return QualType();
3944 
3945       if (getLangOptions().CPlusPlus) {
3946         // Pointee types must be the same: C++ [expr.add]
3947         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
3948           Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
3949             << lex->getType() << rex->getType()
3950             << lex->getSourceRange() << rex->getSourceRange();
3951           return QualType();
3952         }
3953       } else {
3954         // Pointee types must be compatible C99 6.5.6p3
3955         if (!Context.typesAreCompatible(
3956                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
3957                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
3958           Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
3959             << lex->getType() << rex->getType()
3960             << lex->getSourceRange() << rex->getSourceRange();
3961           return QualType();
3962         }
3963       }
3964 
3965       if (ComplainAboutVoid)
3966         Diag(Loc, diag::ext_gnu_void_ptr)
3967           << lex->getSourceRange() << rex->getSourceRange();
3968       if (ComplainAboutFunc)
3969         Diag(Loc, diag::ext_gnu_ptr_func_arith)
3970           << ComplainAboutFunc->getType()
3971           << ComplainAboutFunc->getSourceRange();
3972 
3973       if (CompLHSTy) *CompLHSTy = lex->getType();
3974       return Context.getPointerDiffType();
3975     }
3976   }
3977 
3978   return InvalidOperands(Loc, lex, rex);
3979 }
3980 
3981 // C99 6.5.7
3982 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
3983                                   bool isCompAssign) {
3984   // C99 6.5.7p2: Each of the operands shall have integer type.
3985   if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
3986     return InvalidOperands(Loc, lex, rex);
3987 
3988   // Shifts don't perform usual arithmetic conversions, they just do integer
3989   // promotions on each operand. C99 6.5.7p3
3990   QualType LHSTy;
3991   if (lex->getType()->isPromotableIntegerType())
3992     LHSTy = Context.IntTy;
3993   else {
3994     LHSTy = isPromotableBitField(lex, Context);
3995     if (LHSTy.isNull())
3996       LHSTy = lex->getType();
3997   }
3998   if (!isCompAssign)
3999     ImpCastExprToType(lex, LHSTy);
4000 
4001   UsualUnaryConversions(rex);
4002 
4003   // "The type of the result is that of the promoted left operand."
4004   return LHSTy;
4005 }
4006 
4007 // C99 6.5.8, C++ [expr.rel]
4008 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4009                                     unsigned OpaqueOpc, bool isRelational) {
4010   BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4011 
4012   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4013     return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
4014 
4015   // C99 6.5.8p3 / C99 6.5.9p4
4016   if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4017     UsualArithmeticConversions(lex, rex);
4018   else {
4019     UsualUnaryConversions(lex);
4020     UsualUnaryConversions(rex);
4021   }
4022   QualType lType = lex->getType();
4023   QualType rType = rex->getType();
4024 
4025   if (!lType->isFloatingType()
4026       && !(lType->isBlockPointerType() && isRelational)) {
4027     // For non-floating point types, check for self-comparisons of the form
4028     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4029     // often indicate logic errors in the program.
4030     // NOTE: Don't warn about comparisons of enum constants. These can arise
4031     //  from macro expansions, and are usually quite deliberate.
4032     Expr *LHSStripped = lex->IgnoreParens();
4033     Expr *RHSStripped = rex->IgnoreParens();
4034     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4035       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
4036         if (DRL->getDecl() == DRR->getDecl() &&
4037             !isa<EnumConstantDecl>(DRL->getDecl()))
4038           Diag(Loc, diag::warn_selfcomparison);
4039 
4040     if (isa<CastExpr>(LHSStripped))
4041       LHSStripped = LHSStripped->IgnoreParenCasts();
4042     if (isa<CastExpr>(RHSStripped))
4043       RHSStripped = RHSStripped->IgnoreParenCasts();
4044 
4045     // Warn about comparisons against a string constant (unless the other
4046     // operand is null), the user probably wants strcmp.
4047     Expr *literalString = 0;
4048     Expr *literalStringStripped = 0;
4049     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
4050         !RHSStripped->isNullPointerConstant(Context)) {
4051       literalString = lex;
4052       literalStringStripped = LHSStripped;
4053     }
4054     else if ((isa<StringLiteral>(RHSStripped) ||
4055               isa<ObjCEncodeExpr>(RHSStripped)) &&
4056              !LHSStripped->isNullPointerConstant(Context)) {
4057       literalString = rex;
4058       literalStringStripped = RHSStripped;
4059     }
4060 
4061     if (literalString) {
4062       std::string resultComparison;
4063       switch (Opc) {
4064       case BinaryOperator::LT: resultComparison = ") < 0"; break;
4065       case BinaryOperator::GT: resultComparison = ") > 0"; break;
4066       case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4067       case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4068       case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4069       case BinaryOperator::NE: resultComparison = ") != 0"; break;
4070       default: assert(false && "Invalid comparison operator");
4071       }
4072       Diag(Loc, diag::warn_stringcompare)
4073         << isa<ObjCEncodeExpr>(literalStringStripped)
4074         << literalString->getSourceRange()
4075         << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4076         << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4077                                                  "strcmp(")
4078         << CodeModificationHint::CreateInsertion(
4079                                        PP.getLocForEndOfToken(rex->getLocEnd()),
4080                                        resultComparison);
4081     }
4082   }
4083 
4084   // The result of comparisons is 'bool' in C++, 'int' in C.
4085   QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
4086 
4087   if (isRelational) {
4088     if (lType->isRealType() && rType->isRealType())
4089       return ResultTy;
4090   } else {
4091     // Check for comparisons of floating point operands using != and ==.
4092     if (lType->isFloatingType()) {
4093       assert(rType->isFloatingType());
4094       CheckFloatComparison(Loc,lex,rex);
4095     }
4096 
4097     if (lType->isArithmeticType() && rType->isArithmeticType())
4098       return ResultTy;
4099   }
4100 
4101   bool LHSIsNull = lex->isNullPointerConstant(Context);
4102   bool RHSIsNull = rex->isNullPointerConstant(Context);
4103 
4104   // All of the following pointer related warnings are GCC extensions, except
4105   // when handling null pointer constants. One day, we can consider making them
4106   // errors (when -pedantic-errors is enabled).
4107   if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
4108     QualType LCanPointeeTy =
4109       Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
4110     QualType RCanPointeeTy =
4111       Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
4112 
4113     if (rType->isFunctionPointerType() || lType->isFunctionPointerType()) {
4114       if (isRelational) {
4115         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4116           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4117       }
4118     }
4119     if (((!LHSIsNull || isRelational) && LCanPointeeTy->isVoidType()) !=
4120         ((!RHSIsNull || isRelational) && RCanPointeeTy->isVoidType())) {
4121       Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4122         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4123     }
4124     // Simple check: if the pointee types are identical, we're done.
4125     if (LCanPointeeTy == RCanPointeeTy)
4126       return ResultTy;
4127 
4128     if (getLangOptions().CPlusPlus) {
4129       // C++ [expr.rel]p2:
4130       //   [...] Pointer conversions (4.10) and qualification
4131       //   conversions (4.4) are performed on pointer operands (or on
4132       //   a pointer operand and a null pointer constant) to bring
4133       //   them to their composite pointer type. [...]
4134       //
4135       // C++ [expr.eq]p2 uses the same notion for (in)equality
4136       // comparisons of pointers.
4137       QualType T = FindCompositePointerType(lex, rex);
4138       if (T.isNull()) {
4139         Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4140           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4141         return QualType();
4142       }
4143 
4144       ImpCastExprToType(lex, T);
4145       ImpCastExprToType(rex, T);
4146       return ResultTy;
4147     }
4148 
4149     if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
4150         !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
4151         !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4152                                     RCanPointeeTy.getUnqualifiedType()) &&
4153         !Context.areComparableObjCPointerTypes(lType, rType)) {
4154       Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4155         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4156     }
4157     ImpCastExprToType(rex, lType); // promote the pointer to pointer
4158     return ResultTy;
4159   }
4160   // C++ allows comparison of pointers with null pointer constants.
4161   if (getLangOptions().CPlusPlus) {
4162     if (lType->isPointerType() && RHSIsNull) {
4163       ImpCastExprToType(rex, lType);
4164       return ResultTy;
4165     }
4166     if (rType->isPointerType() && LHSIsNull) {
4167       ImpCastExprToType(lex, rType);
4168       return ResultTy;
4169     }
4170     // And comparison of nullptr_t with itself.
4171     if (lType->isNullPtrType() && rType->isNullPtrType())
4172       return ResultTy;
4173   }
4174   // Handle block pointer types.
4175   if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
4176     QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
4177     QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
4178 
4179     if (!LHSIsNull && !RHSIsNull &&
4180         !Context.typesAreCompatible(lpointee, rpointee)) {
4181       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4182         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4183     }
4184     ImpCastExprToType(rex, lType); // promote the pointer to pointer
4185     return ResultTy;
4186   }
4187   // Allow block pointers to be compared with null pointer constants.
4188   if (!isRelational
4189       && ((lType->isBlockPointerType() && rType->isPointerType())
4190           || (lType->isPointerType() && rType->isBlockPointerType()))) {
4191     if (!LHSIsNull && !RHSIsNull) {
4192       if (!((rType->isPointerType() && rType->getAsPointerType()
4193              ->getPointeeType()->isVoidType())
4194             || (lType->isPointerType() && lType->getAsPointerType()
4195                 ->getPointeeType()->isVoidType())))
4196         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4197           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4198     }
4199     ImpCastExprToType(rex, lType); // promote the pointer to pointer
4200     return ResultTy;
4201   }
4202 
4203   if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
4204     if (lType->isPointerType() || rType->isPointerType()) {
4205       const PointerType *LPT = lType->getAsPointerType();
4206       const PointerType *RPT = rType->getAsPointerType();
4207       bool LPtrToVoid = LPT ?
4208         Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
4209       bool RPtrToVoid = RPT ?
4210         Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
4211 
4212       if (!LPtrToVoid && !RPtrToVoid &&
4213           !Context.typesAreCompatible(lType, rType)) {
4214         Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4215           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4216         ImpCastExprToType(rex, lType);
4217         return ResultTy;
4218       }
4219       ImpCastExprToType(rex, lType);
4220       return ResultTy;
4221     }
4222     if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
4223       ImpCastExprToType(rex, lType);
4224       return ResultTy;
4225     } else {
4226       if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
4227         Diag(Loc, diag::warn_incompatible_qualified_id_operands)
4228           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4229         ImpCastExprToType(rex, lType);
4230         return ResultTy;
4231       }
4232     }
4233   }
4234   if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
4235        rType->isIntegerType()) {
4236     if (isRelational)
4237       Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4238         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4239     else if (!RHSIsNull)
4240       Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
4241         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4242     ImpCastExprToType(rex, lType); // promote the integer to pointer
4243     return ResultTy;
4244   }
4245   if (lType->isIntegerType() &&
4246       (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
4247     if (isRelational)
4248       Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4249         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4250     else if (!LHSIsNull)
4251       Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
4252         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4253     ImpCastExprToType(lex, rType); // promote the integer to pointer
4254     return ResultTy;
4255   }
4256   // Handle block pointers.
4257   if (!isRelational && RHSIsNull
4258       && lType->isBlockPointerType() && rType->isIntegerType()) {
4259     ImpCastExprToType(rex, lType); // promote the integer to pointer
4260     return ResultTy;
4261   }
4262   if (!isRelational && LHSIsNull
4263       && lType->isIntegerType() && rType->isBlockPointerType()) {
4264     ImpCastExprToType(lex, rType); // promote the integer to pointer
4265     return ResultTy;
4266   }
4267   return InvalidOperands(Loc, lex, rex);
4268 }
4269 
4270 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
4271 /// operates on extended vector types.  Instead of producing an IntTy result,
4272 /// like a scalar comparison, a vector comparison produces a vector of integer
4273 /// types.
4274 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
4275                                           SourceLocation Loc,
4276                                           bool isRelational) {
4277   // Check to make sure we're operating on vectors of the same type and width,
4278   // Allowing one side to be a scalar of element type.
4279   QualType vType = CheckVectorOperands(Loc, lex, rex);
4280   if (vType.isNull())
4281     return vType;
4282 
4283   QualType lType = lex->getType();
4284   QualType rType = rex->getType();
4285 
4286   // For non-floating point types, check for self-comparisons of the form
4287   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4288   // often indicate logic errors in the program.
4289   if (!lType->isFloatingType()) {
4290     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4291       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4292         if (DRL->getDecl() == DRR->getDecl())
4293           Diag(Loc, diag::warn_selfcomparison);
4294   }
4295 
4296   // Check for comparisons of floating point operands using != and ==.
4297   if (!isRelational && lType->isFloatingType()) {
4298     assert (rType->isFloatingType());
4299     CheckFloatComparison(Loc,lex,rex);
4300   }
4301 
4302   // FIXME: Vector compare support in the LLVM backend is not fully reliable,
4303   // just reject all vector comparisons for now.
4304   if (1) {
4305     Diag(Loc, diag::err_typecheck_vector_comparison)
4306       << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4307     return QualType();
4308   }
4309 
4310   // Return the type for the comparison, which is the same as vector type for
4311   // integer vectors, or an integer type of identical size and number of
4312   // elements for floating point vectors.
4313   if (lType->isIntegerType())
4314     return lType;
4315 
4316   const VectorType *VTy = lType->getAsVectorType();
4317   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
4318   if (TypeSize == Context.getTypeSize(Context.IntTy))
4319     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
4320   if (TypeSize == Context.getTypeSize(Context.LongTy))
4321     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4322 
4323   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
4324          "Unhandled vector element size in vector compare");
4325   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4326 }
4327 
4328 inline QualType Sema::CheckBitwiseOperands(
4329   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
4330 {
4331   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4332     return CheckVectorOperands(Loc, lex, rex);
4333 
4334   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4335 
4336   if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4337     return compType;
4338   return InvalidOperands(Loc, lex, rex);
4339 }
4340 
4341 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
4342   Expr *&lex, Expr *&rex, SourceLocation Loc)
4343 {
4344   UsualUnaryConversions(lex);
4345   UsualUnaryConversions(rex);
4346 
4347   if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
4348     return Context.IntTy;
4349   return InvalidOperands(Loc, lex, rex);
4350 }
4351 
4352 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4353 /// is a read-only property; return true if so. A readonly property expression
4354 /// depends on various declarations and thus must be treated specially.
4355 ///
4356 static bool IsReadonlyProperty(Expr *E, Sema &S)
4357 {
4358   if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4359     const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4360     if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4361       QualType BaseType = PropExpr->getBase()->getType();
4362       if (const PointerType *PTy = BaseType->getAsPointerType())
4363         if (const ObjCInterfaceType *IFTy =
4364             PTy->getPointeeType()->getAsObjCInterfaceType())
4365           if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
4366             if (S.isPropertyReadonly(PDecl, IFace))
4367               return true;
4368     }
4369   }
4370   return false;
4371 }
4372 
4373 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
4374 /// emit an error and return true.  If so, return false.
4375 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
4376   SourceLocation OrigLoc = Loc;
4377   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4378                                                               &Loc);
4379   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4380     IsLV = Expr::MLV_ReadonlyProperty;
4381   if (IsLV == Expr::MLV_Valid)
4382     return false;
4383 
4384   unsigned Diag = 0;
4385   bool NeedType = false;
4386   switch (IsLV) { // C99 6.5.16p2
4387   default: assert(0 && "Unknown result from isModifiableLvalue!");
4388   case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
4389   case Expr::MLV_ArrayType:
4390     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4391     NeedType = true;
4392     break;
4393   case Expr::MLV_NotObjectType:
4394     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4395     NeedType = true;
4396     break;
4397   case Expr::MLV_LValueCast:
4398     Diag = diag::err_typecheck_lvalue_casts_not_supported;
4399     break;
4400   case Expr::MLV_InvalidExpression:
4401     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4402     break;
4403   case Expr::MLV_IncompleteType:
4404   case Expr::MLV_IncompleteVoidType:
4405     return S.RequireCompleteType(Loc, E->getType(),
4406                       diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4407                                     E->getSourceRange());
4408   case Expr::MLV_DuplicateVectorComponents:
4409     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4410     break;
4411   case Expr::MLV_NotBlockQualified:
4412     Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4413     break;
4414   case Expr::MLV_ReadonlyProperty:
4415     Diag = diag::error_readonly_property_assignment;
4416     break;
4417   case Expr::MLV_NoSetterProperty:
4418     Diag = diag::error_nosetter_property_assignment;
4419     break;
4420   }
4421 
4422   SourceRange Assign;
4423   if (Loc != OrigLoc)
4424     Assign = SourceRange(OrigLoc, OrigLoc);
4425   if (NeedType)
4426     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
4427   else
4428     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
4429   return true;
4430 }
4431 
4432 
4433 
4434 // C99 6.5.16.1
4435 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4436                                        SourceLocation Loc,
4437                                        QualType CompoundType) {
4438   // Verify that LHS is a modifiable lvalue, and emit error if not.
4439   if (CheckForModifiableLvalue(LHS, Loc, *this))
4440     return QualType();
4441 
4442   QualType LHSType = LHS->getType();
4443   QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
4444 
4445   AssignConvertType ConvTy;
4446   if (CompoundType.isNull()) {
4447     // Simple assignment "x = y".
4448     ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
4449     // Special case of NSObject attributes on c-style pointer types.
4450     if (ConvTy == IncompatiblePointer &&
4451         ((Context.isObjCNSObjectType(LHSType) &&
4452           Context.isObjCObjectPointerType(RHSType)) ||
4453          (Context.isObjCNSObjectType(RHSType) &&
4454           Context.isObjCObjectPointerType(LHSType))))
4455       ConvTy = Compatible;
4456 
4457     // If the RHS is a unary plus or minus, check to see if they = and + are
4458     // right next to each other.  If so, the user may have typo'd "x =+ 4"
4459     // instead of "x += 4".
4460     Expr *RHSCheck = RHS;
4461     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4462       RHSCheck = ICE->getSubExpr();
4463     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4464       if ((UO->getOpcode() == UnaryOperator::Plus ||
4465            UO->getOpcode() == UnaryOperator::Minus) &&
4466           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
4467           // Only if the two operators are exactly adjacent.
4468           Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4469           // And there is a space or other character before the subexpr of the
4470           // unary +/-.  We don't want to warn on "x=-1".
4471           Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4472           UO->getSubExpr()->getLocStart().isFileID()) {
4473         Diag(Loc, diag::warn_not_compound_assign)
4474           << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4475           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
4476       }
4477     }
4478   } else {
4479     // Compound assignment "x += y"
4480     ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
4481   }
4482 
4483   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4484                                RHS, "assigning"))
4485     return QualType();
4486 
4487   // C99 6.5.16p3: The type of an assignment expression is the type of the
4488   // left operand unless the left operand has qualified type, in which case
4489   // it is the unqualified version of the type of the left operand.
4490   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4491   // is converted to the type of the assignment expression (above).
4492   // C++ 5.17p1: the type of the assignment expression is that of its left
4493   // operand.
4494   return LHSType.getUnqualifiedType();
4495 }
4496 
4497 // C99 6.5.17
4498 QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
4499   // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
4500   DefaultFunctionArrayConversion(RHS);
4501 
4502   // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4503   // incomplete in C++).
4504 
4505   return RHS->getType();
4506 }
4507 
4508 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4509 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
4510 QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4511                                               bool isInc) {
4512   if (Op->isTypeDependent())
4513     return Context.DependentTy;
4514 
4515   QualType ResType = Op->getType();
4516   assert(!ResType.isNull() && "no type for increment/decrement expression");
4517 
4518   if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4519     // Decrement of bool is not allowed.
4520     if (!isInc) {
4521       Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4522       return QualType();
4523     }
4524     // Increment of bool sets it to true, but is deprecated.
4525     Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4526   } else if (ResType->isRealType()) {
4527     // OK!
4528   } else if (const PointerType *PT = ResType->getAsPointerType()) {
4529     // C99 6.5.2.4p2, 6.5.6p2
4530     if (PT->getPointeeType()->isVoidType()) {
4531       if (getLangOptions().CPlusPlus) {
4532         Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4533           << Op->getSourceRange();
4534         return QualType();
4535       }
4536 
4537       // Pointer to void is a GNU extension in C.
4538       Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
4539     } else if (PT->getPointeeType()->isFunctionType()) {
4540       if (getLangOptions().CPlusPlus) {
4541         Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4542           << Op->getType() << Op->getSourceRange();
4543         return QualType();
4544       }
4545 
4546       Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
4547         << ResType << Op->getSourceRange();
4548     } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
4549                                diag::err_typecheck_arithmetic_incomplete_type,
4550                                    Op->getSourceRange(), SourceRange(),
4551                                    ResType))
4552       return QualType();
4553   } else if (ResType->isComplexType()) {
4554     // C99 does not support ++/-- on complex types, we allow as an extension.
4555     Diag(OpLoc, diag::ext_integer_increment_complex)
4556       << ResType << Op->getSourceRange();
4557   } else {
4558     Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
4559       << ResType << Op->getSourceRange();
4560     return QualType();
4561   }
4562   // At this point, we know we have a real, complex or pointer type.
4563   // Now make sure the operand is a modifiable lvalue.
4564   if (CheckForModifiableLvalue(Op, OpLoc, *this))
4565     return QualType();
4566   return ResType;
4567 }
4568 
4569 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
4570 /// This routine allows us to typecheck complex/recursive expressions
4571 /// where the declaration is needed for type checking. We only need to
4572 /// handle cases when the expression references a function designator
4573 /// or is an lvalue. Here are some examples:
4574 ///  - &(x) => x
4575 ///  - &*****f => f for f a function designator.
4576 ///  - &s.xx => s
4577 ///  - &s.zz[1].yy -> s, if zz is an array
4578 ///  - *(x + 1) -> x, if x is an array
4579 ///  - &"123"[2] -> 0
4580 ///  - & __real__ x -> x
4581 static NamedDecl *getPrimaryDecl(Expr *E) {
4582   switch (E->getStmtClass()) {
4583   case Stmt::DeclRefExprClass:
4584   case Stmt::QualifiedDeclRefExprClass:
4585     return cast<DeclRefExpr>(E)->getDecl();
4586   case Stmt::MemberExprClass:
4587     // If this is an arrow operator, the address is an offset from
4588     // the base's value, so the object the base refers to is
4589     // irrelevant.
4590     if (cast<MemberExpr>(E)->isArrow())
4591       return 0;
4592     // Otherwise, the expression refers to a part of the base
4593     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
4594   case Stmt::ArraySubscriptExprClass: {
4595     // FIXME: This code shouldn't be necessary!  We should catch the implicit
4596     // promotion of register arrays earlier.
4597     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4598     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4599       if (ICE->getSubExpr()->getType()->isArrayType())
4600         return getPrimaryDecl(ICE->getSubExpr());
4601     }
4602     return 0;
4603   }
4604   case Stmt::UnaryOperatorClass: {
4605     UnaryOperator *UO = cast<UnaryOperator>(E);
4606 
4607     switch(UO->getOpcode()) {
4608     case UnaryOperator::Real:
4609     case UnaryOperator::Imag:
4610     case UnaryOperator::Extension:
4611       return getPrimaryDecl(UO->getSubExpr());
4612     default:
4613       return 0;
4614     }
4615   }
4616   case Stmt::ParenExprClass:
4617     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
4618   case Stmt::ImplicitCastExprClass:
4619     // If the result of an implicit cast is an l-value, we care about
4620     // the sub-expression; otherwise, the result here doesn't matter.
4621     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
4622   default:
4623     return 0;
4624   }
4625 }
4626 
4627 /// CheckAddressOfOperand - The operand of & must be either a function
4628 /// designator or an lvalue designating an object. If it is an lvalue, the
4629 /// object cannot be declared with storage class register or be a bit field.
4630 /// Note: The usual conversions are *not* applied to the operand of the &
4631 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
4632 /// In C++, the operand might be an overloaded function name, in which case
4633 /// we allow the '&' but retain the overloaded-function type.
4634 QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
4635   // Make sure to ignore parentheses in subsequent checks
4636   op = op->IgnoreParens();
4637 
4638   if (op->isTypeDependent())
4639     return Context.DependentTy;
4640 
4641   if (getLangOptions().C99) {
4642     // Implement C99-only parts of addressof rules.
4643     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4644       if (uOp->getOpcode() == UnaryOperator::Deref)
4645         // Per C99 6.5.3.2, the address of a deref always returns a valid result
4646         // (assuming the deref expression is valid).
4647         return uOp->getSubExpr()->getType();
4648     }
4649     // Technically, there should be a check for array subscript
4650     // expressions here, but the result of one is always an lvalue anyway.
4651   }
4652   NamedDecl *dcl = getPrimaryDecl(op);
4653   Expr::isLvalueResult lval = op->isLvalue(Context);
4654 
4655   if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4656     // C99 6.5.3.2p1
4657     // The operand must be either an l-value or a function designator
4658     if (!op->getType()->isFunctionType()) {
4659       // FIXME: emit more specific diag...
4660       Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4661         << op->getSourceRange();
4662       return QualType();
4663     }
4664   } else if (op->getBitField()) { // C99 6.5.3.2p1
4665     // The operand cannot be a bit-field
4666     Diag(OpLoc, diag::err_typecheck_address_of)
4667       << "bit-field" << op->getSourceRange();
4668         return QualType();
4669   } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4670            cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
4671     // The operand cannot be an element of a vector
4672     Diag(OpLoc, diag::err_typecheck_address_of)
4673       << "vector element" << op->getSourceRange();
4674     return QualType();
4675   } else if (dcl) { // C99 6.5.3.2p1
4676     // We have an lvalue with a decl. Make sure the decl is not declared
4677     // with the register storage-class specifier.
4678     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4679       if (vd->getStorageClass() == VarDecl::Register) {
4680         Diag(OpLoc, diag::err_typecheck_address_of)
4681           << "register variable" << op->getSourceRange();
4682         return QualType();
4683       }
4684     } else if (isa<OverloadedFunctionDecl>(dcl)) {
4685       return Context.OverloadTy;
4686     } else if (isa<FieldDecl>(dcl)) {
4687       // Okay: we can take the address of a field.
4688       // Could be a pointer to member, though, if there is an explicit
4689       // scope qualifier for the class.
4690       if (isa<QualifiedDeclRefExpr>(op)) {
4691         DeclContext *Ctx = dcl->getDeclContext();
4692         if (Ctx && Ctx->isRecord())
4693           return Context.getMemberPointerType(op->getType(),
4694                 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4695       }
4696     } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
4697       // Okay: we can take the address of a function.
4698       // As above.
4699       if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4700         return Context.getMemberPointerType(op->getType(),
4701               Context.getTypeDeclType(MD->getParent()).getTypePtr());
4702     } else if (!isa<FunctionDecl>(dcl))
4703       assert(0 && "Unknown/unexpected decl type");
4704   }
4705 
4706   if (lval == Expr::LV_IncompleteVoidType) {
4707     // Taking the address of a void variable is technically illegal, but we
4708     // allow it in cases which are otherwise valid.
4709     // Example: "extern void x; void* y = &x;".
4710     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4711   }
4712 
4713   // If the operand has type "type", the result has type "pointer to type".
4714   return Context.getPointerType(op->getType());
4715 }
4716 
4717 QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
4718   if (Op->isTypeDependent())
4719     return Context.DependentTy;
4720 
4721   UsualUnaryConversions(Op);
4722   QualType Ty = Op->getType();
4723 
4724   // Note that per both C89 and C99, this is always legal, even if ptype is an
4725   // incomplete type or void.  It would be possible to warn about dereferencing
4726   // a void pointer, but it's completely well-defined, and such a warning is
4727   // unlikely to catch any mistakes.
4728   if (const PointerType *PT = Ty->getAsPointerType())
4729     return PT->getPointeeType();
4730 
4731   Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
4732     << Ty << Op->getSourceRange();
4733   return QualType();
4734 }
4735 
4736 static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4737   tok::TokenKind Kind) {
4738   BinaryOperator::Opcode Opc;
4739   switch (Kind) {
4740   default: assert(0 && "Unknown binop!");
4741   case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
4742   case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
4743   case tok::star:                 Opc = BinaryOperator::Mul; break;
4744   case tok::slash:                Opc = BinaryOperator::Div; break;
4745   case tok::percent:              Opc = BinaryOperator::Rem; break;
4746   case tok::plus:                 Opc = BinaryOperator::Add; break;
4747   case tok::minus:                Opc = BinaryOperator::Sub; break;
4748   case tok::lessless:             Opc = BinaryOperator::Shl; break;
4749   case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
4750   case tok::lessequal:            Opc = BinaryOperator::LE; break;
4751   case tok::less:                 Opc = BinaryOperator::LT; break;
4752   case tok::greaterequal:         Opc = BinaryOperator::GE; break;
4753   case tok::greater:              Opc = BinaryOperator::GT; break;
4754   case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
4755   case tok::equalequal:           Opc = BinaryOperator::EQ; break;
4756   case tok::amp:                  Opc = BinaryOperator::And; break;
4757   case tok::caret:                Opc = BinaryOperator::Xor; break;
4758   case tok::pipe:                 Opc = BinaryOperator::Or; break;
4759   case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
4760   case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
4761   case tok::equal:                Opc = BinaryOperator::Assign; break;
4762   case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
4763   case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
4764   case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
4765   case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
4766   case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
4767   case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
4768   case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
4769   case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
4770   case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
4771   case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
4772   case tok::comma:                Opc = BinaryOperator::Comma; break;
4773   }
4774   return Opc;
4775 }
4776 
4777 static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4778   tok::TokenKind Kind) {
4779   UnaryOperator::Opcode Opc;
4780   switch (Kind) {
4781   default: assert(0 && "Unknown unary op!");
4782   case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
4783   case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
4784   case tok::amp:          Opc = UnaryOperator::AddrOf; break;
4785   case tok::star:         Opc = UnaryOperator::Deref; break;
4786   case tok::plus:         Opc = UnaryOperator::Plus; break;
4787   case tok::minus:        Opc = UnaryOperator::Minus; break;
4788   case tok::tilde:        Opc = UnaryOperator::Not; break;
4789   case tok::exclaim:      Opc = UnaryOperator::LNot; break;
4790   case tok::kw___real:    Opc = UnaryOperator::Real; break;
4791   case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
4792   case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4793   }
4794   return Opc;
4795 }
4796 
4797 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
4798 /// operator @p Opc at location @c TokLoc. This routine only supports
4799 /// built-in operations; ActOnBinOp handles overloaded operators.
4800 Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4801                                                   unsigned Op,
4802                                                   Expr *lhs, Expr *rhs) {
4803   QualType ResultTy;     // Result type of the binary operator.
4804   BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
4805   // The following two variables are used for compound assignment operators
4806   QualType CompLHSTy;    // Type of LHS after promotions for computation
4807   QualType CompResultTy; // Type of computation result
4808 
4809   switch (Opc) {
4810   case BinaryOperator::Assign:
4811     ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4812     break;
4813   case BinaryOperator::PtrMemD:
4814   case BinaryOperator::PtrMemI:
4815     ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4816                                             Opc == BinaryOperator::PtrMemI);
4817     break;
4818   case BinaryOperator::Mul:
4819   case BinaryOperator::Div:
4820     ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4821     break;
4822   case BinaryOperator::Rem:
4823     ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4824     break;
4825   case BinaryOperator::Add:
4826     ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4827     break;
4828   case BinaryOperator::Sub:
4829     ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4830     break;
4831   case BinaryOperator::Shl:
4832   case BinaryOperator::Shr:
4833     ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4834     break;
4835   case BinaryOperator::LE:
4836   case BinaryOperator::LT:
4837   case BinaryOperator::GE:
4838   case BinaryOperator::GT:
4839     ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
4840     break;
4841   case BinaryOperator::EQ:
4842   case BinaryOperator::NE:
4843     ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
4844     break;
4845   case BinaryOperator::And:
4846   case BinaryOperator::Xor:
4847   case BinaryOperator::Or:
4848     ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4849     break;
4850   case BinaryOperator::LAnd:
4851   case BinaryOperator::LOr:
4852     ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4853     break;
4854   case BinaryOperator::MulAssign:
4855   case BinaryOperator::DivAssign:
4856     CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4857     CompLHSTy = CompResultTy;
4858     if (!CompResultTy.isNull())
4859       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
4860     break;
4861   case BinaryOperator::RemAssign:
4862     CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4863     CompLHSTy = CompResultTy;
4864     if (!CompResultTy.isNull())
4865       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
4866     break;
4867   case BinaryOperator::AddAssign:
4868     CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4869     if (!CompResultTy.isNull())
4870       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
4871     break;
4872   case BinaryOperator::SubAssign:
4873     CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4874     if (!CompResultTy.isNull())
4875       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
4876     break;
4877   case BinaryOperator::ShlAssign:
4878   case BinaryOperator::ShrAssign:
4879     CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4880     CompLHSTy = CompResultTy;
4881     if (!CompResultTy.isNull())
4882       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
4883     break;
4884   case BinaryOperator::AndAssign:
4885   case BinaryOperator::XorAssign:
4886   case BinaryOperator::OrAssign:
4887     CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4888     CompLHSTy = CompResultTy;
4889     if (!CompResultTy.isNull())
4890       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
4891     break;
4892   case BinaryOperator::Comma:
4893     ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4894     break;
4895   }
4896   if (ResultTy.isNull())
4897     return ExprError();
4898   if (CompResultTy.isNull())
4899     return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4900   else
4901     return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
4902                                                       CompLHSTy, CompResultTy,
4903                                                       OpLoc));
4904 }
4905 
4906 // Binary Operators.  'Tok' is the token for the operator.
4907 Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4908                                           tok::TokenKind Kind,
4909                                           ExprArg LHS, ExprArg RHS) {
4910   BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
4911   Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
4912 
4913   assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4914   assert((rhs != 0) && "ActOnBinOp(): missing right expression");
4915 
4916   if (getLangOptions().CPlusPlus &&
4917       (lhs->getType()->isOverloadableType() ||
4918        rhs->getType()->isOverloadableType())) {
4919     // Find all of the overloaded operators visible from this
4920     // point. We perform both an operator-name lookup from the local
4921     // scope and an argument-dependent lookup based on the types of
4922     // the arguments.
4923     FunctionSet Functions;
4924     OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4925     if (OverOp != OO_None) {
4926       LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4927                                    Functions);
4928       Expr *Args[2] = { lhs, rhs };
4929       DeclarationName OpName
4930         = Context.DeclarationNames.getCXXOperatorName(OverOp);
4931       ArgumentDependentLookup(OpName, Args, 2, Functions);
4932     }
4933 
4934     // Build the (potentially-overloaded, potentially-dependent)
4935     // binary operation.
4936     return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
4937   }
4938 
4939   // Build a built-in binary operation.
4940   return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
4941 }
4942 
4943 Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4944                                                     unsigned OpcIn,
4945                                                     ExprArg InputArg) {
4946   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4947 
4948   // FIXME: Input is modified below, but InputArg is not updated appropriately.
4949   Expr *Input = (Expr *)InputArg.get();
4950   QualType resultType;
4951   switch (Opc) {
4952   case UnaryOperator::PostInc:
4953   case UnaryOperator::PostDec:
4954   case UnaryOperator::OffsetOf:
4955     assert(false && "Invalid unary operator");
4956     break;
4957 
4958   case UnaryOperator::PreInc:
4959   case UnaryOperator::PreDec:
4960     resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4961                                                 Opc == UnaryOperator::PreInc);
4962     break;
4963   case UnaryOperator::AddrOf:
4964     resultType = CheckAddressOfOperand(Input, OpLoc);
4965     break;
4966   case UnaryOperator::Deref:
4967     DefaultFunctionArrayConversion(Input);
4968     resultType = CheckIndirectionOperand(Input, OpLoc);
4969     break;
4970   case UnaryOperator::Plus:
4971   case UnaryOperator::Minus:
4972     UsualUnaryConversions(Input);
4973     resultType = Input->getType();
4974     if (resultType->isDependentType())
4975       break;
4976     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4977       break;
4978     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4979              resultType->isEnumeralType())
4980       break;
4981     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4982              Opc == UnaryOperator::Plus &&
4983              resultType->isPointerType())
4984       break;
4985 
4986     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4987       << resultType << Input->getSourceRange());
4988   case UnaryOperator::Not: // bitwise complement
4989     UsualUnaryConversions(Input);
4990     resultType = Input->getType();
4991     if (resultType->isDependentType())
4992       break;
4993     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4994     if (resultType->isComplexType() || resultType->isComplexIntegerType())
4995       // C99 does not support '~' for complex conjugation.
4996       Diag(OpLoc, diag::ext_integer_complement_complex)
4997         << resultType << Input->getSourceRange();
4998     else if (!resultType->isIntegerType())
4999       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5000         << resultType << Input->getSourceRange());
5001     break;
5002   case UnaryOperator::LNot: // logical negation
5003     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5004     DefaultFunctionArrayConversion(Input);
5005     resultType = Input->getType();
5006     if (resultType->isDependentType())
5007       break;
5008     if (!resultType->isScalarType()) // C99 6.5.3.3p1
5009       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5010         << resultType << Input->getSourceRange());
5011     // LNot always has type int. C99 6.5.3.3p5.
5012     // In C++, it's bool. C++ 5.3.1p8
5013     resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
5014     break;
5015   case UnaryOperator::Real:
5016   case UnaryOperator::Imag:
5017     resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
5018     break;
5019   case UnaryOperator::Extension:
5020     resultType = Input->getType();
5021     break;
5022   }
5023   if (resultType.isNull())
5024     return ExprError();
5025 
5026   InputArg.release();
5027   return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
5028 }
5029 
5030 // Unary Operators.  'Tok' is the token for the operator.
5031 Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5032                                             tok::TokenKind Op, ExprArg input) {
5033   Expr *Input = (Expr*)input.get();
5034   UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5035 
5036   if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5037     // Find all of the overloaded operators visible from this
5038     // point. We perform both an operator-name lookup from the local
5039     // scope and an argument-dependent lookup based on the types of
5040     // the arguments.
5041     FunctionSet Functions;
5042     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5043     if (OverOp != OO_None) {
5044       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5045                                    Functions);
5046       DeclarationName OpName
5047         = Context.DeclarationNames.getCXXOperatorName(OverOp);
5048       ArgumentDependentLookup(OpName, &Input, 1, Functions);
5049     }
5050 
5051     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5052   }
5053 
5054   return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5055 }
5056 
5057 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5058 Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5059                                             SourceLocation LabLoc,
5060                                             IdentifierInfo *LabelII) {
5061   // Look up the record for this label identifier.
5062   LabelStmt *&LabelDecl = getLabelMap()[LabelII];
5063 
5064   // If we haven't seen this label yet, create a forward reference. It
5065   // will be validated and/or cleaned up in ActOnFinishFunctionBody.
5066   if (LabelDecl == 0)
5067     LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
5068 
5069   // Create the AST node.  The address of a label always has type 'void*'.
5070   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5071                                        Context.getPointerType(Context.VoidTy)));
5072 }
5073 
5074 Sema::OwningExprResult
5075 Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5076                     SourceLocation RPLoc) { // "({..})"
5077   Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
5078   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5079   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5080 
5081   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
5082   if (isFileScope)
5083     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
5084 
5085   // FIXME: there are a variety of strange constraints to enforce here, for
5086   // example, it is not possible to goto into a stmt expression apparently.
5087   // More semantic analysis is needed.
5088 
5089   // If there are sub stmts in the compound stmt, take the type of the last one
5090   // as the type of the stmtexpr.
5091   QualType Ty = Context.VoidTy;
5092 
5093   if (!Compound->body_empty()) {
5094     Stmt *LastStmt = Compound->body_back();
5095     // If LastStmt is a label, skip down through into the body.
5096     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5097       LastStmt = Label->getSubStmt();
5098 
5099     if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
5100       Ty = LastExpr->getType();
5101   }
5102 
5103   // FIXME: Check that expression type is complete/non-abstract; statement
5104   // expressions are not lvalues.
5105 
5106   substmt.release();
5107   return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
5108 }
5109 
5110 Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5111                                                   SourceLocation BuiltinLoc,
5112                                                   SourceLocation TypeLoc,
5113                                                   TypeTy *argty,
5114                                                   OffsetOfComponent *CompPtr,
5115                                                   unsigned NumComponents,
5116                                                   SourceLocation RPLoc) {
5117   // FIXME: This function leaks all expressions in the offset components on
5118   // error.
5119   QualType ArgTy = QualType::getFromOpaquePtr(argty);
5120   assert(!ArgTy.isNull() && "Missing type argument!");
5121 
5122   bool Dependent = ArgTy->isDependentType();
5123 
5124   // We must have at least one component that refers to the type, and the first
5125   // one is known to be a field designator.  Verify that the ArgTy represents
5126   // a struct/union/class.
5127   if (!Dependent && !ArgTy->isRecordType())
5128     return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
5129 
5130   // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5131   // with an incomplete type would be illegal.
5132 
5133   // Otherwise, create a null pointer as the base, and iteratively process
5134   // the offsetof designators.
5135   QualType ArgTyPtr = Context.getPointerType(ArgTy);
5136   Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
5137   Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
5138                                     ArgTy, SourceLocation());
5139 
5140   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5141   // GCC extension, diagnose them.
5142   // FIXME: This diagnostic isn't actually visible because the location is in
5143   // a system header!
5144   if (NumComponents != 1)
5145     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5146       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
5147 
5148   if (!Dependent) {
5149     bool DidWarnAboutNonPOD = false;
5150 
5151     // FIXME: Dependent case loses a lot of information here. And probably
5152     // leaks like a sieve.
5153     for (unsigned i = 0; i != NumComponents; ++i) {
5154       const OffsetOfComponent &OC = CompPtr[i];
5155       if (OC.isBrackets) {
5156         // Offset of an array sub-field.  TODO: Should we allow vector elements?
5157         const ArrayType *AT = Context.getAsArrayType(Res->getType());
5158         if (!AT) {
5159           Res->Destroy(Context);
5160           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5161             << Res->getType());
5162         }
5163 
5164         // FIXME: C++: Verify that operator[] isn't overloaded.
5165 
5166         // Promote the array so it looks more like a normal array subscript
5167         // expression.
5168         DefaultFunctionArrayConversion(Res);
5169 
5170         // C99 6.5.2.1p1
5171         Expr *Idx = static_cast<Expr*>(OC.U.E);
5172         // FIXME: Leaks Res
5173         if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
5174           return ExprError(Diag(Idx->getLocStart(),
5175                                 diag::err_typecheck_subscript_not_integer)
5176             << Idx->getSourceRange());
5177 
5178         Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5179                                                OC.LocEnd);
5180         continue;
5181       }
5182 
5183       const RecordType *RC = Res->getType()->getAsRecordType();
5184       if (!RC) {
5185         Res->Destroy(Context);
5186         return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5187           << Res->getType());
5188       }
5189 
5190       // Get the decl corresponding to this.
5191       RecordDecl *RD = RC->getDecl();
5192       if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5193         if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
5194           ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5195             << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5196             << Res->getType());
5197           DidWarnAboutNonPOD = true;
5198         }
5199       }
5200 
5201       FieldDecl *MemberDecl
5202         = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5203                                                           LookupMemberName)
5204                                         .getAsDecl());
5205       // FIXME: Leaks Res
5206       if (!MemberDecl)
5207         return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5208          << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
5209 
5210       // FIXME: C++: Verify that MemberDecl isn't a static field.
5211       // FIXME: Verify that MemberDecl isn't a bitfield.
5212       if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
5213         Res = BuildAnonymousStructUnionMemberReference(
5214             SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
5215       } else {
5216         // MemberDecl->getType() doesn't get the right qualifiers, but it
5217         // doesn't matter here.
5218         Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5219                 MemberDecl->getType().getNonReferenceType());
5220       }
5221     }
5222   }
5223 
5224   return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5225                                            Context.getSizeType(), BuiltinLoc));
5226 }
5227 
5228 
5229 Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5230                                                       TypeTy *arg1,TypeTy *arg2,
5231                                                       SourceLocation RPLoc) {
5232   QualType argT1 = QualType::getFromOpaquePtr(arg1);
5233   QualType argT2 = QualType::getFromOpaquePtr(arg2);
5234 
5235   assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
5236 
5237   if (getLangOptions().CPlusPlus) {
5238     Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5239       << SourceRange(BuiltinLoc, RPLoc);
5240     return ExprError();
5241   }
5242 
5243   return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5244                                                  argT1, argT2, RPLoc));
5245 }
5246 
5247 Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5248                                              ExprArg cond,
5249                                              ExprArg expr1, ExprArg expr2,
5250                                              SourceLocation RPLoc) {
5251   Expr *CondExpr = static_cast<Expr*>(cond.get());
5252   Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5253   Expr *RHSExpr = static_cast<Expr*>(expr2.get());
5254 
5255   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5256 
5257   QualType resType;
5258   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
5259     resType = Context.DependentTy;
5260   } else {
5261     // The conditional expression is required to be a constant expression.
5262     llvm::APSInt condEval(32);
5263     SourceLocation ExpLoc;
5264     if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
5265       return ExprError(Diag(ExpLoc,
5266                        diag::err_typecheck_choose_expr_requires_constant)
5267         << CondExpr->getSourceRange());
5268 
5269     // If the condition is > zero, then the AST type is the same as the LSHExpr.
5270     resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5271   }
5272 
5273   cond.release(); expr1.release(); expr2.release();
5274   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5275                                         resType, RPLoc));
5276 }
5277 
5278 //===----------------------------------------------------------------------===//
5279 // Clang Extensions.
5280 //===----------------------------------------------------------------------===//
5281 
5282 /// ActOnBlockStart - This callback is invoked when a block literal is started.
5283 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
5284   // Analyze block parameters.
5285   BlockSemaInfo *BSI = new BlockSemaInfo();
5286 
5287   // Add BSI to CurBlock.
5288   BSI->PrevBlockInfo = CurBlock;
5289   CurBlock = BSI;
5290 
5291   BSI->ReturnType = QualType();
5292   BSI->TheScope = BlockScope;
5293   BSI->hasBlockDeclRefExprs = false;
5294   BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5295   CurFunctionNeedsScopeChecking = false;
5296 
5297   BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
5298   PushDeclContext(BlockScope, BSI->TheDecl);
5299 }
5300 
5301 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
5302   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
5303 
5304   if (ParamInfo.getNumTypeObjects() == 0
5305       || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
5306     ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5307     QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5308 
5309     if (T->isArrayType()) {
5310       Diag(ParamInfo.getSourceRange().getBegin(),
5311            diag::err_block_returns_array);
5312       return;
5313     }
5314 
5315     // The parameter list is optional, if there was none, assume ().
5316     if (!T->isFunctionType())
5317       T = Context.getFunctionType(T, NULL, 0, 0, 0);
5318 
5319     CurBlock->hasPrototype = true;
5320     CurBlock->isVariadic = false;
5321     // Check for a valid sentinel attribute on this block.
5322     if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5323       Diag(ParamInfo.getAttributes()->getLoc(),
5324            diag::warn_attribute_sentinel_not_variadic) << 1;
5325       // FIXME: remove the attribute.
5326     }
5327     QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5328 
5329     // Do not allow returning a objc interface by-value.
5330     if (RetTy->isObjCInterfaceType()) {
5331       Diag(ParamInfo.getSourceRange().getBegin(),
5332            diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5333       return;
5334     }
5335     return;
5336   }
5337 
5338   // Analyze arguments to block.
5339   assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5340          "Not a function declarator!");
5341   DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
5342 
5343   CurBlock->hasPrototype = FTI.hasPrototype;
5344   CurBlock->isVariadic = true;
5345 
5346   // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5347   // no arguments, not a function that takes a single void argument.
5348   if (FTI.hasPrototype &&
5349       FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5350      (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5351         FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
5352     // empty arg list, don't push any params.
5353     CurBlock->isVariadic = false;
5354   } else if (FTI.hasPrototype) {
5355     for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
5356       CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
5357     CurBlock->isVariadic = FTI.isVariadic;
5358   }
5359   CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
5360                                CurBlock->Params.size());
5361   CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
5362   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5363   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5364        E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5365     // If this has an identifier, add it to the scope stack.
5366     if ((*AI)->getIdentifier())
5367       PushOnScopeChains(*AI, CurBlock->TheScope);
5368 
5369   // Check for a valid sentinel attribute on this block.
5370   if (!CurBlock->isVariadic &&
5371       CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5372     Diag(ParamInfo.getAttributes()->getLoc(),
5373          diag::warn_attribute_sentinel_not_variadic) << 1;
5374     // FIXME: remove the attribute.
5375   }
5376 
5377   // Analyze the return type.
5378   QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5379   QualType RetTy = T->getAsFunctionType()->getResultType();
5380 
5381   // Do not allow returning a objc interface by-value.
5382   if (RetTy->isObjCInterfaceType()) {
5383     Diag(ParamInfo.getSourceRange().getBegin(),
5384          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5385   } else if (!RetTy->isDependentType())
5386     CurBlock->ReturnType = RetTy;
5387 }
5388 
5389 /// ActOnBlockError - If there is an error parsing a block, this callback
5390 /// is invoked to pop the information about the block from the action impl.
5391 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5392   // Ensure that CurBlock is deleted.
5393   llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
5394 
5395   CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5396 
5397   // Pop off CurBlock, handle nested blocks.
5398   PopDeclContext();
5399   CurBlock = CurBlock->PrevBlockInfo;
5400   // FIXME: Delete the ParmVarDecl objects as well???
5401 }
5402 
5403 /// ActOnBlockStmtExpr - This is called when the body of a block statement
5404 /// literal was successfully completed.  ^(int x){...}
5405 Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5406                                                 StmtArg body, Scope *CurScope) {
5407   // If blocks are disabled, emit an error.
5408   if (!LangOpts.Blocks)
5409     Diag(CaretLoc, diag::err_blocks_disable);
5410 
5411   // Ensure that CurBlock is deleted.
5412   llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
5413 
5414   PopDeclContext();
5415 
5416   // Pop off CurBlock, handle nested blocks.
5417   CurBlock = CurBlock->PrevBlockInfo;
5418 
5419   QualType RetTy = Context.VoidTy;
5420   if (!BSI->ReturnType.isNull())
5421     RetTy = BSI->ReturnType;
5422 
5423   llvm::SmallVector<QualType, 8> ArgTypes;
5424   for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5425     ArgTypes.push_back(BSI->Params[i]->getType());
5426 
5427   QualType BlockTy;
5428   if (!BSI->hasPrototype)
5429     BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0);
5430   else
5431     BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
5432                                       BSI->isVariadic, 0);
5433 
5434   // FIXME: Check that return/parameter types are complete/non-abstract
5435   DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
5436   BlockTy = Context.getBlockPointerType(BlockTy);
5437 
5438   // If needed, diagnose invalid gotos and switches in the block.
5439   if (CurFunctionNeedsScopeChecking)
5440     DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5441   CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5442 
5443   BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
5444   return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5445                                        BSI->hasBlockDeclRefExprs));
5446 }
5447 
5448 Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5449                                         ExprArg expr, TypeTy *type,
5450                                         SourceLocation RPLoc) {
5451   QualType T = QualType::getFromOpaquePtr(type);
5452   Expr *E = static_cast<Expr*>(expr.get());
5453   Expr *OrigExpr = E;
5454 
5455   InitBuiltinVaListType();
5456 
5457   // Get the va_list type
5458   QualType VaListType = Context.getBuiltinVaListType();
5459   if (VaListType->isArrayType()) {
5460     // Deal with implicit array decay; for example, on x86-64,
5461     // va_list is an array, but it's supposed to decay to
5462     // a pointer for va_arg.
5463     VaListType = Context.getArrayDecayedType(VaListType);
5464     // Make sure the input expression also decays appropriately.
5465     UsualUnaryConversions(E);
5466   } else {
5467     // Otherwise, the va_list argument must be an l-value because
5468     // it is modified by va_arg.
5469     if (!E->isTypeDependent() &&
5470         CheckForModifiableLvalue(E, BuiltinLoc, *this))
5471       return ExprError();
5472   }
5473 
5474   if (!E->isTypeDependent() &&
5475       !Context.hasSameType(VaListType, E->getType())) {
5476     return ExprError(Diag(E->getLocStart(),
5477                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
5478       << OrigExpr->getType() << E->getSourceRange());
5479   }
5480 
5481   // FIXME: Check that type is complete/non-abstract
5482   // FIXME: Warn if a non-POD type is passed in.
5483 
5484   expr.release();
5485   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5486                                        RPLoc));
5487 }
5488 
5489 Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
5490   // The type of __null will be int or long, depending on the size of
5491   // pointers on the target.
5492   QualType Ty;
5493   if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5494     Ty = Context.IntTy;
5495   else
5496     Ty = Context.LongTy;
5497 
5498   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
5499 }
5500 
5501 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5502                                     SourceLocation Loc,
5503                                     QualType DstType, QualType SrcType,
5504                                     Expr *SrcExpr, const char *Flavor) {
5505   // Decode the result (notice that AST's are still created for extensions).
5506   bool isInvalid = false;
5507   unsigned DiagKind;
5508   switch (ConvTy) {
5509   default: assert(0 && "Unknown conversion type");
5510   case Compatible: return false;
5511   case PointerToInt:
5512     DiagKind = diag::ext_typecheck_convert_pointer_int;
5513     break;
5514   case IntToPointer:
5515     DiagKind = diag::ext_typecheck_convert_int_pointer;
5516     break;
5517   case IncompatiblePointer:
5518     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5519     break;
5520   case IncompatiblePointerSign:
5521     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5522     break;
5523   case FunctionVoidPointer:
5524     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5525     break;
5526   case CompatiblePointerDiscardsQualifiers:
5527     // If the qualifiers lost were because we were applying the
5528     // (deprecated) C++ conversion from a string literal to a char*
5529     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
5530     // Ideally, this check would be performed in
5531     // CheckPointerTypesForAssignment. However, that would require a
5532     // bit of refactoring (so that the second argument is an
5533     // expression, rather than a type), which should be done as part
5534     // of a larger effort to fix CheckPointerTypesForAssignment for
5535     // C++ semantics.
5536     if (getLangOptions().CPlusPlus &&
5537         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5538       return false;
5539     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5540     break;
5541   case IntToBlockPointer:
5542     DiagKind = diag::err_int_to_block_pointer;
5543     break;
5544   case IncompatibleBlockPointer:
5545     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
5546     break;
5547   case IncompatibleObjCQualifiedId:
5548     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
5549     // it can give a more specific diagnostic.
5550     DiagKind = diag::warn_incompatible_qualified_id;
5551     break;
5552   case IncompatibleVectors:
5553     DiagKind = diag::warn_incompatible_vectors;
5554     break;
5555   case Incompatible:
5556     DiagKind = diag::err_typecheck_convert_incompatible;
5557     isInvalid = true;
5558     break;
5559   }
5560 
5561   Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5562     << SrcExpr->getSourceRange();
5563   return isInvalid;
5564 }
5565 
5566 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
5567   llvm::APSInt ICEResult;
5568   if (E->isIntegerConstantExpr(ICEResult, Context)) {
5569     if (Result)
5570       *Result = ICEResult;
5571     return false;
5572   }
5573 
5574   Expr::EvalResult EvalResult;
5575 
5576   if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
5577       EvalResult.HasSideEffects) {
5578     Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5579 
5580     if (EvalResult.Diag) {
5581       // We only show the note if it's not the usual "invalid subexpression"
5582       // or if it's actually in a subexpression.
5583       if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5584           E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5585         Diag(EvalResult.DiagLoc, EvalResult.Diag);
5586     }
5587 
5588     return true;
5589   }
5590 
5591   Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5592     E->getSourceRange();
5593 
5594   if (EvalResult.Diag &&
5595       Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5596     Diag(EvalResult.DiagLoc, EvalResult.Diag);
5597 
5598   if (Result)
5599     *Result = EvalResult.Val.getInt();
5600   return false;
5601 }
5602 
5603 Sema::ExpressionEvaluationContext
5604 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5605   // Introduce a new set of potentially referenced declarations to the stack.
5606   if (NewContext == PotentiallyPotentiallyEvaluated)
5607     PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5608 
5609   std::swap(ExprEvalContext, NewContext);
5610   return NewContext;
5611 }
5612 
5613 void
5614 Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5615                                      ExpressionEvaluationContext NewContext) {
5616   ExprEvalContext = NewContext;
5617 
5618   if (OldContext == PotentiallyPotentiallyEvaluated) {
5619     // Mark any remaining declarations in the current position of the stack
5620     // as "referenced". If they were not meant to be referenced, semantic
5621     // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5622     PotentiallyReferencedDecls RemainingDecls;
5623     RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5624     PotentiallyReferencedDeclStack.pop_back();
5625 
5626     for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5627                                            IEnd = RemainingDecls.end();
5628          I != IEnd; ++I)
5629       MarkDeclarationReferenced(I->first, I->second);
5630   }
5631 }
5632 
5633 /// \brief Note that the given declaration was referenced in the source code.
5634 ///
5635 /// This routine should be invoke whenever a given declaration is referenced
5636 /// in the source code, and where that reference occurred. If this declaration
5637 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5638 /// C99 6.9p3), then the declaration will be marked as used.
5639 ///
5640 /// \param Loc the location where the declaration was referenced.
5641 ///
5642 /// \param D the declaration that has been referenced by the source code.
5643 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5644   assert(D && "No declaration?");
5645 
5646   if (D->isUsed())
5647     return;
5648 
5649   // Mark a parameter declaration "used", regardless of whether we're in a
5650   // template or not.
5651   if (isa<ParmVarDecl>(D))
5652     D->setUsed(true);
5653 
5654   // Do not mark anything as "used" within a dependent context; wait for
5655   // an instantiation.
5656   if (CurContext->isDependentContext())
5657     return;
5658 
5659   switch (ExprEvalContext) {
5660     case Unevaluated:
5661       // We are in an expression that is not potentially evaluated; do nothing.
5662       return;
5663 
5664     case PotentiallyEvaluated:
5665       // We are in a potentially-evaluated expression, so this declaration is
5666       // "used"; handle this below.
5667       break;
5668 
5669     case PotentiallyPotentiallyEvaluated:
5670       // We are in an expression that may be potentially evaluated; queue this
5671       // declaration reference until we know whether the expression is
5672       // potentially evaluated.
5673       PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5674       return;
5675   }
5676 
5677   // Note that this declaration has been used.
5678   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
5679     unsigned TypeQuals;
5680     if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5681         if (!Constructor->isUsed())
5682           DefineImplicitDefaultConstructor(Loc, Constructor);
5683     }
5684     else if (Constructor->isImplicit() &&
5685              Constructor->isCopyConstructor(Context, TypeQuals)) {
5686       if (!Constructor->isUsed())
5687         DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5688     }
5689   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5690     if (Destructor->isImplicit() && !Destructor->isUsed())
5691       DefineImplicitDestructor(Loc, Destructor);
5692 
5693   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5694     if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5695         MethodDecl->getOverloadedOperator() == OO_Equal) {
5696       if (!MethodDecl->isUsed())
5697         DefineImplicitOverloadedAssign(Loc, MethodDecl);
5698     }
5699   }
5700   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
5701     // Implicit instantiation of function templates and member functions of
5702     // class templates.
5703     if (!Function->getBody()) {
5704       // FIXME: distinguish between implicit instantiations of function
5705       // templates and explicit specializations (the latter don't get
5706       // instantiated, naturally).
5707       if (Function->getInstantiatedFromMemberFunction() ||
5708           Function->getPrimaryTemplate())
5709         PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
5710     }
5711 
5712 
5713     // FIXME: keep track of references to static functions
5714     Function->setUsed(true);
5715     return;
5716   }
5717 
5718   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
5719     (void)Var;
5720     // FIXME: implicit template instantiation
5721     // FIXME: keep track of references to static data?
5722     D->setUsed(true);
5723   }
5724 }
5725 
5726