clang API Documentation

SemaExpr.cpp

Go to the documentation of this file.
00001 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for expressions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "Sema.h"
00015 #include "SemaInit.h"
00016 #include "Lookup.h"
00017 #include "AnalysisBasedWarnings.h"
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/AST/CXXInheritance.h"
00020 #include "clang/AST/DeclObjC.h"
00021 #include "clang/AST/DeclTemplate.h"
00022 #include "clang/AST/Expr.h"
00023 #include "clang/AST/ExprCXX.h"
00024 #include "clang/AST/ExprObjC.h"
00025 #include "clang/AST/TypeLoc.h"
00026 #include "clang/Basic/PartialDiagnostic.h"
00027 #include "clang/Basic/SourceManager.h"
00028 #include "clang/Basic/TargetInfo.h"
00029 #include "clang/Lex/LiteralSupport.h"
00030 #include "clang/Lex/Preprocessor.h"
00031 #include "clang/Parse/DeclSpec.h"
00032 #include "clang/Parse/Designator.h"
00033 #include "clang/Parse/Scope.h"
00034 #include "clang/Parse/Template.h"
00035 using namespace clang;
00036 
00037 
00038 /// \brief Determine whether the use of this declaration is valid, and
00039 /// emit any corresponding diagnostics.
00040 ///
00041 /// This routine diagnoses various problems with referencing
00042 /// declarations that can occur when using a declaration. For example,
00043 /// it might warn if a deprecated or unavailable declaration is being
00044 /// used, or produce an error (and return true) if a C++0x deleted
00045 /// function is being used.
00046 ///
00047 /// If IgnoreDeprecated is set to true, this should not want about deprecated
00048 /// decls.
00049 ///
00050 /// \returns true if there was an error (this declaration cannot be
00051 /// referenced), false otherwise.
00052 ///
00053 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
00054   // See if the decl is deprecated.
00055   if (D->getAttr<DeprecatedAttr>()) {
00056     EmitDeprecationWarning(D, Loc);
00057   }
00058 
00059   // See if the decl is unavailable
00060   if (D->getAttr<UnavailableAttr>()) {
00061     Diag(Loc, diag::warn_unavailable) << D->getDeclName();
00062     Diag(D->getLocation(), diag::note_unavailable_here) << 0;
00063   }
00064 
00065   // See if this is a deleted function.
00066   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00067     if (FD->isDeleted()) {
00068       Diag(Loc, diag::err_deleted_function_use);
00069       Diag(D->getLocation(), diag::note_unavailable_here) << true;
00070       return true;
00071     }
00072   }
00073 
00074   return false;
00075 }
00076 
00077 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
00078 /// (and other functions in future), which have been declared with sentinel
00079 /// attribute. It warns if call does not have the sentinel argument.
00080 ///
00081 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
00082                                  Expr **Args, unsigned NumArgs) {
00083   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
00084   if (!attr)
00085     return;
00086 
00087   // FIXME: In C++0x, if any of the arguments are parameter pack
00088   // expansions, we can't check for the sentinel now.
00089   int sentinelPos = attr->getSentinel();
00090   int nullPos = attr->getNullPos();
00091 
00092   // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
00093   // base class. Then we won't be needing two versions of the same code.
00094   unsigned int i = 0;
00095   bool warnNotEnoughArgs = false;
00096   int isMethod = 0;
00097   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
00098     // skip over named parameters.
00099     ObjCMethodDecl::param_iterator P, E = MD->param_end();
00100     for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
00101       if (nullPos)
00102         --nullPos;
00103       else
00104         ++i;
00105     }
00106     warnNotEnoughArgs = (P != E || i >= NumArgs);
00107     isMethod = 1;
00108   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00109     // skip over named parameters.
00110     ObjCMethodDecl::param_iterator P, E = FD->param_end();
00111     for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
00112       if (nullPos)
00113         --nullPos;
00114       else
00115         ++i;
00116     }
00117     warnNotEnoughArgs = (P != E || i >= NumArgs);
00118   } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
00119     // block or function pointer call.
00120     QualType Ty = V->getType();
00121     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
00122       const FunctionType *FT = Ty->isFunctionPointerType()
00123       ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
00124       : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
00125       if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
00126         unsigned NumArgsInProto = Proto->getNumArgs();
00127         unsigned k;
00128         for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
00129           if (nullPos)
00130             --nullPos;
00131           else
00132             ++i;
00133         }
00134         warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
00135       }
00136       if (Ty->isBlockPointerType())
00137         isMethod = 2;
00138     } else
00139       return;
00140   } else
00141     return;
00142 
00143   if (warnNotEnoughArgs) {
00144     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
00145     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
00146     return;
00147   }
00148   int sentinel = i;
00149   while (sentinelPos > 0 && i < NumArgs-1) {
00150     --sentinelPos;
00151     ++i;
00152   }
00153   if (sentinelPos > 0) {
00154     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
00155     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
00156     return;
00157   }
00158   while (i < NumArgs-1) {
00159     ++i;
00160     ++sentinel;
00161   }
00162   Expr *sentinelExpr = Args[sentinel];
00163   if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
00164                        !sentinelExpr->isTypeDependent() &&
00165                        !sentinelExpr->isValueDependent() &&
00166                        (!sentinelExpr->getType()->isPointerType() ||
00167                         !sentinelExpr->isNullPointerConstant(Context,
00168                                             Expr::NPC_ValueDependentIsNull)))) {
00169     Diag(Loc, diag::warn_missing_sentinel) << isMethod;
00170     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
00171   }
00172   return;
00173 }
00174 
00175 SourceRange Sema::getExprRange(ExprTy *E) const {
00176   Expr *Ex = (Expr *)E;
00177   return Ex? Ex->getSourceRange() : SourceRange();
00178 }
00179 
00180 //===----------------------------------------------------------------------===//
00181 //  Standard Promotions and Conversions
00182 //===----------------------------------------------------------------------===//
00183 
00184 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
00185 void Sema::DefaultFunctionArrayConversion(Expr *&E) {
00186   QualType Ty = E->getType();
00187   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
00188 
00189   if (Ty->isFunctionType())
00190     ImpCastExprToType(E, Context.getPointerType(Ty),
00191                       CastExpr::CK_FunctionToPointerDecay);
00192   else if (Ty->isArrayType()) {
00193     // In C90 mode, arrays only promote to pointers if the array expression is
00194     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
00195     // type 'array of type' is converted to an expression that has type 'pointer
00196     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
00197     // that has type 'array of type' ...".  The relevant change is "an lvalue"
00198     // (C90) to "an expression" (C99).
00199     //
00200     // C++ 4.2p1:
00201     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
00202     // T" can be converted to an rvalue of type "pointer to T".
00203     //
00204     if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
00205         E->isLvalue(Context) == Expr::LV_Valid)
00206       ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
00207                         CastExpr::CK_ArrayToPointerDecay);
00208   }
00209 }
00210 
00211 void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
00212   DefaultFunctionArrayConversion(E);
00213 
00214   QualType Ty = E->getType();
00215   assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
00216   if (!Ty->isDependentType() && Ty.hasQualifiers() &&
00217       (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
00218       E->isLvalue(Context) == Expr::LV_Valid) {
00219     // C++ [conv.lval]p1:
00220     //   [...] If T is a non-class type, the type of the rvalue is the
00221     //   cv-unqualified version of T. Otherwise, the type of the
00222     //   rvalue is T
00223     //
00224     // C99 6.3.2.1p2:
00225     //   If the lvalue has qualified type, the value has the unqualified
00226     //   version of the type of the lvalue; otherwise, the value has the
00227     //   type of the lvalue.
00228     ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
00229   }
00230 }
00231 
00232 
00233 /// UsualUnaryConversions - Performs various conversions that are common to most
00234 /// operators (C99 6.3). The conversions of array and function types are
00235 /// sometimes surpressed. For example, the array->pointer conversion doesn't
00236 /// apply if the array is an argument to the sizeof or address (&) operators.
00237 /// In these instances, this routine should *not* be called.
00238 Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
00239   QualType Ty = Expr->getType();
00240   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
00241 
00242   // C99 6.3.1.1p2:
00243   //
00244   //   The following may be used in an expression wherever an int or
00245   //   unsigned int may be used:
00246   //     - an object or expression with an integer type whose integer
00247   //       conversion rank is less than or equal to the rank of int
00248   //       and unsigned int.
00249   //     - A bit-field of type _Bool, int, signed int, or unsigned int.
00250   //
00251   //   If an int can represent all values of the original type, the
00252   //   value is converted to an int; otherwise, it is converted to an
00253   //   unsigned int. These are called the integer promotions. All
00254   //   other types are unchanged by the integer promotions.
00255   QualType PTy = Context.isPromotableBitField(Expr);
00256   if (!PTy.isNull()) {
00257     ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
00258     return Expr;
00259   }
00260   if (Ty->isPromotableIntegerType()) {
00261     QualType PT = Context.getPromotedIntegerType(Ty);
00262     ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
00263     return Expr;
00264   }
00265 
00266   DefaultFunctionArrayLvalueConversion(Expr);
00267   return Expr;
00268 }
00269 
00270 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
00271 /// do not have a prototype. Arguments that have type float are promoted to
00272 /// double. All other argument types are converted by UsualUnaryConversions().
00273 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
00274   QualType Ty = Expr->getType();
00275   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
00276 
00277   // If this is a 'float' (CVR qualified or typedef) promote to double.
00278   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
00279     if (BT->getKind() == BuiltinType::Float)
00280       return ImpCastExprToType(Expr, Context.DoubleTy,
00281                                CastExpr::CK_FloatingCast);
00282 
00283   UsualUnaryConversions(Expr);
00284 }
00285 
00286 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
00287 /// will warn if the resulting type is not a POD type, and rejects ObjC
00288 /// interfaces passed by value.  This returns true if the argument type is
00289 /// completely illegal.
00290 bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
00291   DefaultArgumentPromotion(Expr);
00292 
00293   if (Expr->getType()->isObjCInterfaceType() &&
00294       DiagRuntimeBehavior(Expr->getLocStart(),
00295         PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
00296           << Expr->getType() << CT))
00297     return true;
00298 
00299   if (!Expr->getType()->isPODType() &&
00300       DiagRuntimeBehavior(Expr->getLocStart(),
00301                           PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
00302                             << Expr->getType() << CT))
00303     return true;
00304 
00305   return false;
00306 }
00307 
00308 
00309 /// UsualArithmeticConversions - Performs various conversions that are common to
00310 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
00311 /// routine returns the first non-arithmetic type found. The client is
00312 /// responsible for emitting appropriate error diagnostics.
00313 /// FIXME: verify the conversion rules for "complex int" are consistent with
00314 /// GCC.
00315 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
00316                                           bool isCompAssign) {
00317   if (!isCompAssign)
00318     UsualUnaryConversions(lhsExpr);
00319 
00320   UsualUnaryConversions(rhsExpr);
00321 
00322   // For conversion purposes, we ignore any qualifiers.
00323   // For example, "const float" and "float" are equivalent.
00324   QualType lhs =
00325     Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
00326   QualType rhs =
00327     Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
00328 
00329   // If both types are identical, no conversion is needed.
00330   if (lhs == rhs)
00331     return lhs;
00332 
00333   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
00334   // The caller can deal with this (e.g. pointer + int).
00335   if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
00336     return lhs;
00337 
00338   // Perform bitfield promotions.
00339   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
00340   if (!LHSBitfieldPromoteTy.isNull())
00341     lhs = LHSBitfieldPromoteTy;
00342   QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
00343   if (!RHSBitfieldPromoteTy.isNull())
00344     rhs = RHSBitfieldPromoteTy;
00345 
00346   QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
00347   if (!isCompAssign)
00348     ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
00349   ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
00350   return destType;
00351 }
00352 
00353 //===----------------------------------------------------------------------===//
00354 //  Semantic Analysis for various Expression Types
00355 //===----------------------------------------------------------------------===//
00356 
00357 
00358 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
00359 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
00360 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
00361 /// multiple tokens.  However, the common case is that StringToks points to one
00362 /// string.
00363 ///
00364 Action::OwningExprResult
00365 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
00366   assert(NumStringToks && "Must have at least one string!");
00367 
00368   StringLiteralParser Literal(StringToks, NumStringToks, PP);
00369   if (Literal.hadError)
00370     return ExprError();
00371 
00372   llvm::SmallVector<SourceLocation, 4> StringTokLocs;
00373   for (unsigned i = 0; i != NumStringToks; ++i)
00374     StringTokLocs.push_back(StringToks[i].getLocation());
00375 
00376   QualType StrTy = Context.CharTy;
00377   if (Literal.AnyWide) StrTy = Context.getWCharType();
00378   if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
00379 
00380   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
00381   if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings )
00382     StrTy.addConst();
00383 
00384   // Get an array type for the string, according to C99 6.4.5.  This includes
00385   // the nul terminator character as well as the string length for pascal
00386   // strings.
00387   StrTy = Context.getConstantArrayType(StrTy,
00388                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
00389                                        ArrayType::Normal, 0);
00390 
00391   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
00392   return Owned(StringLiteral::Create(Context, Literal.GetString(),
00393                                      Literal.GetStringLength(),
00394                                      Literal.AnyWide, StrTy,
00395                                      &StringTokLocs[0],
00396                                      StringTokLocs.size()));
00397 }
00398 
00399 /// ShouldSnapshotBlockValueReference - Return true if a reference inside of
00400 /// CurBlock to VD should cause it to be snapshotted (as we do for auto
00401 /// variables defined outside the block) or false if this is not needed (e.g.
00402 /// for values inside the block or for globals).
00403 ///
00404 /// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
00405 /// up-to-date.
00406 ///
00407 static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
00408                                               ValueDecl *VD) {
00409   // If the value is defined inside the block, we couldn't snapshot it even if
00410   // we wanted to.
00411   if (CurBlock->TheDecl == VD->getDeclContext())
00412     return false;
00413 
00414   // If this is an enum constant or function, it is constant, don't snapshot.
00415   if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
00416     return false;
00417 
00418   // If this is a reference to an extern, static, or global variable, no need to
00419   // snapshot it.
00420   // FIXME: What about 'const' variables in C++?
00421   if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
00422     if (!Var->hasLocalStorage())
00423       return false;
00424 
00425   // Blocks that have these can't be constant.
00426   CurBlock->hasBlockDeclRefExprs = true;
00427 
00428   // If we have nested blocks, the decl may be declared in an outer block (in
00429   // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
00430   // be defined outside all of the current blocks (in which case the blocks do
00431   // all get the bit).  Walk the nesting chain.
00432   for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
00433     BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
00434 
00435     if (!NextBlock)
00436       continue;
00437 
00438     // If we found the defining block for the variable, don't mark the block as
00439     // having a reference outside it.
00440     if (NextBlock->TheDecl == VD->getDeclContext())
00441       break;
00442 
00443     // Otherwise, the DeclRef from the inner block causes the outer one to need
00444     // a snapshot as well.
00445     NextBlock->hasBlockDeclRefExprs = true;
00446   }
00447 
00448   return true;
00449 }
00450 
00451 
00452 
00453 /// BuildDeclRefExpr - Build a DeclRefExpr.
00454 Sema::OwningExprResult
00455 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
00456                        const CXXScopeSpec *SS) {
00457   if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
00458     Diag(Loc,
00459          diag::err_auto_variable_cannot_appear_in_own_initializer)
00460       << D->getDeclName();
00461     return ExprError();
00462   }
00463 
00464   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
00465     if (isa<NonTypeTemplateParmDecl>(VD)) {
00466       // Non-type template parameters can be referenced anywhere they are
00467       // visible.
00468     } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
00469       if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
00470         if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
00471           Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
00472             << D->getIdentifier() << FD->getDeclName();
00473           Diag(D->getLocation(), diag::note_local_variable_declared_here)
00474             << D->getIdentifier();
00475           return ExprError();
00476         }
00477       }
00478     }
00479   }
00480 
00481   MarkDeclarationReferenced(Loc, D);
00482 
00483   return Owned(DeclRefExpr::Create(Context,
00484                               SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
00485                                    SS? SS->getRange() : SourceRange(),
00486                                    D, Loc, Ty));
00487 }
00488 
00489 /// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
00490 /// variable corresponding to the anonymous union or struct whose type
00491 /// is Record.
00492 static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
00493                                              RecordDecl *Record) {
00494   assert(Record->isAnonymousStructOrUnion() &&
00495          "Record must be an anonymous struct or union!");
00496 
00497   // FIXME: Once Decls are directly linked together, this will be an O(1)
00498   // operation rather than a slow walk through DeclContext's vector (which
00499   // itself will be eliminated). DeclGroups might make this even better.
00500   DeclContext *Ctx = Record->getDeclContext();
00501   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
00502                                DEnd = Ctx->decls_end();
00503        D != DEnd; ++D) {
00504     if (*D == Record) {
00505       // The object for the anonymous struct/union directly
00506       // follows its type in the list of declarations.
00507       ++D;
00508       assert(D != DEnd && "Missing object for anonymous record");
00509       assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
00510       return *D;
00511     }
00512   }
00513 
00514   assert(false && "Missing object for anonymous record");
00515   return 0;
00516 }
00517 
00518 /// \brief Given a field that represents a member of an anonymous
00519 /// struct/union, build the path from that field's context to the
00520 /// actual member.
00521 ///
00522 /// Construct the sequence of field member references we'll have to
00523 /// perform to get to the field in the anonymous union/struct. The
00524 /// list of members is built from the field outward, so traverse it
00525 /// backwards to go from an object in the current context to the field
00526 /// we found.
00527 ///
00528 /// \returns The variable from which the field access should begin,
00529 /// for an anonymous struct/union that is not a member of another
00530 /// class. Otherwise, returns NULL.
00531 VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
00532                                    llvm::SmallVectorImpl<FieldDecl *> &Path) {
00533   assert(Field->getDeclContext()->isRecord() &&
00534          cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
00535          && "Field must be stored inside an anonymous struct or union");
00536 
00537   Path.push_back(Field);
00538   VarDecl *BaseObject = 0;
00539   DeclContext *Ctx = Field->getDeclContext();
00540   do {
00541     RecordDecl *Record = cast<RecordDecl>(Ctx);
00542     Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
00543     if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
00544       Path.push_back(AnonField);
00545     else {
00546       BaseObject = cast<VarDecl>(AnonObject);
00547       break;
00548     }
00549     Ctx = Ctx->getParent();
00550   } while (Ctx->isRecord() &&
00551            cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
00552 
00553   return BaseObject;
00554 }
00555 
00556 Sema::OwningExprResult
00557 Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
00558                                                FieldDecl *Field,
00559                                                Expr *BaseObjectExpr,
00560                                                SourceLocation OpLoc) {
00561   llvm::SmallVector<FieldDecl *, 4> AnonFields;
00562   VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
00563                                                             AnonFields);
00564 
00565   // Build the expression that refers to the base object, from
00566   // which we will build a sequence of member references to each
00567   // of the anonymous union objects and, eventually, the field we
00568   // found via name lookup.
00569   bool BaseObjectIsPointer = false;
00570   Qualifiers BaseQuals;
00571   if (BaseObject) {
00572     // BaseObject is an anonymous struct/union variable (and is,
00573     // therefore, not part of another non-anonymous record).
00574     if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
00575     MarkDeclarationReferenced(Loc, BaseObject);
00576     BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
00577                                                SourceLocation());
00578     BaseQuals
00579       = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
00580   } else if (BaseObjectExpr) {
00581     // The caller provided the base object expression. Determine
00582     // whether its a pointer and whether it adds any qualifiers to the
00583     // anonymous struct/union fields we're looking into.
00584     QualType ObjectType = BaseObjectExpr->getType();
00585     if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
00586       BaseObjectIsPointer = true;
00587       ObjectType = ObjectPtr->getPointeeType();
00588     }
00589     BaseQuals
00590       = Context.getCanonicalType(ObjectType).getQualifiers();
00591   } else {
00592     // We've found a member of an anonymous struct/union that is
00593     // inside a non-anonymous struct/union, so in a well-formed
00594     // program our base object expression is "this".
00595     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
00596       if (!MD->isStatic()) {
00597         QualType AnonFieldType
00598           = Context.getTagDeclType(
00599                      cast<RecordDecl>(AnonFields.back()->getDeclContext()));
00600         QualType ThisType = Context.getTagDeclType(MD->getParent());
00601         if ((Context.getCanonicalType(AnonFieldType)
00602                == Context.getCanonicalType(ThisType)) ||
00603             IsDerivedFrom(ThisType, AnonFieldType)) {
00604           // Our base object expression is "this".
00605           BaseObjectExpr = new (Context) CXXThisExpr(Loc,
00606                                                      MD->getThisType(Context),
00607                                                      /*isImplicit=*/true);
00608           BaseObjectIsPointer = true;
00609         }
00610       } else {
00611         return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
00612           << Field->getDeclName());
00613       }
00614       BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
00615     }
00616 
00617     if (!BaseObjectExpr)
00618       return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
00619         << Field->getDeclName());
00620   }
00621 
00622   // Build the implicit member references to the field of the
00623   // anonymous struct/union.
00624   Expr *Result = BaseObjectExpr;
00625   Qualifiers ResultQuals = BaseQuals;
00626   for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
00627          FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
00628        FI != FIEnd; ++FI) {
00629     QualType MemberType = (*FI)->getType();
00630     Qualifiers MemberTypeQuals =
00631       Context.getCanonicalType(MemberType).getQualifiers();
00632 
00633     // CVR attributes from the base are picked up by members,
00634     // except that 'mutable' members don't pick up 'const'.
00635     if ((*FI)->isMutable())
00636       ResultQuals.removeConst();
00637 
00638     // GC attributes are never picked up by members.
00639     ResultQuals.removeObjCGCAttr();
00640 
00641     // TR 18037 does not allow fields to be declared with address spaces.
00642     assert(!MemberTypeQuals.hasAddressSpace());
00643 
00644     Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
00645     if (NewQuals != MemberTypeQuals)
00646       MemberType = Context.getQualifiedType(MemberType, NewQuals);
00647 
00648     MarkDeclarationReferenced(Loc, *FI);
00649     PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
00650     // FIXME: Might this end up being a qualified name?
00651     Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
00652                                       OpLoc, MemberType);
00653     BaseObjectIsPointer = false;
00654     ResultQuals = NewQuals;
00655   }
00656 
00657   return Owned(Result);
00658 }
00659 
00660 /// Decomposes the given name into a DeclarationName, its location, and
00661 /// possibly a list of template arguments.
00662 ///
00663 /// If this produces template arguments, it is permitted to call
00664 /// DecomposeTemplateName.
00665 ///
00666 /// This actually loses a lot of source location information for
00667 /// non-standard name kinds; we should consider preserving that in
00668 /// some way.
00669 static void DecomposeUnqualifiedId(Sema &SemaRef,
00670                                    const UnqualifiedId &Id,
00671                                    TemplateArgumentListInfo &Buffer,
00672                                    DeclarationName &Name,
00673                                    SourceLocation &NameLoc,
00674                              const TemplateArgumentListInfo *&TemplateArgs) {
00675   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
00676     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
00677     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
00678 
00679     ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
00680                                        Id.TemplateId->getTemplateArgs(),
00681                                        Id.TemplateId->NumArgs);
00682     SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
00683     TemplateArgsPtr.release();
00684 
00685     TemplateName TName =
00686       Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
00687 
00688     Name = SemaRef.Context.getNameForTemplate(TName);
00689     NameLoc = Id.TemplateId->TemplateNameLoc;
00690     TemplateArgs = &Buffer;
00691   } else {
00692     Name = SemaRef.GetNameFromUnqualifiedId(Id);
00693     NameLoc = Id.StartLocation;
00694     TemplateArgs = 0;
00695   }
00696 }
00697 
00698 /// Decompose the given template name into a list of lookup results.
00699 ///
00700 /// The unqualified ID must name a non-dependent template, which can
00701 /// be more easily tested by checking whether DecomposeUnqualifiedId
00702 /// found template arguments.
00703 static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
00704   assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
00705   TemplateName TName =
00706     Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
00707 
00708   if (TemplateDecl *TD = TName.getAsTemplateDecl())
00709     R.addDecl(TD);
00710   else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
00711     for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
00712            I != E; ++I)
00713       R.addDecl(*I);
00714 
00715   R.resolveKind();
00716 }
00717 
00718 /// Determines whether the given record is "fully-formed" at the given
00719 /// location, i.e. whether a qualified lookup into it is assured of
00720 /// getting consistent results already.
00721 static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
00722   if (!Record->hasDefinition())
00723     return false;
00724 
00725   for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
00726          E = Record->bases_end(); I != E; ++I) {
00727     CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
00728     CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
00729     if (!BaseRT) return false;
00730 
00731     CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
00732     if (!BaseRecord->hasDefinition() ||
00733         !IsFullyFormedScope(SemaRef, BaseRecord))
00734       return false;
00735   }
00736 
00737   return true;
00738 }
00739 
00740 /// Determines whether we can lookup this id-expression now or whether
00741 /// we have to wait until template instantiation is complete.
00742 static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
00743   DeclContext *DC = SemaRef.computeDeclContext(SS, false);
00744 
00745   // If the qualifier scope isn't computable, it's definitely dependent.
00746   if (!DC) return true;
00747 
00748   // If the qualifier scope doesn't name a record, we can always look into it.
00749   if (!isa<CXXRecordDecl>(DC)) return false;
00750 
00751   // We can't look into record types unless they're fully-formed.
00752   if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
00753 
00754   return false;
00755 }
00756 
00757 /// Determines if the given class is provably not derived from all of
00758 /// the prospective base classes.
00759 static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
00760                                      CXXRecordDecl *Record,
00761                             const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
00762   if (Bases.count(Record->getCanonicalDecl()))
00763     return false;
00764 
00765   RecordDecl *RD = Record->getDefinition();
00766   if (!RD) return false;
00767   Record = cast<CXXRecordDecl>(RD);
00768 
00769   for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
00770          E = Record->bases_end(); I != E; ++I) {
00771     CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
00772     CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
00773     if (!BaseRT) return false;
00774 
00775     CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
00776     if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
00777       return false;
00778   }
00779 
00780   return true;
00781 }
00782 
00783 enum IMAKind {
00784   /// The reference is definitely not an instance member access.
00785   IMA_Static,
00786 
00787   /// The reference may be an implicit instance member access.
00788   IMA_Mixed,
00789 
00790   /// The reference may be to an instance member, but it is invalid if
00791   /// so, because the context is not an instance method.
00792   IMA_Mixed_StaticContext,
00793 
00794   /// The reference may be to an instance member, but it is invalid if
00795   /// so, because the context is from an unrelated class.
00796   IMA_Mixed_Unrelated,
00797 
00798   /// The reference is definitely an implicit instance member access.
00799   IMA_Instance,
00800 
00801   /// The reference may be to an unresolved using declaration.
00802   IMA_Unresolved,
00803 
00804   /// The reference may be to an unresolved using declaration and the
00805   /// context is not an instance method.
00806   IMA_Unresolved_StaticContext,
00807 
00808   /// The reference is to a member of an anonymous structure in a
00809   /// non-class context.
00810   IMA_AnonymousMember,
00811 
00812   /// All possible referrents are instance members and the current
00813   /// context is not an instance method.
00814   IMA_Error_StaticContext,
00815 
00816   /// All possible referrents are instance members of an unrelated
00817   /// class.
00818   IMA_Error_Unrelated
00819 };
00820 
00821 /// The given lookup names class member(s) and is not being used for
00822 /// an address-of-member expression.  Classify the type of access
00823 /// according to whether it's possible that this reference names an
00824 /// instance member.  This is best-effort; it is okay to
00825 /// conservatively answer "yes", in which case some errors will simply
00826 /// not be caught until template-instantiation.
00827 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
00828                                             const LookupResult &R) {
00829   assert(!R.empty() && (*R.begin())->isCXXClassMember());
00830 
00831   bool isStaticContext =
00832     (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
00833      cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
00834 
00835   if (R.isUnresolvableResult())
00836     return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
00837 
00838   // Collect all the declaring classes of instance members we find.
00839   bool hasNonInstance = false;
00840   llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
00841   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
00842     NamedDecl *D = *I;
00843     if (D->isCXXInstanceMember()) {
00844       CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
00845 
00846       // If this is a member of an anonymous record, move out to the
00847       // innermost non-anonymous struct or union.  If there isn't one,
00848       // that's a special case.
00849       while (R->isAnonymousStructOrUnion()) {
00850         R = dyn_cast<CXXRecordDecl>(R->getParent());
00851         if (!R) return IMA_AnonymousMember;
00852       }
00853       Classes.insert(R->getCanonicalDecl());
00854     }
00855     else
00856       hasNonInstance = true;
00857   }
00858 
00859   // If we didn't find any instance members, it can't be an implicit
00860   // member reference.
00861   if (Classes.empty())
00862     return IMA_Static;
00863 
00864   // If the current context is not an instance method, it can't be
00865   // an implicit member reference.
00866   if (isStaticContext)
00867     return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
00868 
00869   // If we can prove that the current context is unrelated to all the
00870   // declaring classes, it can't be an implicit member reference (in
00871   // which case it's an error if any of those members are selected).
00872   if (IsProvablyNotDerivedFrom(SemaRef,
00873                         cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
00874                                Classes))
00875     return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
00876 
00877   return (hasNonInstance ? IMA_Mixed : IMA_Instance);
00878 }
00879 
00880 /// Diagnose a reference to a field with no object available.
00881 static void DiagnoseInstanceReference(Sema &SemaRef,
00882                                       const CXXScopeSpec &SS,
00883                                       const LookupResult &R) {
00884   SourceLocation Loc = R.getNameLoc();
00885   SourceRange Range(Loc);
00886   if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
00887 
00888   if (R.getAsSingle<FieldDecl>()) {
00889     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
00890       if (MD->isStatic()) {
00891         // "invalid use of member 'x' in static member function"
00892         SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
00893           << Range << R.getLookupName();
00894         return;
00895       }
00896     }
00897 
00898     SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
00899       << R.getLookupName() << Range;
00900     return;
00901   }
00902 
00903   SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
00904 }
00905 
00906 /// Diagnose an empty lookup.
00907 ///
00908 /// \return false if new lookup candidates were found
00909 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS,
00910                                LookupResult &R) {
00911   DeclarationName Name = R.getLookupName();
00912 
00913   unsigned diagnostic = diag::err_undeclared_var_use;
00914   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
00915   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
00916       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
00917       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
00918     diagnostic = diag::err_undeclared_use;
00919     diagnostic_suggest = diag::err_undeclared_use_suggest;
00920   }
00921 
00922   // If the original lookup was an unqualified lookup, fake an
00923   // unqualified lookup.  This is useful when (for example) the
00924   // original lookup would not have found something because it was a
00925   // dependent name.
00926   for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
00927        DC; DC = DC->getParent()) {
00928     if (isa<CXXRecordDecl>(DC)) {
00929       LookupQualifiedName(R, DC);
00930 
00931       if (!R.empty()) {
00932         // Don't give errors about ambiguities in this lookup.
00933         R.suppressDiagnostics();
00934 
00935         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
00936         bool isInstance = CurMethod &&
00937                           CurMethod->isInstance() &&
00938                           DC == CurMethod->getParent();
00939 
00940         // Give a code modification hint to insert 'this->'.
00941         // TODO: fixit for inserting 'Base<T>::' in the other cases.
00942         // Actually quite difficult!
00943         if (isInstance)
00944           Diag(R.getNameLoc(), diagnostic) << Name
00945             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
00946         else
00947           Diag(R.getNameLoc(), diagnostic) << Name;
00948 
00949         // Do we really want to note all of these?
00950         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
00951           Diag((*I)->getLocation(), diag::note_dependent_var_use);
00952 
00953         // Tell the callee to try to recover.
00954         return false;
00955       }
00956     }
00957   }
00958 
00959   // We didn't find anything, so try to correct for a typo.
00960   DeclarationName Corrected;
00961   if (S && (Corrected = CorrectTypo(R, S, &SS))) {
00962     if (!R.empty()) {
00963       if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
00964         if (SS.isEmpty())
00965           Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
00966             << FixItHint::CreateReplacement(R.getNameLoc(),
00967                                             R.getLookupName().getAsString());
00968         else
00969           Diag(R.getNameLoc(), diag::err_no_member_suggest)
00970             << Name << computeDeclContext(SS, false) << R.getLookupName()
00971             << SS.getRange()
00972             << FixItHint::CreateReplacement(R.getNameLoc(),
00973                                             R.getLookupName().getAsString());
00974         if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
00975           Diag(ND->getLocation(), diag::note_previous_decl)
00976             << ND->getDeclName();
00977 
00978         // Tell the callee to try to recover.
00979         return false;
00980       }
00981 
00982       if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
00983         // FIXME: If we ended up with a typo for a type name or
00984         // Objective-C class name, we're in trouble because the parser
00985         // is in the wrong place to recover. Suggest the typo
00986         // correction, but don't make it a fix-it since we're not going
00987         // to recover well anyway.
00988         if (SS.isEmpty())
00989           Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
00990         else
00991           Diag(R.getNameLoc(), diag::err_no_member_suggest)
00992             << Name << computeDeclContext(SS, false) << R.getLookupName()
00993             << SS.getRange();
00994 
00995         // Don't try to recover; it won't work.
00996         return true;
00997       }
00998     } else {
00999       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
01000       // because we aren't able to recover.
01001       if (SS.isEmpty())
01002         Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
01003       else
01004         Diag(R.getNameLoc(), diag::err_no_member_suggest)
01005         << Name << computeDeclContext(SS, false) << Corrected
01006         << SS.getRange();
01007       return true;
01008     }
01009     R.clear();
01010   }
01011 
01012   // Emit a special diagnostic for failed member lookups.
01013   // FIXME: computing the declaration context might fail here (?)
01014   if (!SS.isEmpty()) {
01015     Diag(R.getNameLoc(), diag::err_no_member)
01016       << Name << computeDeclContext(SS, false)
01017       << SS.getRange();
01018     return true;
01019   }
01020 
01021   // Give up, we can't recover.
01022   Diag(R.getNameLoc(), diagnostic) << Name;
01023   return true;
01024 }
01025 
01026 Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
01027                                                CXXScopeSpec &SS,
01028                                                UnqualifiedId &Id,
01029                                                bool HasTrailingLParen,
01030                                                bool isAddressOfOperand) {
01031   assert(!(isAddressOfOperand && HasTrailingLParen) &&
01032          "cannot be direct & operand and have a trailing lparen");
01033 
01034   if (SS.isInvalid())
01035     return ExprError();
01036 
01037   TemplateArgumentListInfo TemplateArgsBuffer;
01038 
01039   // Decompose the UnqualifiedId into the following data.
01040   DeclarationName Name;
01041   SourceLocation NameLoc;
01042   const TemplateArgumentListInfo *TemplateArgs;
01043   DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
01044                          Name, NameLoc, TemplateArgs);
01045 
01046   IdentifierInfo *II = Name.getAsIdentifierInfo();
01047 
01048   // C++ [temp.dep.expr]p3:
01049   //   An id-expression is type-dependent if it contains:
01050   //     -- an identifier that was declared with a dependent type,
01051   //        (note: handled after lookup)
01052   //     -- a template-id that is dependent,
01053   //        (note: handled in BuildTemplateIdExpr)
01054   //     -- a conversion-function-id that specifies a dependent type,
01055   //     -- a nested-name-specifier that contains a class-name that
01056   //        names a dependent type.
01057   // Determine whether this is a member of an unknown specialization;
01058   // we need to handle these differently.
01059   if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
01060        Name.getCXXNameType()->isDependentType()) ||
01061       (SS.isSet() && IsDependentIdExpression(*this, SS))) {
01062     return ActOnDependentIdExpression(SS, Name, NameLoc,
01063                                       isAddressOfOperand,
01064                                       TemplateArgs);
01065   }
01066 
01067   // Perform the required lookup.
01068   LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
01069   if (TemplateArgs) {
01070     // Just re-use the lookup done by isTemplateName.
01071     DecomposeTemplateName(R, Id);
01072 
01073     // Re-derive the naming class.
01074     if (SS.isSet()) {
01075       NestedNameSpecifier *Qualifier
01076         = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
01077       if (const Type *Ty = Qualifier->getAsType())
01078         if (CXXRecordDecl *NamingClass = Ty->getAsCXXRecordDecl())
01079           R.setNamingClass(NamingClass);
01080     }
01081   } else {
01082     bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
01083     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
01084 
01085     // If this reference is in an Objective-C method, then we need to do
01086     // some special Objective-C lookup, too.
01087     if (IvarLookupFollowUp) {
01088       OwningExprResult E(LookupInObjCMethod(R, S, II, true));
01089       if (E.isInvalid())
01090         return ExprError();
01091 
01092       Expr *Ex = E.takeAs<Expr>();
01093       if (Ex) return Owned(Ex);
01094     }
01095   }
01096 
01097   if (R.isAmbiguous())
01098     return ExprError();
01099 
01100   // Determine whether this name might be a candidate for
01101   // argument-dependent lookup.
01102   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
01103 
01104   if (R.empty() && !ADL) {
01105     // Otherwise, this could be an implicitly declared function reference (legal
01106     // in C90, extension in C99, forbidden in C++).
01107     if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
01108       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
01109       if (D) R.addDecl(D);
01110     }
01111 
01112     // If this name wasn't predeclared and if this is not a function
01113     // call, diagnose the problem.
01114     if (R.empty()) {
01115       if (DiagnoseEmptyLookup(S, SS, R))
01116         return ExprError();
01117 
01118       assert(!R.empty() &&
01119              "DiagnoseEmptyLookup returned false but added no results");
01120 
01121       // If we found an Objective-C instance variable, let
01122       // LookupInObjCMethod build the appropriate expression to
01123       // reference the ivar.
01124       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
01125         R.clear();
01126         OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
01127         assert(E.isInvalid() || E.get());
01128         return move(E);
01129       }
01130     }
01131   }
01132 
01133   // This is guaranteed from this point on.
01134   assert(!R.empty() || ADL);
01135 
01136   if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
01137     // Warn about constructs like:
01138     //   if (void *X = foo()) { ... } else { X }.
01139     // In the else block, the pointer is always false.
01140     if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
01141       Scope *CheckS = S;
01142       while (CheckS && CheckS->getControlParent()) {
01143         if ((CheckS->getFlags() & Scope::ElseScope) &&
01144             CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
01145           ExprError(Diag(NameLoc, diag::warn_value_always_zero)
01146             << Var->getDeclName()
01147             << (Var->getType()->isPointerType() ? 2 :
01148                 Var->getType()->isBooleanType() ? 1 : 0));
01149           break;
01150         }
01151 
01152         // Move to the parent of this scope.
01153         CheckS = CheckS->getParent();
01154       }
01155     }
01156   } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
01157     if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
01158       // C99 DR 316 says that, if a function type comes from a
01159       // function definition (without a prototype), that type is only
01160       // used for checking compatibility. Therefore, when referencing
01161       // the function, we pretend that we don't have the full function
01162       // type.
01163       if (DiagnoseUseOfDecl(Func, NameLoc))
01164         return ExprError();
01165 
01166       QualType T = Func->getType();
01167       QualType NoProtoType = T;
01168       if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
01169         NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
01170       return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
01171     }
01172   }
01173 
01174   // Check whether this might be a C++ implicit instance member access.
01175   // C++ [expr.prim.general]p6:
01176   //   Within the definition of a non-static member function, an
01177   //   identifier that names a non-static member is transformed to a
01178   //   class member access expression.
01179   // But note that &SomeClass::foo is grammatically distinct, even
01180   // though we don't parse it that way.
01181   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
01182     bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
01183     if (!isAbstractMemberPointer)
01184       return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
01185   }
01186 
01187   if (TemplateArgs)
01188     return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
01189 
01190   return BuildDeclarationNameExpr(SS, R, ADL);
01191 }
01192 
01193 /// Builds an expression which might be an implicit member expression.
01194 Sema::OwningExprResult
01195 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
01196                                       LookupResult &R,
01197                                 const TemplateArgumentListInfo *TemplateArgs) {
01198   switch (ClassifyImplicitMemberAccess(*this, R)) {
01199   case IMA_Instance:
01200     return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
01201 
01202   case IMA_AnonymousMember:
01203     assert(R.isSingleResult());
01204     return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
01205                                                     R.getAsSingle<FieldDecl>());
01206 
01207   case IMA_Mixed:
01208   case IMA_Mixed_Unrelated:
01209   case IMA_Unresolved:
01210     return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
01211 
01212   case IMA_Static:
01213   case IMA_Mixed_StaticContext:
01214   case IMA_Unresolved_StaticContext:
01215     if (TemplateArgs)
01216       return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
01217     return BuildDeclarationNameExpr(SS, R, false);
01218 
01219   case IMA_Error_StaticContext:
01220   case IMA_Error_Unrelated:
01221     DiagnoseInstanceReference(*this, SS, R);
01222     return ExprError();
01223   }
01224 
01225   llvm_unreachable("unexpected instance member access kind");
01226   return ExprError();
01227 }
01228 
01229 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
01230 /// declaration name, generally during template instantiation.
01231 /// There's a large number of things which don't need to be done along
01232 /// this path.
01233 Sema::OwningExprResult
01234 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
01235                                         DeclarationName Name,
01236                                         SourceLocation NameLoc) {
01237   DeclContext *DC;
01238   if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
01239     return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
01240 
01241   if (RequireCompleteDeclContext(SS, DC))
01242     return ExprError();
01243 
01244   LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
01245   LookupQualifiedName(R, DC);
01246 
01247   if (R.isAmbiguous())
01248     return ExprError();
01249 
01250   if (R.empty()) {
01251     Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
01252     return ExprError();
01253   }
01254 
01255   return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
01256 }
01257 
01258 /// LookupInObjCMethod - The parser has read a name in, and Sema has
01259 /// detected that we're currently inside an ObjC method.  Perform some
01260 /// additional lookup.
01261 ///
01262 /// Ideally, most of this would be done by lookup, but there's
01263 /// actually quite a lot of extra work involved.
01264 ///
01265 /// Returns a null sentinel to indicate trivial success.
01266 Sema::OwningExprResult
01267 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
01268                          IdentifierInfo *II, bool AllowBuiltinCreation) {
01269   SourceLocation Loc = Lookup.getNameLoc();
01270   ObjCMethodDecl *CurMethod = getCurMethodDecl();
01271 
01272   // There are two cases to handle here.  1) scoped lookup could have failed,
01273   // in which case we should look for an ivar.  2) scoped lookup could have
01274   // found a decl, but that decl is outside the current instance method (i.e.
01275   // a global variable).  In these two cases, we do a lookup for an ivar with
01276   // this name, if the lookup sucedes, we replace it our current decl.
01277 
01278   // If we're in a class method, we don't normally want to look for
01279   // ivars.  But if we don't find anything else, and there's an
01280   // ivar, that's an error.
01281   bool IsClassMethod = CurMethod->isClassMethod();
01282 
01283   bool LookForIvars;
01284   if (Lookup.empty())
01285     LookForIvars = true;
01286   else if (IsClassMethod)
01287     LookForIvars = false;
01288   else
01289     LookForIvars = (Lookup.isSingleResult() &&
01290                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
01291   ObjCInterfaceDecl *IFace = 0;
01292   if (LookForIvars) {
01293     IFace = CurMethod->getClassInterface();
01294     ObjCInterfaceDecl *ClassDeclared;
01295     if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
01296       // Diagnose using an ivar in a class method.
01297       if (IsClassMethod)
01298         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
01299                          << IV->getDeclName());
01300 
01301       // If we're referencing an invalid decl, just return this as a silent
01302       // error node.  The error diagnostic was already emitted on the decl.
01303       if (IV->isInvalidDecl())
01304         return ExprError();
01305 
01306       // Check if referencing a field with __attribute__((deprecated)).
01307       if (DiagnoseUseOfDecl(IV, Loc))
01308         return ExprError();
01309 
01310       // Diagnose the use of an ivar outside of the declaring class.
01311       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
01312           ClassDeclared != IFace)
01313         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
01314 
01315       // FIXME: This should use a new expr for a direct reference, don't
01316       // turn this into Self->ivar, just return a BareIVarExpr or something.
01317       IdentifierInfo &II = Context.Idents.get("self");
01318       UnqualifiedId SelfName;
01319       SelfName.setIdentifier(&II, SourceLocation());
01320       CXXScopeSpec SelfScopeSpec;
01321       OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
01322                                                     SelfName, false, false);
01323       MarkDeclarationReferenced(Loc, IV);
01324       return Owned(new (Context)
01325                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
01326                                    SelfExpr.takeAs<Expr>(), true, true));
01327     }
01328   } else if (CurMethod->isInstanceMethod()) {
01329     // We should warn if a local variable hides an ivar.
01330     ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
01331     ObjCInterfaceDecl *ClassDeclared;
01332     if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
01333       if (IV->getAccessControl() != ObjCIvarDecl::Private ||
01334           IFace == ClassDeclared)
01335         Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
01336     }
01337   }
01338 
01339   if (Lookup.empty() && II && AllowBuiltinCreation) {
01340     // FIXME. Consolidate this with similar code in LookupName.
01341     if (unsigned BuiltinID = II->getBuiltinID()) {
01342       if (!(getLangOptions().CPlusPlus &&
01343             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
01344         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
01345                                            S, Lookup.isForRedeclaration(),
01346                                            Lookup.getNameLoc());
01347         if (D) Lookup.addDecl(D);
01348       }
01349     }
01350   }
01351   // Sentinel value saying that we didn't do anything special.
01352   return Owned((Expr*) 0);
01353 }
01354 
01355 /// \brief Cast a base object to a member's actual type.
01356 ///
01357 /// Logically this happens in three phases:
01358 ///
01359 /// * First we cast from the base type to the naming class.
01360 ///   The naming class is the class into which we were looking
01361 ///   when we found the member;  it's the qualifier type if a
01362 ///   qualifier was provided, and otherwise it's the base type.
01363 ///
01364 /// * Next we cast from the naming class to the declaring class.
01365 ///   If the member we found was brought into a class's scope by
01366 ///   a using declaration, this is that class;  otherwise it's
01367 ///   the class declaring the member.
01368 ///
01369 /// * Finally we cast from the declaring class to the "true"
01370 ///   declaring class of the member.  This conversion does not
01371 ///   obey access control.
01372 bool
01373 Sema::PerformObjectMemberConversion(Expr *&From,
01374                                     NestedNameSpecifier *Qualifier,
01375                                     NamedDecl *FoundDecl,
01376                                     NamedDecl *Member) {
01377   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
01378   if (!RD)
01379     return false;
01380 
01381   QualType DestRecordType;
01382   QualType DestType;
01383   QualType FromRecordType;
01384   QualType FromType = From->getType();
01385   bool PointerConversions = false;
01386   if (isa<FieldDecl>(Member)) {
01387     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
01388 
01389     if (FromType->getAs<PointerType>()) {
01390       DestType = Context.getPointerType(DestRecordType);
01391       FromRecordType = FromType->getPointeeType();
01392       PointerConversions = true;
01393     } else {
01394       DestType = DestRecordType;
01395       FromRecordType = FromType;
01396     }
01397   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
01398     if (Method->isStatic())
01399       return false;
01400 
01401     DestType = Method->getThisType(Context);
01402     DestRecordType = DestType->getPointeeType();
01403 
01404     if (FromType->getAs<PointerType>()) {
01405       FromRecordType = FromType->getPointeeType();
01406       PointerConversions = true;
01407     } else {
01408       FromRecordType = FromType;
01409       DestType = DestRecordType;
01410     }
01411   } else {
01412     // No conversion necessary.
01413     return false;
01414   }
01415 
01416   if (DestType->isDependentType() || FromType->isDependentType())
01417     return false;
01418 
01419   // If the unqualified types are the same, no conversion is necessary.
01420   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
01421     return false;
01422 
01423   SourceRange FromRange = From->getSourceRange();
01424   SourceLocation FromLoc = FromRange.getBegin();
01425 
01426   // C++ [class.member.lookup]p8:
01427   //   [...] Ambiguities can often be resolved by qualifying a name with its
01428   //   class name.
01429   //
01430   // If the member was a qualified name and the qualified referred to a
01431   // specific base subobject type, we'll cast to that intermediate type
01432   // first and then to the object in which the member is declared. That allows
01433   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
01434   //
01435   //   class Base { public: int x; };
01436   //   class Derived1 : public Base { };
01437   //   class Derived2 : public Base { };
01438   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
01439   //
01440   //   void VeryDerived::f() {
01441   //     x = 17; // error: ambiguous base subobjects
01442   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
01443   //   }
01444   if (Qualifier) {
01445     QualType QType = QualType(Qualifier->getAsType(), 0);
01446     assert(!QType.isNull() && "lookup done with dependent qualifier?");
01447     assert(QType->isRecordType() && "lookup done with non-record type");
01448 
01449     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
01450 
01451     // In C++98, the qualifier type doesn't actually have to be a base
01452     // type of the object type, in which case we just ignore it.
01453     // Otherwise build the appropriate casts.
01454     if (IsDerivedFrom(FromRecordType, QRecordType)) {
01455       CXXBaseSpecifierArray BasePath;
01456       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
01457                                        FromLoc, FromRange, &BasePath))
01458         return true;
01459 
01460       if (PointerConversions)
01461         QType = Context.getPointerType(QType);
01462       ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
01463                         /*isLvalue=*/!PointerConversions, BasePath);
01464 
01465       FromType = QType;
01466       FromRecordType = QRecordType;
01467 
01468       // If the qualifier type was the same as the destination type,
01469       // we're done.
01470       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
01471         return false;
01472     }
01473   }
01474 
01475   bool IgnoreAccess = false;
01476 
01477   // If we actually found the member through a using declaration, cast
01478   // down to the using declaration's type.
01479   //
01480   // Pointer equality is fine here because only one declaration of a
01481   // class ever has member declarations.
01482   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
01483     assert(isa<UsingShadowDecl>(FoundDecl));
01484     QualType URecordType = Context.getTypeDeclType(
01485                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
01486 
01487     // We only need to do this if the naming-class to declaring-class
01488     // conversion is non-trivial.
01489     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
01490       assert(IsDerivedFrom(FromRecordType, URecordType));
01491       CXXBaseSpecifierArray BasePath;
01492       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
01493                                        FromLoc, FromRange, &BasePath))
01494         return true;
01495 
01496       QualType UType = URecordType;
01497       if (PointerConversions)
01498         UType = Context.getPointerType(UType);
01499       ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
01500                         /*isLvalue=*/!PointerConversions, BasePath);
01501       FromType = UType;
01502       FromRecordType = URecordType;
01503     }
01504 
01505     // We don't do access control for the conversion from the
01506     // declaring class to the true declaring class.
01507     IgnoreAccess = true;
01508   }
01509 
01510   CXXBaseSpecifierArray BasePath;
01511   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
01512                                    FromLoc, FromRange, &BasePath,
01513                                    IgnoreAccess))
01514     return true;
01515 
01516   ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
01517                     /*isLvalue=*/!PointerConversions, BasePath);
01518   return false;
01519 }
01520 
01521 /// \brief Build a MemberExpr AST node.
01522 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
01523                                    const CXXScopeSpec &SS, ValueDecl *Member,
01524                                    DeclAccessPair FoundDecl,
01525                                    SourceLocation Loc, QualType Ty,
01526                           const TemplateArgumentListInfo *TemplateArgs = 0) {
01527   NestedNameSpecifier *Qualifier = 0;
01528   SourceRange QualifierRange;
01529   if (SS.isSet()) {
01530     Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
01531     QualifierRange = SS.getRange();
01532   }
01533 
01534   return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
01535                             Member, FoundDecl, Loc, TemplateArgs, Ty);
01536 }
01537 
01538 /// Builds an implicit member access expression.  The current context
01539 /// is known to be an instance method, and the given unqualified lookup
01540 /// set is known to contain only instance members, at least one of which
01541 /// is from an appropriate type.
01542 Sema::OwningExprResult
01543 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
01544                               LookupResult &R,
01545                               const TemplateArgumentListInfo *TemplateArgs,
01546                               bool IsKnownInstance) {
01547   assert(!R.empty() && !R.isAmbiguous());
01548 
01549   SourceLocation Loc = R.getNameLoc();
01550 
01551   // We may have found a field within an anonymous union or struct
01552   // (C++ [class.union]).
01553   // FIXME: This needs to happen post-isImplicitMemberReference?
01554   // FIXME: template-ids inside anonymous structs?
01555   if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
01556     if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
01557       return BuildAnonymousStructUnionMemberReference(Loc, FD);
01558 
01559   // If this is known to be an instance access, go ahead and build a
01560   // 'this' expression now.
01561   QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
01562   Expr *This = 0; // null signifies implicit access
01563   if (IsKnownInstance) {
01564     SourceLocation Loc = R.getNameLoc();
01565     if (SS.getRange().isValid())
01566       Loc = SS.getRange().getBegin();
01567     This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
01568   }
01569 
01570   return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
01571                                   /*OpLoc*/ SourceLocation(),
01572                                   /*IsArrow*/ true,
01573                                   SS,
01574                                   /*FirstQualifierInScope*/ 0,
01575                                   R, TemplateArgs);
01576 }
01577 
01578 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
01579                                       const LookupResult &R,
01580                                       bool HasTrailingLParen) {
01581   // Only when used directly as the postfix-expression of a call.
01582   if (!HasTrailingLParen)
01583     return false;
01584 
01585   // Never if a scope specifier was provided.
01586   if (SS.isSet())
01587     return false;
01588 
01589   // Only in C++ or ObjC++.
01590   if (!getLangOptions().CPlusPlus)
01591     return false;
01592 
01593   // Turn off ADL when we find certain kinds of declarations during
01594   // normal lookup:
01595   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
01596     NamedDecl *D = *I;
01597 
01598     // C++0x [basic.lookup.argdep]p3:
01599     //     -- a declaration of a class member
01600     // Since using decls preserve this property, we check this on the
01601     // original decl.
01602     if (D->isCXXClassMember())
01603       return false;
01604 
01605     // C++0x [basic.lookup.argdep]p3:
01606     //     -- a block-scope function declaration that is not a
01607     //        using-declaration
01608     // NOTE: we also trigger this for function templates (in fact, we
01609     // don't check the decl type at all, since all other decl types
01610     // turn off ADL anyway).
01611     if (isa<UsingShadowDecl>(D))
01612       D = cast<UsingShadowDecl>(D)->getTargetDecl();
01613     else if (D->getDeclContext()->isFunctionOrMethod())
01614       return false;
01615 
01616     // C++0x [basic.lookup.argdep]p3:
01617     //     -- a declaration that is neither a function or a function
01618     //        template
01619     // And also for builtin functions.
01620     if (isa<FunctionDecl>(D)) {
01621       FunctionDecl *FDecl = cast<FunctionDecl>(D);
01622 
01623       // But also builtin functions.
01624       if (FDecl->getBuiltinID() && FDecl->isImplicit())
01625         return false;
01626     } else if (!isa<FunctionTemplateDecl>(D))
01627       return false;
01628   }
01629 
01630   return true;
01631 }
01632 
01633 
01634 /// Diagnoses obvious problems with the use of the given declaration
01635 /// as an expression.  This is only actually called for lookups that
01636 /// were not overloaded, and it doesn't promise that the declaration
01637 /// will in fact be used.
01638 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
01639   if (isa<TypedefDecl>(D)) {
01640     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
01641     return true;
01642   }
01643 
01644   if (isa<ObjCInterfaceDecl>(D)) {
01645     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
01646     return true;
01647   }
01648 
01649   if (isa<NamespaceDecl>(D)) {
01650     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
01651     return true;
01652   }
01653 
01654   return false;
01655 }
01656 
01657 Sema::OwningExprResult
01658 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
01659                                LookupResult &R,
01660                                bool NeedsADL) {
01661   // If this is a single, fully-resolved result and we don't need ADL,
01662   // just build an ordinary singleton decl ref.
01663   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
01664     return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
01665 
01666   // We only need to check the declaration if there's exactly one
01667   // result, because in the overloaded case the results can only be
01668   // functions and function templates.
01669   if (R.isSingleResult() &&
01670       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
01671     return ExprError();
01672 
01673   // Otherwise, just build an unresolved lookup expression.  Suppress
01674   // any lookup-related diagnostics; we'll hash these out later, when
01675   // we've picked a target.
01676   R.suppressDiagnostics();
01677 
01678   bool Dependent
01679     = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
01680   UnresolvedLookupExpr *ULE
01681     = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
01682                                    (NestedNameSpecifier*) SS.getScopeRep(),
01683                                    SS.getRange(),
01684                                    R.getLookupName(), R.getNameLoc(),
01685                                    NeedsADL, R.isOverloadedResult());
01686   ULE->addDecls(R.begin(), R.end());
01687 
01688   return Owned(ULE);
01689 }
01690 
01691 
01692 /// \brief Complete semantic analysis for a reference to the given declaration.
01693 Sema::OwningExprResult
01694 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
01695                                SourceLocation Loc, NamedDecl *D) {
01696   assert(D && "Cannot refer to a NULL declaration");
01697   assert(!isa<FunctionTemplateDecl>(D) &&
01698          "Cannot refer unambiguously to a function template");
01699 
01700   if (CheckDeclInExpr(*this, Loc, D))
01701     return ExprError();
01702 
01703   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
01704     // Specifically diagnose references to class templates that are missing
01705     // a template argument list.
01706     Diag(Loc, diag::err_template_decl_ref)
01707       << Template << SS.getRange();
01708     Diag(Template->getLocation(), diag::note_template_decl_here);
01709     return ExprError();
01710   }
01711 
01712   // Make sure that we're referring to a value.
01713   ValueDecl *VD = dyn_cast<ValueDecl>(D);
01714   if (!VD) {
01715     Diag(Loc, diag::err_ref_non_value)
01716       << D << SS.getRange();
01717     Diag(D->getLocation(), diag::note_declared_at);
01718     return ExprError();
01719   }
01720 
01721   // Check whether this declaration can be used. Note that we suppress
01722   // this check when we're going to perform argument-dependent lookup
01723   // on this function name, because this might not be the function
01724   // that overload resolution actually selects.
01725   if (DiagnoseUseOfDecl(VD, Loc))
01726     return ExprError();
01727 
01728   // Only create DeclRefExpr's for valid Decl's.
01729   if (VD->isInvalidDecl())
01730     return ExprError();
01731 
01732   // If the identifier reference is inside a block, and it refers to a value
01733   // that is outside the block, create a BlockDeclRefExpr instead of a
01734   // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
01735   // the block is formed.
01736   //
01737   // We do not do this for things like enum constants, global variables, etc,
01738   // as they do not get snapshotted.
01739   //
01740   if (getCurBlock() &&
01741       ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
01742     if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
01743       Diag(Loc, diag::err_ref_vm_type);
01744       Diag(D->getLocation(), diag::note_declared_at);
01745       return ExprError();
01746     }
01747 
01748     if (VD->getType()->isArrayType()) {
01749       Diag(Loc, diag::err_ref_array_type);
01750       Diag(D->getLocation(), diag::note_declared_at);
01751       return ExprError();
01752     }
01753 
01754     MarkDeclarationReferenced(Loc, VD);
01755     QualType ExprTy = VD->getType().getNonReferenceType();
01756     // The BlocksAttr indicates the variable is bound by-reference.
01757     if (VD->getAttr<BlocksAttr>())
01758       return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
01759     // This is to record that a 'const' was actually synthesize and added.
01760     bool constAdded = !ExprTy.isConstQualified();
01761     // Variable will be bound by-copy, make it const within the closure.
01762 
01763     ExprTy.addConst();
01764     return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
01765                                                 constAdded));
01766   }
01767   // If this reference is not in a block or if the referenced variable is
01768   // within the block, create a normal DeclRefExpr.
01769 
01770   return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
01771 }
01772 
01773 Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
01774                                                  tok::TokenKind Kind) {
01775   PredefinedExpr::IdentType IT;
01776 
01777   switch (Kind) {
01778   default: assert(0 && "Unknown simple primary expr!");
01779   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
01780   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
01781   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
01782   }
01783 
01784   // Pre-defined identifiers are of type char[x], where x is the length of the
01785   // string.
01786 
01787   Decl *currentDecl = getCurFunctionOrMethodDecl();
01788   if (!currentDecl) {
01789     Diag(Loc, diag::ext_predef_outside_function);
01790     currentDecl = Context.getTranslationUnitDecl();
01791   }
01792 
01793   QualType ResTy;
01794   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
01795     ResTy = Context.DependentTy;
01796   } else {
01797     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
01798 
01799     llvm::APInt LengthI(32, Length + 1);
01800     ResTy = Context.CharTy.withConst();
01801     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
01802   }
01803   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
01804 }
01805 
01806 Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
01807   llvm::SmallString<16> CharBuffer;
01808   bool Invalid = false;
01809   llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
01810   if (Invalid)
01811     return ExprError();
01812 
01813   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
01814                             PP);
01815   if (Literal.hadError())
01816     return ExprError();
01817 
01818   QualType Ty;
01819   if (!getLangOptions().CPlusPlus)
01820     Ty = Context.IntTy;   // 'x' and L'x' -> int in C.
01821   else if (Literal.isWide())
01822     Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
01823   else if (Literal.isMultiChar())
01824     Ty = Context.IntTy;   // 'wxyz' -> int in C++.
01825   else
01826     Ty = Context.CharTy;  // 'x' -> char in C++
01827 
01828   return Owned(new (Context) CharacterLiteral(Literal.getValue(),
01829                                               Literal.isWide(),
01830                                               Ty, Tok.getLocation()));
01831 }
01832 
01833 Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
01834   // Fast path for a single digit (which is quite common).  A single digit
01835   // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
01836   if (Tok.getLength() == 1) {
01837     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
01838     unsigned IntSize = Context.Target.getIntWidth();
01839     return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
01840                     Context.IntTy, Tok.getLocation()));
01841   }
01842 
01843   llvm::SmallString<512> IntegerBuffer;
01844   // Add padding so that NumericLiteralParser can overread by one character.
01845   IntegerBuffer.resize(Tok.getLength()+1);
01846   const char *ThisTokBegin = &IntegerBuffer[0];
01847 
01848   // Get the spelling of the token, which eliminates trigraphs, etc.
01849   bool Invalid = false;
01850   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
01851   if (Invalid)
01852     return ExprError();
01853 
01854   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
01855                                Tok.getLocation(), PP);
01856   if (Literal.hadError)
01857     return ExprError();
01858 
01859   Expr *Res;
01860 
01861   if (Literal.isFloatingLiteral()) {
01862     QualType Ty;
01863     if (Literal.isFloat)
01864       Ty = Context.FloatTy;
01865     else if (!Literal.isLong)
01866       Ty = Context.DoubleTy;
01867     else
01868       Ty = Context.LongDoubleTy;
01869 
01870     const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
01871 
01872     using llvm::APFloat;
01873     APFloat Val(Format);
01874 
01875     APFloat::opStatus result = Literal.GetFloatValue(Val);
01876 
01877     // Overflow is always an error, but underflow is only an error if
01878     // we underflowed to zero (APFloat reports denormals as underflow).
01879     if ((result & APFloat::opOverflow) ||
01880         ((result & APFloat::opUnderflow) && Val.isZero())) {
01881       unsigned diagnostic;
01882       llvm::SmallString<20> buffer;
01883       if (result & APFloat::opOverflow) {
01884         diagnostic = diag::warn_float_overflow;
01885         APFloat::getLargest(Format).toString(buffer);
01886       } else {
01887         diagnostic = diag::warn_float_underflow;
01888         APFloat::getSmallest(Format).toString(buffer);
01889       }
01890 
01891       Diag(Tok.getLocation(), diagnostic)
01892         << Ty
01893         << llvm::StringRef(buffer.data(), buffer.size());
01894     }
01895 
01896     bool isExact = (result == APFloat::opOK);
01897     Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
01898 
01899   } else if (!Literal.isIntegerLiteral()) {
01900     return ExprError();
01901   } else {
01902     QualType Ty;
01903 
01904     // long long is a C99 feature.
01905     if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
01906         Literal.isLongLong)
01907       Diag(Tok.getLocation(), diag::ext_longlong);
01908 
01909     // Get the value in the widest-possible width.
01910     llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
01911 
01912     if (Literal.GetIntegerValue(ResultVal)) {
01913       // If this value didn't fit into uintmax_t, warn and force to ull.
01914       Diag(Tok.getLocation(), diag::warn_integer_too_large);
01915       Ty = Context.UnsignedLongLongTy;
01916       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
01917              "long long is not intmax_t?");
01918     } else {
01919       // If this value fits into a ULL, try to figure out what else it fits into
01920       // according to the rules of C99 6.4.4.1p5.
01921 
01922       // Octal, Hexadecimal, and integers with a U suffix are allowed to
01923       // be an unsigned int.
01924       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
01925 
01926       // Check from smallest to largest, picking the smallest type we can.
01927       unsigned Width = 0;
01928       if (!Literal.isLong && !Literal.isLongLong) {
01929         // Are int/unsigned possibilities?
01930         unsigned IntSize = Context.Target.getIntWidth();
01931 
01932         // Does it fit in a unsigned int?
01933         if (ResultVal.isIntN(IntSize)) {
01934           // Does it fit in a signed int?
01935           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
01936             Ty = Context.IntTy;
01937           else if (AllowUnsigned)
01938             Ty = Context.UnsignedIntTy;
01939           Width = IntSize;
01940         }
01941       }
01942 
01943       // Are long/unsigned long possibilities?
01944       if (Ty.isNull() && !Literal.isLongLong) {
01945         unsigned LongSize = Context.Target.getLongWidth();
01946 
01947         // Does it fit in a unsigned long?
01948         if (ResultVal.isIntN(LongSize)) {
01949           // Does it fit in a signed long?
01950           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
01951             Ty = Context.LongTy;
01952           else if (AllowUnsigned)
01953             Ty = Context.UnsignedLongTy;
01954           Width = LongSize;
01955         }
01956       }
01957 
01958       // Finally, check long long if needed.
01959       if (Ty.isNull()) {
01960         unsigned LongLongSize = Context.Target.getLongLongWidth();
01961 
01962         // Does it fit in a unsigned long long?
01963         if (ResultVal.isIntN(LongLongSize)) {
01964           // Does it fit in a signed long long?
01965           if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
01966             Ty = Context.LongLongTy;
01967           else if (AllowUnsigned)
01968             Ty = Context.UnsignedLongLongTy;
01969           Width = LongLongSize;
01970         }
01971       }
01972 
01973       // If we still couldn't decide a type, we probably have something that
01974       // does not fit in a signed long long, but has no U suffix.
01975       if (Ty.isNull()) {
01976         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
01977         Ty = Context.UnsignedLongLongTy;
01978         Width = Context.Target.getLongLongWidth();
01979       }
01980 
01981       if (ResultVal.getBitWidth() != Width)
01982         ResultVal.trunc(Width);
01983     }
01984     Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
01985   }
01986 
01987   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
01988   if (Literal.isImaginary)
01989     Res = new (Context) ImaginaryLiteral(Res,
01990                                         Context.getComplexType(Res->getType()));
01991 
01992   return Owned(Res);
01993 }
01994 
01995 Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
01996                                               SourceLocation R, ExprArg Val) {
01997   Expr *E = Val.takeAs<Expr>();
01998   assert((E != 0) && "ActOnParenExpr() missing expr");
01999   return Owned(new (Context) ParenExpr(L, R, E));
02000 }
02001 
02002 /// The UsualUnaryConversions() function is *not* called by this routine.
02003 /// See C99 6.3.2.1p[2-4] for more details.
02004 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
02005                                      SourceLocation OpLoc,
02006                                      const SourceRange &ExprRange,
02007                                      bool isSizeof) {
02008   if (exprType->isDependentType())
02009     return false;
02010 
02011   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
02012   //   the result is the size of the referenced type."
02013   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
02014   //   result shall be the alignment of the referenced type."
02015   if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
02016     exprType = Ref->getPointeeType();
02017 
02018   // C99 6.5.3.4p1:
02019   if (exprType->isFunctionType()) {
02020     // alignof(function) is allowed as an extension.
02021     if (isSizeof)
02022       Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
02023     return false;
02024   }
02025 
02026   // Allow sizeof(void)/alignof(void) as an extension.
02027   if (exprType->isVoidType()) {
02028     Diag(OpLoc, diag::ext_sizeof_void_type)
02029       << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
02030     return false;
02031   }
02032 
02033   if (RequireCompleteType(OpLoc, exprType,
02034                           PDiag(diag::err_sizeof_alignof_incomplete_type)
02035                           << int(!isSizeof) << ExprRange))
02036     return true;
02037 
02038   // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
02039   if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
02040     Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
02041       << exprType << isSizeof << ExprRange;
02042     return true;
02043   }
02044 
02045   return false;
02046 }
02047 
02048 bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
02049                             const SourceRange &ExprRange) {
02050   E = E->IgnoreParens();
02051 
02052   // alignof decl is always ok.
02053   if (isa<DeclRefExpr>(E))
02054     return false;
02055 
02056   // Cannot know anything else if the expression is dependent.
02057   if (E->isTypeDependent())
02058     return false;
02059 
02060   if (E->getBitField()) {
02061     Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
02062     return true;
02063   }
02064 
02065   // Alignment of a field access is always okay, so long as it isn't a
02066   // bit-field.
02067   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
02068     if (isa<FieldDecl>(ME->getMemberDecl()))
02069       return false;
02070 
02071   return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
02072 }
02073 
02074 /// \brief Build a sizeof or alignof expression given a type operand.
02075 Action::OwningExprResult
02076 Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
02077                               SourceLocation OpLoc,
02078                               bool isSizeOf, SourceRange R) {
02079   if (!TInfo)
02080     return ExprError();
02081 
02082   QualType T = TInfo->getType();
02083 
02084   if (!T->isDependentType() &&
02085       CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
02086     return ExprError();
02087 
02088   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
02089   return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
02090                                                Context.getSizeType(), OpLoc,
02091                                                R.getEnd()));
02092 }
02093 
02094 /// \brief Build a sizeof or alignof expression given an expression
02095 /// operand.
02096 Action::OwningExprResult
02097 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
02098                               bool isSizeOf, SourceRange R) {
02099   // Verify that the operand is valid.
02100   bool isInvalid = false;
02101   if (E->isTypeDependent()) {
02102     // Delay type-checking for type-dependent expressions.
02103   } else if (!isSizeOf) {
02104     isInvalid = CheckAlignOfExpr(E, OpLoc, R);
02105   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
02106     Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
02107     isInvalid = true;
02108   } else {
02109     isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
02110   }
02111 
02112   if (isInvalid)
02113     return ExprError();
02114 
02115   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
02116   return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
02117                                                Context.getSizeType(), OpLoc,
02118                                                R.getEnd()));
02119 }
02120 
02121 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
02122 /// the same for @c alignof and @c __alignof
02123 /// Note that the ArgRange is invalid if isType is false.
02124 Action::OwningExprResult
02125 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
02126                              void *TyOrEx, const SourceRange &ArgRange) {
02127   // If error parsing type, ignore.
02128   if (TyOrEx == 0) return ExprError();
02129 
02130   if (isType) {
02131     TypeSourceInfo *TInfo;
02132     (void) GetTypeFromParser(TyOrEx, &TInfo);
02133     return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
02134   }
02135 
02136   Expr *ArgEx = (Expr *)TyOrEx;
02137   Action::OwningExprResult Result
02138     = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
02139 
02140   if (Result.isInvalid())
02141     DeleteExpr(ArgEx);
02142 
02143   return move(Result);
02144 }
02145 
02146 QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
02147   if (V->isTypeDependent())
02148     return Context.DependentTy;
02149 
02150   // These operators return the element type of a complex type.
02151   if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
02152     return CT->getElementType();
02153 
02154   // Otherwise they pass through real integer and floating point types here.
02155   if (V->getType()->isArithmeticType())
02156     return V->getType();
02157 
02158   // Reject anything else.
02159   Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
02160     << (isReal ? "__real" : "__imag");
02161   return QualType();
02162 }
02163 
02164 
02165 
02166 Action::OwningExprResult
02167 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
02168                           tok::TokenKind Kind, ExprArg Input) {
02169   UnaryOperator::Opcode Opc;
02170   switch (Kind) {
02171   default: assert(0 && "Unknown unary op!");
02172   case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
02173   case tok::minusminus: Opc = UnaryOperator::PostDec; break;
02174   }
02175 
02176   return BuildUnaryOp(S, OpLoc, Opc, move(Input));
02177 }
02178 
02179 Action::OwningExprResult
02180 Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
02181                               ExprArg Idx, SourceLocation RLoc) {
02182   // Since this might be a postfix expression, get rid of ParenListExprs.
02183   Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
02184 
02185   Expr *LHSExp = static_cast<Expr*>(Base.get()),
02186        *RHSExp = static_cast<Expr*>(Idx.get());
02187 
02188   if (getLangOptions().CPlusPlus &&
02189       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
02190     Base.release();
02191     Idx.release();
02192     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
02193                                                   Context.DependentTy, RLoc));
02194   }
02195 
02196   if (getLangOptions().CPlusPlus &&
02197       (LHSExp->getType()->isRecordType() ||
02198        LHSExp->getType()->isEnumeralType() ||
02199        RHSExp->getType()->isRecordType() ||
02200        RHSExp->getType()->isEnumeralType())) {
02201     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
02202   }
02203 
02204   return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
02205 }
02206 
02207 
02208 Action::OwningExprResult
02209 Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
02210                                      ExprArg Idx, SourceLocation RLoc) {
02211   Expr *LHSExp = static_cast<Expr*>(Base.get());
02212   Expr *RHSExp = static_cast<Expr*>(Idx.get());
02213 
02214   // Perform default conversions.
02215   if (!LHSExp->getType()->getAs<VectorType>())
02216       DefaultFunctionArrayLvalueConversion(LHSExp);
02217   DefaultFunctionArrayLvalueConversion(RHSExp);
02218 
02219   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
02220 
02221   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
02222   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
02223   // in the subscript position. As a result, we need to derive the array base
02224   // and index from the expression types.
02225   Expr *BaseExpr, *IndexExpr;
02226   QualType ResultType;
02227   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
02228     BaseExpr = LHSExp;
02229     IndexExpr = RHSExp;
02230     ResultType = Context.DependentTy;
02231   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
02232     BaseExpr = LHSExp;
02233     IndexExpr = RHSExp;
02234     ResultType = PTy->getPointeeType();
02235   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
02236      // Handle the uncommon case of "123[Ptr]".
02237     BaseExpr = RHSExp;
02238     IndexExpr = LHSExp;
02239     ResultType = PTy->getPointeeType();
02240   } else if (const ObjCObjectPointerType *PTy =
02241                LHSTy->getAs<ObjCObjectPointerType>()) {
02242     BaseExpr = LHSExp;
02243     IndexExpr = RHSExp;
02244     ResultType = PTy->getPointeeType();
02245   } else if (const ObjCObjectPointerType *PTy =
02246                RHSTy->getAs<ObjCObjectPointerType>()) {
02247      // Handle the uncommon case of "123[Ptr]".
02248     BaseExpr = RHSExp;
02249     IndexExpr = LHSExp;
02250     ResultType = PTy->getPointeeType();
02251   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
02252     BaseExpr = LHSExp;    // vectors: V[123]
02253     IndexExpr = RHSExp;
02254 
02255     // FIXME: need to deal with const...
02256     ResultType = VTy->getElementType();
02257   } else if (LHSTy->isArrayType()) {
02258     // If we see an array that wasn't promoted by
02259     // DefaultFunctionArrayLvalueConversion, it must be an array that
02260     // wasn't promoted because of the C90 rule that doesn't
02261     // allow promoting non-lvalue arrays.  Warn, then
02262     // force the promotion here.
02263     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
02264         LHSExp->getSourceRange();
02265     ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
02266                       CastExpr::CK_ArrayToPointerDecay);
02267     LHSTy = LHSExp->getType();
02268 
02269     BaseExpr = LHSExp;
02270     IndexExpr = RHSExp;
02271     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
02272   } else if (RHSTy->isArrayType()) {
02273     // Same as previous, except for 123[f().a] case
02274     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
02275         RHSExp->getSourceRange();
02276     ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
02277                       CastExpr::CK_ArrayToPointerDecay);
02278     RHSTy = RHSExp->getType();
02279 
02280     BaseExpr = RHSExp;
02281     IndexExpr = LHSExp;
02282     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
02283   } else {
02284     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
02285        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
02286   }
02287   // C99 6.5.2.1p1
02288   if (!(IndexExpr->getType()->isIntegerType() &&
02289         IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
02290     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
02291                      << IndexExpr->getSourceRange());
02292 
02293   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
02294        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
02295          && !IndexExpr->isTypeDependent())
02296     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
02297 
02298   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
02299   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
02300   // type. Note that Functions are not objects, and that (in C99 parlance)
02301   // incomplete types are not object types.
02302   if (ResultType->isFunctionType()) {
02303     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
02304       << ResultType << BaseExpr->getSourceRange();
02305     return ExprError();
02306   }
02307 
02308   if (!ResultType->isDependentType() &&
02309       RequireCompleteType(LLoc, ResultType,
02310                           PDiag(diag::err_subscript_incomplete_type)
02311                             << BaseExpr->getSourceRange()))
02312     return ExprError();
02313 
02314   // Diagnose bad cases where we step over interface counts.
02315   if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
02316     Diag(LLoc, diag::err_subscript_nonfragile_interface)
02317       << ResultType << BaseExpr->getSourceRange();
02318     return ExprError();
02319   }
02320 
02321   Base.release();
02322   Idx.release();
02323   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
02324                                                 ResultType, RLoc));
02325 }
02326 
02327 QualType Sema::
02328 CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
02329                         const IdentifierInfo *CompName,
02330                         SourceLocation CompLoc) {
02331   // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
02332   // see FIXME there.
02333   //
02334   // FIXME: This logic can be greatly simplified by splitting it along
02335   // halving/not halving and reworking the component checking.
02336   const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
02337 
02338   // The vector accessor can't exceed the number of elements.
02339   const char *compStr = CompName->getNameStart();
02340 
02341   // This flag determines whether or not the component is one of the four
02342   // special names that indicate a subset of exactly half the elements are
02343   // to be selected.
02344   bool HalvingSwizzle = false;
02345 
02346   // This flag determines whether or not CompName has an 's' char prefix,
02347   // indicating that it is a string of hex values to be used as vector indices.
02348   bool HexSwizzle = *compStr == 's' || *compStr == 'S';
02349 
02350   // Check that we've found one of the special components, or that the component
02351   // names must come from the same set.
02352   if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
02353       !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
02354     HalvingSwizzle = true;
02355   } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
02356     do
02357       compStr++;
02358     while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
02359   } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
02360     do
02361       compStr++;
02362     while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
02363   }
02364 
02365   if (!HalvingSwizzle && *compStr) {
02366     // We didn't get to the end of the string. This means the component names
02367     // didn't come from the same set *or* we encountered an illegal name.
02368     Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
02369       << std::string(compStr,compStr+1) << SourceRange(CompLoc);
02370     return QualType();
02371   }
02372 
02373   // Ensure no component accessor exceeds the width of the vector type it
02374   // operates on.
02375   if (!HalvingSwizzle) {
02376     compStr = CompName->getNameStart();
02377 
02378     if (HexSwizzle)
02379       compStr++;
02380 
02381     while (*compStr) {
02382       if (!vecType->isAccessorWithinNumElements(*compStr++)) {
02383         Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
02384           << baseType << SourceRange(CompLoc);
02385         return QualType();
02386       }
02387     }
02388   }
02389 
02390   // The component accessor looks fine - now we need to compute the actual type.
02391   // The vector type is implied by the component accessor. For example,
02392   // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
02393   // vec4.s0 is a float, vec4.s23 is a vec3, etc.
02394   // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
02395   unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
02396                                      : CompName->getLength();
02397   if (HexSwizzle)
02398     CompSize--;
02399 
02400   if (CompSize == 1)
02401     return vecType->getElementType();
02402 
02403   QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
02404   // Now look up the TypeDefDecl from the vector type. Without this,
02405   // diagostics look bad. We want extended vector types to appear built-in.
02406   for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
02407     if (ExtVectorDecls[i]->getUnderlyingType() == VT)
02408       return Context.getTypedefType(ExtVectorDecls[i]);
02409   }
02410   return VT; // should never get here (a typedef type should always be found).
02411 }
02412 
02413 static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
02414                                                 IdentifierInfo *Member,
02415                                                 const Selector &Sel,
02416                                                 ASTContext &Context) {
02417 
02418   if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
02419     return PD;
02420   if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
02421     return OMD;
02422 
02423   for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
02424        E = PDecl->protocol_end(); I != E; ++I) {
02425     if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
02426                                                      Context))
02427       return D;
02428   }
02429   return 0;
02430 }
02431 
02432 static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
02433                                 IdentifierInfo *Member,
02434                                 const Selector &Sel,
02435                                 ASTContext &Context) {
02436   // Check protocols on qualified interfaces.
02437   Decl *GDecl = 0;
02438   for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
02439        E = QIdTy->qual_end(); I != E; ++I) {
02440     if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
02441       GDecl = PD;
02442       break;
02443     }
02444     // Also must look for a getter name which uses property syntax.
02445     if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
02446       GDecl = OMD;
02447       break;
02448     }
02449   }
02450   if (!GDecl) {
02451     for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
02452          E = QIdTy->qual_end(); I != E; ++I) {
02453       // Search in the protocol-qualifier list of current protocol.
02454       GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
02455       if (GDecl)
02456         return GDecl;
02457     }
02458   }
02459   return GDecl;
02460 }
02461 
02462 Sema::OwningExprResult
02463 Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
02464                                bool IsArrow, SourceLocation OpLoc,
02465                                const CXXScopeSpec &SS,
02466                                NamedDecl *FirstQualifierInScope,
02467                                DeclarationName Name, SourceLocation NameLoc,
02468                                const TemplateArgumentListInfo *TemplateArgs) {
02469   Expr *BaseExpr = Base.takeAs<Expr>();
02470 
02471   // Even in dependent contexts, try to diagnose base expressions with
02472   // obviously wrong types, e.g.:
02473   //
02474   // T* t;
02475   // t.f;
02476   //
02477   // In Obj-C++, however, the above expression is valid, since it could be
02478   // accessing the 'f' property if T is an Obj-C interface. The extra check
02479   // allows this, while still reporting an error if T is a struct pointer.
02480   if (!IsArrow) {
02481     const PointerType *PT = BaseType->getAs<PointerType>();
02482     if (PT && (!getLangOptions().ObjC1 ||
02483                PT->getPointeeType()->isRecordType())) {
02484       assert(BaseExpr && "cannot happen with implicit member accesses");
02485       Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
02486         << BaseType << BaseExpr->getSourceRange();
02487       return ExprError();
02488     }
02489   }
02490 
02491   assert(BaseType->isDependentType() || Name.isDependentName() ||
02492          isDependentScopeSpecifier(SS));
02493 
02494   // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
02495   // must have pointer type, and the accessed type is the pointee.
02496   return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
02497                                                    IsArrow, OpLoc,
02498                  static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
02499                                                    SS.getRange(),
02500                                                    FirstQualifierInScope,
02501                                                    Name, NameLoc,
02502                                                    TemplateArgs));
02503 }
02504 
02505 /// We know that the given qualified member reference points only to
02506 /// declarations which do not belong to the static type of the base
02507 /// expression.  Diagnose the problem.
02508 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
02509                                              Expr *BaseExpr,
02510                                              QualType BaseType,
02511                                              const CXXScopeSpec &SS,
02512                                              const LookupResult &R) {
02513   // If this is an implicit member access, use a different set of
02514   // diagnostics.
02515   if (!BaseExpr)
02516     return DiagnoseInstanceReference(SemaRef, SS, R);
02517 
02518   SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
02519     << SS.getRange() << R.getRepresentativeDecl() << BaseType;
02520 }
02521 
02522 // Check whether the declarations we found through a nested-name
02523 // specifier in a member expression are actually members of the base
02524 // type.  The restriction here is:
02525 //
02526 //   C++ [expr.ref]p2:
02527 //     ... In these cases, the id-expression shall name a
02528 //     member of the class or of one of its base classes.
02529 //
02530 // So it's perfectly legitimate for the nested-name specifier to name
02531 // an unrelated class, and for us to find an overload set including
02532 // decls from classes which are not superclasses, as long as the decl
02533 // we actually pick through overload resolution is from a superclass.
02534 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
02535                                          QualType BaseType,
02536                                          const CXXScopeSpec &SS,
02537                                          const LookupResult &R) {
02538   const RecordType *BaseRT = BaseType->getAs<RecordType>();
02539   if (!BaseRT) {
02540     // We can't check this yet because the base type is still
02541     // dependent.
02542     assert(BaseType->isDependentType());
02543     return false;
02544   }
02545   CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
02546 
02547   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
02548     // If this is an implicit member reference and we find a
02549     // non-instance member, it's not an error.
02550     if (!BaseExpr && !(*I)->isCXXInstanceMember())
02551       return false;
02552 
02553     // Note that we use the DC of the decl, not the underlying decl.
02554     CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
02555     while (RecordD->isAnonymousStructOrUnion())
02556       RecordD = cast<CXXRecordDecl>(RecordD->getParent());
02557 
02558     llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
02559     MemberRecord.insert(RecordD->getCanonicalDecl());
02560 
02561     if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
02562       return false;
02563   }
02564 
02565   DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
02566   return true;
02567 }
02568 
02569 static bool
02570 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
02571                          SourceRange BaseRange, const RecordType *RTy,
02572                          SourceLocation OpLoc, CXXScopeSpec &SS) {
02573   RecordDecl *RDecl = RTy->getDecl();
02574   if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
02575                               SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
02576                                     << BaseRange))
02577     return true;
02578 
02579   DeclContext *DC = RDecl;
02580   if (SS.isSet()) {
02581     // If the member name was a qualified-id, look into the
02582     // nested-name-specifier.
02583     DC = SemaRef.computeDeclContext(SS, false);
02584 
02585     if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
02586       SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
02587         << SS.getRange() << DC;
02588       return true;
02589     }
02590 
02591     assert(DC && "Cannot handle non-computable dependent contexts in lookup");
02592 
02593     if (!isa<TypeDecl>(DC)) {
02594       SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
02595         << DC << SS.getRange();
02596       return true;
02597     }
02598   }
02599 
02600   // The record definition is complete, now look up the member.
02601   SemaRef.LookupQualifiedName(R, DC);
02602 
02603   if (!R.empty())
02604     return false;
02605 
02606   // We didn't find anything with the given name, so try to correct
02607   // for typos.
02608   DeclarationName Name = R.getLookupName();
02609   if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
02610       !R.empty() &&
02611       (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
02612     SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
02613       << Name << DC << R.getLookupName() << SS.getRange()
02614       << FixItHint::CreateReplacement(R.getNameLoc(),
02615                                       R.getLookupName().getAsString());
02616     if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
02617       SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
02618         << ND->getDeclName();
02619     return false;
02620   } else {
02621     R.clear();
02622   }
02623 
02624   return false;
02625 }
02626 
02627 Sema::OwningExprResult
02628 Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
02629                                SourceLocation OpLoc, bool IsArrow,
02630                                CXXScopeSpec &SS,
02631                                NamedDecl *FirstQualifierInScope,
02632                                DeclarationName Name, SourceLocation NameLoc,
02633                                const TemplateArgumentListInfo *TemplateArgs) {
02634   Expr *Base = BaseArg.takeAs<Expr>();
02635 
02636   if (BaseType->isDependentType() ||
02637       (SS.isSet() && isDependentScopeSpecifier(SS)))
02638     return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
02639                                     IsArrow, OpLoc,
02640                                     SS, FirstQualifierInScope,
02641                                     Name, NameLoc,
02642                                     TemplateArgs);
02643 
02644   LookupResult R(*this, Name, NameLoc, LookupMemberName);
02645 
02646   // Implicit member accesses.
02647   if (!Base) {
02648     QualType RecordTy = BaseType;
02649     if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
02650     if (LookupMemberExprInRecord(*this, R, SourceRange(),
02651                                  RecordTy->getAs<RecordType>(),
02652                                  OpLoc, SS))
02653       return ExprError();
02654 
02655   // Explicit member accesses.
02656   } else {
02657     OwningExprResult Result =
02658       LookupMemberExpr(R, Base, IsArrow, OpLoc,
02659                        SS, /*ObjCImpDecl*/ DeclPtrTy());
02660 
02661     if (Result.isInvalid()) {
02662       Owned(Base);
02663       return ExprError();
02664     }
02665 
02666     if (Result.get())
02667       return move(Result);
02668   }
02669 
02670   return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
02671                                   OpLoc, IsArrow, SS, FirstQualifierInScope,
02672                                   R, TemplateArgs);
02673 }
02674 
02675 Sema::OwningExprResult
02676 Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
02677                                SourceLocation OpLoc, bool IsArrow,
02678                                const CXXScopeSpec &SS,
02679                                NamedDecl *FirstQualifierInScope,
02680                                LookupResult &R,
02681                          const TemplateArgumentListInfo *TemplateArgs,
02682                                bool SuppressQualifierCheck) {
02683   Expr *BaseExpr = Base.takeAs<Expr>();
02684   QualType BaseType = BaseExprType;
02685   if (IsArrow) {
02686     assert(BaseType->isPointerType());
02687     BaseType = BaseType->getAs<PointerType>()->getPointeeType();
02688   }
02689   R.setBaseObjectType(BaseType);
02690 
02691   NestedNameSpecifier *Qualifier =
02692     static_cast<NestedNameSpecifier*>(SS.getScopeRep());
02693   DeclarationName MemberName = R.getLookupName();
02694   SourceLocation MemberLoc = R.getNameLoc();
02695 
02696   if (R.isAmbiguous())
02697     return ExprError();
02698 
02699   if (R.empty()) {
02700     // Rederive where we looked up.
02701     DeclContext *DC = (SS.isSet()
02702                        ? computeDeclContext(SS, false)
02703                        : BaseType->getAs<RecordType>()->getDecl());
02704 
02705     Diag(R.getNameLoc(), diag::err_no_member)
02706       << MemberName << DC
02707       << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
02708     return ExprError();
02709   }
02710 
02711   // Diagnose lookups that find only declarations from a non-base
02712   // type.  This is possible for either qualified lookups (which may
02713   // have been qualified with an unrelated type) or implicit member
02714   // expressions (which were found with unqualified lookup and thus
02715   // may have come from an enclosing scope).  Note that it's okay for
02716   // lookup to find declarations from a non-base type as long as those
02717   // aren't the ones picked by overload resolution.
02718   if ((SS.isSet() || !BaseExpr ||
02719        (isa<CXXThisExpr>(BaseExpr) &&
02720         cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
02721       !SuppressQualifierCheck &&
02722       CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
02723     return ExprError();
02724 
02725   // Construct an unresolved result if we in fact got an unresolved
02726   // result.
02727   if (R.isOverloadedResult() || R.isUnresolvableResult()) {
02728     bool Dependent =
02729       BaseExprType->isDependentType() ||
02730       R.isUnresolvableResult() ||
02731       OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
02732 
02733     // Suppress any lookup-related diagnostics; we'll do these when we
02734     // pick a member.
02735     R.suppressDiagnostics();
02736 
02737     UnresolvedMemberExpr *MemExpr
02738       = UnresolvedMemberExpr::Create(Context, Dependent,
02739                                      R.isUnresolvableResult(),
02740                                      BaseExpr, BaseExprType,
02741                                      IsArrow, OpLoc,
02742                                      Qualifier, SS.getRange(),
02743                                      MemberName, MemberLoc,
02744                                      TemplateArgs);
02745     MemExpr->addDecls(R.begin(), R.end());
02746 
02747     return Owned(MemExpr);
02748   }
02749 
02750   assert(R.isSingleResult());
02751   DeclAccessPair FoundDecl = R.begin().getPair();
02752   NamedDecl *MemberDecl = R.getFoundDecl();
02753 
02754   // FIXME: diagnose the presence of template arguments now.
02755 
02756   // If the decl being referenced had an error, return an error for this
02757   // sub-expr without emitting another error, in order to avoid cascading
02758   // error cases.
02759   if (MemberDecl->isInvalidDecl())
02760     return ExprError();
02761 
02762   // Handle the implicit-member-access case.
02763   if (!BaseExpr) {
02764     // If this is not an instance member, convert to a non-member access.
02765     if (!MemberDecl->isCXXInstanceMember())
02766       return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
02767 
02768     SourceLocation Loc = R.getNameLoc();
02769     if (SS.getRange().isValid())
02770       Loc = SS.getRange().getBegin();
02771     BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
02772   }
02773 
02774   bool ShouldCheckUse = true;
02775   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
02776     // Don't diagnose the use of a virtual member function unless it's
02777     // explicitly qualified.
02778     if (MD->isVirtual() && !SS.isSet())
02779       ShouldCheckUse = false;
02780   }
02781 
02782   // Check the use of this member.
02783   if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
02784     Owned(BaseExpr);
02785     return ExprError();
02786   }
02787 
02788   if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
02789     // We may have found a field within an anonymous union or struct
02790     // (C++ [class.union]).
02791     if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
02792         !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
02793       return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
02794                                                       BaseExpr, OpLoc);
02795 
02796     // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
02797     QualType MemberType = FD->getType();
02798     if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
02799       MemberType = Ref->getPointeeType();
02800     else {
02801       Qualifiers BaseQuals = BaseType.getQualifiers();
02802       BaseQuals.removeObjCGCAttr();
02803       if (FD->isMutable()) BaseQuals.removeConst();
02804 
02805       Qualifiers MemberQuals
02806         = Context.getCanonicalType(MemberType).getQualifiers();
02807 
02808       Qualifiers Combined = BaseQuals + MemberQuals;
02809       if (Combined != MemberQuals)
02810         MemberType = Context.getQualifiedType(MemberType, Combined);
02811     }
02812 
02813     MarkDeclarationReferenced(MemberLoc, FD);
02814     if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
02815       return ExprError();
02816     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
02817                                  FD, FoundDecl, MemberLoc, MemberType));
02818   }
02819 
02820   if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
02821     MarkDeclarationReferenced(MemberLoc, Var);
02822     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
02823                                  Var, FoundDecl, MemberLoc,
02824                                  Var->getType().getNonReferenceType()));
02825   }
02826 
02827   if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
02828     MarkDeclarationReferenced(MemberLoc, MemberDecl);
02829     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
02830                                  MemberFn, FoundDecl, MemberLoc,
02831                                  MemberFn->getType()));
02832   }
02833 
02834   if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
02835     MarkDeclarationReferenced(MemberLoc, MemberDecl);
02836     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
02837                                  Enum, FoundDecl, MemberLoc, Enum->getType()));
02838   }
02839 
02840   Owned(BaseExpr);
02841 
02842   // We found something that we didn't expect. Complain.
02843   if (isa<TypeDecl>(MemberDecl))
02844     Diag(MemberLoc,diag::err_typecheck_member_reference_type)
02845       << MemberName << BaseType << int(IsArrow);
02846   else
02847     Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
02848       << MemberName << BaseType << int(IsArrow);
02849 
02850   Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
02851     << MemberName;
02852   R.suppressDiagnostics();
02853   return ExprError();
02854 }
02855 
02856 /// Look up the given member of the given non-type-dependent
02857 /// expression.  This can return in one of two ways:
02858 ///  * If it returns a sentinel null-but-valid result, the caller will
02859 ///    assume that lookup was performed and the results written into
02860 ///    the provided structure.  It will take over from there.
02861 ///  * Otherwise, the returned expression will be produced in place of
02862 ///    an ordinary member expression.
02863 ///
02864 /// The ObjCImpDecl bit is a gross hack that will need to be properly
02865 /// fixed for ObjC++.
02866 Sema::OwningExprResult
02867 Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
02868                        bool &IsArrow, SourceLocation OpLoc,
02869                        CXXScopeSpec &SS,
02870                        DeclPtrTy ObjCImpDecl) {
02871   assert(BaseExpr && "no base expression");
02872 
02873   // Perform default conversions.
02874   DefaultFunctionArrayConversion(BaseExpr);
02875 
02876   QualType BaseType = BaseExpr->getType();
02877   assert(!BaseType->isDependentType());
02878 
02879   DeclarationName MemberName = R.getLookupName();
02880   SourceLocation MemberLoc = R.getNameLoc();
02881 
02882   // If the user is trying to apply -> or . to a function pointer
02883   // type, it's probably because they forgot parentheses to call that
02884   // function. Suggest the addition of those parentheses, build the
02885   // call, and continue on.
02886   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
02887     if (const FunctionProtoType *Fun
02888           = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
02889       QualType ResultTy = Fun->getResultType();
02890       if (Fun->getNumArgs() == 0 &&
02891           ((!IsArrow && ResultTy->isRecordType()) ||
02892            (IsArrow && ResultTy->isPointerType() &&
02893             ResultTy->getAs<PointerType>()->getPointeeType()
02894                                                           ->isRecordType()))) {
02895         SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
02896         Diag(Loc, diag::err_member_reference_needs_call)
02897           << QualType(Fun, 0)
02898           << FixItHint::CreateInsertion(Loc, "()");
02899 
02900         OwningExprResult NewBase
02901           = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
02902                           MultiExprArg(*this, 0, 0), 0, Loc);
02903         if (NewBase.isInvalid())
02904           return ExprError();
02905 
02906         BaseExpr = NewBase.takeAs<Expr>();
02907         DefaultFunctionArrayConversion(BaseExpr);
02908         BaseType = BaseExpr->getType();
02909       }
02910     }
02911   }
02912 
02913   // If this is an Objective-C pseudo-builtin and a definition is provided then
02914   // use that.
02915   if (BaseType->isObjCIdType()) {
02916     if (IsArrow) {
02917       // Handle the following exceptional case PObj->isa.
02918       if (const ObjCObjectPointerType *OPT =
02919           BaseType->getAs<ObjCObjectPointerType>()) {
02920         if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
02921             MemberName.getAsIdentifierInfo()->isStr("isa"))
02922           return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
02923                                                  Context.getObjCClassType()));
02924       }
02925     }
02926     // We have an 'id' type. Rather than fall through, we check if this
02927     // is a reference to 'isa'.
02928     if (BaseType != Context.ObjCIdRedefinitionType) {
02929       BaseType = Context.ObjCIdRedefinitionType;
02930       ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
02931     }
02932   }
02933 
02934   // If this is an Objective-C pseudo-builtin and a definition is provided then
02935   // use that.
02936   if (Context.isObjCSelType(BaseType)) {
02937     // We have an 'SEL' type. Rather than fall through, we check if this
02938     // is a reference to 'sel_id'.
02939     if (BaseType != Context.ObjCSelRedefinitionType) {
02940       BaseType = Context.ObjCSelRedefinitionType;
02941       ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
02942     }
02943   }
02944 
02945   assert(!BaseType.isNull() && "no type for member expression");
02946 
02947   // Handle properties on ObjC 'Class' types.
02948   if (!IsArrow && BaseType->isObjCClassType()) {
02949     // Also must look for a getter name which uses property syntax.
02950     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
02951     Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
02952     if (ObjCMethodDecl *MD = getCurMethodDecl()) {
02953       ObjCInterfaceDecl *IFace = MD->getClassInterface();
02954       ObjCMethodDecl *Getter;
02955       // FIXME: need to also look locally in the implementation.
02956       if ((Getter = IFace->lookupClassMethod(Sel))) {
02957         // Check the use of this method.
02958         if (DiagnoseUseOfDecl(Getter, MemberLoc))
02959           return ExprError();
02960       }
02961       // If we found a getter then this may be a valid dot-reference, we
02962       // will look for the matching setter, in case it is needed.
02963       Selector SetterSel =
02964       SelectorTable::constructSetterName(PP.getIdentifierTable(),
02965                                          PP.getSelectorTable(), Member);
02966       ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
02967       if (!Setter) {
02968         // If this reference is in an @implementation, also check for 'private'
02969         // methods.
02970         Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
02971       }
02972       // Look through local category implementations associated with the class.
02973       if (!Setter)
02974         Setter = IFace->getCategoryClassMethod(SetterSel);
02975 
02976       if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
02977         return ExprError();
02978 
02979       if (Getter || Setter) {
02980         QualType PType;
02981 
02982         if (Getter)
02983           PType = Getter->getResultType();
02984         else
02985           // Get the expression type from Setter's incoming parameter.
02986           PType = (*(Setter->param_end() -1))->getType();
02987         // FIXME: we must check that the setter has property type.
02988         return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
02989                                                   PType,
02990                                                   Setter, MemberLoc, BaseExpr));
02991       }
02992       return ExprError(Diag(MemberLoc, diag::err_property_not_found)
02993                        << MemberName << BaseType);
02994     }
02995   }
02996 
02997   if (BaseType->isObjCClassType() &&
02998       BaseType != Context.ObjCClassRedefinitionType) {
02999     BaseType = Context.ObjCClassRedefinitionType;
03000     ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
03001   }
03002 
03003   if (IsArrow) {
03004     if (const PointerType *PT = BaseType->getAs<PointerType>())
03005       BaseType = PT->getPointeeType();
03006     else if (BaseType->isObjCObjectPointerType())
03007       ;
03008     else if (BaseType->isRecordType()) {
03009       // Recover from arrow accesses to records, e.g.:
03010       //   struct MyRecord foo;
03011       //   foo->bar
03012       // This is actually well-formed in C++ if MyRecord has an
03013       // overloaded operator->, but that should have been dealt with
03014       // by now.
03015       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
03016         << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
03017         << FixItHint::CreateReplacement(OpLoc, ".");
03018       IsArrow = false;
03019     } else {
03020       Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
03021         << BaseType << BaseExpr->getSourceRange();
03022       return ExprError();
03023     }
03024   } else {
03025     // Recover from dot accesses to pointers, e.g.:
03026     //   type *foo;
03027     //   foo.bar
03028     // This is actually well-formed in two cases:
03029     //   - 'type' is an Objective C type
03030     //   - 'bar' is a pseudo-destructor name which happens to refer to
03031     //     the appropriate pointer type
03032     if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
03033       const PointerType *PT = BaseType->getAs<PointerType>();
03034       if (PT && PT->getPointeeType()->isRecordType()) {
03035         Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
03036           << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
03037           << FixItHint::CreateReplacement(OpLoc, "->");
03038         BaseType = PT->getPointeeType();
03039         IsArrow = true;
03040       }
03041     }
03042   }
03043 
03044   // Handle field access to simple records.  This also handles access
03045   // to fields of the ObjC 'id' struct.
03046   if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
03047     if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
03048                                  RTy, OpLoc, SS))
03049       return ExprError();
03050     return Owned((Expr*) 0);
03051   }
03052 
03053   // Handle access to Objective-C instance variables, such as "Obj->ivar" and
03054   // (*Obj).ivar.
03055   if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
03056       (!IsArrow && BaseType->isObjCInterfaceType())) {
03057     const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
03058     const ObjCInterfaceType *IFaceT =
03059       OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
03060     if (IFaceT) {
03061       IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
03062 
03063       ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
03064       ObjCInterfaceDecl *ClassDeclared;
03065       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
03066 
03067       if (!IV) {
03068         // Attempt to correct for typos in ivar names.
03069         LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
03070                          LookupMemberName);
03071         if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
03072             (IV = Res.getAsSingle<ObjCIvarDecl>())) {
03073           Diag(R.getNameLoc(),
03074                diag::err_typecheck_member_reference_ivar_suggest)
03075             << IDecl->getDeclName() << MemberName << IV->getDeclName()
03076             << FixItHint::CreateReplacement(R.getNameLoc(),
03077                                             IV->getNameAsString());
03078           Diag(IV->getLocation(), diag::note_previous_decl)
03079             << IV->getDeclName();
03080         }
03081       }
03082 
03083       if (IV) {
03084         // If the decl being referenced had an error, return an error for this
03085         // sub-expr without emitting another error, in order to avoid cascading
03086         // error cases.
03087         if (IV->isInvalidDecl())
03088           return ExprError();
03089 
03090         // Check whether we can reference this field.
03091         if (DiagnoseUseOfDecl(IV, MemberLoc))
03092           return ExprError();
03093         if (IV->getAccessControl() != ObjCIvarDecl::Public &&
03094             IV->getAccessControl() != ObjCIvarDecl::Package) {
03095           ObjCInterfaceDecl *ClassOfMethodDecl = 0;
03096           if (ObjCMethodDecl *MD = getCurMethodDecl())
03097             ClassOfMethodDecl =  MD->getClassInterface();
03098           else if (ObjCImpDecl && getCurFunctionDecl()) {
03099             // Case of a c-function declared inside an objc implementation.
03100             // FIXME: For a c-style function nested inside an objc implementation
03101             // class, there is no implementation context available, so we pass
03102             // down the context as argument to this routine. Ideally, this context
03103             // need be passed down in the AST node and somehow calculated from the
03104             // AST for a function decl.
03105             Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
03106             if (ObjCImplementationDecl *IMPD =
03107                 dyn_cast<ObjCImplementationDecl>(ImplDecl))
03108               ClassOfMethodDecl = IMPD->getClassInterface();
03109             else if (ObjCCategoryImplDecl* CatImplClass =
03110                         dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
03111               ClassOfMethodDecl = CatImplClass->getClassInterface();
03112           }
03113 
03114           if (IV->getAccessControl() == ObjCIvarDecl::Private) {
03115             if (ClassDeclared != IDecl ||
03116                 ClassOfMethodDecl != ClassDeclared)
03117               Diag(MemberLoc, diag::error_private_ivar_access)
03118                 << IV->getDeclName();
03119           } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
03120             // @protected
03121             Diag(MemberLoc, diag::error_protected_ivar_access)
03122               << IV->getDeclName();
03123         }
03124 
03125         return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
03126                                                    MemberLoc, BaseExpr,
03127                                                    IsArrow));
03128       }
03129       return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
03130                          << IDecl->getDeclName() << MemberName
03131                          << BaseExpr->getSourceRange());
03132     }
03133   }
03134   // Handle properties on 'id' and qualified "id".
03135   if (!IsArrow && (BaseType->isObjCIdType() ||
03136                    BaseType->isObjCQualifiedIdType())) {
03137     const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
03138     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
03139 
03140     // Check protocols on qualified interfaces.
03141     Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
03142     if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
03143       if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
03144         // Check the use of this declaration
03145         if (DiagnoseUseOfDecl(PD, MemberLoc))
03146           return ExprError();
03147 
03148         return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
03149                                                        MemberLoc, BaseExpr));
03150       }
03151       if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
03152         // Check the use of this method.
03153         if (DiagnoseUseOfDecl(OMD, MemberLoc))
03154           return ExprError();
03155 
03156         return Owned(ObjCMessageExpr::Create(Context,
03157                                      OMD->getResultType().getNonReferenceType(),
03158                                              OpLoc, BaseExpr, Sel,
03159                                              OMD, NULL, 0, MemberLoc));
03160       }
03161     }
03162 
03163     return ExprError(Diag(MemberLoc, diag::err_property_not_found)
03164                        << MemberName << BaseType);
03165   }
03166 
03167   // Handle Objective-C property access, which is "Obj.property" where Obj is a
03168   // pointer to a (potentially qualified) interface type.
03169   if (!IsArrow)
03170     if (const ObjCObjectPointerType *OPT =
03171           BaseType->getAsObjCInterfacePointerType())
03172       return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
03173 
03174   // Handle the following exceptional case (*Obj).isa.
03175   if (!IsArrow &&
03176       BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
03177       MemberName.getAsIdentifierInfo()->isStr("isa"))
03178     return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
03179                                            Context.getObjCClassType()));
03180 
03181   // Handle 'field access' to vectors, such as 'V.xx'.
03182   if (BaseType->isExtVectorType()) {
03183     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
03184     QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
03185     if (ret.isNull())
03186       return ExprError();
03187     return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
03188                                                     MemberLoc));
03189   }
03190 
03191   Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
03192     << BaseType << BaseExpr->getSourceRange();
03193 
03194   return ExprError();
03195 }
03196 
03197 /// The main callback when the parser finds something like
03198 ///   expression . [nested-name-specifier] identifier
03199 ///   expression -> [nested-name-specifier] identifier
03200 /// where 'identifier' encompasses a fairly broad spectrum of
03201 /// possibilities, including destructor and operator references.
03202 ///
03203 /// \param OpKind either tok::arrow or tok::period
03204 /// \param HasTrailingLParen whether the next token is '(', which
03205 ///   is used to diagnose mis-uses of special members that can
03206 ///   only be called
03207 /// \param ObjCImpDecl the current ObjC @implementation decl;
03208 ///   this is an ugly hack around the fact that ObjC @implementations
03209 ///   aren't properly put in the context chain
03210 Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
03211                                                    SourceLocation OpLoc,
03212                                                    tok::TokenKind OpKind,
03213                                                    CXXScopeSpec &SS,
03214                                                    UnqualifiedId &Id,
03215                                                    DeclPtrTy ObjCImpDecl,
03216                                                    bool HasTrailingLParen) {
03217   if (SS.isSet() && SS.isInvalid())
03218     return ExprError();
03219 
03220   TemplateArgumentListInfo TemplateArgsBuffer;
03221 
03222   // Decompose the name into its component parts.
03223   DeclarationName Name;
03224   SourceLocation NameLoc;
03225   const TemplateArgumentListInfo *TemplateArgs;
03226   DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
03227                          Name, NameLoc, TemplateArgs);
03228 
03229   bool IsArrow = (OpKind == tok::arrow);
03230 
03231   NamedDecl *FirstQualifierInScope
03232     = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
03233                        static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
03234 
03235   // This is a postfix expression, so get rid of ParenListExprs.
03236   BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
03237 
03238   Expr *Base = BaseArg.takeAs<Expr>();
03239   OwningExprResult Result(*this);
03240   if (Base->getType()->isDependentType() || Name.isDependentName() ||
03241       isDependentScopeSpecifier(SS)) {
03242     Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
03243                                       IsArrow, OpLoc,
03244                                       SS, FirstQualifierInScope,
03245                                       Name, NameLoc,
03246                                       TemplateArgs);
03247   } else {
03248     LookupResult R(*this, Name, NameLoc, LookupMemberName);
03249     if (TemplateArgs) {
03250       // Re-use the lookup done for the template name.
03251       DecomposeTemplateName(R, Id);
03252 
03253       // Re-derive the naming class.
03254       if (SS.isSet()) {
03255         NestedNameSpecifier *Qualifier
03256         = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
03257         if (const Type *Ty = Qualifier->getAsType())
03258           if (CXXRecordDecl *NamingClass = Ty->getAsCXXRecordDecl())
03259             R.setNamingClass(NamingClass);
03260       } else {
03261         QualType BaseType = Base->getType();
03262         if (const PointerType *Ptr = BaseType->getAs<PointerType>())
03263           BaseType = Ptr->getPointeeType();
03264         if (CXXRecordDecl *NamingClass = BaseType->getAsCXXRecordDecl())
03265           R.setNamingClass(NamingClass);
03266       }
03267     } else {
03268       Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
03269                                 SS, ObjCImpDecl);
03270 
03271       if (Result.isInvalid()) {
03272         Owned(Base);
03273         return ExprError();
03274       }
03275 
03276       if (Result.get()) {
03277         // The only way a reference to a destructor can be used is to
03278         // immediately call it, which falls into this case.  If the
03279         // next token is not a '(', produce a diagnostic and build the
03280         // call now.
03281         if (!HasTrailingLParen &&
03282             Id.getKind() == UnqualifiedId::IK_DestructorName)
03283           return DiagnoseDtorReference(NameLoc, move(Result));
03284 
03285         return move(Result);
03286       }
03287     }
03288 
03289     Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
03290                                       OpLoc, IsArrow, SS, FirstQualifierInScope,
03291                                       R, TemplateArgs);
03292   }
03293 
03294   return move(Result);
03295 }
03296 
03297 Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
03298                                                     FunctionDecl *FD,
03299                                                     ParmVarDecl *Param) {
03300   if (Param->hasUnparsedDefaultArg()) {
03301     Diag (CallLoc,
03302           diag::err_use_of_default_argument_to_function_declared_later) <<
03303       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
03304     Diag(UnparsedDefaultArgLocs[Param],
03305           diag::note_default_argument_declared_here);
03306   } else {
03307     if (Param->hasUninstantiatedDefaultArg()) {
03308       Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
03309 
03310       // Instantiate the expression.
03311       MultiLevelTemplateArgumentList ArgList
03312         = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
03313 
03314       InstantiatingTemplate Inst(*this, CallLoc, Param,
03315                                  ArgList.getInnermost().getFlatArgumentList(),
03316                                  ArgList.getInnermost().flat_size());
03317 
03318       OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
03319       if (Result.isInvalid())
03320         return ExprError();
03321 
03322       // Check the expression as an initializer for the parameter.
03323       InitializedEntity Entity
03324         = InitializedEntity::InitializeParameter(Param);
03325       InitializationKind Kind
03326         = InitializationKind::CreateCopy(Param->getLocation(),
03327                /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
03328       Expr *ResultE = Result.takeAs<Expr>();
03329 
03330       InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
03331       Result = InitSeq.Perform(*this, Entity, Kind,
03332                                MultiExprArg(*this, (void**)&ResultE, 1));
03333       if (Result.isInvalid())
03334         return ExprError();
03335 
03336       // Build the default argument expression.
03337       return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
03338                                              Result.takeAs<Expr>()));
03339     }
03340 
03341     // If the default expression creates temporaries, we need to
03342     // push them to the current stack of expression temporaries so they'll
03343     // be properly destroyed.
03344     // FIXME: We should really be rebuilding the default argument with new
03345     // bound temporaries; see the comment in PR5810.
03346     for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
03347       ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
03348   }
03349 
03350   // We already type-checked the argument, so we know it works.
03351   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
03352 }
03353 
03354 /// ConvertArgumentsForCall - Converts the arguments specified in
03355 /// Args/NumArgs to the parameter types of the function FDecl with
03356 /// function prototype Proto. Call is the call expression itself, and
03357 /// Fn is the function expression. For a C++ member function, this
03358 /// routine does not attempt to convert the object argument. Returns
03359 /// true if the call is ill-formed.
03360 bool
03361 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
03362                               FunctionDecl *FDecl,
03363                               const FunctionProtoType *Proto,
03364                               Expr **Args, unsigned NumArgs,
03365                               SourceLocation RParenLoc) {
03366   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
03367   // assignment, to the types of the corresponding parameter, ...
03368   unsigned NumArgsInProto = Proto->getNumArgs();
03369   bool Invalid = false;
03370 
03371   // If too few arguments are available (and we don't have default
03372   // arguments for the remaining parameters), don't make the call.
03373   if (NumArgs < NumArgsInProto) {
03374     if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
03375       return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
03376         << Fn->getType()->isBlockPointerType()
03377         << NumArgsInProto << NumArgs << Fn->getSourceRange();
03378     Call->setNumArgs(Context, NumArgsInProto);
03379   }
03380 
03381   // If too many are passed and not variadic, error on the extras and drop
03382   // them.
03383   if (NumArgs > NumArgsInProto) {
03384     if (!Proto->isVariadic()) {
03385       Diag(Args[NumArgsInProto]->getLocStart(),
03386            diag::err_typecheck_call_too_many_args)
03387         << Fn->getType()->isBlockPointerType()
03388         << NumArgsInProto << NumArgs << Fn->getSourceRange()
03389         << SourceRange(Args[NumArgsInProto]->getLocStart(),
03390                        Args[NumArgs-1]->getLocEnd());
03391       // This deletes the extra arguments.
03392       Call->setNumArgs(Context, NumArgsInProto);
03393       return true;
03394     }
03395   }
03396   llvm::SmallVector<Expr *, 8> AllArgs;
03397   VariadicCallType CallType =
03398     Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
03399   if (Fn->getType()->isBlockPointerType())
03400     CallType = VariadicBlock; // Block
03401   else if (isa<MemberExpr>(Fn))
03402     CallType = VariadicMethod;
03403   Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
03404                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
03405   if (Invalid)
03406     return true;
03407   unsigned TotalNumArgs = AllArgs.size();
03408   for (unsigned i = 0; i < TotalNumArgs; ++i)
03409     Call->setArg(i, AllArgs[i]);
03410 
03411   return false;
03412 }
03413 
03414 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
03415                                   FunctionDecl *FDecl,
03416                                   const FunctionProtoType *Proto,
03417                                   unsigned FirstProtoArg,
03418                                   Expr **Args, unsigned NumArgs,
03419                                   llvm::SmallVector<Expr *, 8> &AllArgs,
03420                                   VariadicCallType CallType) {
03421   unsigned NumArgsInProto = Proto->getNumArgs();
03422   unsigned NumArgsToCheck = NumArgs;
03423   bool Invalid = false;
03424   if (NumArgs != NumArgsInProto)
03425     // Use default arguments for missing arguments
03426     NumArgsToCheck = NumArgsInProto;
03427   unsigned ArgIx = 0;
03428   // Continue to check argument types (even if we have too few/many args).
03429   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
03430     QualType ProtoArgType = Proto->getArgType(i);
03431 
03432     Expr *Arg;
03433     if (ArgIx < NumArgs) {
03434       Arg = Args[ArgIx++];
03435 
03436       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
03437                               ProtoArgType,
03438                               PDiag(diag::err_call_incomplete_argument)
03439                               << Arg->getSourceRange()))
03440         return true;
03441 
03442       // Pass the argument
03443       ParmVarDecl *Param = 0;
03444       if (FDecl && i < FDecl->getNumParams())
03445         Param = FDecl->getParamDecl(i);
03446 
03447 
03448       InitializedEntity Entity =
03449         Param? InitializedEntity::InitializeParameter(Param)
03450              : InitializedEntity::InitializeParameter(ProtoArgType);
03451       OwningExprResult ArgE = PerformCopyInitialization(Entity,
03452                                                         SourceLocation(),
03453                                                         Owned(Arg));
03454       if (ArgE.isInvalid())
03455         return true;
03456 
03457       Arg = ArgE.takeAs<Expr>();
03458     } else {
03459       ParmVarDecl *Param = FDecl->getParamDecl(i);
03460 
03461       OwningExprResult ArgExpr =
03462         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
03463       if (ArgExpr.isInvalid())
03464         return true;
03465 
03466       Arg = ArgExpr.takeAs<Expr>();
03467     }
03468     AllArgs.push_back(Arg);
03469   }
03470 
03471   // If this is a variadic call, handle args passed through "...".
03472   if (CallType != VariadicDoesNotApply) {
03473     // Promote the arguments (C99 6.5.2.2p7).
03474     for (unsigned i = ArgIx; i < NumArgs; i++) {
03475       Expr *Arg = Args[i];
03476       Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
03477       AllArgs.push_back(Arg);
03478     }
03479   }
03480   return Invalid;
03481 }
03482 
03483 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
03484 /// This provides the location of the left/right parens and a list of comma
03485 /// locations.
03486 Action::OwningExprResult
03487 Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
03488                     MultiExprArg args,
03489                     SourceLocation *CommaLocs, SourceLocation RParenLoc) {
03490   unsigned NumArgs = args.size();
03491 
03492   // Since this might be a postfix expression, get rid of ParenListExprs.
03493   fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
03494 
03495   Expr *Fn = fn.takeAs<Expr>();
03496   Expr **Args = reinterpret_cast<Expr**>(args.release());
03497   assert(Fn && "no function call expression");
03498 
03499   if (getLangOptions().CPlusPlus) {
03500     // If this is a pseudo-destructor expression, build the call immediately.
03501     if (isa<CXXPseudoDestructorExpr>(Fn)) {
03502       if (NumArgs > 0) {
03503         // Pseudo-destructor calls should not have any arguments.
03504         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
03505           << FixItHint::CreateRemoval(
03506                                     SourceRange(Args[0]->getLocStart(),
03507                                                 Args[NumArgs-1]->getLocEnd()));
03508 
03509         for (unsigned I = 0; I != NumArgs; ++I)
03510           Args[I]->Destroy(Context);
03511 
03512         NumArgs = 0;
03513       }
03514 
03515       return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
03516                                           RParenLoc));
03517     }
03518 
03519     // Determine whether this is a dependent call inside a C++ template,
03520     // in which case we won't do any semantic analysis now.
03521     // FIXME: Will need to cache the results of name lookup (including ADL) in
03522     // Fn.
03523     bool Dependent = false;
03524     if (Fn->isTypeDependent())
03525       Dependent = true;
03526     else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
03527       Dependent = true;
03528 
03529     if (Dependent)
03530       return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
03531                                           Context.DependentTy, RParenLoc));
03532 
03533     // Determine whether this is a call to an object (C++ [over.call.object]).
03534     if (Fn->getType()->isRecordType())
03535       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
03536                                                 CommaLocs, RParenLoc));
03537 
03538     Expr *NakedFn = Fn->IgnoreParens();
03539 
03540     // Determine whether this is a call to an unresolved member function.
03541     if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
03542       // If lookup was unresolved but not dependent (i.e. didn't find
03543       // an unresolved using declaration), it has to be an overloaded
03544       // function set, which means it must contain either multiple
03545       // declarations (all methods or method templates) or a single
03546       // method template.
03547       assert((MemE->getNumDecls() > 1) ||
03548              isa<FunctionTemplateDecl>(
03549                                  (*MemE->decls_begin())->getUnderlyingDecl()));
03550       (void)MemE;
03551 
03552       return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
03553                                        CommaLocs, RParenLoc);
03554     }
03555 
03556     // Determine whether this is a call to a member function.
03557     if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
03558       NamedDecl *MemDecl = MemExpr->getMemberDecl();
03559       if (isa<CXXMethodDecl>(MemDecl))
03560         return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
03561                                          CommaLocs, RParenLoc);
03562     }
03563 
03564     // Determine whether this is a call to a pointer-to-member function.
03565     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
03566       if (BO->getOpcode() == BinaryOperator::PtrMemD ||
03567           BO->getOpcode() == BinaryOperator::PtrMemI) {
03568         if (const FunctionProtoType *FPT
03569                                 = BO->getType()->getAs<FunctionProtoType>()) {
03570           QualType ResultTy = FPT->getResultType().getNonReferenceType();
03571 
03572           ExprOwningPtr<CXXMemberCallExpr>
03573             TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
03574                                                           NumArgs, ResultTy,
03575                                                           RParenLoc));
03576 
03577           if (CheckCallReturnType(FPT->getResultType(),
03578                                   BO->getRHS()->getSourceRange().getBegin(),
03579                                   TheCall.get(), 0))
03580             return ExprError();
03581 
03582           if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
03583                                       RParenLoc))
03584             return ExprError();
03585 
03586           return Owned(MaybeBindToTemporary(TheCall.release()).release());
03587         }
03588         return ExprError(Diag(Fn->getLocStart(),
03589                               diag::err_typecheck_call_not_function)
03590                               << Fn->getType() << Fn->getSourceRange());
03591       }
03592     }
03593   }
03594 
03595   // If we're directly calling a function, get the appropriate declaration.
03596   // Also, in C++, keep track of whether we should perform argument-dependent
03597   // lookup and whether there were any explicitly-specified template arguments.
03598 
03599   Expr *NakedFn = Fn->IgnoreParens();
03600   if (isa<UnresolvedLookupExpr>(NakedFn)) {
03601     UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
03602     return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
03603                                    CommaLocs, RParenLoc);
03604   }
03605 
03606   NamedDecl *NDecl = 0;
03607   if (isa<DeclRefExpr>(NakedFn))
03608     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
03609 
03610   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
03611 }
03612 
03613 /// BuildResolvedCallExpr - Build a call to a resolved expression,
03614 /// i.e. an expression not of \p OverloadTy.  The expression should
03615 /// unary-convert to an expression of function-pointer or
03616 /// block-pointer type.
03617 ///
03618 /// \param NDecl the declaration being called, if available
03619 Sema::OwningExprResult
03620 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
03621                             SourceLocation LParenLoc,
03622                             Expr **Args, unsigned NumArgs,
03623                             SourceLocation RParenLoc) {
03624   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
03625 
03626   // Promote the function operand.
03627   UsualUnaryConversions(Fn);
03628 
03629   // Make the call expr early, before semantic checks.  This guarantees cleanup
03630   // of arguments and function on error.
03631   ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
03632                                                                Args, NumArgs,
03633                                                                Context.BoolTy,
03634                                                                RParenLoc));
03635 
03636   const FunctionType *FuncT;
03637   if (!Fn->getType()->isBlockPointerType()) {
03638     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
03639     // have type pointer to function".
03640     const PointerType *PT = Fn->getType()->getAs<PointerType>();
03641     if (PT == 0)
03642       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
03643         << Fn->getType() << Fn->getSourceRange());
03644     FuncT = PT->getPointeeType()->getAs<FunctionType>();
03645   } else { // This is a block call.
03646     FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
03647                 getAs<FunctionType>();
03648   }
03649   if (FuncT == 0)
03650     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
03651       << Fn->getType() << Fn->getSourceRange());
03652 
03653   // Check for a valid return type
03654   if (CheckCallReturnType(FuncT->getResultType(),
03655                           Fn->getSourceRange().getBegin(), TheCall.get(),
03656                           FDecl))
03657     return ExprError();
03658 
03659   // We know the result type of the call, set it.
03660   TheCall->setType(FuncT->getResultType().getNonReferenceType());
03661 
03662   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
03663     if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
03664                                 RParenLoc))
03665       return ExprError();
03666   } else {
03667     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
03668 
03669     if (FDecl) {
03670       // Check if we have too few/too many template arguments, based
03671       // on our knowledge of the function definition.
03672       const FunctionDecl *Def = 0;
03673       if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
03674         const FunctionProtoType *Proto =
03675             Def->getType()->getAs<FunctionProtoType>();
03676         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
03677           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
03678             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
03679         }
03680       }
03681     }
03682 
03683     // Promote the arguments (C99 6.5.2.2p6).
03684     for (unsigned i = 0; i != NumArgs; i++) {
03685       Expr *Arg = Args[i];
03686       DefaultArgumentPromotion(Arg);
03687       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
03688                               Arg->getType(),
03689                               PDiag(diag::err_call_incomplete_argument)
03690                                 << Arg->getSourceRange()))
03691         return ExprError();
03692       TheCall->setArg(i, Arg);
03693     }
03694   }
03695 
03696   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
03697     if (!Method->isStatic())
03698       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
03699         << Fn->getSourceRange());
03700 
03701   // Check for sentinels
03702   if (NDecl)
03703     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
03704 
03705   // Do special checking on direct calls to functions.
03706   if (FDecl) {
03707     if (CheckFunctionCall(FDecl, TheCall.get()))
03708       return ExprError();
03709 
03710     if (unsigned BuiltinID = FDecl->getBuiltinID())
03711       return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
03712   } else if (NDecl) {
03713     if (CheckBlockCall(NDecl, TheCall.get()))
03714       return ExprError();
03715   }
03716 
03717   return MaybeBindToTemporary(TheCall.take());
03718 }
03719 
03720 Action::OwningExprResult
03721 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
03722                            SourceLocation RParenLoc, ExprArg InitExpr) {
03723   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
03724   // FIXME: put back this assert when initializers are worked out.
03725   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
03726 
03727   TypeSourceInfo *TInfo;
03728   QualType literalType = GetTypeFromParser(Ty, &TInfo);
03729   if (!TInfo)
03730     TInfo = Context.getTrivialTypeSourceInfo(literalType);
03731 
03732   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
03733 }
03734 
03735 Action::OwningExprResult
03736 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
03737                                SourceLocation RParenLoc, ExprArg InitExpr) {
03738   QualType literalType = TInfo->getType();
03739   Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
03740 
03741   if (literalType->isArrayType()) {
03742     if (literalType->isVariableArrayType())
03743       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
03744         << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
03745   } else if (!literalType->isDependentType() &&
03746              RequireCompleteType(LParenLoc, literalType,
03747                       PDiag(diag::err_typecheck_decl_incomplete_type)
03748                         << SourceRange(LParenLoc,
03749                                        literalExpr->getSourceRange().getEnd())))
03750     return ExprError();
03751 
03752   InitializedEntity Entity
03753     = InitializedEntity::InitializeTemporary(literalType);
03754   InitializationKind Kind
03755     = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
03756                                      /*IsCStyleCast=*/true);
03757   InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
03758   OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
03759                                    MultiExprArg(*this, (void**)&literalExpr, 1),
03760                                             &literalType);
03761   if (Result.isInvalid())
03762     return ExprError();
03763   InitExpr.release();
03764   literalExpr = static_cast<Expr*>(Result.get());
03765 
03766   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
03767   if (isFileScope) { // 6.5.2.5p3
03768     if (CheckForConstantInitializer(literalExpr, literalType))
03769       return ExprError();
03770   }
03771 
03772   Result.release();
03773 
03774   return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
03775                                                  literalExpr, isFileScope));
03776 }
03777 
03778 Action::OwningExprResult
03779 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
03780                     SourceLocation RBraceLoc) {
03781   unsigned NumInit = initlist.size();
03782   Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
03783 
03784   // Semantic analysis for initializers is done by ActOnDeclarator() and
03785   // CheckInitializer() - it requires knowledge of the object being intialized.
03786 
03787   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
03788                                                NumInit, RBraceLoc);
03789   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
03790   return Owned(E);
03791 }
03792 
03793 static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
03794                                             QualType SrcTy, QualType DestTy) {
03795   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
03796     return CastExpr::CK_NoOp;
03797 
03798   if (SrcTy->hasPointerRepresentation()) {
03799     if (DestTy->hasPointerRepresentation())
03800       return DestTy->isObjCObjectPointerType() ?
03801                 CastExpr::CK_AnyPointerToObjCPointerCast :
03802                 CastExpr::CK_BitCast;
03803     if (DestTy->isIntegerType())
03804       return CastExpr::CK_PointerToIntegral;
03805   }
03806 
03807   if (SrcTy->isIntegerType()) {
03808     if (DestTy->isIntegerType())
03809       return CastExpr::CK_IntegralCast;
03810     if (DestTy->hasPointerRepresentation())
03811       return CastExpr::CK_IntegralToPointer;
03812     if (DestTy->isRealFloatingType())
03813       return CastExpr::CK_IntegralToFloating;
03814   }
03815 
03816   if (SrcTy->isRealFloatingType()) {
03817     if (DestTy->isRealFloatingType())
03818       return CastExpr::CK_FloatingCast;
03819     if (DestTy->isIntegerType())
03820       return CastExpr::CK_FloatingToIntegral;
03821   }
03822 
03823   // FIXME: Assert here.
03824   // assert(false && "Unhandled cast combination!");
03825   return CastExpr::CK_Unknown;
03826 }
03827 
03828 /// CheckCastTypes - Check type constraints for casting between types.
03829 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
03830                           CastExpr::CastKind& Kind,
03831                           CXXBaseSpecifierArray &BasePath,
03832                           bool FunctionalStyle) {
03833   if (getLangOptions().CPlusPlus)
03834     return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath,
03835                               FunctionalStyle);
03836 
03837   DefaultFunctionArrayLvalueConversion(castExpr);
03838 
03839   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
03840   // type needs to be scalar.
03841   if (castType->isVoidType()) {
03842     // Cast to void allows any expr type.
03843     Kind = CastExpr::CK_ToVoid;
03844     return false;
03845   }
03846 
03847   if (!castType->isScalarType() && !castType->isVectorType()) {
03848     if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
03849         (castType->isStructureType() || castType->isUnionType())) {
03850       // GCC struct/union extension: allow cast to self.
03851       // FIXME: Check that the cast destination type is complete.
03852       Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
03853         << castType << castExpr->getSourceRange();
03854       Kind = CastExpr::CK_NoOp;
03855       return false;
03856     }
03857 
03858     if (castType->isUnionType()) {
03859       // GCC cast to union extension
03860       RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
03861       RecordDecl::field_iterator Field, FieldEnd;
03862       for (Field = RD->field_begin(), FieldEnd = RD->field_end();
03863            Field != FieldEnd; ++Field) {
03864         if (Context.hasSameUnqualifiedType(Field->getType(),
03865                                            castExpr->getType())) {
03866           Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
03867             << castExpr->getSourceRange();
03868           break;
03869         }
03870       }
03871       if (Field == FieldEnd)
03872         return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
03873           << castExpr->getType() << castExpr->getSourceRange();
03874       Kind = CastExpr::CK_ToUnion;
03875       return false;
03876     }
03877 
03878     // Reject any other conversions to non-scalar types.
03879     return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
03880       << castType << castExpr->getSourceRange();
03881   }
03882 
03883   if (!castExpr->getType()->isScalarType() &&
03884       !castExpr->getType()->isVectorType()) {
03885     return Diag(castExpr->getLocStart(),
03886                 diag::err_typecheck_expect_scalar_operand)
03887       << castExpr->getType() << castExpr->getSourceRange();
03888   }
03889 
03890   if (castType->isExtVectorType())
03891     return CheckExtVectorCast(TyR, castType, castExpr, Kind);
03892 
03893   if (castType->isVectorType())
03894     return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
03895   if (castExpr->getType()->isVectorType())
03896     return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
03897 
03898   if (isa<ObjCSelectorExpr>(castExpr))
03899     return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
03900 
03901   if (!castType->isArithmeticType()) {
03902     QualType castExprType = castExpr->getType();
03903     if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
03904       return Diag(castExpr->getLocStart(),
03905                   diag::err_cast_pointer_from_non_pointer_int)
03906         << castExprType << castExpr->getSourceRange();
03907   } else if (!castExpr->getType()->isArithmeticType()) {
03908     if (!castType->isIntegralType() && castType->isArithmeticType())
03909       return Diag(castExpr->getLocStart(),
03910                   diag::err_cast_pointer_to_non_pointer_int)
03911         << castType << castExpr->getSourceRange();
03912   }
03913 
03914   Kind = getScalarCastKind(Context, castExpr->getType(), castType);
03915   return false;
03916 }
03917 
03918 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
03919                            CastExpr::CastKind &Kind) {
03920   assert(VectorTy->isVectorType() && "Not a vector type!");
03921 
03922   if (Ty->isVectorType() || Ty->isIntegerType()) {
03923     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
03924       return Diag(R.getBegin(),
03925                   Ty->isVectorType() ?
03926                   diag::err_invalid_conversion_between_vectors :
03927                   diag::err_invalid_conversion_between_vector_and_integer)
03928         << VectorTy << Ty << R;
03929   } else
03930     return Diag(R.getBegin(),
03931                 diag::err_invalid_conversion_between_vector_and_scalar)
03932       << VectorTy << Ty << R;
03933 
03934   Kind = CastExpr::CK_BitCast;
03935   return false;
03936 }
03937 
03938 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
03939                               CastExpr::CastKind &Kind) {
03940   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
03941 
03942   QualType SrcTy = CastExpr->getType();
03943 
03944   // If SrcTy is a VectorType, the total size must match to explicitly cast to
03945   // an ExtVectorType.
03946   if (SrcTy->isVectorType()) {
03947     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
03948       return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
03949         << DestTy << SrcTy << R;
03950     Kind = CastExpr::CK_BitCast;
03951     return false;
03952   }
03953 
03954   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
03955   // conversion will take place first from scalar to elt type, and then
03956   // splat from elt type to vector.
03957   if (SrcTy->isPointerType())
03958     return Diag(R.getBegin(),
03959                 diag::err_invalid_conversion_between_vector_and_scalar)
03960       << DestTy << SrcTy << R;
03961 
03962   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
03963   ImpCastExprToType(CastExpr, DestElemTy,
03964                     getScalarCastKind(Context, SrcTy, DestElemTy));
03965 
03966   Kind = CastExpr::CK_VectorSplat;
03967   return false;
03968 }
03969 
03970 Action::OwningExprResult
03971 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
03972                     SourceLocation RParenLoc, ExprArg Op) {
03973   assert((Ty != 0) && (Op.get() != 0) &&
03974          "ActOnCastExpr(): missing type or expr");
03975 
03976   TypeSourceInfo *castTInfo;
03977   QualType castType = GetTypeFromParser(Ty, &castTInfo);
03978   if (!castTInfo)
03979     castTInfo = Context.getTrivialTypeSourceInfo(castType);
03980 
03981   // If the Expr being casted is a ParenListExpr, handle it specially.
03982   Expr *castExpr = (Expr *)Op.get();
03983   if (isa<ParenListExpr>(castExpr))
03984     return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
03985                                     castTInfo);
03986 
03987   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
03988 }
03989 
03990 Action::OwningExprResult
03991 Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
03992                           SourceLocation RParenLoc, ExprArg Op) {
03993   Expr *castExpr = static_cast<Expr*>(Op.get());
03994 
03995   CastExpr::CastKind Kind = CastExpr::CK_Unknown;
03996   CXXBaseSpecifierArray BasePath;
03997   if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
03998                      Kind, BasePath))
03999     return ExprError();
04000 
04001   Op.release();
04002   return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
04003                                             Kind, castExpr, BasePath, Ty,
04004                                             LParenLoc, RParenLoc));
04005 }
04006 
04007 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
04008 /// of comma binary operators.
04009 Action::OwningExprResult
04010 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
04011   Expr *expr = EA.takeAs<Expr>();
04012   ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
04013   if (!E)
04014     return Owned(expr);
04015 
04016   OwningExprResult Result(*this, E->getExpr(0));
04017 
04018   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
04019     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
04020                         Owned(E->getExpr(i)));
04021 
04022   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
04023 }
04024 
04025 Action::OwningExprResult
04026 Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
04027                                SourceLocation RParenLoc, ExprArg Op,
04028                                TypeSourceInfo *TInfo) {
04029   ParenListExpr *PE = (ParenListExpr *)Op.get();
04030   QualType Ty = TInfo->getType();
04031 
04032   // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
04033   // then handle it as such.
04034   if (getLangOptions().AltiVec && Ty->isVectorType()) {
04035     if (PE->getNumExprs() == 0) {
04036       Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
04037       return ExprError();
04038     }
04039 
04040     llvm::SmallVector<Expr *, 8> initExprs;
04041     for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
04042       initExprs.push_back(PE->getExpr(i));
04043 
04044     // FIXME: This means that pretty-printing the final AST will produce curly
04045     // braces instead of the original commas.
04046     Op.release();
04047     InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
04048                                                  &initExprs[0],
04049                                                  initExprs.size(), RParenLoc);
04050     E->setType(Ty);
04051     return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
04052   } else {
04053     // This is not an AltiVec-style cast, so turn the ParenListExpr into a
04054     // sequence of BinOp comma operators.
04055     Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
04056     return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
04057   }
04058 }
04059 
04060 Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
04061                                                   SourceLocation R,
04062                                                   MultiExprArg Val,
04063                                                   TypeTy *TypeOfCast) {
04064   unsigned nexprs = Val.size();
04065   Expr **exprs = reinterpret_cast<Expr**>(Val.release());
04066   assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
04067   Expr *expr;
04068   if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
04069     expr = new (Context) ParenExpr(L, R, exprs[0]);
04070   else
04071     expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
04072   return Owned(expr);
04073 }
04074 
04075 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
04076 /// In that case, lhs = cond.
04077 /// C99 6.5.15
04078 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
04079                                         SourceLocation QuestionLoc) {
04080   // C++ is sufficiently different to merit its own checker.
04081   if (getLangOptions().CPlusPlus)
04082     return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
04083 
04084   CheckSignCompare(LHS, RHS, QuestionLoc);
04085 
04086   UsualUnaryConversions(Cond);
04087   UsualUnaryConversions(LHS);
04088   UsualUnaryConversions(RHS);
04089   QualType CondTy = Cond->getType();
04090   QualType LHSTy = LHS->getType();
04091   QualType RHSTy = RHS->getType();
04092 
04093   // first, check the condition.
04094   if (!CondTy->isScalarType()) { // C99 6.5.15p2
04095     Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
04096       << CondTy;
04097     return QualType();
04098   }
04099 
04100   // Now check the two expressions.
04101   if (LHSTy->isVectorType() || RHSTy->isVectorType())
04102     return CheckVectorOperands(QuestionLoc, LHS, RHS);
04103 
04104   // If both operands have arithmetic type, do the usual arithmetic conversions
04105   // to find a common type: C99 6.5.15p3,5.
04106   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
04107     UsualArithmeticConversions(LHS, RHS);
04108     return LHS->getType();
04109   }
04110 
04111   // If both operands are the same structure or union type, the result is that
04112   // type.
04113   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
04114     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
04115       if (LHSRT->getDecl() == RHSRT->getDecl())
04116         // "If both the operands have structure or union type, the result has
04117         // that type."  This implies that CV qualifiers are dropped.
04118         return LHSTy.getUnqualifiedType();
04119     // FIXME: Type of conditional expression must be complete in C mode.
04120   }
04121 
04122   // C99 6.5.15p5: "If both operands have void type, the result has void type."
04123   // The following || allows only one side to be void (a GCC-ism).
04124   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
04125     if (!LHSTy->isVoidType())
04126       Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
04127         << RHS->getSourceRange();
04128     if (!RHSTy->isVoidType())
04129       Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
04130         << LHS->getSourceRange();
04131     ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
04132     ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
04133     return Context.VoidTy;
04134   }
04135   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
04136   // the type of the other operand."
04137   if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
04138       RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
04139     // promote the null to a pointer.
04140     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
04141     return LHSTy;
04142   }
04143   if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
04144       LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
04145     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
04146     return RHSTy;
04147   }
04148 
04149   // All objective-c pointer type analysis is done here.
04150   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
04151                                                         QuestionLoc);
04152   if (!compositeType.isNull())
04153     return compositeType;
04154 
04155 
04156   // Handle block pointer types.
04157   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
04158     if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
04159       if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
04160         QualType destType = Context.getPointerType(Context.VoidTy);
04161         ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
04162         ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
04163         return destType;
04164       }
04165       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
04166       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04167       return QualType();
04168     }
04169     // We have 2 block pointer types.
04170     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
04171       // Two identical block pointer types are always compatible.
04172       return LHSTy;
04173     }
04174     // The block pointer types aren't identical, continue checking.
04175     QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
04176     QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
04177 
04178     if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
04179                                     rhptee.getUnqualifiedType())) {
04180       Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
04181       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04182       // In this situation, we assume void* type. No especially good
04183       // reason, but this is what gcc does, and we do have to pick
04184       // to get a consistent AST.
04185       QualType incompatTy = Context.getPointerType(Context.VoidTy);
04186       ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
04187       ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
04188       return incompatTy;
04189     }
04190     // The block pointer types are compatible.
04191     ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
04192     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
04193     return LHSTy;
04194   }
04195 
04196   // Check constraints for C object pointers types (C99 6.5.15p3,6).
04197   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
04198     // get the "pointed to" types
04199     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
04200     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
04201 
04202     // ignore qualifiers on void (C99 6.5.15p3, clause 6)
04203     if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
04204       // Figure out necessary qualifiers (C99 6.5.15p6)
04205       QualType destPointee
04206         = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
04207       QualType destType = Context.getPointerType(destPointee);
04208       // Add qualifiers if necessary.
04209       ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
04210       // Promote to void*.
04211       ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
04212       return destType;
04213     }
04214     if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
04215       QualType destPointee
04216         = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
04217       QualType destType = Context.getPointerType(destPointee);
04218       // Add qualifiers if necessary.
04219       ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
04220       // Promote to void*.
04221       ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
04222       return destType;
04223     }
04224 
04225     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
04226       // Two identical pointer types are always compatible.
04227       return LHSTy;
04228     }
04229     if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
04230                                     rhptee.getUnqualifiedType())) {
04231       Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
04232         << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04233       // In this situation, we assume void* type. No especially good
04234       // reason, but this is what gcc does, and we do have to pick
04235       // to get a consistent AST.
04236       QualType incompatTy = Context.getPointerType(Context.VoidTy);
04237       ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
04238       ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
04239       return incompatTy;
04240     }
04241     // The pointer types are compatible.
04242     // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
04243     // differently qualified versions of compatible types, the result type is
04244     // a pointer to an appropriately qualified version of the *composite*
04245     // type.
04246     // FIXME: Need to calculate the composite type.
04247     // FIXME: Need to add qualifiers
04248     ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
04249     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
04250     return LHSTy;
04251   }
04252 
04253   // GCC compatibility: soften pointer/integer mismatch.
04254   if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
04255     Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
04256       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04257     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
04258     return RHSTy;
04259   }
04260   if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
04261     Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
04262       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04263     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
04264     return LHSTy;
04265   }
04266 
04267   // Otherwise, the operands are not compatible.
04268   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
04269     << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04270   return QualType();
04271 }
04272 
04273 /// FindCompositeObjCPointerType - Helper method to find composite type of
04274 /// two objective-c pointer types of the two input expressions.
04275 QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
04276                                         SourceLocation QuestionLoc) {
04277   QualType LHSTy = LHS->getType();
04278   QualType RHSTy = RHS->getType();
04279 
04280   // Handle things like Class and struct objc_class*.  Here we case the result
04281   // to the pseudo-builtin, because that will be implicitly cast back to the
04282   // redefinition type if an attempt is made to access its fields.
04283   if (LHSTy->isObjCClassType() &&
04284       (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
04285     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
04286     return LHSTy;
04287   }
04288   if (RHSTy->isObjCClassType() &&
04289       (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
04290     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
04291     return RHSTy;
04292   }
04293   // And the same for struct objc_object* / id
04294   if (LHSTy->isObjCIdType() &&
04295       (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
04296     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
04297     return LHSTy;
04298   }
04299   if (RHSTy->isObjCIdType() &&
04300       (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
04301     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
04302     return RHSTy;
04303   }
04304   // And the same for struct objc_selector* / SEL
04305   if (Context.isObjCSelType(LHSTy) &&
04306       (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
04307     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
04308     return LHSTy;
04309   }
04310   if (Context.isObjCSelType(RHSTy) &&
04311       (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
04312     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
04313     return RHSTy;
04314   }
04315   // Check constraints for Objective-C object pointers types.
04316   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
04317 
04318     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
04319       // Two identical object pointer types are always compatible.
04320       return LHSTy;
04321     }
04322     const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
04323     const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
04324     QualType compositeType = LHSTy;
04325 
04326     // If both operands are interfaces and either operand can be
04327     // assigned to the other, use that type as the composite
04328     // type. This allows
04329     //   xxx ? (A*) a : (B*) b
04330     // where B is a subclass of A.
04331     //
04332     // Additionally, as for assignment, if either type is 'id'
04333     // allow silent coercion. Finally, if the types are
04334     // incompatible then make sure to use 'id' as the composite
04335     // type so the result is acceptable for sending messages to.
04336 
04337     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
04338     // It could return the composite type.
04339     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
04340       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
04341     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
04342       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
04343     } else if ((LHSTy->isObjCQualifiedIdType() ||
04344                 RHSTy->isObjCQualifiedIdType()) &&
04345                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
04346       // Need to handle "id<xx>" explicitly.
04347       // GCC allows qualified id and any Objective-C type to devolve to
04348       // id. Currently localizing to here until clear this should be
04349       // part of ObjCQualifiedIdTypesAreCompatible.
04350       compositeType = Context.getObjCIdType();
04351     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
04352       compositeType = Context.getObjCIdType();
04353     } else if (!(compositeType =
04354                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
04355       ;
04356     else {
04357       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
04358       << LHSTy << RHSTy
04359       << LHS->getSourceRange() << RHS->getSourceRange();
04360       QualType incompatTy = Context.getObjCIdType();
04361       ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
04362       ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
04363       return incompatTy;
04364     }
04365     // The object pointer types are compatible.
04366     ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
04367     ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
04368     return compositeType;
04369   }
04370   // Check Objective-C object pointer types and 'void *'
04371   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
04372     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
04373     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
04374     QualType destPointee
04375     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
04376     QualType destType = Context.getPointerType(destPointee);
04377     // Add qualifiers if necessary.
04378     ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
04379     // Promote to void*.
04380     ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
04381     return destType;
04382   }
04383   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
04384     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
04385     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
04386     QualType destPointee
04387     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
04388     QualType destType = Context.getPointerType(destPointee);
04389     // Add qualifiers if necessary.
04390     ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
04391     // Promote to void*.
04392     ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
04393     return destType;
04394   }
04395   return QualType();
04396 }
04397 
04398 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
04399 /// in the case of a the GNU conditional expr extension.
04400 Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
04401                                                   SourceLocation ColonLoc,
04402                                                   ExprArg Cond, ExprArg LHS,
04403                                                   ExprArg RHS) {
04404   Expr *CondExpr = (Expr *) Cond.get();
04405   Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
04406 
04407   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
04408   // was the condition.
04409   bool isLHSNull = LHSExpr == 0;
04410   if (isLHSNull)
04411     LHSExpr = CondExpr;
04412 
04413   QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
04414                                              RHSExpr, QuestionLoc);
04415   if (result.isNull())
04416     return ExprError();
04417 
04418   Cond.release();
04419   LHS.release();
04420   RHS.release();
04421   return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
04422                                                  isLHSNull ? 0 : LHSExpr,
04423                                                  ColonLoc, RHSExpr, result));
04424 }
04425 
04426 // CheckPointerTypesForAssignment - This is a very tricky routine (despite
04427 // being closely modeled after the C99 spec:-). The odd characteristic of this
04428 // routine is it effectively iqnores the qualifiers on the top level pointee.
04429 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
04430 // FIXME: add a couple examples in this comment.
04431 Sema::AssignConvertType
04432 Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
04433   QualType lhptee, rhptee;
04434 
04435   if ((lhsType->isObjCClassType() &&
04436        (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
04437      (rhsType->isObjCClassType() &&
04438        (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
04439       return Compatible;
04440   }
04441 
04442   // get the "pointed to" type (ignoring qualifiers at the top level)
04443   lhptee = lhsType->getAs<PointerType>()->getPointeeType();
04444   rhptee = rhsType->getAs<PointerType>()->getPointeeType();
04445 
04446   // make sure we operate on the canonical type
04447   lhptee = Context.getCanonicalType(lhptee);
04448   rhptee = Context.getCanonicalType(rhptee);
04449 
04450   AssignConvertType ConvTy = Compatible;
04451 
04452   // C99 6.5.16.1p1: This following citation is common to constraints
04453   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
04454   // qualifiers of the type *pointed to* by the right;
04455   // FIXME: Handle ExtQualType
04456   if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
04457     ConvTy = CompatiblePointerDiscardsQualifiers;
04458 
04459   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
04460   // incomplete type and the other is a pointer to a qualified or unqualified
04461   // version of void...
04462   if (lhptee->isVoidType()) {
04463     if (rhptee->isIncompleteOrObjectType())
04464       return ConvTy;
04465 
04466     // As an extension, we allow cast to/from void* to function pointer.
04467     assert(rhptee->isFunctionType());
04468     return FunctionVoidPointer;
04469   }
04470 
04471   if (rhptee->isVoidType()) {
04472     if (lhptee->isIncompleteOrObjectType())
04473       return ConvTy;
04474 
04475     // As an extension, we allow cast to/from void* to function pointer.
04476     assert(lhptee->isFunctionType());
04477     return FunctionVoidPointer;
04478   }
04479   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
04480   // unqualified versions of compatible types, ...
04481   lhptee = lhptee.getUnqualifiedType();
04482   rhptee = rhptee.getUnqualifiedType();
04483   if (!Context.typesAreCompatible(lhptee, rhptee)) {
04484     // Check if the pointee types are compatible ignoring the sign.
04485     // We explicitly check for char so that we catch "char" vs
04486     // "unsigned char" on systems where "char" is unsigned.
04487     if (lhptee->isCharType())
04488       lhptee = Context.UnsignedCharTy;
04489     else if (lhptee->isSignedIntegerType())
04490       lhptee = Context.getCorrespondingUnsignedType(lhptee);
04491 
04492     if (rhptee->isCharType())
04493       rhptee = Context.UnsignedCharTy;
04494     else if (rhptee->isSignedIntegerType())
04495       rhptee = Context.getCorrespondingUnsignedType(rhptee);
04496 
04497     if (lhptee == rhptee) {
04498       // Types are compatible ignoring the sign. Qualifier incompatibility
04499       // takes priority over sign incompatibility because the sign
04500       // warning can be disabled.
04501       if (ConvTy != Compatible)
04502         return ConvTy;
04503       return IncompatiblePointerSign;
04504     }
04505 
04506     // If we are a multi-level pointer, it's possible that our issue is simply
04507     // one of qualification - e.g. char ** -> const char ** is not allowed. If
04508     // the eventual target type is the same and the pointers have the same
04509     // level of indirection, this must be the issue.
04510     if (lhptee->isPointerType() && rhptee->isPointerType()) {
04511       do {
04512         lhptee = lhptee->getAs<PointerType>()->getPointeeType();
04513         rhptee = rhptee->getAs<PointerType>()->getPointeeType();
04514 
04515         lhptee = Context.getCanonicalType(lhptee);
04516         rhptee = Context.getCanonicalType(rhptee);
04517       } while (lhptee->isPointerType() && rhptee->isPointerType());
04518 
04519       if (Context.hasSameUnqualifiedType(lhptee, rhptee))
04520         return IncompatibleNestedPointerQualifiers;
04521     }
04522 
04523     // General pointer incompatibility takes priority over qualifiers.
04524     return IncompatiblePointer;
04525   }
04526   return ConvTy;
04527 }
04528 
04529 /// CheckBlockPointerTypesForAssignment - This routine determines whether two
04530 /// block pointer types are compatible or whether a block and normal pointer
04531 /// are compatible. It is more restrict than comparing two function pointer
04532 // types.
04533 Sema::AssignConvertType
04534 Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
04535                                           QualType rhsType) {
04536   QualType lhptee, rhptee;
04537 
04538   // get the "pointed to" type (ignoring qualifiers at the top level)
04539   lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
04540   rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
04541 
04542   // make sure we operate on the canonical type
04543   lhptee = Context.getCanonicalType(lhptee);
04544   rhptee = Context.getCanonicalType(rhptee);
04545 
04546   AssignConvertType ConvTy = Compatible;
04547 
04548   // For blocks we enforce that qualifiers are identical.
04549   if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
04550     ConvTy = CompatiblePointerDiscardsQualifiers;
04551 
04552   if (!getLangOptions().CPlusPlus) {
04553     if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
04554       return IncompatibleBlockPointer;
04555   }
04556   else if (!Context.typesAreCompatible(lhptee, rhptee))
04557     return IncompatibleBlockPointer;
04558   return ConvTy;
04559 }
04560 
04561 /// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
04562 /// for assignment compatibility.
04563 Sema::AssignConvertType
04564 Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
04565   if (lhsType->isObjCBuiltinType()) {
04566     // Class is not compatible with ObjC object pointers.
04567     if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
04568         !rhsType->isObjCQualifiedClassType())
04569       return IncompatiblePointer;
04570     return Compatible;
04571   }
04572   if (rhsType->isObjCBuiltinType()) {
04573     // Class is not compatible with ObjC object pointers.
04574     if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
04575         !lhsType->isObjCQualifiedClassType())
04576       return IncompatiblePointer;
04577     return Compatible;
04578   }
04579   QualType lhptee =
04580   lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
04581   QualType rhptee =
04582   rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
04583   // make sure we operate on the canonical type
04584   lhptee = Context.getCanonicalType(lhptee);
04585   rhptee = Context.getCanonicalType(rhptee);
04586   if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
04587     return CompatiblePointerDiscardsQualifiers;
04588 
04589   if (Context.typesAreCompatible(lhsType, rhsType))
04590     return Compatible;
04591   if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
04592     return IncompatibleObjCQualifiedId;
04593   return IncompatiblePointer;
04594 }
04595 
04596 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
04597 /// has code to accommodate several GCC extensions when type checking
04598 /// pointers. Here are some objectionable examples that GCC considers warnings:
04599 ///
04600 ///  int a, *pint;
04601 ///  short *pshort;
04602 ///  struct foo *pfoo;
04603 ///
04604 ///  pint = pshort; // warning: assignment from incompatible pointer type
04605 ///  a = pint; // warning: assignment makes integer from pointer without a cast
04606 ///  pint = a; // warning: assignment makes pointer from integer without a cast
04607 ///  pint = pfoo; // warning: assignment from incompatible pointer type
04608 ///
04609 /// As a result, the code for dealing with pointers is more complex than the
04610 /// C99 spec dictates.
04611 ///
04612 Sema::AssignConvertType
04613 Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
04614   // Get canonical types.  We're not formatting these types, just comparing
04615   // them.
04616   lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
04617   rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
04618 
04619   if (lhsType == rhsType)
04620     return Compatible; // Common case: fast path an exact match.
04621 
04622   if ((lhsType->isObjCClassType() &&
04623        (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
04624      (rhsType->isObjCClassType() &&
04625        (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
04626       return Compatible;
04627   }
04628 
04629   // If the left-hand side is a reference type, then we are in a
04630   // (rare!) case where we've allowed the use of references in C,
04631   // e.g., as a parameter type in a built-in function. In this case,
04632   // just make sure that the type referenced is compatible with the
04633   // right-hand side type. The caller is responsible for adjusting
04634   // lhsType so that the resulting expression does not have reference
04635   // type.
04636   if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
04637     if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
04638       return Compatible;
04639     return Incompatible;
04640   }
04641   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
04642   // to the same ExtVector type.
04643   if (lhsType->isExtVectorType()) {
04644     if (rhsType->isExtVectorType())
04645       return lhsType == rhsType ? Compatible : Incompatible;
04646     if (!rhsType->isVectorType() && rhsType->isArithmeticType())
04647       return Compatible;
04648   }
04649 
04650   if (lhsType->isVectorType() || rhsType->isVectorType()) {
04651     // If we are allowing lax vector conversions, and LHS and RHS are both
04652     // vectors, the total size only needs to be the same. This is a bitcast;
04653     // no bits are changed but the result type is different.
04654     if (getLangOptions().LaxVectorConversions &&
04655         lhsType->isVectorType() && rhsType->isVectorType()) {
04656       if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
04657         return IncompatibleVectors;
04658     }
04659     return Incompatible;
04660   }
04661 
04662   if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
04663     return Compatible;
04664 
04665   if (isa<PointerType>(lhsType)) {
04666     if (rhsType->isIntegerType())
04667       return IntToPointer;
04668 
04669     if (isa<PointerType>(rhsType))
04670       return CheckPointerTypesForAssignment(lhsType, rhsType);
04671 
04672     // In general, C pointers are not compatible with ObjC object pointers.
04673     if (isa<ObjCObjectPointerType>(rhsType)) {
04674       if (lhsType->isVoidPointerType()) // an exception to the rule.
04675         return Compatible;
04676       return IncompatiblePointer;
04677     }
04678     if (rhsType->getAs<BlockPointerType>()) {
04679       if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
04680         return Compatible;
04681 
04682       // Treat block pointers as objects.
04683       if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
04684         return Compatible;
04685     }
04686     return Incompatible;
04687   }
04688 
04689   if (isa<BlockPointerType>(lhsType)) {
04690     if (rhsType->isIntegerType())
04691       return IntToBlockPointer;
04692 
04693     // Treat block pointers as objects.
04694     if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
04695       return Compatible;
04696 
04697     if (rhsType->isBlockPointerType())
04698       return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
04699 
04700     if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
04701       if (RHSPT->getPointeeType()->isVoidType())
04702         return Compatible;
04703     }
04704     return Incompatible;
04705   }
04706 
04707   if (isa<ObjCObjectPointerType>(lhsType)) {
04708     if (rhsType->isIntegerType())
04709       return IntToPointer;
04710 
04711     // In general, C pointers are not compatible with ObjC object pointers.
04712     if (isa<PointerType>(rhsType)) {
04713       if (rhsType->isVoidPointerType()) // an exception to the rule.
04714         return Compatible;
04715       return IncompatiblePointer;
04716     }
04717     if (rhsType->isObjCObjectPointerType()) {
04718       return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
04719     }
04720     if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
04721       if (RHSPT->getPointeeType()->isVoidType())
04722         return Compatible;
04723     }
04724     // Treat block pointers as objects.
04725     if (rhsType->isBlockPointerType())
04726       return Compatible;
04727     return Incompatible;
04728   }
04729   if (isa<PointerType>(rhsType)) {
04730     // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
04731     if (lhsType == Context.BoolTy)
04732       return Compatible;
04733 
04734     if (lhsType->isIntegerType())
04735       return PointerToInt;
04736 
04737     if (isa<PointerType>(lhsType))
04738       return CheckPointerTypesForAssignment(lhsType, rhsType);
04739 
04740     if (isa<BlockPointerType>(lhsType) &&
04741         rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
04742       return Compatible;
04743     return Incompatible;
04744   }
04745   if (isa<ObjCObjectPointerType>(rhsType)) {
04746     // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
04747     if (lhsType == Context.BoolTy)
04748       return Compatible;
04749 
04750     if (lhsType->isIntegerType())
04751       return PointerToInt;
04752 
04753     // In general, C pointers are not compatible with ObjC object pointers.
04754     if (isa<PointerType>(lhsType)) {
04755       if (lhsType->isVoidPointerType()) // an exception to the rule.
04756         return Compatible;
04757       return IncompatiblePointer;
04758     }
04759     if (isa<BlockPointerType>(lhsType) &&
04760         rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
04761       return Compatible;
04762     return Incompatible;
04763   }
04764 
04765   if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
04766     if (Context.typesAreCompatible(lhsType, rhsType))
04767       return Compatible;
04768   }
04769   return Incompatible;
04770 }
04771 
04772 /// \brief Constructs a transparent union from an expression that is
04773 /// used to initialize the transparent union.
04774 static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
04775                                       QualType UnionType, FieldDecl *Field) {
04776   // Build an initializer list that designates the appropriate member
04777   // of the transparent union.
04778   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
04779                                                    &E, 1,
04780                                                    SourceLocation());
04781   Initializer->setType(UnionType);
04782   Initializer->setInitializedFieldInUnion(Field);
04783 
04784   // Build a compound literal constructing a value of the transparent
04785   // union type from this initializer list.
04786   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
04787   E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
04788                                   Initializer, false);
04789 }
04790 
04791 Sema::AssignConvertType
04792 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
04793   QualType FromType = rExpr->getType();
04794 
04795   // If the ArgType is a Union type, we want to handle a potential
04796   // transparent_union GCC extension.
04797   const RecordType *UT = ArgType->getAsUnionType();
04798   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
04799     return Incompatible;
04800 
04801   // The field to initialize within the transparent union.
04802   RecordDecl *UD = UT->getDecl();
04803   FieldDecl *InitField = 0;
04804   // It's compatible if the expression matches any of the fields.
04805   for (RecordDecl::field_iterator it = UD->field_begin(),
04806          itend = UD->field_end();
04807        it != itend; ++it) {
04808     if (it->getType()->isPointerType()) {
04809       // If the transparent union contains a pointer type, we allow:
04810       // 1) void pointer
04811       // 2) null pointer constant
04812       if (FromType->isPointerType())
04813         if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
04814           ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
04815           InitField = *it;
04816           break;
04817         }
04818 
04819       if (rExpr->isNullPointerConstant(Context,
04820                                        Expr::NPC_ValueDependentIsNull)) {
04821         ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
04822         InitField = *it;
04823         break;
04824       }
04825     }
04826 
04827     if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
04828           == Compatible) {
04829       InitField = *it;
04830       break;
04831     }
04832   }
04833 
04834   if (!InitField)
04835     return Incompatible;
04836 
04837   ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
04838   return Compatible;
04839 }
04840 
04841 Sema::AssignConvertType
04842 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
04843   if (getLangOptions().CPlusPlus) {
04844     if (!lhsType->isRecordType()) {
04845       // C++ 5.17p3: If the left operand is not of class type, the
04846       // expression is implicitly converted (C++ 4) to the
04847       // cv-unqualified type of the left operand.
04848       if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
04849                                     AA_Assigning))
04850         return Incompatible;
04851       return Compatible;
04852     }
04853 
04854     // FIXME: Currently, we fall through and treat C++ classes like C
04855     // structures.
04856   }
04857 
04858   // C99 6.5.16.1p1: the left operand is a pointer and the right is
04859   // a null pointer constant.
04860   if ((lhsType->isPointerType() ||
04861        lhsType->isObjCObjectPointerType() ||
04862        lhsType->isBlockPointerType())
04863       && rExpr->isNullPointerConstant(Context,
04864                                       Expr::NPC_ValueDependentIsNull)) {
04865     ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
04866     return Compatible;
04867   }
04868 
04869   // This check seems unnatural, however it is necessary to ensure the proper
04870   // conversion of functions/arrays. If the conversion were done for all
04871   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
04872   // expressions that surpress this implicit conversion (&, sizeof).
04873   //
04874   // Suppress this for references: C++ 8.5.3p5.
04875   if (!lhsType->isReferenceType())
04876     DefaultFunctionArrayLvalueConversion(rExpr);
04877 
04878   Sema::AssignConvertType result =
04879     CheckAssignmentConstraints(lhsType, rExpr->getType());
04880 
04881   // C99 6.5.16.1p2: The value of the right operand is converted to the
04882   // type of the assignment expression.
04883   // CheckAssignmentConstraints allows the left-hand side to be a reference,
04884   // so that we can use references in built-in functions even in C.
04885   // The getNonReferenceType() call makes sure that the resulting expression
04886   // does not have reference type.
04887   if (result != Incompatible && rExpr->getType() != lhsType)
04888     ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
04889                       CastExpr::CK_Unknown);
04890   return result;
04891 }
04892 
04893 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
04894   Diag(Loc, diag::err_typecheck_invalid_operands)
04895     << lex->getType() << rex->getType()
04896     << lex->getSourceRange() << rex->getSourceRange();
04897   return QualType();
04898 }
04899 
04900 QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
04901   // For conversion purposes, we ignore any qualifiers.
04902   // For example, "const float" and "float" are equivalent.
04903   QualType lhsType =
04904     Context.getCanonicalType(lex->getType()).getUnqualifiedType();
04905   QualType rhsType =
04906     Context.getCanonicalType(rex->getType()).getUnqualifiedType();
04907 
04908   // If the vector types are identical, return.
04909   if (lhsType == rhsType)
04910     return lhsType;
04911 
04912   // Handle the case of a vector & extvector type of the same size and element
04913   // type.  It would be nice if we only had one vector type someday.
04914   if (getLangOptions().LaxVectorConversions) {
04915     // FIXME: Should we warn here?
04916     if (const VectorType *LV = lhsType->getAs<VectorType>()) {
04917       if (const VectorType *RV = rhsType->getAs<VectorType>())
04918         if (LV->getElementType() == RV->getElementType() &&
04919             LV->getNumElements() == RV->getNumElements()) {
04920           return lhsType->isExtVectorType() ? lhsType : rhsType;
04921         }
04922     }
04923   }
04924 
04925   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
04926   // swap back (so that we don't reverse the inputs to a subtract, for instance.
04927   bool swapped = false;
04928   if (rhsType->isExtVectorType()) {
04929     swapped = true;
04930     std::swap(rex, lex);
04931     std::swap(rhsType, lhsType);
04932   }
04933 
04934   // Handle the case of an ext vector and scalar.
04935   if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
04936     QualType EltTy = LV->getElementType();
04937     if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
04938       if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
04939         ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
04940         if (swapped) std::swap(rex, lex);
04941         return lhsType;
04942       }
04943     }
04944     if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
04945         rhsType->isRealFloatingType()) {
04946       if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
04947         ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
04948         if (swapped) std::swap(rex, lex);
04949         return lhsType;
04950       }
04951     }
04952   }
04953 
04954   // Vectors of different size or scalar and non-ext-vector are errors.
04955   Diag(Loc, diag::err_typecheck_vector_not_convertable)
04956     << lex->getType() << rex->getType()
04957     << lex->getSourceRange() << rex->getSourceRange();
04958   return QualType();
04959 }
04960 
04961 QualType Sema::CheckMultiplyDivideOperands(
04962   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
04963   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
04964     return CheckVectorOperands(Loc, lex, rex);
04965 
04966   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
04967 
04968   if (!lex->getType()->isArithmeticType() ||
04969       !rex->getType()->isArithmeticType())
04970     return InvalidOperands(Loc, lex, rex);
04971 
04972   // Check for division by zero.
04973   if (isDiv &&
04974       rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
04975     DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
04976                                      << rex->getSourceRange());
04977 
04978   return compType;
04979 }
04980 
04981 QualType Sema::CheckRemainderOperands(
04982   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
04983   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
04984     if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
04985       return CheckVectorOperands(Loc, lex, rex);
04986     return InvalidOperands(Loc, lex, rex);
04987   }
04988 
04989   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
04990 
04991   if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
04992     return InvalidOperands(Loc, lex, rex);
04993 
04994   // Check for remainder by zero.
04995   if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
04996     DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
04997                                  << rex->getSourceRange());
04998 
04999   return compType;
05000 }
05001 
05002 QualType Sema::CheckAdditionOperands( // C99 6.5.6
05003   Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
05004   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
05005     QualType compType = CheckVectorOperands(Loc, lex, rex);
05006     if (CompLHSTy) *CompLHSTy = compType;
05007     return compType;
05008   }
05009 
05010   QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
05011 
05012   // handle the common case first (both operands are arithmetic).
05013   if (lex->getType()->isArithmeticType() &&
05014       rex->getType()->isArithmeticType()) {
05015     if (CompLHSTy) *CompLHSTy = compType;
05016     return compType;
05017   }
05018 
05019   // Put any potential pointer into PExp
05020   Expr* PExp = lex, *IExp = rex;
05021   if (IExp->getType()->isAnyPointerType())
05022     std::swap(PExp, IExp);
05023 
05024   if (PExp->getType()->isAnyPointerType()) {
05025 
05026     if (IExp->getType()->isIntegerType()) {
05027       QualType PointeeTy = PExp->getType()->getPointeeType();
05028 
05029       // Check for arithmetic on pointers to incomplete types.
05030       if (PointeeTy->isVoidType()) {
05031         if (getLangOptions().CPlusPlus) {
05032           Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
05033             << lex->getSourceRange() << rex->getSourceRange();
05034           return QualType();
05035         }
05036 
05037         // GNU extension: arithmetic on pointer to void
05038         Diag(Loc, diag::ext_gnu_void_ptr)
05039           << lex->getSourceRange() << rex->getSourceRange();
05040       } else if (PointeeTy->isFunctionType()) {
05041         if (getLangOptions().CPlusPlus) {
05042           Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
05043             << lex->getType() << lex->getSourceRange();
05044           return QualType();
05045         }
05046 
05047         // GNU extension: arithmetic on pointer to function
05048         Diag(Loc, diag::ext_gnu_ptr_func_arith)
05049           << lex->getType() << lex->getSourceRange();
05050       } else {
05051         // Check if we require a complete type.
05052         if (((PExp->getType()->isPointerType() &&
05053               !PExp->getType()->isDependentType()) ||
05054               PExp->getType()->isObjCObjectPointerType()) &&
05055              RequireCompleteType(Loc, PointeeTy,
05056                            PDiag(diag::err_typecheck_arithmetic_incomplete_type)
05057                              << PExp->getSourceRange()
05058                              << PExp->getType()))
05059           return QualType();
05060       }
05061       // Diagnose bad cases where we step over interface counts.
05062       if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
05063         Diag(Loc, diag::err_arithmetic_nonfragile_interface)
05064           << PointeeTy << PExp->getSourceRange();
05065         return QualType();
05066       }
05067 
05068       if (CompLHSTy) {
05069         QualType LHSTy = Context.isPromotableBitField(lex);
05070         if (LHSTy.isNull()) {
05071           LHSTy = lex->getType();
05072           if (LHSTy->isPromotableIntegerType())
05073             LHSTy = Context.getPromotedIntegerType(LHSTy);
05074         }
05075         *CompLHSTy = LHSTy;
05076       }
05077       return PExp->getType();
05078     }
05079   }
05080 
05081   return InvalidOperands(Loc, lex, rex);
05082 }
05083 
05084 // C99 6.5.6
05085 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
05086                                         SourceLocation Loc, QualType* CompLHSTy) {
05087   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
05088     QualType compType = CheckVectorOperands(Loc, lex, rex);
05089     if (CompLHSTy) *CompLHSTy = compType;
05090     return compType;
05091   }
05092 
05093   QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
05094 
05095   // Enforce type constraints: C99 6.5.6p3.
05096 
05097   // Handle the common case first (both operands are arithmetic).
05098   if (lex->getType()->isArithmeticType()
05099       && rex->getType()->isArithmeticType()) {
05100     if (CompLHSTy) *CompLHSTy = compType;
05101     return compType;
05102   }
05103 
05104   // Either ptr - int   or   ptr - ptr.
05105   if (lex->getType()->isAnyPointerType()) {
05106     QualType lpointee = lex->getType()->getPointeeType();
05107 
05108     // The LHS must be an completely-defined object type.
05109 
05110     bool ComplainAboutVoid = false;
05111     Expr *ComplainAboutFunc = 0;
05112     if (lpointee->isVoidType()) {
05113       if (getLangOptions().CPlusPlus) {
05114         Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
05115           << lex->getSourceRange() << rex->getSourceRange();
05116         return QualType();
05117       }
05118 
05119       // GNU C extension: arithmetic on pointer to void
05120       ComplainAboutVoid = true;
05121     } else if (lpointee->isFunctionType()) {
05122       if (getLangOptions().CPlusPlus) {
05123         Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
05124           << lex->getType() << lex->getSourceRange();
05125         return QualType();
05126       }
05127 
05128       // GNU C extension: arithmetic on pointer to function
05129       ComplainAboutFunc = lex;
05130     } else if (!lpointee->isDependentType() &&
05131                RequireCompleteType(Loc, lpointee,
05132                                    PDiag(diag::err_typecheck_sub_ptr_object)
05133                                      << lex->getSourceRange()
05134                                      << lex->getType()))
05135       return QualType();
05136 
05137     // Diagnose bad cases where we step over interface counts.
05138     if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
05139       Diag(Loc, diag::err_arithmetic_nonfragile_interface)
05140         << lpointee << lex->getSourceRange();
05141       return QualType();
05142     }
05143 
05144     // The result type of a pointer-int computation is the pointer type.
05145     if (rex->getType()->isIntegerType()) {
05146       if (ComplainAboutVoid)
05147         Diag(Loc, diag::ext_gnu_void_ptr)
05148           << lex->getSourceRange() << rex->getSourceRange();
05149       if (ComplainAboutFunc)
05150         Diag(Loc, diag::ext_gnu_ptr_func_arith)
05151           << ComplainAboutFunc->getType()
05152           << ComplainAboutFunc->getSourceRange();
05153 
05154       if (CompLHSTy) *CompLHSTy = lex->getType();
05155       return lex->getType();
05156     }
05157 
05158     // Handle pointer-pointer subtractions.
05159     if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
05160       QualType rpointee = RHSPTy->getPointeeType();
05161 
05162       // RHS must be a completely-type object type.
05163       // Handle the GNU void* extension.
05164       if (rpointee->isVoidType()) {
05165         if (getLangOptions().CPlusPlus) {
05166           Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
05167             << lex->getSourceRange() << rex->getSourceRange();
05168           return QualType();
05169         }
05170 
05171         ComplainAboutVoid = true;
05172       } else if (rpointee->isFunctionType()) {
05173         if (getLangOptions().CPlusPlus) {
05174           Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
05175             << rex->getType() << rex->getSourceRange();
05176           return QualType();
05177         }
05178 
05179         // GNU extension: arithmetic on pointer to function
05180         if (!ComplainAboutFunc)
05181           ComplainAboutFunc = rex;
05182       } else if (!rpointee->isDependentType() &&
05183                  RequireCompleteType(Loc, rpointee,
05184                                      PDiag(diag::err_typecheck_sub_ptr_object)
05185                                        << rex->getSourceRange()
05186                                        << rex->getType()))
05187         return QualType();
05188 
05189       if (getLangOptions().CPlusPlus) {
05190         // Pointee types must be the same: C++ [expr.add]
05191         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
05192           Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
05193             << lex->getType() << rex->getType()
05194             << lex->getSourceRange() << rex->getSourceRange();
05195           return QualType();
05196         }
05197       } else {
05198         // Pointee types must be compatible C99 6.5.6p3
05199         if (!Context.typesAreCompatible(
05200                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
05201                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
05202           Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
05203             << lex->getType() << rex->getType()
05204             << lex->getSourceRange() << rex->getSourceRange();
05205           return QualType();
05206         }
05207       }
05208 
05209       if (ComplainAboutVoid)
05210         Diag(Loc, diag::ext_gnu_void_ptr)
05211           << lex->getSourceRange() << rex->getSourceRange();
05212       if (ComplainAboutFunc)
05213         Diag(Loc, diag::ext_gnu_ptr_func_arith)
05214           << ComplainAboutFunc->getType()
05215           << ComplainAboutFunc->getSourceRange();
05216 
05217       if (CompLHSTy) *CompLHSTy = lex->getType();
05218       return Context.getPointerDiffType();
05219     }
05220   }
05221 
05222   return InvalidOperands(Loc, lex, rex);
05223 }
05224 
05225 // C99 6.5.7
05226 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
05227                                   bool isCompAssign) {
05228   // C99 6.5.7p2: Each of the operands shall have integer type.
05229   if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
05230     return InvalidOperands(Loc, lex, rex);
05231 
05232   // Vector shifts promote their scalar inputs to vector type.
05233   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
05234     return CheckVectorOperands(Loc, lex, rex);
05235 
05236   // Shifts don't perform usual arithmetic conversions, they just do integer
05237   // promotions on each operand. C99 6.5.7p3
05238   QualType LHSTy = Context.isPromotableBitField(lex);
05239   if (LHSTy.isNull()) {
05240     LHSTy = lex->getType();
05241     if (LHSTy->isPromotableIntegerType())
05242       LHSTy = Context.getPromotedIntegerType(LHSTy);
05243   }
05244   if (!isCompAssign)
05245     ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
05246 
05247   UsualUnaryConversions(rex);
05248 
05249   // Sanity-check shift operands
05250   llvm::APSInt Right;
05251   // Check right/shifter operand
05252   if (!rex->isValueDependent() &&
05253       rex->isIntegerConstantExpr(Right, Context)) {
05254     if (Right.isNegative())
05255       Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
05256     else {
05257       llvm::APInt LeftBits(Right.getBitWidth(),
05258                           Context.getTypeSize(lex->getType()));
05259       if (Right.uge(LeftBits))
05260         Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
05261     }
05262   }
05263 
05264   // "The type of the result is that of the promoted left operand."
05265   return LHSTy;
05266 }
05267 
05268 // C99 6.5.8, C++ [expr.rel]
05269 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
05270                                     unsigned OpaqueOpc, bool isRelational) {
05271   BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
05272 
05273   // Handle vector comparisons separately.
05274   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
05275     return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
05276 
05277   CheckSignCompare(lex, rex, Loc, &Opc);
05278 
05279   // C99 6.5.8p3 / C99 6.5.9p4
05280   if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
05281     UsualArithmeticConversions(lex, rex);
05282   else {
05283     UsualUnaryConversions(lex);
05284     UsualUnaryConversions(rex);
05285   }
05286   QualType lType = lex->getType();
05287   QualType rType = rex->getType();
05288 
05289   if (!lType->isFloatingType()
05290       && !(lType->isBlockPointerType() && isRelational)) {
05291     // For non-floating point types, check for self-comparisons of the form
05292     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
05293     // often indicate logic errors in the program.
05294     // NOTE: Don't warn about comparisons of enum constants. These can arise
05295     //  from macro expansions, and are usually quite deliberate.
05296     Expr *LHSStripped = lex->IgnoreParens();
05297     Expr *RHSStripped = rex->IgnoreParens();
05298     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
05299       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
05300         if (DRL->getDecl() == DRR->getDecl() &&
05301             !isa<EnumConstantDecl>(DRL->getDecl()))
05302           DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
05303 
05304     if (isa<CastExpr>(LHSStripped))
05305       LHSStripped = LHSStripped->IgnoreParenCasts();
05306     if (isa<CastExpr>(RHSStripped))
05307       RHSStripped = RHSStripped->IgnoreParenCasts();
05308 
05309     // Warn about comparisons against a string constant (unless the other
05310     // operand is null), the user probably wants strcmp.
05311     Expr *literalString = 0;
05312     Expr *literalStringStripped = 0;
05313     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
05314         !RHSStripped->isNullPointerConstant(Context,
05315                                             Expr::NPC_ValueDependentIsNull)) {
05316       literalString = lex;
05317       literalStringStripped = LHSStripped;
05318     } else if ((isa<StringLiteral>(RHSStripped) ||
05319                 isa<ObjCEncodeExpr>(RHSStripped)) &&
05320                !LHSStripped->isNullPointerConstant(Context,
05321                                             Expr::NPC_ValueDependentIsNull)) {
05322       literalString = rex;
05323       literalStringStripped = RHSStripped;
05324     }
05325 
05326     if (literalString) {
05327       std::string resultComparison;
05328       switch (Opc) {
05329       case BinaryOperator::LT: resultComparison = ") < 0"; break;
05330       case BinaryOperator::GT: resultComparison = ") > 0"; break;
05331       case BinaryOperator::LE: resultComparison = ") <= 0"; break;
05332       case BinaryOperator::GE: resultComparison = ") >= 0"; break;
05333       case BinaryOperator::EQ: resultComparison = ") == 0"; break;
05334       case BinaryOperator::NE: resultComparison = ") != 0"; break;
05335       default: assert(false && "Invalid comparison operator");
05336       }
05337 
05338       DiagRuntimeBehavior(Loc,
05339         PDiag(diag::warn_stringcompare)
05340           << isa<ObjCEncodeExpr>(literalStringStripped)
05341           << literalString->getSourceRange());
05342     }
05343   }
05344 
05345   // The result of comparisons is 'bool' in C++, 'int' in C.
05346   QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
05347 
05348   if (isRelational) {
05349     if (lType->isRealType() && rType->isRealType())
05350       return ResultTy;
05351   } else {
05352     // Check for comparisons of floating point operands using != and ==.
05353     if (lType->isFloatingType() && rType->isFloatingType())
05354       CheckFloatComparison(Loc,lex,rex);
05355 
05356     if (lType->isArithmeticType() && rType->isArithmeticType())
05357       return ResultTy;
05358   }
05359 
05360   bool LHSIsNull = lex->isNullPointerConstant(Context,
05361                                               Expr::NPC_ValueDependentIsNull);
05362   bool RHSIsNull = rex->isNullPointerConstant(Context,
05363                                               Expr::NPC_ValueDependentIsNull);
05364 
05365   // All of the following pointer related warnings are GCC extensions, except
05366   // when handling null pointer constants. One day, we can consider making them
05367   // errors (when -pedantic-errors is enabled).
05368   if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
05369     QualType LCanPointeeTy =
05370       Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
05371     QualType RCanPointeeTy =
05372       Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
05373 
05374     if (getLangOptions().CPlusPlus) {
05375       if (LCanPointeeTy == RCanPointeeTy)
05376         return ResultTy;
05377       if (!isRelational &&
05378           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
05379         // Valid unless comparison between non-null pointer and function pointer
05380         // This is a gcc extension compatibility comparison.
05381         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
05382             && !LHSIsNull && !RHSIsNull) {
05383           Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
05384             << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05385           ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05386           return ResultTy;
05387         }
05388       }
05389       // C++ [expr.rel]p2:
05390       //   [...] Pointer conversions (4.10) and qualification
05391       //   conversions (4.4) are performed on pointer operands (or on
05392       //   a pointer operand and a null pointer constant) to bring
05393       //   them to their composite pointer type. [...]
05394       //
05395       // C++ [expr.eq]p1 uses the same notion for (in)equality
05396       // comparisons of pointers.
05397       bool NonStandardCompositeType = false;
05398       QualType T = FindCompositePointerType(Loc, lex, rex,
05399                               isSFINAEContext()? 0 : &NonStandardCompositeType);
05400       if (T.isNull()) {
05401         Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
05402           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05403         return QualType();
05404       } else if (NonStandardCompositeType) {
05405         Diag(Loc,
05406              diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
05407           << lType << rType << T
05408           << lex->getSourceRange() << rex->getSourceRange();
05409       }
05410 
05411       ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
05412       ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
05413       return ResultTy;
05414     }
05415     // C99 6.5.9p2 and C99 6.5.8p2
05416     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
05417                                    RCanPointeeTy.getUnqualifiedType())) {
05418       // Valid unless a relational comparison of function pointers
05419       if (isRelational && LCanPointeeTy->isFunctionType()) {
05420         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
05421           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05422       }
05423     } else if (!isRelational &&
05424                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
05425       // Valid unless comparison between non-null pointer and function pointer
05426       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
05427           && !LHSIsNull && !RHSIsNull) {
05428         Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
05429           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05430       }
05431     } else {
05432       // Invalid
05433       Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
05434         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05435     }
05436     if (LCanPointeeTy != RCanPointeeTy)
05437       ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05438     return ResultTy;
05439   }
05440 
05441   if (getLangOptions().CPlusPlus) {
05442     // Comparison of pointers with null pointer constants and equality
05443     // comparisons of member pointers to null pointer constants.
05444     if (RHSIsNull &&
05445         (lType->isPointerType() ||
05446          (!isRelational && lType->isMemberPointerType()))) {
05447       ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
05448       return ResultTy;
05449     }
05450     if (LHSIsNull &&
05451         (rType->isPointerType() ||
05452          (!isRelational && rType->isMemberPointerType()))) {
05453       ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
05454       return ResultTy;
05455     }
05456 
05457     // Comparison of member pointers.
05458     if (!isRelational &&
05459         lType->isMemberPointerType() && rType->isMemberPointerType()) {
05460       // C++ [expr.eq]p2:
05461       //   In addition, pointers to members can be compared, or a pointer to
05462       //   member and a null pointer constant. Pointer to member conversions
05463       //   (4.11) and qualification conversions (4.4) are performed to bring
05464       //   them to a common type. If one operand is a null pointer constant,
05465       //   the common type is the type of the other operand. Otherwise, the
05466       //   common type is a pointer to member type similar (4.4) to the type
05467       //   of one of the operands, with a cv-qualification signature (4.4)
05468       //   that is the union of the cv-qualification signatures of the operand
05469       //   types.
05470       bool NonStandardCompositeType = false;
05471       QualType T = FindCompositePointerType(Loc, lex, rex,
05472                               isSFINAEContext()? 0 : &NonStandardCompositeType);
05473       if (T.isNull()) {
05474         Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
05475           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05476         return QualType();
05477       } else if (NonStandardCompositeType) {
05478         Diag(Loc,
05479              diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
05480           << lType << rType << T
05481           << lex->getSourceRange() << rex->getSourceRange();
05482       }
05483 
05484       ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
05485       ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
05486       return ResultTy;
05487     }
05488 
05489     // Comparison of nullptr_t with itself.
05490     if (lType->isNullPtrType() && rType->isNullPtrType())
05491       return ResultTy;
05492   }
05493 
05494   // Handle block pointer types.
05495   if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
05496     QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
05497     QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
05498 
05499     if (!LHSIsNull && !RHSIsNull &&
05500         !Context.typesAreCompatible(lpointee, rpointee)) {
05501       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
05502         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05503     }
05504     ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05505     return ResultTy;
05506   }
05507   // Allow block pointers to be compared with null pointer constants.
05508   if (!isRelational
05509       && ((lType->isBlockPointerType() && rType->isPointerType())
05510           || (lType->isPointerType() && rType->isBlockPointerType()))) {
05511     if (!LHSIsNull && !RHSIsNull) {
05512       if (!((rType->isPointerType() && rType->getAs<PointerType>()
05513              ->getPointeeType()->isVoidType())
05514             || (lType->isPointerType() && lType->getAs<PointerType>()
05515                 ->getPointeeType()->isVoidType())))
05516         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
05517           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05518     }
05519     ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05520     return ResultTy;
05521   }
05522 
05523   if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
05524     if (lType->isPointerType() || rType->isPointerType()) {
05525       const PointerType *LPT = lType->getAs<PointerType>();
05526       const PointerType *RPT = rType->getAs<PointerType>();
05527       bool LPtrToVoid = LPT ?
05528         Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
05529       bool RPtrToVoid = RPT ?
05530         Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
05531 
05532       if (!LPtrToVoid && !RPtrToVoid &&
05533           !Context.typesAreCompatible(lType, rType)) {
05534         Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
05535           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05536       }
05537       ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05538       return ResultTy;
05539     }
05540     if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
05541       if (!Context.areComparableObjCPointerTypes(lType, rType))
05542         Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
05543           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05544       ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05545       return ResultTy;
05546     }
05547   }
05548   if (lType->isAnyPointerType() && rType->isIntegerType()) {
05549     unsigned DiagID = 0;
05550     if (RHSIsNull) {
05551       if (isRelational)
05552         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
05553     } else if (isRelational)
05554       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
05555     else
05556       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
05557 
05558     if (DiagID) {
05559       Diag(Loc, DiagID)
05560         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05561     }
05562     ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
05563     return ResultTy;
05564   }
05565   if (lType->isIntegerType() && rType->isAnyPointerType()) {
05566     unsigned DiagID = 0;
05567     if (LHSIsNull) {
05568       if (isRelational)
05569         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
05570     } else if (isRelational)
05571       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
05572     else
05573       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
05574 
05575     if (DiagID) {
05576       Diag(Loc, DiagID)
05577         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05578     }
05579     ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
05580     return ResultTy;
05581   }
05582   // Handle block pointers.
05583   if (!isRelational && RHSIsNull
05584       && lType->isBlockPointerType() && rType->isIntegerType()) {
05585     ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
05586     return ResultTy;
05587   }
05588   if (!isRelational && LHSIsNull
05589       && lType->isIntegerType() && rType->isBlockPointerType()) {
05590     ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
05591     return ResultTy;
05592   }
05593   return InvalidOperands(Loc, lex, rex);
05594 }
05595 
05596 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
05597 /// operates on extended vector types.  Instead of producing an IntTy result,
05598 /// like a scalar comparison, a vector comparison produces a vector of integer
05599 /// types.
05600 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
05601                                           SourceLocation Loc,
05602                                           bool isRelational) {
05603   // Check to make sure we're operating on vectors of the same type and width,
05604   // Allowing one side to be a scalar of element type.
05605   QualType vType = CheckVectorOperands(Loc, lex, rex);
05606   if (vType.isNull())
05607     return vType;
05608 
05609   QualType lType = lex->getType();
05610   QualType rType = rex->getType();
05611 
05612   // For non-floating point types, check for self-comparisons of the form
05613   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
05614   // often indicate logic errors in the program.
05615   if (!lType->isFloatingType()) {
05616     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
05617       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
05618         if (DRL->getDecl() == DRR->getDecl())
05619           DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
05620   }
05621 
05622   // Check for comparisons of floating point operands using != and ==.
05623   if (!isRelational && lType->isFloatingType()) {
05624     assert (rType->isFloatingType());
05625     CheckFloatComparison(Loc,lex,rex);
05626   }
05627 
05628   // Return the type for the comparison, which is the same as vector type for
05629   // integer vectors, or an integer type of identical size and number of
05630   // elements for floating point vectors.
05631   if (lType->isIntegerType())
05632     return lType;
05633 
05634   const VectorType *VTy = lType->getAs<VectorType>();
05635   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
05636   if (TypeSize == Context.getTypeSize(Context.IntTy))
05637     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
05638   if (TypeSize == Context.getTypeSize(Context.LongTy))
05639     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
05640 
05641   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
05642          "Unhandled vector element size in vector compare");
05643   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
05644 }
05645 
05646 inline QualType Sema::CheckBitwiseOperands(
05647   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
05648   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
05649     return CheckVectorOperands(Loc, lex, rex);
05650 
05651   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
05652 
05653   if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
05654     return compType;
05655   return InvalidOperands(Loc, lex, rex);
05656 }
05657 
05658 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
05659   Expr *&lex, Expr *&rex, SourceLocation Loc) {
05660   if (!Context.getLangOptions().CPlusPlus) {
05661     UsualUnaryConversions(lex);
05662     UsualUnaryConversions(rex);
05663 
05664     if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
05665       return InvalidOperands(Loc, lex, rex);
05666 
05667     return Context.IntTy;
05668   }
05669 
05670   // C++ [expr.log.and]p1
05671   // C++ [expr.log.or]p1
05672   // The operands are both implicitly converted to type bool (clause 4).
05673   StandardConversionSequence LHS;
05674   if (!IsStandardConversion(lex, Context.BoolTy,
05675                             /*InOverloadResolution=*/false, LHS))
05676     return InvalidOperands(Loc, lex, rex);
05677 
05678   if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
05679                                 AA_Passing, /*IgnoreBaseAccess=*/false))
05680     return InvalidOperands(Loc, lex, rex);
05681 
05682   StandardConversionSequence RHS;
05683   if (!IsStandardConversion(rex, Context.BoolTy,
05684                             /*InOverloadResolution=*/false, RHS))
05685     return InvalidOperands(Loc, lex, rex);
05686 
05687   if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
05688                                 AA_Passing, /*IgnoreBaseAccess=*/false))
05689     return InvalidOperands(Loc, lex, rex);
05690 
05691   // C++ [expr.log.and]p2
05692   // C++ [expr.log.or]p2
05693   // The result is a bool.
05694   return Context.BoolTy;
05695 }
05696 
05697 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
05698 /// is a read-only property; return true if so. A readonly property expression
05699 /// depends on various declarations and thus must be treated specially.
05700 ///
05701 static bool IsReadonlyProperty(Expr *E, Sema &S) {
05702   if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
05703     const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
05704     if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
05705       QualType BaseType = PropExpr->getBase()->getType();
05706       if (const ObjCObjectPointerType *OPT =
05707             BaseType->getAsObjCInterfacePointerType())
05708         if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
05709           if (S.isPropertyReadonly(PDecl, IFace))
05710             return true;
05711     }
05712   }
05713   return false;
05714 }
05715 
05716 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
05717 /// emit an error and return true.  If so, return false.
05718 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
05719   SourceLocation OrigLoc = Loc;
05720   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
05721                                                               &Loc);
05722   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
05723     IsLV = Expr::MLV_ReadonlyProperty;
05724   if (IsLV == Expr::MLV_Valid)
05725     return false;
05726 
05727   unsigned Diag = 0;
05728   bool NeedType = false;
05729   switch (IsLV) { // C99 6.5.16p2
05730   case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
05731   case Expr::MLV_ArrayType:
05732     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
05733     NeedType = true;
05734     break;
05735   case Expr::MLV_NotObjectType:
05736     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
05737     NeedType = true;
05738     break;
05739   case Expr::MLV_LValueCast:
05740     Diag = diag::err_typecheck_lvalue_casts_not_supported;
05741     break;
05742   case Expr::MLV_Valid:
05743     llvm_unreachable("did not take early return for MLV_Valid");
05744   case Expr::MLV_InvalidExpression:
05745   case Expr::MLV_MemberFunction:
05746   case Expr::MLV_ClassTemporary:
05747     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
05748     break;
05749   case Expr::MLV_IncompleteType:
05750   case Expr::MLV_IncompleteVoidType:
05751     return S.RequireCompleteType(Loc, E->getType(),
05752               S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
05753                   << E->getSourceRange());
05754   case Expr::MLV_DuplicateVectorComponents:
05755     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
05756     break;
05757   case Expr::MLV_NotBlockQualified:
05758     Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
05759     break;
05760   case Expr::MLV_ReadonlyProperty:
05761     Diag = diag::error_readonly_property_assignment;
05762     break;
05763   case Expr::MLV_NoSetterProperty:
05764     Diag = diag::error_nosetter_property_assignment;
05765     break;
05766   case Expr::MLV_SubObjCPropertySetting:
05767     Diag = diag::error_no_subobject_property_setting;
05768     break;
05769   }
05770 
05771   SourceRange Assign;
05772   if (Loc != OrigLoc)
05773     Assign = SourceRange(OrigLoc, OrigLoc);
05774   if (NeedType)
05775     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
05776   else
05777     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
05778   return true;
05779 }
05780 
05781 
05782 
05783 // C99 6.5.16.1
05784 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
05785                                        SourceLocation Loc,
05786                                        QualType CompoundType) {
05787   // Verify that LHS is a modifiable lvalue, and emit error if not.
05788   if (CheckForModifiableLvalue(LHS, Loc, *this))
05789     return QualType();
05790 
05791   QualType LHSType = LHS->getType();
05792   QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
05793 
05794   AssignConvertType ConvTy;
05795   if (CompoundType.isNull()) {
05796     // Simple assignment "x = y".
05797     ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
05798     // Special case of NSObject attributes on c-style pointer types.
05799     if (ConvTy == IncompatiblePointer &&
05800         ((Context.isObjCNSObjectType(LHSType) &&
05801           RHSType->isObjCObjectPointerType()) ||
05802          (Context.isObjCNSObjectType(RHSType) &&
05803           LHSType->isObjCObjectPointerType())))
05804       ConvTy = Compatible;
05805 
05806     // If the RHS is a unary plus or minus, check to see if they = and + are
05807     // right next to each other.  If so, the user may have typo'd "x =+ 4"
05808     // instead of "x += 4".
05809     Expr *RHSCheck = RHS;
05810     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
05811       RHSCheck = ICE->getSubExpr();
05812     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
05813       if ((UO->getOpcode() == UnaryOperator::Plus ||
05814            UO->getOpcode() == UnaryOperator::Minus) &&
05815           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
05816           // Only if the two operators are exactly adjacent.
05817           Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
05818           // And there is a space or other character before the subexpr of the
05819           // unary +/-.  We don't want to warn on "x=-1".
05820           Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
05821           UO->getSubExpr()->getLocStart().isFileID()) {
05822         Diag(Loc, diag::warn_not_compound_assign)
05823           << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
05824           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
05825       }
05826     }
05827   } else {
05828     // Compound assignment "x += y"
05829     ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
05830   }
05831 
05832   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
05833                                RHS, AA_Assigning))
05834     return QualType();
05835 
05836   // C99 6.5.16p3: The type of an assignment expression is the type of the
05837   // left operand unless the left operand has qualified type, in which case
05838   // it is the unqualified version of the type of the left operand.
05839   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
05840   // is converted to the type of the assignment expression (above).
05841   // C++ 5.17p1: the type of the assignment expression is that of its left
05842   // operand.
05843   return LHSType.getUnqualifiedType();
05844 }
05845 
05846 // C99 6.5.17
05847 QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
05848   // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
05849   // C++ does not perform this conversion (C++ [expr.comma]p1).
05850   if (!getLangOptions().CPlusPlus)
05851     DefaultFunctionArrayLvalueConversion(RHS);
05852 
05853   // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
05854   // incomplete in C++).
05855 
05856   return RHS->getType();
05857 }
05858 
05859 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
05860 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
05861 QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
05862                                               bool isInc, bool isPrefix) {
05863   if (Op->isTypeDependent())
05864     return Context.DependentTy;
05865 
05866   QualType ResType = Op->getType();
05867   assert(!ResType.isNull() && "no type for increment/decrement expression");
05868 
05869   if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
05870     // Decrement of bool is not allowed.
05871     if (!isInc) {
05872       Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
05873       return QualType();
05874     }
05875     // Increment of bool sets it to true, but is deprecated.
05876     Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
05877   } else if (ResType->isRealType()) {
05878     // OK!
05879   } else if (ResType->isAnyPointerType()) {
05880     QualType PointeeTy = ResType->getPointeeType();
05881 
05882     // C99 6.5.2.4p2, 6.5.6p2
05883     if (PointeeTy->isVoidType()) {
05884       if (getLangOptions().CPlusPlus) {
05885         Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
05886           << Op->getSourceRange();
05887         return QualType();
05888       }
05889 
05890       // Pointer to void is a GNU extension in C.
05891       Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
05892     } else if (PointeeTy->isFunctionType()) {
05893       if (getLangOptions().CPlusPlus) {
05894         Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
05895           << Op->getType() << Op->getSourceRange();
05896         return QualType();
05897       }
05898 
05899       Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
05900         << ResType << Op->getSourceRange();
05901     } else if (RequireCompleteType(OpLoc, PointeeTy,
05902                            PDiag(diag::err_typecheck_arithmetic_incomplete_type)
05903                              << Op->getSourceRange()
05904                              << ResType))
05905       return QualType();
05906     // Diagnose bad cases where we step over interface counts.
05907     else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
05908       Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
05909         << PointeeTy << Op->getSourceRange();
05910       return QualType();
05911     }
05912   } else if (ResType->isAnyComplexType()) {
05913     // C99 does not support ++/-- on complex types, we allow as an extension.
05914     Diag(OpLoc, diag::ext_integer_increment_complex)
05915       << ResType << Op->getSourceRange();
05916   } else {
05917     Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
05918       << ResType << int(isInc) << Op->getSourceRange();
05919     return QualType();
05920   }
05921   // At this point, we know we have a real, complex or pointer type.
05922   // Now make sure the operand is a modifiable lvalue.
05923   if (CheckForModifiableLvalue(Op, OpLoc, *this))
05924     return QualType();
05925   // In C++, a prefix increment is the same type as the operand. Otherwise
05926   // (in C or with postfix), the increment is the unqualified type of the
05927   // operand.
05928   return isPrefix && getLangOptions().CPlusPlus
05929     ? ResType : ResType.getUnqualifiedType();
05930 }
05931 
05932 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
05933 /// This routine allows us to typecheck complex/recursive expressions
05934 /// where the declaration is needed for type checking. We only need to
05935 /// handle cases when the expression references a function designator
05936 /// or is an lvalue. Here are some examples:
05937 ///  - &(x) => x
05938 ///  - &*****f => f for f a function designator.
05939 ///  - &s.xx => s
05940 ///  - &s.zz[1].yy -> s, if zz is an array
05941 ///  - *(x + 1) -> x, if x is an array
05942 ///  - &"123"[2] -> 0
05943 ///  - & __real__ x -> x
05944 static NamedDecl *getPrimaryDecl(Expr *E) {
05945   switch (E->getStmtClass()) {
05946   case Stmt::DeclRefExprClass:
05947     return cast<DeclRefExpr>(E)->getDecl();
05948   case Stmt::MemberExprClass:
05949     // If this is an arrow operator, the address is an offset from
05950     // the base's value, so the object the base refers to is
05951     // irrelevant.
05952     if (cast<MemberExpr>(E)->isArrow())
05953       return 0;
05954     // Otherwise, the expression refers to a part of the base
05955     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
05956   case Stmt::ArraySubscriptExprClass: {
05957     // FIXME: This code shouldn't be necessary!  We should catch the implicit
05958     // promotion of register arrays earlier.
05959     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
05960     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
05961       if (ICE->getSubExpr()->getType()->isArrayType())
05962         return getPrimaryDecl(ICE->getSubExpr());
05963     }
05964     return 0;
05965   }
05966   case Stmt::UnaryOperatorClass: {
05967     UnaryOperator *UO = cast<UnaryOperator>(E);
05968 
05969     switch(UO->getOpcode()) {
05970     case UnaryOperator::Real:
05971     case UnaryOperator::Imag:
05972     case UnaryOperator::Extension:
05973       return getPrimaryDecl(UO->getSubExpr());
05974     default:
05975       return 0;
05976     }
05977   }
05978   case Stmt::ParenExprClass:
05979     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
05980   case Stmt::ImplicitCastExprClass:
05981     // If the result of an implicit cast is an l-value, we care about
05982     // the sub-expression; otherwise, the result here doesn't matter.
05983     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
05984   default:
05985     return 0;
05986   }
05987 }
05988 
05989 /// CheckAddressOfOperand - The operand of & must be either a function
05990 /// designator or an lvalue designating an object. If it is an lvalue, the
05991 /// object cannot be declared with storage class register or be a bit field.
05992 /// Note: The usual conversions are *not* applied to the operand of the &
05993 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
05994 /// In C++, the operand might be an overloaded function name, in which case
05995 /// we allow the '&' but retain the overloaded-function type.
05996 QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
05997   // Make sure to ignore parentheses in subsequent checks
05998   op = op->IgnoreParens();
05999 
06000   if (op->isTypeDependent())
06001     return Context.DependentTy;
06002 
06003   if (getLangOptions().C99) {
06004     // Implement C99-only parts of addressof rules.
06005     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
06006       if (uOp->getOpcode() == UnaryOperator::Deref)
06007         // Per C99 6.5.3.2, the address of a deref always returns a valid result
06008         // (assuming the deref expression is valid).
06009         return uOp->getSubExpr()->getType();
06010     }
06011     // Technically, there should be a check for array subscript
06012     // expressions here, but the result of one is always an lvalue anyway.
06013   }
06014   NamedDecl *dcl = getPrimaryDecl(op);
06015   Expr::isLvalueResult lval = op->isLvalue(Context);
06016 
06017   MemberExpr *ME = dyn_cast<MemberExpr>(op);
06018   if (lval == Expr::LV_MemberFunction && ME &&
06019       isa<CXXMethodDecl>(ME->getMemberDecl())) {
06020     ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
06021     // &f where f is a member of the current object, or &o.f, or &p->f
06022     // All these are not allowed, and we need to catch them before the dcl
06023     // branch of the if, below.
06024     Diag(OpLoc, diag::err_unqualified_pointer_member_function)
06025         << dcl;
06026     // FIXME: Improve this diagnostic and provide a fixit.
06027 
06028     // Now recover by acting as if the function had been accessed qualified.
06029     return Context.getMemberPointerType(op->getType(),
06030                 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
06031                        .getTypePtr());
06032   } else if (lval == Expr::LV_ClassTemporary) {
06033     Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
06034                                  : diag::ext_typecheck_addrof_class_temporary)
06035       << op->getType() << op->getSourceRange();
06036     if (isSFINAEContext())
06037       return QualType();
06038   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
06039     // C99 6.5.3.2p1
06040     // The operand must be either an l-value or a function designator
06041     if (!op->getType()->isFunctionType()) {
06042       // FIXME: emit more specific diag...
06043       Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
06044         << op->getSourceRange();
06045       return QualType();
06046     }
06047   } else if (op->getBitField()) { // C99 6.5.3.2p1
06048     // The operand cannot be a bit-field
06049     Diag(OpLoc, diag::err_typecheck_address_of)
06050       << "bit-field" << op->getSourceRange();
06051         return QualType();
06052   } else if (op->refersToVectorElement()) {
06053     // The operand cannot be an element of a vector
06054     Diag(OpLoc, diag::err_typecheck_address_of)
06055       << "vector element" << op->getSourceRange();
06056     return QualType();
06057   } else if (isa<ObjCPropertyRefExpr>(op)) {
06058     // cannot take address of a property expression.
06059     Diag(OpLoc, diag::err_typecheck_address_of)
06060       << "property expression" << op->getSourceRange();
06061     return QualType();
06062   } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
06063     // FIXME: Can LHS ever be null here?
06064     if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
06065       return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
06066   } else if (isa<UnresolvedLookupExpr>(op)) {
06067     return Context.OverloadTy;
06068   } else if (dcl) { // C99 6.5.3.2p1
06069     // We have an lvalue with a decl. Make sure the decl is not declared
06070     // with the register storage-class specifier.
06071     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
06072       if (vd->getStorageClass() == VarDecl::Register) {
06073         Diag(OpLoc, diag::err_typecheck_address_of)
06074           << "register variable" << op->getSourceRange();
06075         return QualType();
06076       }
06077     } else if (isa<FunctionTemplateDecl>(dcl)) {
06078       return Context.OverloadTy;
06079     } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
06080       // Okay: we can take the address of a field.
06081       // Could be a pointer to member, though, if there is an explicit
06082       // scope qualifier for the class.
06083       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
06084         DeclContext *Ctx = dcl->getDeclContext();
06085         if (Ctx && Ctx->isRecord()) {
06086           if (FD->getType()->isReferenceType()) {
06087             Diag(OpLoc,
06088                  diag::err_cannot_form_pointer_to_member_of_reference_type)
06089               << FD->getDeclName() << FD->getType();
06090             return QualType();
06091           }
06092 
06093           return Context.getMemberPointerType(op->getType(),
06094                 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
06095         }
06096       }
06097     } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
06098       // Okay: we can take the address of a function.
06099       // As above.
06100       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
06101           MD->isInstance())
06102         return Context.getMemberPointerType(op->getType(),
06103               Context.getTypeDeclType(MD->getParent()).getTypePtr());
06104     } else if (!isa<FunctionDecl>(dcl))
06105       assert(0 && "Unknown/unexpected decl type");
06106   }
06107 
06108   if (lval == Expr::LV_IncompleteVoidType) {
06109     // Taking the address of a void variable is technically illegal, but we
06110     // allow it in cases which are otherwise valid.
06111     // Example: "extern void x; void* y = &x;".
06112     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
06113   }
06114 
06115   // If the operand has type "type", the result has type "pointer to type".
06116   return Context.getPointerType(op->getType());
06117 }
06118 
06119 QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
06120   if (Op->isTypeDependent())
06121     return Context.DependentTy;
06122 
06123   UsualUnaryConversions(Op);
06124   QualType Ty = Op->getType();
06125 
06126   // Note that per both C89 and C99, this is always legal, even if ptype is an
06127   // incomplete type or void.  It would be possible to warn about dereferencing
06128   // a void pointer, but it's completely well-defined, and such a warning is
06129   // unlikely to catch any mistakes.
06130   if (const PointerType *PT = Ty->getAs<PointerType>())
06131     return PT->getPointeeType();
06132 
06133   if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
06134     return OPT->getPointeeType();
06135 
06136   Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
06137     << Ty << Op->getSourceRange();
06138   return QualType();
06139 }
06140 
06141 static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
06142   tok::TokenKind Kind) {
06143   BinaryOperator::Opcode Opc;
06144   switch (Kind) {
06145   default: assert(0 && "Unknown binop!");
06146   case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
06147   case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
06148   case tok::star:                 Opc = BinaryOperator::Mul; break;
06149   case tok::slash:                Opc = BinaryOperator::Div; break;
06150   case tok::percent:              Opc = BinaryOperator::Rem; break;
06151   case tok::plus:                 Opc = BinaryOperator::Add; break;
06152   case tok::minus:                Opc = BinaryOperator::Sub; break;
06153   case tok::lessless:             Opc = BinaryOperator::Shl; break;
06154   case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
06155   case tok::lessequal:            Opc = BinaryOperator::LE; break;
06156   case tok::less:                 Opc = BinaryOperator::LT; break;
06157   case tok::greaterequal:         Opc = BinaryOperator::GE; break;
06158   case tok::greater:              Opc = BinaryOperator::GT; break;
06159   case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
06160   case tok::equalequal:           Opc = BinaryOperator::EQ; break;
06161   case tok::amp:                  Opc = BinaryOperator::And; break;
06162   case tok::caret:                Opc = BinaryOperator::Xor; break;
06163   case tok::pipe:                 Opc = BinaryOperator::Or; break;
06164   case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
06165   case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
06166   case tok::equal:                Opc = BinaryOperator::Assign; break;
06167   case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
06168   case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
06169   case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
06170   case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
06171   case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
06172   case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
06173   case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
06174   case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
06175   case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
06176   case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
06177   case tok::comma:                Opc = BinaryOperator::Comma; break;
06178   }
06179   return Opc;
06180 }
06181 
06182 static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
06183   tok::TokenKind Kind) {
06184   UnaryOperator::Opcode Opc;
06185   switch (Kind) {
06186   default: assert(0 && "Unknown unary op!");
06187   case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
06188   case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
06189   case tok::amp:          Opc = UnaryOperator::AddrOf; break;
06190   case tok::star:         Opc = UnaryOperator::Deref; break;
06191   case tok::plus:         Opc = UnaryOperator::Plus; break;
06192   case tok::minus:        Opc = UnaryOperator::Minus; break;
06193   case tok::tilde:        Opc = UnaryOperator::Not; break;
06194   case tok::exclaim:      Opc = UnaryOperator::LNot; break;
06195   case tok::kw___real:    Opc = UnaryOperator::Real; break;
06196   case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
06197   case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
06198   }
06199   return Opc;
06200 }
06201 
06202 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
06203 /// operator @p Opc at location @c TokLoc. This routine only supports
06204 /// built-in operations; ActOnBinOp handles overloaded operators.
06205 Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
06206                                                   unsigned Op,
06207                                                   Expr *lhs, Expr *rhs) {
06208   QualType ResultTy;     // Result type of the binary operator.
06209   BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
06210   // The following two variables are used for compound assignment operators
06211   QualType CompLHSTy;    // Type of LHS after promotions for computation
06212   QualType CompResultTy; // Type of computation result
06213 
06214   switch (Opc) {
06215   case BinaryOperator::Assign:
06216     ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
06217     break;
06218   case BinaryOperator::PtrMemD:
06219   case BinaryOperator::PtrMemI:
06220     ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
06221                                             Opc == BinaryOperator::PtrMemI);
06222     break;
06223   case BinaryOperator::Mul:
06224   case BinaryOperator::Div:
06225     ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
06226                                            Opc == BinaryOperator::Div);
06227     break;
06228   case BinaryOperator::Rem:
06229     ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
06230     break;
06231   case BinaryOperator::Add:
06232     ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
06233     break;
06234   case BinaryOperator::Sub:
06235     ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
06236     break;
06237   case BinaryOperator::Shl:
06238   case BinaryOperator::Shr:
06239     ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
06240     break;
06241   case BinaryOperator::LE:
06242   case BinaryOperator::LT:
06243   case BinaryOperator::GE:
06244   case BinaryOperator::GT:
06245     ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
06246     break;
06247   case BinaryOperator::EQ:
06248   case BinaryOperator::NE:
06249     ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
06250     break;
06251   case BinaryOperator::And:
06252   case BinaryOperator::Xor:
06253   case BinaryOperator::Or:
06254     ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
06255     break;
06256   case BinaryOperator::LAnd:
06257   case BinaryOperator::LOr:
06258     ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
06259     break;
06260   case BinaryOperator::MulAssign:
06261   case BinaryOperator::DivAssign:
06262     CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
06263                                               Opc == BinaryOperator::DivAssign);
06264     CompLHSTy = CompResultTy;
06265     if (!CompResultTy.isNull())
06266       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06267     break;
06268   case BinaryOperator::RemAssign:
06269     CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
06270     CompLHSTy = CompResultTy;
06271     if (!CompResultTy.isNull())
06272       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06273     break;
06274   case BinaryOperator::AddAssign:
06275     CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
06276     if (!CompResultTy.isNull())
06277       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06278     break;
06279   case BinaryOperator::SubAssign:
06280     CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
06281     if (!CompResultTy.isNull())
06282       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06283     break;
06284   case BinaryOperator::ShlAssign:
06285   case BinaryOperator::ShrAssign:
06286     CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
06287     CompLHSTy = CompResultTy;
06288     if (!CompResultTy.isNull())
06289       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06290     break;
06291   case BinaryOperator::AndAssign:
06292   case BinaryOperator::XorAssign:
06293   case BinaryOperator::OrAssign:
06294     CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
06295     CompLHSTy = CompResultTy;
06296     if (!CompResultTy.isNull())
06297       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06298     break;
06299   case BinaryOperator::Comma:
06300     ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
06301     break;
06302   }
06303   if (ResultTy.isNull())
06304     return ExprError();
06305   if (CompResultTy.isNull())
06306     return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
06307   else
06308     return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
06309                                                       CompLHSTy, CompResultTy,
06310                                                       OpLoc));
06311 }
06312 
06313 /// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
06314 /// ParenRange in parentheses.
06315 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
06316                                const PartialDiagnostic &PD,
06317                                const PartialDiagnostic &FirstNote,
06318                                SourceRange FirstParenRange,
06319                                const PartialDiagnostic &SecondNote,
06320                                SourceRange SecondParenRange) {
06321   Self.Diag(Loc, PD);
06322 
06323   if (!FirstNote.getDiagID())
06324     return;
06325 
06326   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
06327   if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
06328     // We can't display the parentheses, so just return.
06329     return;
06330   }
06331 
06332   Self.Diag(Loc, FirstNote)
06333     << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
06334     << FixItHint::CreateInsertion(EndLoc, ")");
06335 
06336   if (!SecondNote.getDiagID())
06337     return;
06338 
06339   EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
06340   if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
06341     // We can't display the parentheses, so just dig the
06342     // warning/error and return.
06343     Self.Diag(Loc, SecondNote);
06344     return;
06345   }
06346 
06347   Self.Diag(Loc, SecondNote)
06348     << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
06349     << FixItHint::CreateInsertion(EndLoc, ")");
06350 }
06351 
06352 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
06353 /// operators are mixed in a way that suggests that the programmer forgot that
06354 /// comparison operators have higher precedence. The most typical example of
06355 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
06356 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
06357                                       SourceLocation OpLoc,Expr *lhs,Expr *rhs){
06358   typedef BinaryOperator BinOp;
06359   BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
06360                 rhsopc = static_cast<BinOp::Opcode>(-1);
06361   if (BinOp *BO = dyn_cast<BinOp>(lhs))
06362     lhsopc = BO->getOpcode();
06363   if (BinOp *BO = dyn_cast<BinOp>(rhs))
06364     rhsopc = BO->getOpcode();
06365 
06366   // Subs are not binary operators.
06367   if (lhsopc == -1 && rhsopc == -1)
06368     return;
06369 
06370   // Bitwise operations are sometimes used as eager logical ops.
06371   // Don't diagnose this.
06372   if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
06373       (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
06374     return;
06375 
06376   if (BinOp::isComparisonOp(lhsopc))
06377     SuggestParentheses(Self, OpLoc,
06378       Self.PDiag(diag::warn_precedence_bitwise_rel)
06379           << SourceRange(lhs->getLocStart(), OpLoc)
06380           << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
06381       Self.PDiag(diag::note_precedence_bitwise_first)
06382           << BinOp::getOpcodeStr(Opc),
06383       SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
06384       Self.PDiag(diag::note_precedence_bitwise_silence)
06385           << BinOp::getOpcodeStr(lhsopc),
06386                        lhs->getSourceRange());
06387   else if (BinOp::isComparisonOp(rhsopc))
06388     SuggestParentheses(Self, OpLoc,
06389       Self.PDiag(diag::warn_precedence_bitwise_rel)
06390           << SourceRange(OpLoc, rhs->getLocEnd())
06391           << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
06392       Self.PDiag(diag::note_precedence_bitwise_first)
06393         << BinOp::getOpcodeStr(Opc),
06394       SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
06395       Self.PDiag(diag::note_precedence_bitwise_silence)
06396         << BinOp::getOpcodeStr(rhsopc),
06397                        rhs->getSourceRange());
06398 }
06399 
06400 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
06401 /// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
06402 /// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
06403 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
06404                                     SourceLocation OpLoc, Expr *lhs, Expr *rhs){
06405   if (BinaryOperator::isBitwiseOp(Opc))
06406     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
06407 }
06408 
06409 // Binary Operators.  'Tok' is the token for the operator.
06410 Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
06411                                           tok::TokenKind Kind,
06412                                           ExprArg LHS, ExprArg RHS) {
06413   BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
06414   Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
06415 
06416   assert((lhs != 0) && "ActOnBinOp(): missing left expression");
06417   assert((rhs != 0) && "ActOnBinOp(): missing right expression");
06418 
06419   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
06420   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
06421 
06422   return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
06423 }
06424 
06425 Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
06426                                           BinaryOperator::Opcode Opc,
06427                                           Expr *lhs, Expr *rhs) {
06428   if (getLangOptions().CPlusPlus &&
06429       (lhs->getType()->isOverloadableType() ||
06430        rhs->getType()->isOverloadableType())) {
06431     // Find all of the overloaded operators visible from this
06432     // point. We perform both an operator-name lookup from the local
06433     // scope and an argument-dependent lookup based on the types of
06434     // the arguments.
06435     UnresolvedSet<16> Functions;
06436     OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
06437     if (S && OverOp != OO_None)
06438       LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
06439                                    Functions);
06440 
06441     // Build the (potentially-overloaded, potentially-dependent)
06442     // binary operation.
06443     return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
06444   }
06445 
06446   // Build a built-in binary operation.
06447   return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
06448 }
06449 
06450 Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
06451                                                     unsigned OpcIn,
06452                                                     ExprArg InputArg) {
06453   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
06454 
06455   // FIXME: Input is modified below, but InputArg is not updated appropriately.
06456   Expr *Input = (Expr *)InputArg.get();
06457   QualType resultType;
06458   switch (Opc) {
06459   case UnaryOperator::OffsetOf:
06460     assert(false && "Invalid unary operator");
06461     break;
06462       
06463   case UnaryOperator::PreInc:
06464   case UnaryOperator::PreDec:
06465   case UnaryOperator::PostInc:
06466   case UnaryOperator::PostDec:
06467     resultType = CheckIncrementDecrementOperand(Input, OpLoc,
06468                                                 Opc == UnaryOperator::PreInc ||
06469                                                 Opc == UnaryOperator::PostInc,
06470                                                 Opc == UnaryOperator::PreInc ||
06471                                                 Opc == UnaryOperator::PreDec);
06472     break;
06473   case UnaryOperator::AddrOf:
06474     resultType = CheckAddressOfOperand(Input, OpLoc);
06475     break;
06476   case UnaryOperator::Deref:
06477     DefaultFunctionArrayLvalueConversion(Input);
06478     resultType = CheckIndirectionOperand(Input, OpLoc);
06479     break;
06480   case UnaryOperator::Plus:
06481   case UnaryOperator::Minus:
06482     UsualUnaryConversions(Input);
06483     resultType = Input->getType();
06484     if (resultType->isDependentType())
06485       break;
06486     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
06487       break;
06488     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
06489              resultType->isEnumeralType())
06490       break;
06491     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
06492              Opc == UnaryOperator::Plus &&
06493              resultType->isPointerType())
06494       break;
06495 
06496     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
06497       << resultType << Input->getSourceRange());
06498   case UnaryOperator::Not: // bitwise complement
06499     UsualUnaryConversions(Input);
06500     resultType = Input->getType();
06501     if (resultType->isDependentType())
06502       break;
06503     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
06504     if (resultType->isComplexType() || resultType->isComplexIntegerType())
06505       // C99 does not support '~' for complex conjugation.
06506       Diag(OpLoc, diag::ext_integer_complement_complex)
06507         << resultType << Input->getSourceRange();
06508     else if (!resultType->isIntegerType())
06509       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
06510         << resultType << Input->getSourceRange());
06511     break;
06512   case UnaryOperator::LNot: // logical negation
06513     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
06514     DefaultFunctionArrayLvalueConversion(Input);
06515     resultType = Input->getType();
06516     if (resultType->isDependentType())
06517       break;
06518     if (!resultType->isScalarType()) // C99 6.5.3.3p1
06519       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
06520         << resultType << Input->getSourceRange());
06521     // LNot always has type int. C99 6.5.3.3p5.
06522     // In C++, it's bool. C++ 5.3.1p8
06523     resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
06524     break;
06525   case UnaryOperator::Real:
06526   case UnaryOperator::Imag:
06527     resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
06528     break;
06529   case UnaryOperator::Extension:
06530     resultType = Input->getType();
06531     break;
06532   }
06533   if (resultType.isNull())
06534     return ExprError();
06535 
06536   InputArg.release();
06537   return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
06538 }
06539 
06540 Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
06541                                             UnaryOperator::Opcode Opc,
06542                                             ExprArg input) {
06543   Expr *Input = (Expr*)input.get();
06544   if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
06545       Opc != UnaryOperator::Extension) {
06546     // Find all of the overloaded operators visible from this
06547     // point. We perform both an operator-name lookup from the local
06548     // scope and an argument-dependent lookup based on the types of
06549     // the arguments.
06550     UnresolvedSet<16> Functions;
06551     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
06552     if (S && OverOp != OO_None)
06553       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
06554                                    Functions);
06555 
06556     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
06557   }
06558 
06559   return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
06560 }
06561 
06562 // Unary Operators.  'Tok' is the token for the operator.
06563 Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
06564                                             tok::TokenKind Op, ExprArg input) {
06565   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
06566 }
06567 
06568 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
06569 Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
06570                                             SourceLocation LabLoc,
06571                                             IdentifierInfo *LabelII) {
06572   // Look up the record for this label identifier.
06573   LabelStmt *&LabelDecl = getLabelMap()[LabelII];
06574 
06575   // If we haven't seen this label yet, create a forward reference. It
06576   // will be validated and/or cleaned up in ActOnFinishFunctionBody.
06577   if (LabelDecl == 0)
06578     LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
06579 
06580   // Create the AST node.  The address of a label always has type 'void*'.
06581   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
06582                                        Context.getPointerType(Context.VoidTy)));
06583 }
06584 
06585 Sema::OwningExprResult
06586 Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
06587                     SourceLocation RPLoc) { // "({..})"
06588   Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
06589   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
06590   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
06591 
06592   bool isFileScope
06593     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
06594   if (isFileScope)
06595     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
06596 
06597   // FIXME: there are a variety of strange constraints to enforce here, for
06598   // example, it is not possible to goto into a stmt expression apparently.
06599   // More semantic analysis is needed.
06600 
06601   // If there are sub stmts in the compound stmt, take the type of the last one
06602   // as the type of the stmtexpr.
06603   QualType Ty = Context.VoidTy;
06604 
06605   if (!Compound->body_empty()) {
06606     Stmt *LastStmt = Compound->body_back();
06607     // If LastStmt is a label, skip down through into the body.
06608     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
06609       LastStmt = Label->getSubStmt();
06610 
06611     if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
06612       Ty = LastExpr->getType();
06613   }
06614 
06615   // FIXME: Check that expression type is complete/non-abstract; statement
06616   // expressions are not lvalues.
06617 
06618   substmt.release();
06619   return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
06620 }
06621 
06622 Sema::OwningExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
06623                                                   TypeSourceInfo *TInfo,
06624                                                   OffsetOfComponent *CompPtr,
06625                                                   unsigned NumComponents,
06626                                                   SourceLocation RParenLoc) {
06627   QualType ArgTy = TInfo->getType();
06628   bool Dependent = ArgTy->isDependentType();
06629   SourceRange TypeRange = TInfo->getTypeLoc().getSourceRange();
06630   
06631   // We must have at least one component that refers to the type, and the first
06632   // one is known to be a field designator.  Verify that the ArgTy represents
06633   // a struct/union/class.
06634   if (!Dependent && !ArgTy->isRecordType())
06635     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
06636                        << ArgTy << TypeRange);
06637   
06638   // Type must be complete per C99 7.17p3 because a declaring a variable
06639   // with an incomplete type would be ill-formed.
06640   if (!Dependent 
06641       && RequireCompleteType(BuiltinLoc, ArgTy,
06642                              PDiag(diag::err_offsetof_incomplete_type)
06643                                << TypeRange))
06644     return ExprError();
06645   
06646   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
06647   // GCC extension, diagnose them.
06648   // FIXME: This diagnostic isn't actually visible because the location is in
06649   // a system header!
06650   if (NumComponents != 1)
06651     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
06652       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
06653   
06654   bool DidWarnAboutNonPOD = false;
06655   QualType CurrentType = ArgTy;
06656   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
06657   llvm::SmallVector<OffsetOfNode, 4> Comps;
06658   llvm::SmallVector<Expr*, 4> Exprs;
06659   for (unsigned i = 0; i != NumComponents; ++i) {
06660     const OffsetOfComponent &OC = CompPtr[i];
06661     if (OC.isBrackets) {
06662       // Offset of an array sub-field.  TODO: Should we allow vector elements?
06663       if (!CurrentType->isDependentType()) {
06664         const ArrayType *AT = Context.getAsArrayType(CurrentType);
06665         if(!AT)
06666           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
06667                            << CurrentType);
06668         CurrentType = AT->getElementType();
06669       } else
06670         CurrentType = Context.DependentTy;
06671       
06672       // The expression must be an integral expression.
06673       // FIXME: An integral constant expression?
06674       Expr *Idx = static_cast<Expr*>(OC.U.E);
06675       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
06676           !Idx->getType()->isIntegerType())
06677         return ExprError(Diag(Idx->getLocStart(),
06678                               diag::err_typecheck_subscript_not_integer)
06679                          << Idx->getSourceRange());
06680       
06681       // Record this array index.
06682       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
06683       Exprs.push_back(Idx);
06684       continue;
06685     }
06686     
06687     // Offset of a field.
06688     if (CurrentType->isDependentType()) {
06689       // We have the offset of a field, but we can't look into the dependent
06690       // type. Just record the identifier of the field.
06691       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
06692       CurrentType = Context.DependentTy;
06693       continue;
06694     }
06695     
06696     // We need to have a complete type to look into.
06697     if (RequireCompleteType(OC.LocStart, CurrentType,
06698                             diag::err_offsetof_incomplete_type))
06699       return ExprError();
06700     
06701     // Look for the designated field.
06702     const RecordType *RC = CurrentType->getAs<RecordType>();
06703     if (!RC) 
06704       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
06705                        << CurrentType);
06706     RecordDecl *RD = RC->getDecl();
06707     
06708     // C++ [lib.support.types]p5:
06709     //   The macro offsetof accepts a restricted set of type arguments in this
06710     //   International Standard. type shall be a POD structure or a POD union
06711     //   (clause 9).
06712     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
06713       if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
06714           DiagRuntimeBehavior(BuiltinLoc,
06715                               PDiag(diag::warn_offsetof_non_pod_type)
06716                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
06717                               << CurrentType))
06718         DidWarnAboutNonPOD = true;
06719     }
06720     
06721     // Look for the field.
06722     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
06723     LookupQualifiedName(R, RD);
06724     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
06725     if (!MemberDecl)
06726       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
06727                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
06728                                                               OC.LocEnd));
06729     
06730     // C99 7.17p3:
06731     //   (If the specified member is a bit-field, the behavior is undefined.)
06732     //
06733     // We diagnose this as an error.
06734     if (MemberDecl->getBitWidth()) {
06735       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
06736         << MemberDecl->getDeclName()
06737         << SourceRange(BuiltinLoc, RParenLoc);
06738       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
06739       return ExprError();
06740     }
06741       
06742     // If the member was found in a base class, introduce OffsetOfNodes for
06743     // the base class indirections.
06744     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
06745                        /*DetectVirtual=*/false);
06746     if (IsDerivedFrom(CurrentType, 
06747                       Context.getTypeDeclType(MemberDecl->getParent()), 
06748                       Paths)) {
06749       CXXBasePath &Path = Paths.front();
06750       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
06751            B != BEnd; ++B)
06752         Comps.push_back(OffsetOfNode(B->Base));
06753     }
06754     
06755     if (cast<RecordDecl>(MemberDecl->getDeclContext())->
06756                                                 isAnonymousStructOrUnion()) {
06757       llvm::SmallVector<FieldDecl*, 4> Path;
06758       BuildAnonymousStructUnionMemberPath(MemberDecl, Path);
06759       unsigned n = Path.size();
06760       for (int j = n - 1; j > -1; --j)
06761         Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd));
06762     } else {
06763       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
06764     }
06765     CurrentType = MemberDecl->getType().getNonReferenceType(); 
06766   }
06767   
06768   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 
06769                                     TInfo, Comps.data(), Comps.size(),
06770                                     Exprs.data(), Exprs.size(), RParenLoc));  
06771 }
06772 
06773 Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
06774                                                   SourceLocation BuiltinLoc,
06775                                                   SourceLocation TypeLoc,
06776                                                   TypeTy *argty,
06777                                                   OffsetOfComponent *CompPtr,
06778                                                   unsigned NumComponents,
06779                                                   SourceLocation RPLoc) {
06780 
06781   TypeSourceInfo *ArgTInfo;
06782   QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
06783   if (ArgTy.isNull())
06784     return ExprError();
06785 
06786   if (getLangOptions().CPlusPlus) {
06787     if (!ArgTInfo)
06788       ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
06789     
06790     return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 
06791                                 RPLoc);
06792   }
06793   
06794   // FIXME: The code below is marked for death, once we have proper CodeGen
06795   // support for non-constant OffsetOf expressions.
06796   
06797   bool Dependent = ArgTy->isDependentType();
06798   
06799   // We must have at least one component that refers to the type, and the first
06800   // one is known to be a field designator.  Verify that the ArgTy represents
06801   // a struct/union/class.
06802   if (!Dependent && !ArgTy->isRecordType())
06803     return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
06804   
06805   // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
06806   // with an incomplete type would be illegal.
06807   
06808   // Otherwise, create a null pointer as the base, and iteratively process
06809   // the offsetof designators.
06810   QualType ArgTyPtr = Context.getPointerType(ArgTy);
06811   Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
06812   Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
06813                                     ArgTy, SourceLocation());
06814   
06815   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
06816   // GCC extension, diagnose them.
06817   // FIXME: This diagnostic isn't actually visible because the location is in
06818   // a system header!
06819   if (NumComponents != 1)
06820     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
06821     << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
06822   
06823   if (!Dependent) {
06824     bool DidWarnAboutNonPOD = false;
06825     
06826     if (RequireCompleteType(TypeLoc, Res->getType(),
06827                             diag::err_offsetof_incomplete_type))
06828       return ExprError();
06829     
06830     // FIXME: Dependent case loses a lot of information here. And probably
06831     // leaks like a sieve.
06832     for (unsigned i = 0; i != NumComponents; ++i) {
06833       const OffsetOfComponent &OC = CompPtr[i];
06834       if (OC.isBrackets) {
06835         // Offset of an array sub-field.  TODO: Should we allow vector elements?
06836         const ArrayType *AT = Context.getAsArrayType(Res->getType());
06837         if (!AT) {
06838           Res->Destroy(Context);
06839           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
06840                            << Res->getType());
06841         }
06842         
06843         // FIXME: C++: Verify that operator[] isn't overloaded.
06844         
06845         // Promote the array so it looks more like a normal array subscript
06846         // expression.
06847         DefaultFunctionArrayLvalueConversion(Res);
06848         
06849         // C99 6.5.2.1p1
06850         Expr *Idx = static_cast<Expr*>(OC.U.E);
06851         // FIXME: Leaks Res
06852         if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
06853           return ExprError(Diag(Idx->getLocStart(),
06854                                 diag::err_typecheck_subscript_not_integer)
06855                            << Idx->getSourceRange());
06856         
06857         Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
06858                                                OC.LocEnd);
06859         continue;
06860       }
06861       
06862       const RecordType *RC = Res->getType()->getAs<RecordType>();
06863       if (!RC) {
06864         Res->Destroy(Context);
06865         return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
06866                          << Res->getType());
06867       }
06868       
06869       // Get the decl corresponding to this.
06870       RecordDecl *RD = RC->getDecl();
06871       if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
06872         if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
06873             DiagRuntimeBehavior(BuiltinLoc,
06874                                 PDiag(diag::warn_offsetof_non_pod_type)
06875                                 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
06876                                 << Res->getType()))
06877           DidWarnAboutNonPOD = true;
06878       }
06879       
06880       LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
06881       LookupQualifiedName(R, RD);
06882       
06883       FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
06884       // FIXME: Leaks Res
06885       if (!MemberDecl)
06886         return ExprError(Diag(BuiltinLoc, diag::err_no_member)
06887                          << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
06888       
06889       // C99 7.17p3:
06890       //   (If the specified member is a bit-field, the behavior is undefined.)
06891       //
06892       // We diagnose this as an error.
06893       if (MemberDecl->getBitWidth()) {
06894         Diag(OC.LocEnd, diag::err_offsetof_bitfield)
06895           << MemberDecl->getDeclName()
06896           << SourceRange(BuiltinLoc, RPLoc);
06897         Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
06898         return ExprError();
06899       }
06900       
06901       // FIXME: C++: Verify that MemberDecl isn't a static field.
06902       // FIXME: Verify that MemberDecl isn't a bitfield.
06903       if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
06904         Res = BuildAnonymousStructUnionMemberReference(
06905                                                        OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
06906       } else {
06907         PerformObjectMemberConversion(Res, /*Qualifier=*/0,
06908                                       *R.begin(), MemberDecl);
06909         // MemberDecl->getType() doesn't get the right qualifiers, but it
06910         // doesn't matter here.
06911         Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
06912                                        MemberDecl->getType().getNonReferenceType());
06913       }
06914     }
06915   }
06916   
06917   return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
06918                                            Context.getSizeType(), BuiltinLoc));
06919 }
06920 
06921 
06922 Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
06923                                                       TypeTy *arg1,TypeTy *arg2,
06924                                                       SourceLocation RPLoc) {
06925   // FIXME: Preserve type source info.
06926   QualType argT1 = GetTypeFromParser(arg1);
06927   QualType argT2 = GetTypeFromParser(arg2);
06928 
06929   assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
06930 
06931   if (getLangOptions().CPlusPlus) {
06932     Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
06933       << SourceRange(BuiltinLoc, RPLoc);
06934     return ExprError();
06935   }
06936 
06937   return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
06938                                                  argT1, argT2, RPLoc));
06939 }
06940 
06941 Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
06942                                              ExprArg cond,
06943                                              ExprArg expr1, ExprArg expr2,
06944                                              SourceLocation RPLoc) {
06945   Expr *CondExpr = static_cast<Expr*>(cond.get());
06946   Expr *LHSExpr = static_cast<Expr*>(expr1.get());
06947   Expr *RHSExpr = static_cast<Expr*>(expr2.get());
06948 
06949   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
06950 
06951   QualType resType;
06952   bool ValueDependent = false;
06953   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
06954     resType = Context.DependentTy;
06955     ValueDependent = true;
06956   } else {
06957     // The conditional expression is required to be a constant expression.
06958     llvm::APSInt condEval(32);
06959     SourceLocation ExpLoc;
06960     if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
06961       return ExprError(Diag(ExpLoc,
06962                        diag::err_typecheck_choose_expr_requires_constant)
06963         << CondExpr->getSourceRange());
06964 
06965     // If the condition is > zero, then the AST type is the same as the LSHExpr.
06966     resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
06967     ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
06968                                              : RHSExpr->isValueDependent();
06969   }
06970 
06971   cond.release(); expr1.release(); expr2.release();
06972   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
06973                                         resType, RPLoc,
06974                                         resType->isDependentType(),
06975                                         ValueDependent));
06976 }
06977 
06978 //===----------------------------------------------------------------------===//
06979 // Clang Extensions.
06980 //===----------------------------------------------------------------------===//
06981 
06982 /// ActOnBlockStart - This callback is invoked when a block literal is started.
06983 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
06984   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
06985   PushBlockScope(BlockScope, Block);
06986   CurContext->addDecl(Block);
06987   PushDeclContext(BlockScope, Block);
06988 }
06989 
06990 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
06991   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
06992   BlockScopeInfo *CurBlock = getCurBlock();
06993 
06994   if (ParamInfo.getNumTypeObjects() == 0
06995       || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
06996     ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
06997     QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
06998 
06999     if (T->isArrayType()) {
07000       Diag(ParamInfo.getSourceRange().getBegin(),
07001            diag::err_block_returns_array);
07002       return;
07003     }
07004 
07005     // The parameter list is optional, if there was none, assume ().
07006     if (!T->isFunctionType())
07007       T = Context.getFunctionType(T, 0, 0, false, 0, false, false, 0, 0,
07008                                   FunctionType::ExtInfo());
07009 
07010     CurBlock->hasPrototype = true;
07011     CurBlock->isVariadic = false;
07012     // Check for a valid sentinel attribute on this block.
07013     if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
07014       Diag(ParamInfo.getAttributes()->getLoc(),
07015            diag::warn_attribute_sentinel_not_variadic) << 1;
07016       // FIXME: remove the attribute.
07017     }
07018     QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
07019 
07020     // Do not allow returning a objc interface by-value.
07021     if (RetTy->isObjCInterfaceType()) {
07022       Diag(ParamInfo.getSourceRange().getBegin(),
07023            diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
07024       return;
07025     }
07026 
07027     CurBlock->ReturnType = RetTy;
07028     return;
07029   }
07030 
07031   // Analyze arguments to block.
07032   assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
07033          "Not a function declarator!");
07034   DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
07035 
07036   CurBlock->hasPrototype = FTI.hasPrototype;
07037   CurBlock->isVariadic = true;
07038 
07039   // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
07040   // no arguments, not a function that takes a single void argument.
07041   if (FTI.hasPrototype &&
07042       FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
07043      (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
07044         FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
07045     // empty arg list, don't push any params.
07046     CurBlock->isVariadic = false;
07047   } else if (FTI.hasPrototype) {
07048     for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
07049       ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
07050       if (Param->getIdentifier() == 0 &&
07051           !Param->isImplicit() &&
07052           !Param->isInvalidDecl() &&
07053           !getLangOptions().CPlusPlus)
07054         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
07055       CurBlock->Params.push_back(Param);
07056     }
07057     CurBlock->isVariadic = FTI.isVariadic;
07058   }
07059   CurBlock->TheDecl->setParams(CurBlock->Params.data(),
07060                                CurBlock->Params.size());
07061   CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
07062   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
07063 
07064   bool ShouldCheckShadow =
07065     Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
07066 
07067   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
07068          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
07069     (*AI)->setOwningFunction(CurBlock->TheDecl);
07070 
07071     // If this has an identifier, add it to the scope stack.
07072     if ((*AI)->getIdentifier()) {
07073       if (ShouldCheckShadow)
07074         CheckShadow(CurBlock->TheScope, *AI);
07075 
07076       PushOnScopeChains(*AI, CurBlock->TheScope);
07077     }
07078   }
07079 
07080   // Check for a valid sentinel attribute on this block.
07081   if (!CurBlock->isVariadic &&
07082       CurBlock->TheDecl->getAttr<SentinelAttr>()) {
07083     Diag(ParamInfo.getAttributes()->getLoc(),
07084          diag::warn_attribute_sentinel_not_variadic) << 1;
07085     // FIXME: remove the attribute.
07086   }
07087 
07088   // Analyze the return type.
07089   QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
07090   QualType RetTy = T->getAs<FunctionType>()->getResultType();
07091 
07092   // Do not allow returning a objc interface by-value.
07093   if (RetTy->isObjCInterfaceType()) {
07094     Diag(ParamInfo.getSourceRange().getBegin(),
07095          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
07096   } else if (!RetTy->isDependentType())
07097     CurBlock->ReturnType = RetTy;
07098 }
07099 
07100 /// ActOnBlockError - If there is an error parsing a block, this callback
07101 /// is invoked to pop the information about the block from the action impl.
07102 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
07103   // Pop off CurBlock, handle nested blocks.
07104   PopDeclContext();
07105   PopFunctionOrBlockScope();
07106   // FIXME: Delete the ParmVarDecl objects as well???
07107 }
07108 
07109 /// ActOnBlockStmtExpr - This is called when the body of a block statement
07110 /// literal was successfully completed.  ^(int x){...}
07111 Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
07112                                                 StmtArg body, Scope *CurScope) {
07113   // If blocks are disabled, emit an error.
07114   if (!LangOpts.Blocks)
07115     Diag(CaretLoc, diag::err_blocks_disable);
07116 
07117   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
07118 
07119   PopDeclContext();
07120 
07121   QualType RetTy = Context.VoidTy;
07122   if (!BSI->ReturnType.isNull())
07123     RetTy = BSI->ReturnType;
07124 
07125   llvm::SmallVector<QualType, 8> ArgTypes;
07126   for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
07127     ArgTypes.push_back(BSI->Params[i]->getType());
07128 
07129   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
07130   QualType BlockTy;
07131   if (!BSI->hasPrototype)
07132     BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
07133                                 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
07134   else
07135     BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
07136                                       BSI->isVariadic, 0, false, false, 0, 0,
07137                                 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
07138 
07139   // FIXME: Check that return/parameter types are complete/non-abstract
07140   DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
07141   BlockTy = Context.getBlockPointerType(BlockTy);
07142 
07143   // If needed, diagnose invalid gotos and switches in the block.
07144   if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
07145     DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
07146 
07147   BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
07148 
07149   bool Good = true;
07150   // Check goto/label use.
07151   for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
07152          I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
07153     LabelStmt *L = I->second;
07154 
07155     // Verify that we have no forward references left.  If so, there was a goto
07156     // or address of a label taken, but no definition of it.
07157     if (L->getSubStmt() != 0)
07158       continue;
07159 
07160     // Emit error.
07161     Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
07162     Good = false;
07163   }
07164   if (!Good) {
07165     PopFunctionOrBlockScope();
07166     return ExprError();
07167   }
07168 
07169   // Issue any analysis-based warnings.
07170   const sema::AnalysisBasedWarnings::Policy &WP =
07171     AnalysisWarnings.getDefaultPolicy();
07172   AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
07173 
07174   Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
07175                                          BSI->hasBlockDeclRefExprs);
07176   PopFunctionOrBlockScope();
07177   return Owned(Result);
07178 }
07179 
07180 Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
07181                                         ExprArg expr, TypeTy *type,
07182                                         SourceLocation RPLoc) {
07183   QualType T = GetTypeFromParser(type);
07184   Expr *E = static_cast<Expr*>(expr.get());
07185   Expr *OrigExpr = E;
07186 
07187   InitBuiltinVaListType();
07188 
07189   // Get the va_list type
07190   QualType VaListType = Context.getBuiltinVaListType();
07191   if (VaListType->isArrayType()) {
07192     // Deal with implicit array decay; for example, on x86-64,
07193     // va_list is an array, but it's supposed to decay to
07194     // a pointer for va_arg.
07195     VaListType = Context.getArrayDecayedType(VaListType);
07196     // Make sure the input expression also decays appropriately.
07197     UsualUnaryConversions(E);
07198   } else {
07199     // Otherwise, the va_list argument must be an l-value because
07200     // it is modified by va_arg.
07201     if (!E->isTypeDependent() &&
07202         CheckForModifiableLvalue(E, BuiltinLoc, *this))
07203       return ExprError();
07204   }
07205 
07206   if (!E->isTypeDependent() &&
07207       !Context.hasSameType(VaListType, E->getType())) {
07208     return ExprError(Diag(E->getLocStart(),
07209                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
07210       << OrigExpr->getType() << E->getSourceRange());
07211   }
07212 
07213   // FIXME: Check that type is complete/non-abstract
07214   // FIXME: Warn if a non-POD type is passed in.
07215 
07216   expr.release();
07217   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
07218                                        RPLoc));
07219 }
07220 
07221 Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
07222   // The type of __null will be int or long, depending on the size of
07223   // pointers on the target.
07224   QualType Ty;
07225   if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
07226     Ty = Context.IntTy;
07227   else
07228     Ty = Context.LongTy;
07229 
07230   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
07231 }
07232 
07233 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
07234                                            Expr *SrcExpr, FixItHint &Hint) {
07235   if (!SemaRef.getLangOptions().ObjC1)
07236     return;
07237 
07238   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
07239   if (!PT)
07240     return;
07241 
07242   // Check if the destination is of type 'id'.
07243   if (!PT->isObjCIdType()) {
07244     // Check if the destination is the 'NSString' interface.
07245     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
07246     if (!ID || !ID->getIdentifier()->isStr("NSString"))
07247       return;
07248   }
07249 
07250   // Strip off any parens and casts.
07251   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
07252   if (!SL || SL->isWide())
07253     return;
07254 
07255   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
07256 }
07257 
07258 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
07259                                     SourceLocation Loc,
07260                                     QualType DstType, QualType SrcType,
07261                                     Expr *SrcExpr, AssignmentAction Action,
07262                                     bool *Complained) {
07263   if (Complained)
07264     *Complained = false;
07265 
07266   // Decode the result (notice that AST's are still created for extensions).
07267   bool isInvalid = false;
07268   unsigned DiagKind;
07269   FixItHint Hint;
07270 
07271   switch (ConvTy) {
07272   default: assert(0 && "Unknown conversion type");
07273   case Compatible: return false;
07274   case PointerToInt:
07275     DiagKind = diag::ext_typecheck_convert_pointer_int;
07276     break;
07277   case IntToPointer:
07278     DiagKind = diag::ext_typecheck_convert_int_pointer;
07279     break;
07280   case IncompatiblePointer:
07281     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
07282     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
07283     break;
07284   case IncompatiblePointerSign:
07285     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
07286     break;
07287   case FunctionVoidPointer:
07288     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
07289     break;
07290   case CompatiblePointerDiscardsQualifiers:
07291     // If the qualifiers lost were because we were applying the
07292     // (deprecated) C++ conversion from a string literal to a char*
07293     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
07294     // Ideally, this check would be performed in
07295     // CheckPointerTypesForAssignment. However, that would require a
07296     // bit of refactoring (so that the second argument is an
07297     // expression, rather than a type), which should be done as part
07298     // of a larger effort to fix CheckPointerTypesForAssignment for
07299     // C++ semantics.
07300     if (getLangOptions().CPlusPlus &&
07301         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
07302       return false;
07303     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
07304     break;
07305   case IncompatibleNestedPointerQualifiers:
07306     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
07307     break;
07308   case IntToBlockPointer:
07309     DiagKind = diag::err_int_to_block_pointer;
07310     break;
07311   case IncompatibleBlockPointer:
07312     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
07313     break;
07314   case IncompatibleObjCQualifiedId:
07315     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
07316     // it can give a more specific diagnostic.
07317     DiagKind = diag::warn_incompatible_qualified_id;
07318     break;
07319   case IncompatibleVectors:
07320     DiagKind = diag::warn_incompatible_vectors;
07321     break;
07322   case Incompatible:
07323     DiagKind = diag::err_typecheck_convert_incompatible;
07324     isInvalid = true;
07325     break;
07326   }
07327 
07328   QualType FirstType, SecondType;
07329   switch (Action) {
07330   case AA_Assigning:
07331   case AA_Initializing:
07332     // The destination type comes first.
07333     FirstType = DstType;
07334     SecondType = SrcType;
07335     break;
07336 
07337   case AA_Returning:
07338   case AA_Passing:
07339   case AA_Converting:
07340   case AA_Sending:
07341   case AA_Casting:
07342     // The source type comes first.
07343     FirstType = SrcType;
07344     SecondType = DstType;
07345     break;
07346   }
07347 
07348   Diag(Loc, DiagKind) << FirstType << SecondType << Action
07349     << SrcExpr->getSourceRange() << Hint;
07350   if (Complained)
07351     *Complained = true;
07352   return isInvalid;
07353 }
07354 
07355 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
07356   llvm::APSInt ICEResult;
07357   if (E->isIntegerConstantExpr(ICEResult, Context)) {
07358     if (Result)
07359       *Result = ICEResult;
07360     return false;
07361   }
07362 
07363   Expr::EvalResult EvalResult;
07364 
07365   if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
07366       EvalResult.HasSideEffects) {
07367     Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
07368 
07369     if (EvalResult.Diag) {
07370       // We only show the note if it's not the usual "invalid subexpression"
07371       // or if it's actually in a subexpression.
07372       if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
07373           E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
07374         Diag(EvalResult.DiagLoc, EvalResult.Diag);
07375     }
07376 
07377     return true;
07378   }
07379 
07380   Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
07381     E->getSourceRange();
07382 
07383   if (EvalResult.Diag &&
07384       Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
07385     Diag(EvalResult.DiagLoc, EvalResult.Diag);
07386 
07387   if (Result)
07388     *Result = EvalResult.Val.getInt();
07389   return false;
07390 }
07391 
07392 void
07393 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
07394   ExprEvalContexts.push_back(
07395         ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
07396 }
07397 
07398 void
07399 Sema::PopExpressionEvaluationContext() {
07400   // Pop the current expression evaluation context off the stack.
07401   ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
07402   ExprEvalContexts.pop_back();
07403 
07404   if (Rec.Context == PotentiallyPotentiallyEvaluated) {
07405     if (Rec.PotentiallyReferenced) {
07406       // Mark any remaining declarations in the current position of the stack
07407       // as "referenced". If they were not meant to be referenced, semantic
07408       // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
07409       for (PotentiallyReferencedDecls::iterator
07410              I = Rec.PotentiallyReferenced->begin(),
07411              IEnd = Rec.PotentiallyReferenced->end();
07412            I != IEnd; ++I)
07413         MarkDeclarationReferenced(I->first, I->second);
07414     }
07415 
07416     if (Rec.PotentiallyDiagnosed) {
07417       // Emit any pending diagnostics.
07418       for (PotentiallyEmittedDiagnostics::iterator
07419                 I = Rec.PotentiallyDiagnosed->begin(),
07420              IEnd = Rec.PotentiallyDiagnosed->end();
07421            I != IEnd; ++I)
07422         Diag(I->first, I->second);
07423     }
07424   }
07425 
07426   // When are coming out of an unevaluated context, clear out any
07427   // temporaries that we may have created as part of the evaluation of
07428   // the expression in that context: they aren't relevant because they
07429   // will never be constructed.
07430   if (Rec.Context == Unevaluated &&
07431       ExprTemporaries.size() > Rec.NumTemporaries)
07432     ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
07433                           ExprTemporaries.end());
07434 
07435   // Destroy the popped expression evaluation record.
07436   Rec.Destroy();
07437 }
07438 
07439 /// \brief Note that the given declaration was referenced in the source code.
07440 ///
07441 /// This routine should be invoke whenever a given declaration is referenced
07442 /// in the source code, and where that reference occurred. If this declaration
07443 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
07444 /// C99 6.9p3), then the declaration will be marked as used.
07445 ///
07446 /// \param Loc the location where the declaration was referenced.
07447 ///
07448 /// \param D the declaration that has been referenced by the source code.
07449 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
07450   assert(D && "No declaration?");
07451 
07452   if (D->isUsed())
07453     return;
07454 
07455   // Mark a parameter or variable declaration "used", regardless of whether we're in a
07456   // template or not. The reason for this is that unevaluated expressions
07457   // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
07458   // -Wunused-parameters)
07459   if (isa<ParmVarDecl>(D) ||
07460       (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
07461     D->setUsed(true);
07462     return;
07463   }
07464 
07465   if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
07466     return;
07467 
07468   // Do not mark anything as "used" within a dependent context; wait for
07469   // an instantiation.
07470   if (CurContext->isDependentContext())
07471     return;
07472 
07473   switch (ExprEvalContexts.back().Context) {
07474     case Unevaluated:
07475       // We are in an expression that is not potentially evaluated; do nothing.
07476       return;
07477 
07478     case PotentiallyEvaluated:
07479       // We are in a potentially-evaluated expression, so this declaration is
07480       // "used"; handle this below.
07481       break;
07482 
07483     case PotentiallyPotentiallyEvaluated:
07484       // We are in an expression that may be potentially evaluated; queue this
07485       // declaration reference until we know whether the expression is
07486       // potentially evaluated.
07487       ExprEvalContexts.back().addReferencedDecl(Loc, D);
07488       return;
07489   }
07490 
07491   // Note that this declaration has been used.
07492   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
07493     unsigned TypeQuals;
07494     if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
07495         if (!Constructor->isUsed())
07496           DefineImplicitDefaultConstructor(Loc, Constructor);
07497     } else if (Constructor->isImplicit() &&
07498                Constructor->isCopyConstructor(TypeQuals)) {
07499       if (!Constructor->isUsed())
07500         DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
07501     }
07502 
07503     MaybeMarkVirtualMembersReferenced(Loc, Constructor);
07504   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
07505     if (Destructor->isImplicit() && !Destructor->isUsed())
07506       DefineImplicitDestructor(Loc, Destructor);
07507 
07508   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
07509     if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
07510         MethodDecl->getOverloadedOperator() == OO_Equal) {
07511       if (!MethodDecl->isUsed())
07512         DefineImplicitCopyAssignment(Loc, MethodDecl);
07513     }
07514   }
07515   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
07516     // Implicit instantiation of function templates and member functions of
07517     // class templates.
07518     if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
07519       bool AlreadyInstantiated = false;
07520       if (FunctionTemplateSpecializationInfo *SpecInfo
07521                                 = Function->getTemplateSpecializationInfo()) {
07522         if (SpecInfo->getPointOfInstantiation().isInvalid())
07523           SpecInfo->setPointOfInstantiation(Loc);
07524         else if (SpecInfo->getTemplateSpecializationKind()
07525                    == TSK_ImplicitInstantiation)
07526           AlreadyInstantiated = true;
07527       } else if (MemberSpecializationInfo *MSInfo
07528                                   = Function->getMemberSpecializationInfo()) {
07529         if (MSInfo->getPointOfInstantiation().isInvalid())
07530           MSInfo->setPointOfInstantiation(Loc);
07531         else if (MSInfo->getTemplateSpecializationKind()
07532                    == TSK_ImplicitInstantiation)
07533           AlreadyInstantiated = true;
07534       }
07535 
07536       if (!AlreadyInstantiated) {
07537         if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
07538             cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
07539           PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
07540                                                                       Loc));
07541         else
07542           PendingImplicitInstantiations.push_back(std::make_pair(Function,
07543                                                                  Loc));
07544       }
07545     }
07546 
07547     // FIXME: keep track of references to static functions
07548     Function->setUsed(true);
07549 
07550     return;
07551   }
07552 
07553   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
07554     // Implicit instantiation of static data members of class templates.
07555     if (Var->isStaticDataMember() &&
07556         Var->getInstantiatedFromStaticDataMember()) {
07557       MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
07558       assert(MSInfo && "Missing member specialization information?");
07559       if (MSInfo->getPointOfInstantiation().isInvalid() &&
07560           MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
07561         MSInfo->setPointOfInstantiation(Loc);
07562         PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
07563       }
07564     }
07565 
07566     // FIXME: keep track of references to static data?
07567 
07568     D->setUsed(true);
07569     return;
07570   }
07571 }
07572 
07573 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
07574 /// of the program being compiled.
07575 ///
07576 /// This routine emits the given diagnostic when the code currently being
07577 /// type-checked is "potentially evaluated", meaning that there is a
07578 /// possibility that the code will actually be executable. Code in sizeof()
07579 /// expressions, code used only during overload resolution, etc., are not
07580 /// potentially evaluated. This routine will suppress such diagnostics or,
07581 /// in the absolutely nutty case of potentially potentially evaluated
07582 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
07583 /// later.
07584 ///
07585 /// This routine should be used for all diagnostics that describe the run-time
07586 /// behavior of a program, such as passing a non-POD value through an ellipsis.
07587 /// Failure to do so will likely result in spurious diagnostics or failures
07588 /// during overload resolution or within sizeof/alignof/typeof/typeid.
07589 bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
07590                                const PartialDiagnostic &PD) {
07591   switch (ExprEvalContexts.back().Context ) {
07592   case Unevaluated:
07593     // The argument will never be evaluated, so don't complain.
07594     break;
07595 
07596   case PotentiallyEvaluated:
07597     Diag(Loc, PD);
07598     return true;
07599 
07600   case PotentiallyPotentiallyEvaluated:
07601     ExprEvalContexts.back().addDiagnostic(Loc, PD);
07602     break;
07603   }
07604 
07605   return false;
07606 }
07607 
07608 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
07609                                CallExpr *CE, FunctionDecl *FD) {
07610   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
07611     return false;
07612 
07613   PartialDiagnostic Note =
07614     FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
07615     << FD->getDeclName() : PDiag();
07616   SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
07617 
07618   if (RequireCompleteType(Loc, ReturnType,
07619                           FD ?
07620                           PDiag(diag::err_call_function_incomplete_return)
07621                             << CE->getSourceRange() << FD->getDeclName() :
07622                           PDiag(diag::err_call_incomplete_return)
07623                             << CE->getSourceRange(),
07624                           std::make_pair(NoteLoc, Note)))
07625     return true;
07626 
07627   return false;
07628 }
07629 
07630 // Diagnose the common s/=/==/ typo.  Note that adding parentheses
07631 // will prevent this condition from triggering, which is what we want.
07632 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
07633   SourceLocation Loc;
07634 
07635   unsigned diagnostic = diag::warn_condition_is_assignment;
07636 
07637   if (isa<BinaryOperator>(E)) {
07638     BinaryOperator *Op = cast<BinaryOperator>(E);
07639     if (Op->getOpcode() != BinaryOperator::Assign)
07640       return;
07641 
07642     // Greylist some idioms by putting them into a warning subcategory.
07643     if (ObjCMessageExpr *ME
07644           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
07645       Selector Sel = ME->getSelector();
07646 
07647       // self = [<foo> init...]
07648       if (isSelfExpr(Op->getLHS())
07649           && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
07650         diagnostic = diag::warn_condition_is_idiomatic_assignment;
07651 
07652       // <foo> = [<bar> nextObject]
07653       else if (Sel.isUnarySelector() &&
07654                Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
07655         diagnostic = diag::warn_condition_is_idiomatic_assignment;
07656     }
07657 
07658     Loc = Op->getOperatorLoc();
07659   } else if (isa<CXXOperatorCallExpr>(E)) {
07660     CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
07661     if (Op->getOperator() != OO_Equal)
07662       return;
07663 
07664     Loc = Op->getOperatorLoc();
07665   } else {
07666     // Not an assignment.
07667     return;
07668   }
07669 
07670   SourceLocation Open = E->getSourceRange().getBegin();
07671   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
07672 
07673   Diag(Loc, diagnostic) << E->getSourceRange();
07674   Diag(Loc, diag::note_condition_assign_to_comparison)
07675     << FixItHint::CreateReplacement(Loc, "==");
07676   Diag(Loc, diag::note_condition_assign_silence)
07677     << FixItHint::CreateInsertion(Open, "(")
07678     << FixItHint::CreateInsertion(Close, ")");
07679 }
07680 
07681 bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
07682   DiagnoseAssignmentAsCondition(E);
07683 
07684   if (!E->isTypeDependent()) {
07685     DefaultFunctionArrayLvalueConversion(E);
07686 
07687     QualType T = E->getType();
07688 
07689     if (getLangOptions().CPlusPlus) {
07690       if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
07691         return true;
07692     } else if (!T->isScalarType()) { // C99 6.8.4.1p1
07693       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
07694         << T << E->getSourceRange();
07695       return true;
07696     }
07697   }
07698 
07699   return false;
07700 }